diff --git a/common/rediscommand.cpp b/common/rediscommand.cpp index 3b8ed7041..9ffdd17e3 100644 --- a/common/rediscommand.cpp +++ b/common/rediscommand.cpp @@ -24,17 +24,19 @@ void RedisCommand::format(const char *fmt, ...) { redisFreeCommand(temp); temp = nullptr; + len = 0; } va_list ap; va_start(ap, fmt); - len = redisvFormatCommand(&temp, fmt, ap); + int ret = redisvFormatCommand(&temp, fmt, ap); va_end(ap); - if (len == -1) { + if (ret == -1) { throw std::bad_alloc(); - } else if (len == -2) { + } else if (ret == -2) { throw std::invalid_argument("fmt"); } + len = ret; } void RedisCommand::formatArgv(int argc, const char **argv, const size_t *argvlen) @@ -43,12 +45,14 @@ void RedisCommand::formatArgv(int argc, const char **argv, const size_t *argvlen { redisFreeCommand(temp); temp = nullptr; + len = 0; } - len = redisFormatCommandArgv(&temp, argc, argv, argvlen); - if (len == -1) { + int ret = redisFormatCommandArgv(&temp, argc, argv, argvlen); + if (ret == -1) { throw std::bad_alloc(); } + len = ret; } void RedisCommand::format(const vector &commands) @@ -135,6 +139,8 @@ std::string RedisCommand::toPrintableString() const const char *RedisCommand::c_str() const { + if (len == 0) + return nullptr; return temp; } diff --git a/tests/Makefile.am b/tests/Makefile.am index 2be3114ea..ac69ddce6 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -5,6 +5,7 @@ LDADD_GTEST = -L/usr/src/gtest -lgtest -lgtest_main -lgmock -lgmock_main tests_tests_SOURCES = tests/redis_ut.cpp \ tests/redis_piped_ut.cpp \ + tests/redis_command_ut.cpp \ tests/redis_state_ut.cpp \ tests/redis_piped_state_ut.cpp \ tests/tokenize_ut.cpp \ @@ -44,5 +45,5 @@ tests_tests_SOURCES = tests/redis_ut.cpp \ tests/main.cpp tests_tests_CFLAGS = $(DBGFLAGS) $(AM_CFLAGS) $(CFLAGS_COMMON) $(CFLAGS_GTEST) $(LIBNL_CFLAGS) -tests_tests_CPPFLAGS = $(DBGFLAGS) $(AM_CFLAGS) $(CFLAGS_COMMON) $(CFLAGS_GTEST) $(LIBNL_CFLAGS) +tests_tests_CPPFLAGS = $(DBGFLAGS) $(AM_CFLAGS) $(CFLAGS_COMMON) $(CFLAGS_GTEST) $(LIBNL_CFLAGS) -fno-access-control tests_tests_LDADD = $(LDADD_GTEST) -lpthread common/libswsscommon.la $(LIBNL_LIBS) $(CODE_COVERAGE_LIBS) sonic-db-cli/libsonicdbcli.la -lzmq -luuid -lboost_serialization diff --git a/tests/redis_command_ut.cpp b/tests/redis_command_ut.cpp new file mode 100644 index 000000000..e199e7667 --- /dev/null +++ b/tests/redis_command_ut.cpp @@ -0,0 +1,13 @@ +#include "gtest/gtest.h" +#include "common/rediscommand.h" + +TEST(RedisCommand, invalid_redis_command) +{ + swss::RedisCommand cmd; + EXPECT_THROW(cmd.format("invalid redis command %s %s"), std::invalid_argument); + EXPECT_EQ(cmd.c_str(), nullptr); + EXPECT_EQ(cmd.length(), 0); + EXPECT_EQ(cmd.len, 0); + // temp will be allocated memory after format command even if the command is invalid + EXPECT_NE(cmd.temp, nullptr); +}