From 11e3e5bc02dac75ee24dc234ce09c740d21ae479 Mon Sep 17 00:00:00 2001 From: xuyong Date: Fri, 25 Mar 2022 17:12:05 +0800 Subject: [PATCH] =?UTF-8?q?CodeCheck=E6=B8=85=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: xuyong --- adapter/properties.cpp | 25 +- adapter/socket_server_adapter.cpp | 8 +- frameworks/native/BUILD.gn | 0 frameworks/native/dgram_socket_server.cpp | 2 +- frameworks/native/format.cpp | 105 +- frameworks/native/hilog_base.cpp | 14 +- frameworks/native/hilog_inner.h | 2 +- .../native/hilog_input_socket_client.cpp | 16 +- frameworks/native/hilog_ndk.c | 29 +- frameworks/native/hilog_ndk/hilog_ndk.c | 29 +- frameworks/native/hilog_printf.cpp | 16 +- frameworks/native/include/format.h | 1 + .../include/hilog_input_socket_client.h | 2 +- .../include/hilog_input_socket_server.h | 1 + frameworks/native/include/hilogtool_msg.h | 174 +- frameworks/native/include/log_time_stamp.h | 9 +- frameworks/native/include/socket.h | 2 +- frameworks/native/output_p.inl | 1810 ++++++++--------- .../native/seq_packet_socket_server.cpp | 6 +- frameworks/native/socket_client.cpp | 1 - frameworks/native/socket_server.cpp | 1 - frameworks/native/vsnprintf_s_p.cpp | 20 +- .../js/kits/napi/src/common/napi/n_class.cpp | 2 +- .../js/kits/napi/src/common/napi/n_class.h | 6 +- .../js/kits/napi/src/common/napi/n_exporter.h | 6 +- .../kits/napi/src/common/napi/n_func_arg.cpp | 14 +- .../js/kits/napi/src/common/napi/n_func_arg.h | 2 +- .../js/kits/napi/src/common/napi/n_val.cpp | 21 +- .../js/kits/napi/src/common/napi/n_val.h | 3 +- .../js/kits/napi/src/common/napi/uni_header.h | 3 +- .../js/kits/napi/src/common/napi/util.h | 3 +- .../src/hilog/include/context/hilog_napi.h | 6 +- .../hilog/include/context/hilog_napi_base.h | 2 +- interfaces/js/kits/napi/src/hilog/module.cpp | 13 +- .../js/kits/napi/src/hilog/src/hilog_napi.cpp | 2 +- .../napi/src/hilog/src/hilog_napi_base.cpp | 8 +- .../native/innerkits/include/hilog/log.h | 16 +- .../native/innerkits/include/hilog/log_cpp.h | 11 +- services/hilogd/cmd_executor.cpp | 14 +- services/hilogd/etc/hilog.para | 0 services/hilogd/etc/hilog.para.dac | 0 services/hilogd/etc/hilog_domains.conf | 0 services/hilogd/flow_control_init.cpp | 17 +- services/hilogd/include/cmd_executor.h | 3 +- services/hilogd/include/flow_control_init.h | 1 + services/hilogd/include/kmsg_parser.h | 2 +- services/hilogd/include/log_buffer.h | 1 + services/hilogd/include/log_collector.h | 3 +- services/hilogd/include/log_compress.h | 12 +- services/hilogd/include/log_data.h | 4 +- services/hilogd/include/log_kmsg.h | 4 +- services/hilogd/include/log_persister.h | 8 +- .../hilogd/include/log_persister_rotator.h | 8 +- services/hilogd/include/service_controller.h | 2 + services/hilogd/kmsg_parser.cpp | 25 +- services/hilogd/log_buffer.cpp | 4 +- services/hilogd/log_collector.cpp | 2 +- services/hilogd/log_compress.cpp | 24 +- services/hilogd/log_kmsg.cpp | 4 +- services/hilogd/log_persister.cpp | 15 +- services/hilogd/log_persister_rotator.cpp | 19 +- services/hilogd/main.cpp | 8 +- services/hilogd/service_controller.cpp | 6 +- services/hilogtool/include/hilogtool.h | 5 +- services/hilogtool/include/log_display.h | 2 +- services/hilogtool/log_controller.cpp | 90 +- services/hilogtool/log_display.cpp | 110 +- services/hilogtool/main.cpp | 181 +- .../moduletest/common/hilog_base_ndk_test.cpp | 8 +- test/moduletest/common/hilog_ndk_test.cpp | 8 +- 70 files changed, 1556 insertions(+), 1425 deletions(-) mode change 100755 => 100644 frameworks/native/BUILD.gn mode change 100755 => 100644 frameworks/native/output_p.inl mode change 100755 => 100644 services/hilogd/etc/hilog.para mode change 100755 => 100644 services/hilogd/etc/hilog.para.dac mode change 100755 => 100644 services/hilogd/etc/hilog_domains.conf diff --git a/adapter/properties.cpp b/adapter/properties.cpp index aa62ef4..65299f2 100644 --- a/adapter/properties.cpp +++ b/adapter/properties.cpp @@ -76,6 +76,7 @@ public: { return m_isLocked; } + private: uint32_t m_propType; bool m_isLocked; @@ -89,10 +90,7 @@ public: using DataConverter = std::function; CacheData(DataConverter converter, const T& defaultValue, uint32_t propType, const std::string& suffix = "") - : m_value(defaultValue) - , m_defaultValue(defaultValue) - , m_propType(propType) - , m_converter(converter) + : m_value(defaultValue), m_defaultValue(defaultValue), m_propType(propType), m_converter(converter) { m_key = GetPropertyName(m_propType) + suffix; } @@ -122,6 +120,7 @@ public: return getDirectValue(); } } + private: bool getRawValue(char *value, unsigned int len) { @@ -328,36 +327,54 @@ bool IsDebugOn() bool IsSingleDebugOn() { static auto *switchCache = new SwitchCache(textToBool, false, PROP_SINGLE_DEBUG); + if (switchCache == nullptr) { + return false; + } return switchCache->getValue(); } bool IsPersistDebugOn() { static auto *switchCache = new SwitchCache(textToBool, false, PROP_PERSIST_DEBUG); + if (switchCache == nullptr) { + return false; + } return switchCache->getValue(); } bool IsPrivateSwitchOn() { static auto *switchCache = new SwitchCache(textToBool, true, PROP_PRIVATE); + if (switchCache == nullptr) { + return false; + } return switchCache->getValue(); } bool IsProcessSwitchOn() { static auto *switchCache = new SwitchCache(textToBool, false, PROP_PROCESS_FLOWCTRL); + if (switchCache == nullptr) { + return false; + } return switchCache->getValue(); } bool IsDomainSwitchOn() { static auto *switchCache = new SwitchCache(textToBool, false, PROP_DOMAIN_FLOWCTRL); + if (switchCache == nullptr) { + return false; + } return switchCache->getValue(); } bool IsKmsgSwitchOn() { static auto *switchCache = new SwitchCache(textToBool, false, PROP_KMSG); + if (switchCache == nullptr) { + return false; + } return switchCache->getValue(); } diff --git a/adapter/socket_server_adapter.cpp b/adapter/socket_server_adapter.cpp index 63a6a19..d4737d0 100644 --- a/adapter/socket_server_adapter.cpp +++ b/adapter/socket_server_adapter.cpp @@ -30,6 +30,8 @@ #define OHOS_SOCKET_DIR "/dev/socket/" #define OHOS_SOCKET_FILE_PREFIX "socket" +static constexpr int DECIMAL = 10; + static std::string GetFileNameByFd(const int fd) { if (fd <= 0) { @@ -60,7 +62,7 @@ static void GetSocketFds(std::vector &fds) if (dp->d_name[0] == '.') { continue; } - fd = atoi(dp->d_name); + fd = strtol(dp->d_name, nullptr, DECIMAL); auto name = GetFileNameByFd(fd); if (strncmp(name.c_str(), OHOS_SOCKET_FILE_PREFIX, strlen(OHOS_SOCKET_FILE_PREFIX))) { continue; @@ -76,7 +78,7 @@ static bool CheckSocketType(int fd, int type) { int soType = -1; socklen_t optlen = static_cast(sizeof(soType)); - if (getsockopt(fd, SOL_SOCKET,SO_TYPE, &soType, &optlen)) { + if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &soType, &optlen)) { return false; } @@ -98,7 +100,7 @@ int GetExistingSocketServer(const char *name, int type) struct sockaddr_un addr; socklen_t addrLen = static_cast(sizeof(addr)); - if (CheckSocketType(fd, type) == false) { + if (!CheckSocketType(fd, type)) { continue; } diff --git a/frameworks/native/BUILD.gn b/frameworks/native/BUILD.gn old mode 100755 new mode 100644 diff --git a/frameworks/native/dgram_socket_server.cpp b/frameworks/native/dgram_socket_server.cpp index 67fa6d3..d53d995 100644 --- a/frameworks/native/dgram_socket_server.cpp +++ b/frameworks/native/dgram_socket_server.cpp @@ -42,7 +42,7 @@ int DgramSocketServer::RecvPacket(std::vector& buffer, struct ucred *cred) iov.iov_len = packetLen; msgh.msg_iov = &iov; msgh.msg_iovlen = 1; - + msgh.msg_control = control.data(); msgh.msg_controllen = control.size(); diff --git a/frameworks/native/format.cpp b/frameworks/native/format.cpp index 64854dc..a61e755 100644 --- a/frameworks/native/format.cpp +++ b/frameworks/native/format.cpp @@ -35,24 +35,36 @@ static const int HILOG_COLOR_YELLOW = 226; const char* ParsedFromLevel(uint16_t level) { switch (level) { - case LOG_DEBUG: return "D"; - case LOG_INFO: return "I"; - case LOG_WARN: return "W"; - case LOG_ERROR: return "E"; - case LOG_FATAL: return "F"; - default: return " "; + case LOG_DEBUG: + return "D"; + case LOG_INFO: + return "I"; + case LOG_WARN: + return "W"; + case LOG_ERROR: + return "E"; + case LOG_FATAL: + return "F"; + default: + return " "; } } int ColorFromLevel(uint16_t level) { switch (level) { - case LOG_DEBUG: return HILOG_COLOR_BLUE; - case LOG_INFO: return HILOG_COLOR_GREEN; - case LOG_WARN: return HILOG_COLOR_ORANGE; - case LOG_ERROR: return HILOG_COLOR_YELLOW; - case LOG_FATAL: return HILOG_COLOR_RED; - default: return HILOG_COLOR_DEFAULT; + case LOG_DEBUG: + return HILOG_COLOR_BLUE; + case LOG_INFO: + return HILOG_COLOR_GREEN; + case LOG_WARN: + return HILOG_COLOR_ORANGE; + case LOG_ERROR: + return HILOG_COLOR_YELLOW; + case LOG_FATAL: + return HILOG_COLOR_RED; + default: + return HILOG_COLOR_DEFAULT; } } @@ -63,11 +75,16 @@ int HilogShowTimeBuffer(char* buffer, int bufLen, uint32_t showFormat, unsigned long nsecTime = contentOut.tv_nsec; size_t timeLen = 0; int ret = 0; + if (buffer == nullptr) { + return ret; + } nsecTime = (now < 0) ? (NSEC - nsecTime) : nsecTime; if ((showFormat & (1 << EPOCH_SHOWFORMAT)) || (showFormat & (1 << MONOTONIC_SHOWFORMAT))) { - ret = snprintf_s(buffer, bufLen, bufLen - 1, - (showFormat & (1 << MONOTONIC_SHOWFORMAT)) ? "%6lld" : "%19lld", (long long)now); + if (bufLen > 1) { + ret = snprintf_s(buffer, bufLen, bufLen - 1, + (showFormat & (1 << MONOTONIC_SHOWFORMAT)) ? "%6lld" : "%19lld", (long long)now); + } timeLen += ((ret > 0) ? ret : 0); } else { struct tm tmLocal; @@ -86,16 +103,22 @@ int HilogShowTimeBuffer(char* buffer, int bufLen, uint32_t showFormat, } } if (showFormat & (1 << TIME_NSEC_SHOWFORMAT)) { - ret = snprintf_s(buffer + timeLen, bufLen - timeLen, bufLen - timeLen - 1, - ".%09lu", nsecTime); + if ((bufLen - timeLen) > 1) { + ret = snprintf_s(buffer + timeLen, bufLen - timeLen, bufLen - timeLen - 1, + ".%09lu", nsecTime); + } timeLen += ((ret > 0) ? ret : 0); } else if (showFormat & (1 << TIME_USEC_SHOWFORMAT)) { - ret = snprintf_s(buffer + timeLen, bufLen - timeLen, bufLen - timeLen - 1, - ".%06llu", nsecTime / NS2US); + if ((bufLen - timeLen) > 1) { + ret = snprintf_s(buffer + timeLen, bufLen - timeLen, bufLen - timeLen - 1, + ".%06llu", nsecTime / NS2US); + } timeLen += ((ret > 0) ? ret : 0); } else { - ret = snprintf_s(buffer + timeLen, bufLen - timeLen, bufLen - timeLen - 1, - ".%03llu", nsecTime / NS2MS); + if ((bufLen - timeLen) > 1) { + ret = snprintf_s(buffer + timeLen, bufLen - timeLen, bufLen - timeLen - 1, + ".%03llu", nsecTime / NS2MS); + } timeLen += ((ret > 0) ? ret : 0); } return timeLen; @@ -109,26 +132,30 @@ void HilogShowBuffer(char* buffer, int bufLen, const HilogShowFormatBuffer& cont return; } if (showFormat & (1 << COLOR_SHOWFORMAT)) { - ret = snprintf_s(buffer, bufLen, bufLen - logLen - 1, - "\x1B[38;5;%dm", ColorFromLevel(contentOut.level)); + if ((bufLen - logLen) > 1) { + ret = snprintf_s(buffer, bufLen, bufLen - logLen - 1, + "\x1B[38;5;%dm", ColorFromLevel(contentOut.level)); + } logLen += ((ret > 0) ? ret : 0); } logLen += HilogShowTimeBuffer(buffer + logLen, bufLen - logLen, showFormat, contentOut); - ret = snprintf_s(buffer + logLen, bufLen - logLen, bufLen - logLen - 1, - " %5d", contentOut.pid); - logLen += ((ret > 0) ? ret : 0); - ret = snprintf_s(buffer + logLen, bufLen - logLen, bufLen - logLen - 1, - " %5d", contentOut.tid); - logLen += ((ret > 0) ? ret : 0); - ret = snprintf_s(buffer + logLen, bufLen - logLen, bufLen - logLen - 1, - " %s ", ParsedFromLevel(contentOut.level)); - logLen += ((ret > 0) ? ret : 0); - ret = snprintf_s(buffer + logLen, bufLen - logLen, bufLen - logLen - 1, - "%05x/%s:", contentOut.domain & 0xFFFFF, contentOut.data); - logLen += ((ret > 0) ? ret : 0); - ret = snprintf_s(buffer + logLen, bufLen - logLen, bufLen - logLen - 1, - " %s", contentOut.data + contentOut.tag_len); - logLen += ((ret > 0) ? ret : 0); + if (bufLen - logLen > 1) { + ret = snprintf_s(buffer + logLen, bufLen - logLen, bufLen - logLen - 1, + " %5d", contentOut.pid); + logLen += ((ret > 0) ? ret : 0); + ret = snprintf_s(buffer + logLen, bufLen - logLen, bufLen - logLen - 1, + " %5d", contentOut.tid); + logLen += ((ret > 0) ? ret : 0); + ret = snprintf_s(buffer + logLen, bufLen - logLen, bufLen - logLen - 1, + " %s ", ParsedFromLevel(contentOut.level)); + logLen += ((ret > 0) ? ret : 0); + ret = snprintf_s(buffer + logLen, bufLen - logLen, bufLen - logLen - 1, + "%05x/%s:", contentOut.domain & 0xFFFFF, contentOut.data); + logLen += ((ret > 0) ? ret : 0); + ret = snprintf_s(buffer + logLen, bufLen - logLen, bufLen - logLen - 1, + " %s", contentOut.data + contentOut.tag_len); + logLen += ((ret > 0) ? ret : 0); + } if (showFormat & (1 << COLOR_SHOWFORMAT)) { const char suffixColor[] = "\x1B[0m"; if (strcpy_s(buffer + logLen, sizeof(suffixColor), suffixColor) != 0) { @@ -137,5 +164,5 @@ void HilogShowBuffer(char* buffer, int bufLen, const HilogShowFormatBuffer& cont logLen += strlen(suffixColor); } } -} -} \ No newline at end of file +} // namespace HiviewDFX +} // namespace OHOS diff --git a/frameworks/native/hilog_base.cpp b/frameworks/native/hilog_base.cpp index 00a0e35..b98c4d2 100644 --- a/frameworks/native/hilog_base.cpp +++ b/frameworks/native/hilog_base.cpp @@ -90,7 +90,7 @@ static int CheckConnection(SocketHandler& socketHandler) return 0; } - auto result = TEMP_FAILURE_RETRY(connect(socketHandler.socketFd.load(), + auto result = TEMP_FAILURE_RETRY(connect(socketHandler.socketFd.load(), reinterpret_cast(&SOCKET_ADDR), sizeof(SOCKET_ADDR))); if (result < 0) { std::cerr << __FILE__ << __LINE__ << " Can't connect to server. Errno: " << errno << "\n"; @@ -120,12 +120,12 @@ static int SendMessage(HilogMsg *header, const char *tag, uint16_t tagLen, const header->tag_len = tagLen; std::array vec; - vec[0].iov_base = header; // 0 : index of hos log header - vec[0].iov_len = sizeof(HilogMsg); // 0 : index of hos log header - vec[1].iov_base = (void*)tag; // 1 : index of log tag - vec[1].iov_len = tagLen; // 1 : index of log tag - vec[2].iov_base = (void*)fmt; // 2 : index of log content - vec[2].iov_len = fmtLen; // 2 : index of log content + vec[0].iov_base = header; // 0 : index of hos log header + vec[0].iov_len = sizeof(HilogMsg); // 0 : index of hos log header + vec[1].iov_base = reinterpret_cast(const_cast(tag)); // 1 : index of log tag + vec[1].iov_len = tagLen; // 1 : index of log tag + vec[2].iov_base = reinterpret_cast(const_cast(fmt)); // 2 : index of log content + vec[2].iov_len = fmtLen; // 2 : index of log content ret = TEMP_FAILURE_RETRY(::writev(socketHandler.socketFd.load(), vec.data(), vec.size())); return ret; } diff --git a/frameworks/native/hilog_inner.h b/frameworks/native/hilog_inner.h index 611d189..b653d69 100644 --- a/frameworks/native/hilog_inner.h +++ b/frameworks/native/hilog_inner.h @@ -28,4 +28,4 @@ int HiLogPrintArgs(const LogType type, const LogLevel level, const unsigned int #ifdef __cplusplus } #endif -#endif /* HILOG_INNER_H */ \ No newline at end of file +#endif /* HILOG_INNER_H */ diff --git a/frameworks/native/hilog_input_socket_client.cpp b/frameworks/native/hilog_input_socket_client.cpp index 19f4355..4e7017f 100644 --- a/frameworks/native/hilog_input_socket_client.cpp +++ b/frameworks/native/hilog_input_socket_client.cpp @@ -44,16 +44,16 @@ int HilogInputSocketClient::WriteLogMessage(HilogMsg *header, const char *tag, u header->tag_len = tagLen; iovec vec[3]; - vec[0].iov_base = header; // 0 : index of hos log header - vec[0].iov_len = sizeof(HilogMsg); // 0 : index of hos log header - vec[1].iov_base = (void*)tag; // 1 : index of log tag - vec[1].iov_len = tagLen; // 1 : index of log tag - vec[2].iov_base = (void*)fmt; // 2 : index of log content - vec[2].iov_len = fmtLen; // 2 : index of log content - ret = WriteV(vec, 3); // 3 : written size of vector + vec[0].iov_base = header; // 0 : index of hos log header + vec[0].iov_len = sizeof(HilogMsg); // 0 : index of hos log header + vec[1].iov_base = reinterpret_cast(const_cast(tag)); // 1 : index of log tag + vec[1].iov_len = tagLen; // 1 : index of log tag + vec[2].iov_base = reinterpret_cast(const_cast(fmt)); // 2 : index of log content + vec[2].iov_len = fmtLen; // 2 : index of log content + ret = WriteV(vec, 3); // 3 : written size of vector if (ret < 0) { Connect(); - ret = WriteV(vec, 3); // 3 : written size of vector + ret = WriteV(vec, 3); // 3 : written size of vector } return ret; diff --git a/frameworks/native/hilog_ndk.c b/frameworks/native/hilog_ndk.c index a576bc2..9a2ca19 100644 --- a/frameworks/native/hilog_ndk.c +++ b/frameworks/native/hilog_ndk.c @@ -1,17 +1,17 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #include @@ -32,4 +32,3 @@ bool OHOSHiLogIsLoggable(unsigned int domain, const char *tag, LogLevel level) { return HiLogIsLoggable(domain, tag, level); } - diff --git a/frameworks/native/hilog_ndk/hilog_ndk.c b/frameworks/native/hilog_ndk/hilog_ndk.c index 3087327..79466f3 100644 --- a/frameworks/native/hilog_ndk/hilog_ndk.c +++ b/frameworks/native/hilog_ndk/hilog_ndk.c @@ -1,17 +1,17 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #include @@ -32,4 +32,3 @@ bool OH_LOG_IsLoggable(unsigned int domain, const char *tag, LogLevel level) { return HiLogIsLoggable(domain, tag, level); } - diff --git a/frameworks/native/hilog_printf.cpp b/frameworks/native/hilog_printf.cpp index e6d523d..fe672d3 100644 --- a/frameworks/native/hilog_printf.cpp +++ b/frameworks/native/hilog_printf.cpp @@ -160,10 +160,13 @@ static int HiLogFlowCtrlProcess(int len, uint16_t logType, bool debug) static size_t GetExecutablePath(char *processdir, char *processname, size_t len) { char* path_end = nullptr; + if (processdir == nullptr || processname == nullptr) { + return -1; + } if (readlink("/proc/self/exe", processdir, len) <= 0) return -1; path_end = strrchr(processdir, '/'); - if (path_end == NULL) + if (path_end == nullptr) return -1; ++path_end; if (strncpy_s(processname, MAX_PATH_LEN, path_end, MAX_PATH_LEN - 1)) { @@ -203,7 +206,7 @@ int HiLogPrintArgs(const LogType type, const LogLevel level, const unsigned int } /* print traceid */ - if (g_registerFunc != NULL) { + if (g_registerFunc != nullptr) { uint64_t chainId = 0; uint32_t flag = 0; uint64_t spanId = 0; @@ -211,7 +214,7 @@ int HiLogPrintArgs(const LogType type, const LogLevel level, const unsigned int int ret = -1; /* default value -1: invalid trace id */ atomic_fetch_add_explicit(&g_hiLogGetIdCallCount, 1, memory_order_relaxed); RegisterFunc func = g_registerFunc; - if (g_registerFunc != NULL) { + if (g_registerFunc != nullptr) { ret = func(&chainId, &flag, &spanId, &parentSpanId); } atomic_fetch_sub_explicit(&g_hiLogGetIdCallCount, 1, memory_order_relaxed); @@ -266,9 +269,10 @@ int HiLogPrintArgs(const LogType type, const LogLevel level, const unsigned int return ret; } else if (ret > 0) { char dropLogBuf[MAX_LOG_LEN] = {0}; - (void)snprintf_s(dropLogBuf, MAX_LOG_LEN, MAX_LOG_LEN - 1, "%d line(s) dopped!", ret); - HilogWriteLogMessage(&header, P_LIMIT_TAG, strlen(P_LIMIT_TAG) + 1, dropLogBuf, - strnlen(dropLogBuf, MAX_LOG_LEN - 1) + 1); + if (snprintf_s(dropLogBuf, MAX_LOG_LEN, MAX_LOG_LEN - 1, "%d line(s) dopped!", ret) == EOK) { + HilogWriteLogMessage(&header, P_LIMIT_TAG, strlen(P_LIMIT_TAG) + 1, dropLogBuf, + strnlen(dropLogBuf, MAX_LOG_LEN - 1) + 1); + } } return HilogWriteLogMessage(&header, tag, tagLen + 1, buf, logLen + 1); diff --git a/frameworks/native/include/format.h b/frameworks/native/include/format.h index a3a6923..f06d878 100644 --- a/frameworks/native/include/format.h +++ b/frameworks/native/include/format.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef LOG_FORMAT_H #define LOG_FORMAT_H #include diff --git a/frameworks/native/include/hilog_input_socket_client.h b/frameworks/native/include/hilog_input_socket_client.h index 0bea240..83b4e62 100644 --- a/frameworks/native/include/hilog_input_socket_client.h +++ b/frameworks/native/include/hilog_input_socket_client.h @@ -23,7 +23,7 @@ namespace OHOS { namespace HiviewDFX { class HilogInputSocketClient : DgramSocketClient { public: - HilogInputSocketClient() : DgramSocketClient(INPUT_SOCKET_NAME, SOCK_NONBLOCK | SOCK_CLOEXEC) {}; + HilogInputSocketClient() : DgramSocketClient(INPUT_SOCKET_NAME, SOCK_NONBLOCK | SOCK_CLOEXEC) {} int WriteLogMessage(HilogMsg *header, const char *tag, uint16_t tagLen, const char *fmt, uint16_t fmtLen); ~HilogInputSocketClient() = default; }; diff --git a/frameworks/native/include/hilog_input_socket_server.h b/frameworks/native/include/hilog_input_socket_server.h index c8f7200..b5ab75c 100644 --- a/frameworks/native/include/hilog_input_socket_server.h +++ b/frameworks/native/include/hilog_input_socket_server.h @@ -50,6 +50,7 @@ public: ServerThreadState RunServingThread(); void StopServingThread(); + private: void ServingThread(); diff --git a/frameworks/native/include/hilogtool_msg.h b/frameworks/native/include/hilogtool_msg.h index 1123a5f..3967f66 100644 --- a/frameworks/native/include/hilogtool_msg.h +++ b/frameworks/native/include/hilogtool_msg.h @@ -24,7 +24,7 @@ #define FILE_PATH_MAX_LEN 100 #define JOB_ID_ALL 0xffffffff -typedef enum { +using OperationCmd = enum { LOG_QUERY_REQUEST = 0x01, LOG_QUERY_RESPONSE, NEXT_REQUEST, @@ -48,20 +48,19 @@ typedef enum { MC_RSP_FLOW_CONTROL, // set flow control response MC_REQ_LOG_CLEAR, // clear log request MC_RSP_LOG_CLEAR // clear log response -} OperationCmd; +}; /* * property operation, such as private switch ,log level, flow switch */ -typedef enum { +using OperateType = enum { OT_PRIVATE_SWITCH = 0x01, OT_KMSG_SWITCH, OT_LOG_LEVEL, OT_FLOW_SWITCH, -} OperateType; +}; - -typedef enum { +using PersisterResponse = enum { CREATE_SUCCESS = 1, CREATE_DUPLICATE = 2, CREATE_DENIED = 3, @@ -69,15 +68,15 @@ typedef enum { QUERY_NOT_EXIST = 5, DELETE_SUCCESS = 6, DELETE_DENIED = 7, -} PersisterResponse; +}; -typedef enum { +using CompressAlg = enum { COMPRESS_TYPE_NONE = 0, COMPRESS_TYPE_ZSTD, COMPRESS_TYPE_ZLIB, -} CompressAlg; +}; -typedef enum { +using HilogShowFormat = enum { OFF_SHOWFORMAT = 0, COLOR_SHOWFORMAT, TIME_SHOWFORMAT, @@ -87,15 +86,15 @@ typedef enum { EPOCH_SHOWFORMAT, MONOTONIC_SHOWFORMAT, TIME_NSEC_SHOWFORMAT, -} HilogShowFormat; +}; -typedef struct { +using MessageHeader = struct { uint8_t version; uint8_t msgType; // hilogtool-hilogd message type uint16_t msgLen; // message length -} MessageHeader; +}; -typedef struct { +using LogQueryRequest = struct { MessageHeader header; uint8_t nPid; uint8_t nNoPid; @@ -114,9 +113,9 @@ typedef struct { uint32_t noPids[MAX_PIDS]; uint32_t noDomains[MAX_DOMAINS]; char noTags[MAX_TAGS][MAX_TAG_LEN]; -} LogQueryRequest; +}; -typedef struct { +using HilogDataMessage = struct { uint16_t sendId; uint16_t length; /* data len, equals tag_len plus content length, include '\0' */ uint16_t level; @@ -128,76 +127,76 @@ typedef struct { uint32_t tv_sec; uint32_t tv_nsec; char data[]; /* tag and content, include '\0' */ -} HilogDataMessage; +}; -typedef struct { +using LogQueryResponse = struct { MessageHeader header; HilogDataMessage data; -} LogQueryResponse; +}; -typedef struct { +using NewDataNotify = struct { MessageHeader header; -} NewDataNotify; +}; -typedef struct { +using NextRequest = struct { MessageHeader header; uint16_t sendId; -} NextRequest; +}; -typedef struct { +using NextResponce = struct { MessageHeader header; uint16_t sendId; char data[]; -} NextResponce; +}; -typedef struct { +using BuffSizeMsg = struct { uint16_t logType; -} BuffSizeMsg; +}; -typedef struct { +using BufferSizeRequest = struct { MessageHeader msgHeader; BuffSizeMsg buffSizeMsg[]; -} BufferSizeRequest; +}; -typedef struct { +using BuffSizeResult = struct { uint16_t logType; uint64_t buffSize; int32_t result; -} BuffSizeResult; +}; -typedef struct { +using BufferSizeResponse = struct { MessageHeader msgHeader; BuffSizeResult buffSizeRst[]; -} BufferSizeResponse; +}; -typedef struct { +using BuffResizeMsg = struct { uint16_t logType; uint64_t buffSize; -} BuffResizeMsg; +}; -typedef struct { +using BufferResizeRequest = struct { MessageHeader msgHeader; BuffResizeMsg buffResizeMsg[]; -} BufferResizeRequest; +}; -typedef struct { +using BuffResizeResult = struct { uint16_t logType; uint64_t buffSize; int32_t result; -} BuffResizeResult; +}; -typedef struct { +using BufferResizeResponse = struct { MessageHeader msgHeader; BuffResizeResult buffResizeRst[]; -} BufferResizeResponse; +}; -typedef struct { +using StatisticInfoQueryRequest = struct { MessageHeader msgHeader; uint16_t logType; uint32_t domain; -} StatisticInfoQueryRequest; +}; -typedef struct { +using StatisticInfoQueryResponse = struct { MessageHeader msgHeader; int32_t result; uint16_t logType; @@ -205,97 +204,101 @@ typedef struct { uint64_t printLen; uint64_t cacheLen; int32_t dropped; -} StatisticInfoQueryResponse; +}; -typedef struct { +using StatisticInfoClearRequest = struct { MessageHeader msgHeader; uint16_t logType; uint32_t domain; -} StatisticInfoClearRequest; +}; -typedef struct { +using StatisticInfoClearResponse = struct { MessageHeader msgHeader; int32_t result; uint16_t logType; uint32_t domain; -} StatisticInfoClearResponse; +}; -typedef struct { +using LogClearMsg = struct { uint16_t logType; -} LogClearMsg; +}; -typedef struct { +using LogClearRequest = struct { MessageHeader msgHeader; LogClearMsg logClearMsg[]; -} LogClearRequest; +}; -typedef struct { +using LogClearResult = struct { uint16_t logType; int32_t result; -} LogClearResult; +}; -typedef struct { +using LogClearResponse = struct { MessageHeader msgHeader; LogClearResult logClearRst[]; -} LogClearResponse; +}; -typedef struct { +using LogPersistParam = struct { std::string logTypeStr; std::string compressAlgStr; std::string fileSizeStr; std::string fileNumStr; std::string fileNameStr; std::string jobIdStr; -} LogPersistParam; -typedef struct { +}; + +using LogPersistStartMsg = struct { uint16_t logType; // union logType uint16_t compressAlg; char filePath[FILE_PATH_MAX_LEN]; uint32_t fileSize; uint32_t fileNum; uint32_t jobId; -} LogPersistStartMsg; -typedef struct { +}; + +using LogPersistStartRequest = struct { MessageHeader msgHeader; LogPersistStartMsg logPersistStartMsg; -} LogPersistStartRequest; +}; -typedef struct { +using LogPersistStartResult = struct { int32_t result; uint32_t jobId; -} LogPersistStartResult; +}; -typedef struct { +using LogPersistStartResponse = struct { MessageHeader msgHeader; LogPersistStartResult logPersistStartRst; -} LogPersistStartResponse; +}; -typedef struct { +using LogPersistStopMsg = struct { uint32_t jobId; -} LogPersistStopMsg; -typedef struct { +}; + +using LogPersistStopRequest = struct { MessageHeader msgHeader; LogPersistStopMsg logPersistStopMsg[]; -} LogPersistStopRequest; +}; -typedef struct { +using LogPersistStopResult = struct { int32_t result; uint32_t jobId; -} LogPersistStopResult; -typedef struct { +}; + +using LogPersistStopResponse = struct { MessageHeader msgHeader; LogPersistStopResult logPersistStopRst[]; -} LogPersistStopResponse; +}; -typedef struct { +using LogPersistQueryMsg = struct { uint16_t logType; -} LogPersistQueryMsg; -typedef struct { +}; +using LogPersistQueryRequest = struct { MessageHeader msgHeader; LogPersistQueryMsg logPersistQueryMsg; -} LogPersistQueryRequest; +}; -typedef struct { +using LogPersistQueryResult = struct { int32_t result; uint32_t jobId; uint16_t logType; @@ -303,13 +306,14 @@ typedef struct { char filePath[FILE_PATH_MAX_LEN]; uint32_t fileSize; uint32_t fileNum; -} LogPersistQueryResult; -typedef struct { +}; + +using LogPersistQueryResponse = struct { MessageHeader msgHeader; LogPersistQueryResult logPersistQueryRst[]; -} LogPersistQueryResponse; +}; -typedef struct { +using SetPropertyParam = struct { std::string privateSwitchStr; std::string kmsgSwitchStr; std::string flowSwitchStr; @@ -317,6 +321,6 @@ typedef struct { std::string domainStr; std::string tagStr; std::string pidStr; -} SetPropertyParam; +}; #endif /* HILOGTOOL_MSG_H */ diff --git a/frameworks/native/include/log_time_stamp.h b/frameworks/native/include/log_time_stamp.h index 4c8df97..952abdb 100644 --- a/frameworks/native/include/log_time_stamp.h +++ b/frameworks/native/include/log_time_stamp.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef LOG_TIME_STAMP_H #define LOG_TIME_STAMP_H @@ -31,10 +32,10 @@ public: } #endif explicit LogTimeStamp(const timespec& time) - : tv_sec(static_cast(time.tv_sec)), - tv_nsec(static_cast(time.tv_nsec)) {}; + : tv_sec(static_cast(time.tv_sec)), + tv_nsec(static_cast(time.tv_nsec)) {} explicit LogTimeStamp(uint32_t sec, uint32_t nsec = 0) - : tv_sec(sec), tv_nsec(nsec) {}; + : tv_sec(sec), tv_nsec(nsec) {} /* LogTimeStamp */ bool operator == (const LogTimeStamp& time) const { @@ -96,4 +97,4 @@ public: uint32_t tv_nsec = 0; }; -#endif \ No newline at end of file +#endif diff --git a/frameworks/native/include/socket.h b/frameworks/native/include/socket.h index 18e5a90..6f91762 100644 --- a/frameworks/native/include/socket.h +++ b/frameworks/native/include/socket.h @@ -24,7 +24,7 @@ namespace OHOS { namespace HiviewDFX { class Socket { public: - Socket(int socketType); + explicit Socket(int socketType); ~Socket(); bool closeHandler(); bool setHandler(int socketHandler); diff --git a/frameworks/native/output_p.inl b/frameworks/native/output_p.inl old mode 100755 new mode 100644 index 501bf03..bb6327a --- a/frameworks/native/output_p.inl +++ b/frameworks/native/output_p.inl @@ -22,8 +22,8 @@ #ifndef OUTPUT_P_INL_2B263E9C_43D8_44BB_B17A_6D2033DECEE5 #define OUTPUT_P_INL_2B263E9C_43D8_44BB_B17A_6D2033DECEE5 -#define SECUREC_FLOAT_BUFSIZE (309+40) /* max float point value */ -#define SECUREC_FLOAT_BUFSIZE_LB (4932+40) /* max long double value */ +#define SECUREC_FLOAT_BUFSIZE (309+40) // max float point value +#define SECUREC_FLOAT_BUFSIZE_LB (4932+40) // max long double value #define SECUREC_INT_MAX 2147483647 @@ -37,30 +37,54 @@ #define SECUREC_FMT_STR_LEN (16) #endif -typedef struct { +static constexpr int BINARY = 2; +static constexpr int OCTAL = 8; +static constexpr int DECIMAL = 10; +static constexpr int HEX = 16; +static constexpr int UNSIGNED_CHAR_BITS_BOUND = 128; +static constexpr int DEFAULT_PREFIX_LEN = 0; +static constexpr int FORMATTED_PREFIX_LEN = 2; +static constexpr int DEFAULT_TXT_LEN = 0; +static constexpr int ONT_BIT_TXT_LEN = 1; +static constexpr int FORMATTED_TXT_LEN = 5; +static constexpr int ONE_BIT = 1; +static constexpr int TWO_BITS = 2; +static constexpr int THREE_BITS = 3; +static constexpr int FOUR_BITS = 4; +static constexpr int ONE_BYTE_BITS = 8; +static constexpr int TWO_BYTES_BITS = 16; +static constexpr int FOUR_BYTES_BITS = 32; +static constexpr int PRECISION_MULTI_FACTOR = 2; +static constexpr int DEFAULT_PRECISION = 0; +static constexpr int REVERSE_PRECISION = -1; +static constexpr int NORMAL_PRECISION = 1; +static constexpr int FORMATTED_PRECISION = 6; +static constexpr int SAFE_WRITE_TXT_LEN_BOUND = 12; + +using SecFormatAttr = struct { unsigned int flags; int fldWidth; int precision; - int bufferIsWide; /* flag for buffer contains wide chars */ - int dynWidth; /* %* 1 width from variable parameter ;0 not */ - int dynPrecision; /* %.* 1 precision from variable parameter ;0 not */ -} SecFormatAttr; + int bufferIsWide; // flag for buffer contains wide chars + int dynWidth; // %* 1 width from variable parameter ;0 not + int dynPrecision; // %.* 1 precision from variable parameter ;0 not +}; -typedef union { - char *str; /* not a null terminated string */ +using SecFormatBuf = union { + char *str; // not a null terminated string wchar_t *wStr; -} SecFormatBuf; +}; -typedef union { +using SecBuffer = union { char str[SECUREC_BUFFER_SIZE + 1]; #ifdef SECUREC_FOR_WCHAR wchar_t wStr[SECUREC_BUFFER_SIZE + 1]; #endif -} SecBuffer; +}; static int SecIndirectSprintf(char *strDest, const char *format, ...) { - int ret; /* If initialization causes e838 */ + int ret; // If initialization causes e838 va_list arglist; va_start(arglist, format); @@ -68,110 +92,139 @@ static int SecIndirectSprintf(char *strDest, const char *format, ...) ret = vsprintf(strDest, format, arglist); SECUREC_END_MASK_MSVC_CRT_WARNING va_end(arglist); - (void)arglist; /* to clear e438 last value assigned not used , the compiler will optimize this code */ + (void)arglist; // to clear e438 last value assigned not used , the compiler will optimize this code return ret; } #ifdef SECUREC_COMPATIBLE_LINUX_FORMAT -/* to clear e506 warning */ +// to clear e506 warning static int SecIsSameSize(size_t sizeA, size_t sizeB) { return sizeA == sizeB; } #endif -#define SECUREC_SPECIAL(_val, Base) \ - case Base: \ - do { \ - *--formatBuf.str = digits[_val % Base]; \ - }while ((_val /= Base) != 0) +static void SecurecSpecial(SecFormatBuf& formatBuf, const char* digits, + SecUnsignedInt64 num, const int radix) +{ + if (radix == BINARY || radix == OCTAL + || radix == DECIMAL || radix == HEX) { + do { + *--formatBuf.str = digits[num % radix]; + } while ((num /= radix) != 0); + } +} -#define SECUREC_SAFE_WRITE_PREFIX(src, txtLen, _stream, outChars) do { \ - for (ii = 0; ii < txtLen; ++ii) { \ - *((SecChar *)(void *)(_stream->cur)) = *(src); \ - _stream->cur += sizeof(SecChar); \ - ++(src); \ - } \ - _stream->count -= txtLen * (int)(sizeof(SecChar)); \ - *(outChars) = *(outChars) + (txtLen); \ - } SECUREC_WHILE_ZERO +static void SecureSafeWritePrefix(SecChar* src, int txtLen, + SecPrintfStream* stream, int* outChars) +{ + for (int ii = 0; ii < txtLen; ++ii) { + *(reinterpret_cast(reinterpret_cast(stream->cur))) = *src; + stream->cur += sizeof(SecChar); + ++src; + } + stream->count -= txtLen * (static_cast(sizeof(SecChar))); + *outChars = *outChars + txtLen; +} -#define SECUREC_SAFE_WRITE_STR(src, txtLen, _stream, outChars) do { \ - if (txtLen < 12 /* for mobile number length */) { \ - for (ii = 0; ii < txtLen; ++ii) { \ - *((SecChar *)(void *)(_stream->cur)) = *(src); \ - _stream->cur += sizeof(SecChar); \ - ++(src); \ - } \ - } else { \ - (void)memcpy(_stream->cur, src, ((size_t)(unsigned int)txtLen * (sizeof(SecChar)))); \ - _stream->cur += (size_t)(unsigned int)txtLen * (sizeof(SecChar)); \ - } \ - _stream->count -= txtLen * (int)(sizeof(SecChar)); \ - *(outChars) = *(outChars) + (txtLen); \ - } SECUREC_WHILE_ZERO +static void SecurecSafeWriteStr(const char* src, int txtLen, + SecPrintfStream* stream, int* outChars) +{ + if (txtLen < SAFE_WRITE_TXT_LEN_BOUND) { + for (int ii = 0; ii < txtLen; ++ii) { + *(reinterpret_cast(reinterpret_cast(stream->cur))) = *src; + stream->cur += sizeof(SecChar); + ++src; + } + } else { + (void)memcpy(stream->cur, src, + (static_cast(static_cast(txtLen)) * (sizeof(SecChar)))); + stream->cur += (static_cast(static_cast(txtLen))) * (sizeof(SecChar)); + } + stream->count -= txtLen * (static_cast(sizeof(SecChar))); + *outChars = *outChars + txtLen; +} -#define SECUREC_SAFE_WRITE_CHAR(_ch, _stream, outChars) do { \ - *((SecChar *)(void *)(_stream->cur)) = (SecChar)_ch; \ - _stream->cur += sizeof(SecChar); \ - _stream->count -= (int)(sizeof(SecChar)); \ - *(outChars) = *(outChars) + 1; \ - } SECUREC_WHILE_ZERO +static void SecurecSafeWriteChar(SecChar ch, SecPrintfStream* stream, int* outChars) +{ + *(reinterpret_cast(reinterpret_cast(stream->cur))) = + (reinterpret_cast(ch)); + stream->cur += sizeof(SecChar); + stream->count -= (static_cast(sizeof(SecChar))); + *outChars = *outChars + 1; +} -#define SECUREC_SAFE_PADDING(padChar, padLen, _stream, outChars) do { \ - for (ii = 0; ii < padLen; ++ii) { \ - *((SecChar *)(void *)(_stream->cur)) = (SecChar)padChar; \ - _stream->cur += sizeof(SecChar); \ - } \ - _stream->count -= padLen * (int)(sizeof(SecChar)); \ - *(outChars) = *(outChars) + (padLen); \ - } SECUREC_WHILE_ZERO +static void SecurecSafePadding(char padChar, int padLen, SecPrintfStream* stream, int* outChars) +{ + for (int ii = 0; ii < padLen; ++ii) { + *(reinterpret_cast(reinterpret_cast(stream->cur))) = + (reinterpret_cast(padChar)); + stream->cur += sizeof(SecChar); + } + stream->count -= padLen * (static_cast(sizeof(SecChar))); + *outChars = *outChars + padLen; +} + +// The count variable can be reduced to 0, and the external function complements the \0 terminator. +static bool SecurecIsRestBufEnough(SecPrintfStream* stream, int needLen) +{ + return static_cast((stream->count) - (static_cast(needLen)) + * (static_cast(sizeof(SecChar)))) >= 0; +} -/* The count variable can be reduced to 0, and the external function complements the \0 terminator. */ -#define SECUREC_IS_REST_BUF_ENOUGH(needLen) ((int)(stream->count - (int)needLen * (int)(sizeof(SecChar))) >= 0) +constexpr int SECUREC_FMT_STATE_OFFSET = 256; -#define SECUREC_FMT_STATE_OFFSET 256 #ifdef SECUREC_FOR_WCHAR -#define SECUREC_FMT_TYPE(c,fmtTable) ((((unsigned int)(int)(c)) <= (unsigned int)(int)SECUREC_CHAR('~')) ? \ - (fmtTable[(unsigned char)(c)]) : 0) -#define SECUREC_DECODE_STATE(c,fmtTable,laststate) (SecFmtState)(((fmtTable[(SECUREC_FMT_TYPE(c,fmtTable)) * \ - ((unsigned char)STAT_INVALID + 1) + \ - (unsigned char)(laststate) + \ - SECUREC_FMT_STATE_OFFSET]))) +static SecFmtState SecurecDecodeState(SecChar c, const unsigned char* fmtTable, SecFmtState laststate) +{ + if (static_cast(static_cast(c))) <= + (static_cast(static_cast(SECUREC_CHAR('~')))) { + return static_cast(fmtTable[static_cast(c)] * + (static_cast(STAT_INVALID) + 1) + + static_cast(laststate) + + SECUREC_FMT_STATE_OFFSET]); + } else { + return static_cast(fmtTable[0] * + (static_cast(STAT_INVALID) + 1) + + static_cast(laststate) + + SECUREC_FMT_STATE_OFFSET]); + } + +} #else -#define SECUREC_DECODE_STATE(c,fmtTable,laststate) (SecFmtState)((fmtTable[(fmtTable[(unsigned char)(c)]) * \ - ((unsigned char)STAT_INVALID + 1) + \ - (unsigned char)(laststate) + \ - SECUREC_FMT_STATE_OFFSET])) +static SecFmtState SecurecDecodeState(SecChar c, const unsigned char* fmtTable, SecFmtState laststate) +{ + return static_cast(fmtTable[fmtTable[static_cast(c)] * + (static_cast(STAT_INVALID) + 1) + + static_cast(laststate) + + SECUREC_FMT_STATE_OFFSET]); +} #endif -#define PUBLIC_FLAG_LEN 8 -#define PRIVATE_FLAG_LEN 9 -#define PUBLIC_FLAG "{public}" -#define PRIVATE_FLAG "{private}" +constexpr int PUBLIC_FLAG_LEN = 8; +constexpr int PRIVATE_FLAG_LEN = 9; +constexpr int PRIVATE_STR_LEN = 9; +constexpr char PUBLIC_FLAG[] = "{public}"; +constexpr char PRIVATE_FLAG[] = "{private}"; -static void SecWritePrivateStr(SecPrintfStream *stream, int *pCharsOut) +static void SecWritePrivateStr(SecPrintfStream *stream, int *pCharsOut, int len) { - int ii = 0; -#define PRIVATE_STR_LEN (9) #ifndef SECUREC_FOR_WCHAR static const char privacyString[] = ""; const char *pPrivStr = privacyString; - - if (SECUREC_IS_REST_BUF_ENOUGH(PRIVATE_STR_LEN)) { - SECUREC_SAFE_WRITE_STR(pPrivStr, PRIVATE_STR_LEN, stream, pCharsOut); + if (SecurecIsRestBufEnough(stream, len)) { + SecurecSafeWriteStr(pPrivStr, len, stream, pCharsOut); } else { - SECUREC_WRITE_STRING(pPrivStr, PRIVATE_STR_LEN, stream, pCharsOut); + SECUREC_WRITE_STRING(pPrivStr, len, stream, pCharsOut); } #else static const wchar_t wprivacyString[] = { L'<', L'p', L'r', L'i', L'v', L'a', L't', L'e', L'>', L'\0' }; const wchar_t *pwPrivStr = wprivacyString; - - if (SECUREC_IS_REST_BUF_ENOUGH(PRIVATE_STR_LEN)) { - SECUREC_SAFE_WRITE_STR(pwPrivStr, PRIVATE_STR_LEN, stream, pCharsOut); + if (SecurecIsRestBufEnough(stream, len)) { + SecurecSafeWriteStr(pwPrivStr, len, stream, pCharsOut); } else { - SECUREC_WRITE_STRING(pwPrivStr, PRIVATE_STR_LEN, stream, pCharsOut); + SECUREC_WRITE_STRING(pwPrivStr, len, stream, pCharsOut); } #endif } @@ -179,115 +232,112 @@ static void SecWritePrivateStr(SecPrintfStream *stream, int *pCharsOut) static void SecDecodeFlags(SecChar ch, SecFormatAttr *attr) { switch (ch) { - case SECUREC_CHAR(' '): - attr->flags |= SECUREC_FLAG_SIGN_SPACE; - break; - case SECUREC_CHAR('+'): - attr->flags |= SECUREC_FLAG_SIGN; - break; - case SECUREC_CHAR('-'): - attr->flags |= SECUREC_FLAG_LEFT; - break; - case SECUREC_CHAR('0'): - attr->flags |= SECUREC_FLAG_LEADZERO; /* add zero th the front */ - break; - case SECUREC_CHAR('#'): - attr->flags |= SECUREC_FLAG_ALTERNATE; /* output %x with 0x */ - break; - default: - break; + case SECUREC_CHAR(' '): + attr->flags |= SECUREC_FLAG_SIGN_SPACE; + break; + case SECUREC_CHAR('+'): + attr->flags |= SECUREC_FLAG_SIGN; + break; + case SECUREC_CHAR('-'): + attr->flags |= SECUREC_FLAG_LEFT; + break; + case SECUREC_CHAR('0'): + attr->flags |= SECUREC_FLAG_LEADZERO; // add zero to the front + break; + case SECUREC_CHAR('#'): + attr->flags |= SECUREC_FLAG_ALTERNATE; // output %x with 0x + break; + default: + break; } return; } -static int SecDecodeSize(SecChar ch, SecFormatAttr *attr, const SecChar **format) +static int SecDecodeSize(SecChar ch, SecFormatAttr *attr, + const SecChar **format) { switch (ch) { #ifdef SECUREC_COMPATIBLE_LINUX_FORMAT - case SECUREC_CHAR('j'): - attr->flags |= SECUREC_FLAG_INTMAX; - break; + case SECUREC_CHAR('j'): + attr->flags |= SECUREC_FLAG_INTMAX; + break; #endif - case SECUREC_CHAR('q'): [[fallthrough]]; - case SECUREC_CHAR('L'): - attr->flags |= SECUREC_FLAG_LONGLONG | SECUREC_FLAG_LONG_DOUBLE; - break; - case SECUREC_CHAR('l'): - if (**format == SECUREC_CHAR('l')) { - ++(*format); - attr->flags |= SECUREC_FLAG_LONGLONG; /* long long */ - } else { - attr->flags |= SECUREC_FLAG_LONG; /* long int or wchar_t */ - } - break; - case SECUREC_CHAR('t'): - attr->flags |= SECUREC_FLAG_PTRDIFF; - break; + case SECUREC_CHAR('q'): [[fallthrough]]; + case SECUREC_CHAR('L'): + attr->flags |= SECUREC_FLAG_LONGLONG | SECUREC_FLAG_LONG_DOUBLE; + break; + case SECUREC_CHAR('l'): + if (**format == SECUREC_CHAR('l')) { + ++(*format); + attr->flags |= SECUREC_FLAG_LONGLONG; + } else { + attr->flags |= SECUREC_FLAG_LONG; // long int or wchar_t + } + break; + case SECUREC_CHAR('t'): + attr->flags |= SECUREC_FLAG_PTRDIFF; + break; #ifdef SECUREC_COMPATIBLE_LINUX_FORMAT - case SECUREC_CHAR('z'): - attr->flags |= SECUREC_FLAG_SIZE; - break; - case SECUREC_CHAR('Z'): - attr->flags |= SECUREC_FLAG_SIZE; - break; + case SECUREC_CHAR('z'): + attr->flags |= SECUREC_FLAG_SIZE; + break; + case SECUREC_CHAR('Z'): + attr->flags |= SECUREC_FLAG_SIZE; + break; #endif - - case SECUREC_CHAR('I'): + case SECUREC_CHAR('I'): #ifdef SECUREC_ON_64BITS - attr->flags |= SECUREC_FLAG_I64; /* %I to INT64 */ + attr->flags |= SECUREC_FLAG_I64; // %I to INT64 #endif - if ((**format == SECUREC_CHAR('6')) && (*((*format) + 1) == SECUREC_CHAR('4'))) { - (*format) += 2; - attr->flags |= SECUREC_FLAG_I64; /* %I64 to INT64 */ - } else if ((**format == SECUREC_CHAR('3')) && (*((*format) + 1) == SECUREC_CHAR('2'))) { - (*format) += 2; - attr->flags &= ~SECUREC_FLAG_I64; /* %I64 to INT32 */ - } else if ((**format == SECUREC_CHAR('d')) || (**format == SECUREC_CHAR('i')) || - (**format == SECUREC_CHAR('o')) || (**format == SECUREC_CHAR('u')) || - (**format == SECUREC_CHAR('x')) || (**format == SECUREC_CHAR('X'))) { - /* do nothing */ - } else { - /* Compatibility code for "%I" just print I */ - return -1; - } - break; - - case SECUREC_CHAR('h'): - if (**format == SECUREC_CHAR('h')) - attr->flags |= SECUREC_FLAG_CHAR; /* char */ - else - attr->flags |= SECUREC_FLAG_SHORT; /* short int */ - break; - - case SECUREC_CHAR('w'): - attr->flags |= SECUREC_FLAG_WIDECHAR; /* wide char */ - break; - default: - break; - + if ((**format == SECUREC_CHAR('6')) && (*((*format) + 1) == SECUREC_CHAR('4'))) { + (*format) += TWO_BITS; + attr->flags |= SECUREC_FLAG_I64; // %I64 to INT64 + } else if ((**format == SECUREC_CHAR('3')) && (*((*format) + 1) == SECUREC_CHAR('2'))) { + (*format) += TWO_BITS; + attr->flags &= ~SECUREC_FLAG_I64; // %I64 to INT32 + } else if ((**format == SECUREC_CHAR('d')) || (**format == SECUREC_CHAR('i')) || + (**format == SECUREC_CHAR('o')) || (**format == SECUREC_CHAR('u')) || + (**format == SECUREC_CHAR('x')) || (**format == SECUREC_CHAR('X'))) { + // do nothing + } else { + // Compatibility code for "%I" just print I + return -1; + } + break; + case SECUREC_CHAR('h'): + if (**format == SECUREC_CHAR('h')) { + attr->flags |= SECUREC_FLAG_CHAR; + } else { + attr->flags |= SECUREC_FLAG_SHORT; + } + break; + case SECUREC_CHAR('w'): + attr->flags |= SECUREC_FLAG_WIDECHAR; + break; + default: + break; } - return 0; } static int SecDecodeTypeC(SecFormatAttr *attr, unsigned int cValue, SecFormatBuf *formatBuf, SecBuffer *buffer) { - int textLen; + int textLen = DEFAULT_TXT_LEN; wchar_t wchar; - + if (attr == nullptr || formatBuf == nullptr || buffer == nullptr) { + return -1; + } #if (defined(SECUREC_COMPATIBLE_LINUX_FORMAT)) && !(defined(__hpux)) && !(defined(SECUREC_ON_SOLARIS)) attr->flags &= ~SECUREC_FLAG_LEADZERO; #endif - #ifdef SECUREC_FOR_WCHAR attr->bufferIsWide = 1; - wchar = (wchar_t)cValue; + wchar = static_cast(cValue); if (attr->flags & SECUREC_FLAG_SHORT) { - /* multibyte character to wide character */ + // multibyte character to wide character char tempchar[2]; - tempchar[0] = (char)(wchar & 0x00ff); + tempchar[0] = static_cast(wchar & 0x00ff); tempchar[1] = '\0'; - if (mbtowc(buffer->wStr, tempchar, sizeof(tempchar)) < 0) { return -1; } @@ -295,12 +345,12 @@ static int SecDecodeTypeC(SecFormatAttr *attr, unsigned int cValue, SecFormatBuf buffer->wStr[0] = wchar; } formatBuf->wStr = buffer->wStr; - textLen = 1; /* only 1 wide character */ + textLen = ONT_BIT_TXT_LEN; // only 1 wide character #else attr->bufferIsWide = 0; if (attr->flags & (SECUREC_FLAG_LONG | SECUREC_FLAG_WIDECHAR)) { - wchar = (wchar_t)cValue; - /* wide character to multibyte character */ + wchar = static_cast(cValue); + // wide character to multibyte character SECUREC_MASK_MSVC_CRT_WARNING textLen = wctomb(buffer->str, wchar); SECUREC_END_MASK_MSVC_CRT_WARNING @@ -308,15 +358,13 @@ static int SecDecodeTypeC(SecFormatAttr *attr, unsigned int cValue, SecFormatBuf return -1; } } else { - /* get multibyte character from argument */ - unsigned short temp; - temp = (unsigned short)cValue; - buffer->str[0] = (char)temp; - textLen = 1; + // get multibyte character from argument + unsigned short temp = static_cast(cValue); + buffer->str[0] = static_cast(temp); + textLen = ONT_BIT_TXT_LEN; } formatBuf->str = buffer->str; #endif - return textLen; } @@ -326,18 +374,18 @@ static int SecDecodeTypeS(SecFormatAttr *attr, char *argPtr, SecFormatBuf *forma is to avoid gcc warning with pointing const text with variable */ static char strNullString[8] = "(null)"; static wchar_t wStrNullString[8] = { L'(', L'n', L'u', L'l', L'l', L')', L'\0', L'\0' }; - int finalPrecision; - char *strEnd = NULL; - wchar_t *wStrEnd = NULL; - int textLen; - + char *strEnd = nullptr; + wchar_t *wStrEnd = nullptr; + int textLen = DEFAULT_TXT_LEN; + if (attr == nullptr || argPtr == nullptr || formatBuf == nullptr) { + return textLen; + } #if (defined(SECUREC_COMPATIBLE_LINUX_FORMAT)) && (!defined(SECUREC_ON_UNIX)) attr->flags &= ~SECUREC_FLAG_LEADZERO; #endif finalPrecision = (attr->precision == -1) ? SECUREC_INT_MAX : attr->precision; formatBuf->str = argPtr; - #ifdef SECUREC_FOR_WCHAR #if defined(SECUREC_COMPATIBLE_LINUX_FORMAT) if (!(attr->flags & SECUREC_FLAG_LONG)) { @@ -345,16 +393,16 @@ static int SecDecodeTypeS(SecFormatAttr *attr, char *argPtr, SecFormatBuf *forma } #endif if (attr->flags & SECUREC_FLAG_SHORT) { - if (formatBuf->str == NULL) { /* NULL passed, use special string */ + if (formatBuf->str == nullptr) { // NULL passed, use special string formatBuf->str = strNullString; } strEnd = formatBuf->str; for (textLen = 0; textLen < finalPrecision && *strEnd; textLen++) { ++strEnd; } - /* textLen now contains length in multibyte chars */ + // textLen now contains length in multibyte chars } else { - if (formatBuf->wStr == NULL) { /* NULL passed, use special string */ + if (formatBuf->wStr == nullptr) { // NULL passed, use special string formatBuf->wStr = wStrNullString; } attr->bufferIsWide = 1; @@ -362,12 +410,12 @@ static int SecDecodeTypeS(SecFormatAttr *attr, char *argPtr, SecFormatBuf *forma while (finalPrecision-- && *wStrEnd) { ++wStrEnd; } - textLen = (int)(wStrEnd - formatBuf->wStr); /* in wchar_ts */ - /* textLen now contains length in wide chars */ + textLen = static_cast(wStrEnd - formatBuf->wStr); // in wchar_ts + // textLen now contains length in wide chars } -#else /* SECUREC_FOR_WCHAR */ +#else // SECUREC_FOR_WCHAR if (attr->flags & (SECUREC_FLAG_LONG | SECUREC_FLAG_WIDECHAR)) { - if (formatBuf->wStr == NULL) { /* NULL passed, use special string */ + if (formatBuf->wStr == nullptr) { // NULL passed, use special string formatBuf->wStr = wStrNullString; } attr->bufferIsWide = 1; @@ -375,59 +423,51 @@ static int SecDecodeTypeS(SecFormatAttr *attr, char *argPtr, SecFormatBuf *forma while (finalPrecision-- && *wStrEnd) { ++wStrEnd; } - textLen = (int)(wStrEnd - formatBuf->wStr); + textLen = static_cast(wStrEnd - formatBuf->wStr); } else { - if (formatBuf->str == NULL) { /* meet NULL, use special string */ + if (formatBuf->str == nullptr) { // meet NULL, use special string formatBuf->str = strNullString; } - if (finalPrecision == SECUREC_INT_MAX) { - /* precision NOT assigned */ - /* The strlen performance is high when the string length is greater than 32 */ - textLen = (int)strlen(formatBuf->str); + /* precision NOT assigned + The strlen performance is high when the string length is greater than 32 */ + textLen = static_cast(strlen(formatBuf->str)); } else { - /* precision assigned */ + // precision assigned strEnd = formatBuf->str; while (finalPrecision-- && *strEnd) { ++strEnd; } - textLen = (int)(strEnd - formatBuf->str); /* length of the string */ + textLen = static_cast(strEnd - formatBuf->str); // length of the string } - } - -#endif /* SECUREC_FOR_WCHAR */ +#endif // SECUREC_FOR_WCHAR return textLen; } HILOG_LOCAL_API int SecOutputPS(SecPrintfStream *stream, int priv, const char *cformat, va_list arglist) { + if (stream == nullptr || cformat == nullptr) { + return -1; + } const SecChar *format = cformat; - - char *floatBuf = NULL; + char *floatBuf = nullptr; SecFormatBuf formatBuf; static const char *itoaUpperDigits = "0123456789ABCDEFX"; static const char *itoaLowerDigits = "0123456789abcdefx"; const char *digits = itoaUpperDigits; - int ii = 0; - unsigned int radix; - int charsOut; /* characters written */ - - int prefixLen = 0; + int charsOut; // characters written + int prefixLen = DEFAULT_PREFIX_LEN; int padding = 0; - - int textLen; /* length of the text */ - int bufferSize = 0; /* size of formatBuf.str */ + int textLen = DEFAULT_TXT_LEN; // length of the text + int bufferSize = 0; // size of formatBuf.str int noOutput = 0; - SecFmtState state; SecFmtState laststate; - SecChar prefix[2] = { 0 }; - SecChar ch; /* currently read character */ - + SecChar ch; // currently read character static const unsigned char fmtCharTable[337] = { /* type 0: nospecial meaning; 1: '%'; @@ -473,823 +513,751 @@ int SecOutputPS(SecPrintfStream *stream, int priv, const char *cformat, va_list 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x00, 0x00, 0x00, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x00, 0x00 }; - SecFormatAttr formatAttr; SecBuffer buffer; formatAttr.flags = 0; - formatAttr.bufferIsWide = 0; /* flag for buffer contains wide chars */ + formatAttr.bufferIsWide = 0; // flag for buffer contains wide chars formatAttr.fldWidth = 0; - formatAttr.precision = 0; + formatAttr.precision = DEFAULT_PRECISION; formatAttr.dynWidth = 0; formatAttr.dynPrecision = 0; - charsOut = 0; - textLen = 0; - state = STAT_NORMAL; /* starting state */ - formatBuf.str = NULL; - - int isPrivacy = 1; /*whether show private string*/ - - /* loop each format character */ - /* remove format != NULL */ + textLen = DEFAULT_TXT_LEN; + state = STAT_NORMAL; // starting state + formatBuf.str = nullptr; + int isPrivacy = 1; // whether show private string + // loop each format character + // remove format != NULL while ((ch = *format++) != SECUREC_CHAR('\0') && charsOut >= 0) { laststate = state; - state = SECUREC_DECODE_STATE(ch, fmtCharTable, laststate); - + state = SecurecDecodeState(ch, fmtCharTable, laststate); switch (state) { - case STAT_NORMAL: - + case STAT_NORMAL: NORMAL_CHAR: - - /* normal state, write character */ - if (SECUREC_IS_REST_BUF_ENOUGH(1 /* only one char */ )) { - SECUREC_SAFE_WRITE_CHAR(ch, stream, &charsOut); /* char * cast to wchar * */ - } else { + // normal state, write character + if (SecurecIsRestBufEnough(stream, 1)) { // only one char + SecurecSafeWriteChar(ch, stream, &charsOut); // char cast to wchar * + } else { #ifdef SECUREC_FOR_WCHAR - SECUREC_WRITE_CHAR(ch, stream, &charsOut); + SECUREC_WRITE_CHAR(ch, stream, &charsOut); #else - /* optimize function call to code */ - charsOut = -1; - stream->count = -1; + // optimize function call to code + charsOut = -1; + stream->count = -1; #endif - } - - continue; - - case STAT_PERCENT: - /* set default values */ - prefixLen = 0; - noOutput = 0; - formatAttr.flags = 0; - formatAttr.fldWidth = 0; - formatAttr.precision = -1; - formatAttr.bufferIsWide = 0; - if (*format == SECUREC_CHAR('{')) { - if (strncmp(format, PUBLIC_FLAG, PUBLIC_FLAG_LEN) == 0) { - isPrivacy = 0; - format += PUBLIC_FLAG_LEN; } - else if (strncmp(format, PRIVATE_FLAG, PRIVATE_FLAG_LEN) == 0) { + continue; + case STAT_PERCENT: + // set default values + prefixLen = DEFAULT_PREFIX_LEN; + noOutput = 0; + formatAttr.flags = 0; + formatAttr.fldWidth = 0; + formatAttr.precision = REVERSE_PRECISION; + formatAttr.bufferIsWide = 0; + if (*format == SECUREC_CHAR('{')) { + if (strncmp(format, PUBLIC_FLAG, PUBLIC_FLAG_LEN) == 0) { + isPrivacy = 0; + format += PUBLIC_FLAG_LEN; + } else if (strncmp(format, PRIVATE_FLAG, PRIVATE_FLAG_LEN) == 0) { + isPrivacy = 1; + format += PRIVATE_FLAG_LEN; + } + } else { isPrivacy = 1; - format += PRIVATE_FLAG_LEN; } - } - else { - isPrivacy = 1; - } - - if (0 == priv) { - isPrivacy = 0; - } - - break; - - case STAT_FLAG: - /* set flag based on which flag character */ - SecDecodeFlags(ch, &formatAttr); - break; - - case STAT_WIDTH: - /* update width value */ - if (ch == SECUREC_CHAR('*')) { - /* get width */ - formatAttr.fldWidth = (int)va_arg(arglist, int); - if (formatAttr.fldWidth < 0) { - formatAttr.flags |= SECUREC_FLAG_LEFT; - formatAttr.fldWidth = -formatAttr.fldWidth; - } - formatAttr.dynWidth = 1; - } else { - if (laststate != STAT_WIDTH) { - formatAttr.fldWidth = 0; - } - if (SECUREC_MUL10_ADD_BEYOND_MAX(formatAttr.fldWidth)) { - return -1; - } - formatAttr.fldWidth = (int)SECUREC_MUL10((unsigned int)formatAttr.fldWidth) + (ch - SECUREC_CHAR('0')); - formatAttr.dynWidth = 0; - } - break; - - case STAT_DOT: - formatAttr.precision = 0; - break; - - case STAT_PRECIS: - /* update precision value */ - if (ch == SECUREC_CHAR('*')) { - /* get precision from arg list */ - formatAttr.precision = (int)va_arg(arglist, int); - if (formatAttr.precision < 0) { - formatAttr.precision = -1; - } - formatAttr.dynPrecision = 1; - } else { - /* add digit to current precision */ - if (SECUREC_MUL10_ADD_BEYOND_MAX(formatAttr.precision)) { - return -1; - } - formatAttr.precision = - (int)SECUREC_MUL10((unsigned int)formatAttr.precision) + (ch - SECUREC_CHAR('0')); - formatAttr.dynPrecision = 0; - } - break; - - case STAT_SIZE: - /* read a size specifier, set the formatAttr.flags based on it */ - if (SecDecodeSize(ch, &formatAttr, &format) != 0) { - /* Compatibility code for "%I" just print I */ - state = STAT_NORMAL; - goto NORMAL_CHAR; - } - break; - - case STAT_TYPE: - - switch (ch) { - - case SECUREC_CHAR('C'): - /* wide char */ - if (!(formatAttr.flags & (SECUREC_FLAG_SHORT | SECUREC_FLAG_LONG | SECUREC_FLAG_WIDECHAR))) { - -#ifdef SECUREC_FOR_WCHAR - formatAttr.flags |= SECUREC_FLAG_SHORT; -#else - formatAttr.flags |= SECUREC_FLAG_WIDECHAR; -#endif + if (priv == 0) { + isPrivacy = 0; } - [[fallthrough]]; - case SECUREC_CHAR('c'): - { - unsigned int cValue = (unsigned int)va_arg(arglist, int); - /*if it's a private arg, just write to stream*/ - if (isPrivacy == 1) { - break; + break; + case STAT_FLAG: + // set flag based on which flag character + SecDecodeFlags(ch, &formatAttr); + break; + case STAT_WIDTH: + // update width value + if (ch == SECUREC_CHAR('*')) { + // get width + formatAttr.fldWidth = static_cast(va_arg(arglist, int)); + if (formatAttr.fldWidth < 0) { + formatAttr.flags |= SECUREC_FLAG_LEFT; + formatAttr.fldWidth = -formatAttr.fldWidth; + } + formatAttr.dynWidth = 1; + } else { + if (laststate != STAT_WIDTH) { + formatAttr.fldWidth = 0; } - textLen = SecDecodeTypeC(&formatAttr, cValue, &formatBuf, &buffer); - if (textLen < 0) { - noOutput = 1; + if (SECUREC_MUL10_ADD_BEYOND_MAX(formatAttr.fldWidth)) { + return -1; } + formatAttr.fldWidth = static_cast(SECUREC_MUL10( + static_cast(formatAttr.fldWidth)) + (ch - SECUREC_CHAR('0'))); + formatAttr.dynWidth = 0; } break; - case SECUREC_CHAR('S'): /* wide char string */ -#ifndef SECUREC_FOR_WCHAR - if (!(formatAttr.flags & (SECUREC_FLAG_SHORT | SECUREC_FLAG_LONG | SECUREC_FLAG_WIDECHAR))) { - formatAttr.flags |= SECUREC_FLAG_WIDECHAR; - } -#else - if (!(formatAttr.flags & (SECUREC_FLAG_SHORT | SECUREC_FLAG_LONG | SECUREC_FLAG_WIDECHAR))) { - formatAttr.flags |= SECUREC_FLAG_SHORT; - } -#endif - [[fallthrough]]; - case SECUREC_CHAR('s'): - { - char *argPtr = (char *)va_arg(arglist, char *); - /*if it's a private arg, just write to stream*/ - if (isPrivacy == 1) { - break; + case STAT_DOT: + formatAttr.precision = DEFAULT_PRECISION; + break; + case STAT_PRECIS: + // update precision value + if (ch == SECUREC_CHAR('*')) { + // get precision from arg list + formatAttr.precision = static_cast(va_arg(arglist, int)); + if (formatAttr.precision < 0) { + formatAttr.precision = REVERSE_PRECISION; + } + formatAttr.dynPrecision = NORMAL_PRECISION; + } else { + // add digit to current precision + if (SECUREC_MUL10_ADD_BEYOND_MAX(formatAttr.precision)) { + return -1; } - textLen = SecDecodeTypeS(&formatAttr, argPtr, &formatBuf); + formatAttr.precision = + static_cast(SECUREC_MUL10( + static_cast(formatAttr.precision)) + (ch - SECUREC_CHAR('0'))); + formatAttr.dynPrecision = 0; } break; - - case SECUREC_CHAR('n'): - /* higher risk disable it */ - return -1; - - case SECUREC_CHAR('E'): /* fall-through */ /* FALLTHRU */ - case SECUREC_CHAR('F'): /* fall-through */ /* FALLTHRU */ - case SECUREC_CHAR('G'): /* fall-through */ /* FALLTHRU */ - case SECUREC_CHAR('A'): /* fall-through */ /* FALLTHRU */ - /* convert format char to lower , use Explicit conversion to clean up compilation warning */ - ch = (SecChar) (ch + ((SecChar) (SECUREC_CHAR('a')) - (SECUREC_CHAR('A')))); - [[fallthrough]]; - case SECUREC_CHAR('e'): /* fall-through */ /* FALLTHRU */ - case SECUREC_CHAR('f'): /* fall-through */ /* FALLTHRU */ - case SECUREC_CHAR('g'): /* fall-through */ /* FALLTHRU */ - case SECUREC_CHAR('a'): - { - /*if it's a private arg, just write to stream*/ - if (isPrivacy == 1) { -#ifdef SECUREC_COMPATIBLE_LINUX_FORMAT - if (formatAttr.flags & SECUREC_FLAG_LONG_DOUBLE) { - (void)va_arg(arglist, long double); - } else + case STAT_SIZE: + // read a size specifier, set the formatAttr.flags based on it + if (SecDecodeSize(ch, &formatAttr, &format) != 0) { + // Compatibility code for "%I" just print I + state = STAT_NORMAL; + goto NORMAL_CHAR; + } + break; + case STAT_TYPE: + switch (ch) { + case SECUREC_CHAR('C'): + // wide char + if (!(formatAttr.flags & (SECUREC_FLAG_SHORT | SECUREC_FLAG_LONG | SECUREC_FLAG_WIDECHAR))) { +#ifdef SECUREC_FOR_WCHAR + formatAttr.flags |= SECUREC_FLAG_SHORT; +#else + formatAttr.flags |= SECUREC_FLAG_WIDECHAR; #endif + } + [[fallthrough]]; + case SECUREC_CHAR('c'): { - (void)va_arg(arglist, double); + unsigned int cValue = static_cast(va_arg(arglist, int)); + // if it's a private arg, just write to stream + if (isPrivacy == 1) { + break; + } + textLen = SecDecodeTypeC(&formatAttr, cValue, &formatBuf, &buffer); + if (textLen < 0) { + noOutput = 1; + } } break; - } - - /* floating point conversion */ - formatBuf.str = buffer.str; /* output buffer for float string with default size */ - - /* compute the precision value */ - if (formatAttr.precision < 0) { - formatAttr.precision = 6; - } else if (formatAttr.precision == 0 && ch == SECUREC_CHAR('g')) { - formatAttr.precision = 1; - } - - /* calc buffer size to store long double value */ - if (formatAttr.flags & SECUREC_FLAG_LONG_DOUBLE) { - if (formatAttr.precision > (SECUREC_INT_MAX - SECUREC_FLOAT_BUFSIZE_LB)) { - noOutput = 1; - break; - } - bufferSize = SECUREC_FLOAT_BUFSIZE_LB + formatAttr.precision; - } else { - if (formatAttr.precision > (SECUREC_INT_MAX - SECUREC_FLOAT_BUFSIZE)) { - noOutput = 1; - break; + case SECUREC_CHAR('S'): // wide char string +#ifndef SECUREC_FOR_WCHAR + if (!(formatAttr.flags & (SECUREC_FLAG_SHORT | SECUREC_FLAG_LONG | SECUREC_FLAG_WIDECHAR))) { + formatAttr.flags |= SECUREC_FLAG_WIDECHAR; } - bufferSize = SECUREC_FLOAT_BUFSIZE + formatAttr.precision; - } - if (formatAttr.fldWidth > bufferSize) { - bufferSize = formatAttr.fldWidth; - } - - if (bufferSize >= SECUREC_BUFFER_SIZE) { - /* the current value of SECUREC_BUFFER_SIZE could NOT store the formatted float string */ - /* size include '+' and '\0' */ - floatBuf = (char *)SECUREC_MALLOC(((size_t)(unsigned int)bufferSize + (size_t)2)); - if (floatBuf != NULL) { - formatBuf.str = floatBuf; - } else { - noOutput = 1; - break; +#else + if (!(formatAttr.flags & (SECUREC_FLAG_SHORT | SECUREC_FLAG_LONG | SECUREC_FLAG_WIDECHAR))) { + formatAttr.flags |= SECUREC_FLAG_SHORT; } - } - - { - /* add following code to call system sprintf API for float number */ - const SecChar *pFltFmt = format - 2; /* point to the position before 'f' or 'g' */ - int k; - int fltFmtStrLen; - char fltFmtBuf[SECUREC_FMT_STR_LEN]; - char *fltFmtStr = fltFmtBuf; - char *fltFmtHeap = NULL; /* to clear warning */ - - /* must meet '%' (normal format) or '}'(with{private} or{public} format)*/ - while (SECUREC_CHAR('%') != *pFltFmt && SECUREC_CHAR('}') != *pFltFmt) { - --pFltFmt; +#endif + [[fallthrough]]; + case SECUREC_CHAR('s'): + { + char *argPtr = reinterpret_cast(va_arg(arglist, char *)); + // if it's a private arg, just write to stream + if (isPrivacy == 1) { + break; + } + textLen = SecDecodeTypeS(&formatAttr, argPtr, &formatBuf); } - fltFmtStrLen = (int)((format - pFltFmt) + 1); /* with ending terminator */ - if (fltFmtStrLen > SECUREC_FMT_STR_LEN) { - /* if SECUREC_FMT_STR_LEN is NOT enough, alloc a new buffer */ - fltFmtHeap = (char *)SECUREC_MALLOC((size_t)((unsigned int)fltFmtStrLen)); - if (fltFmtHeap == NULL) { - noOutput = 1; + break; + case SECUREC_CHAR('n'): + // higher risk disable it + return -1; + case SECUREC_CHAR('E'): // fall-through FALLTHRU + case SECUREC_CHAR('F'): // fall-through FALLTHRU + case SECUREC_CHAR('G'): // fall-through FALLTHRU + case SECUREC_CHAR('A'): // fall-through FALLTHRU + // convert format char to lower , use Explicit conversion to clean up compilation warning + ch = static_cast(ch + (static_cast(SECUREC_CHAR('a')) - (SECUREC_CHAR('A')))); + [[fallthrough]]; + case SECUREC_CHAR('e'): // fall-through FALLTHRU + case SECUREC_CHAR('f'): // fall-through FALLTHRU + case SECUREC_CHAR('g'): // fall-through FALLTHRU + case SECUREC_CHAR('a'): + { + // if it's a private arg, just write to stream + if (isPrivacy == 1) { +#ifdef SECUREC_COMPATIBLE_LINUX_FORMAT + if (formatAttr.flags & SECUREC_FLAG_LONG_DOUBLE) { + (void)va_arg(arglist, long double); + } else +#endif + { + (void)va_arg(arglist, double); + } break; + } + // floating point conversion + formatBuf.str = buffer.str; // output buffer for float string with default size + // compute the precision value + if (formatAttr.precision < DEFAULT_PRECISION) { + formatAttr.precision = FORMATTED_PRECISION; + } else if (formatAttr.precision == DEFAULT_PRECISION && ch == SECUREC_CHAR('g')) { + formatAttr.precision = NORMAL_PRECISION; + } + // calc buffer size to store long double value + if (formatAttr.flags & SECUREC_FLAG_LONG_DOUBLE) { + if (formatAttr.precision > (SECUREC_INT_MAX - SECUREC_FLOAT_BUFSIZE_LB)) { + noOutput = 1; + break; + } + bufferSize = SECUREC_FLOAT_BUFSIZE_LB + formatAttr.precision; } else { - fltFmtHeap[0] = '%'; - for (k = 1; k < fltFmtStrLen - 1; ++k) { - /* convert wchar to char */ - fltFmtHeap[k] = (char)(pFltFmt[k]); /* copy the format string */ + if (formatAttr.precision > (SECUREC_INT_MAX - SECUREC_FLOAT_BUFSIZE)) { + noOutput = 1; + break; } - fltFmtHeap[k] = '\0'; - - fltFmtStr = fltFmtHeap; + bufferSize = SECUREC_FLOAT_BUFSIZE + formatAttr.precision; } - } else { - /* purpose of the repeat code is to solve the tool alarm Redundant_Null_Check */ - fltFmtBuf[0] = '%'; - for (k = 1; k < fltFmtStrLen - 1; ++k) { - /* convert wchar to char */ - fltFmtBuf[k] = (char)(pFltFmt[k]); /* copy the format string */ + if (formatAttr.fldWidth > bufferSize) { + bufferSize = formatAttr.fldWidth; } - fltFmtBuf[k] = '\0'; - } - -#ifdef SECUREC_COMPATIBLE_LINUX_FORMAT - if (formatAttr.flags & SECUREC_FLAG_LONG_DOUBLE) { - long double tmp = (long double)va_arg(arglist, long double); - /* call system sprintf to format float value */ - if (formatAttr.dynWidth && formatAttr.dynPrecision) { - textLen = SecIndirectSprintf(formatBuf.str, (char *)fltFmtStr, - formatAttr.fldWidth,formatAttr.precision, tmp); - } else if (formatAttr.dynWidth) { - textLen = SecIndirectSprintf(formatBuf.str, (char *)fltFmtStr, - formatAttr.fldWidth, tmp); - } else if (formatAttr.dynPrecision) { - textLen = SecIndirectSprintf(formatBuf.str, (char *)fltFmtStr, - formatAttr.precision, tmp); - } else { - textLen = SecIndirectSprintf(formatBuf.str, (char *)fltFmtStr, tmp); + if (bufferSize >= SECUREC_BUFFER_SIZE) { + // the current value of SECUREC_BUFFER_SIZE could NOT + // store the formatted float string size include '+' and '\0' + floatBuf = (char*)(SECUREC_MALLOC(( + static_cast(static_cast(bufferSize) + TWO_BITS)))); + if (floatBuf != nullptr) { + formatBuf.str = floatBuf; + } else { + noOutput = 1; + break; + } } - } else + { + // add following code to call system sprintf API for float number + const SecChar *pFltFmt = format - 2; // point to the position before 'f' or 'g' + int k; + int fltFmtStrLen; + char fltFmtBuf[SECUREC_FMT_STR_LEN]; + char *fltFmtStr = fltFmtBuf; + char *fltFmtHeap = nullptr; // to clear warning + // must meet '%' (normal format) or '}'(with{private} or{public} format) + while (SECUREC_CHAR('%') != *pFltFmt && SECUREC_CHAR('}') != *pFltFmt) { + --pFltFmt; + } + fltFmtStrLen = static_cast((format - pFltFmt) + 1); /* with ending terminator */ + if (fltFmtStrLen > SECUREC_FMT_STR_LEN) { + // if SECUREC_FMT_STR_LEN is NOT enough, alloc a new buffer + fltFmtHeap = (char*)(SECUREC_MALLOC( + static_cast(static_cast(fltFmtStrLen)))); + if (fltFmtHeap == nullptr) { + noOutput = 1; + break; + } else { + fltFmtHeap[0] = '%'; + for (k = 1; k < fltFmtStrLen - 1; ++k) { + // convert wchar to char + fltFmtHeap[k] = static_cast(pFltFmt[k]); // copy the format string + } + fltFmtHeap[k] = '\0'; + fltFmtStr = fltFmtHeap; + } + } else { + // purpose of the repeat code is to solve the tool alarm Redundant_Null_Check + fltFmtBuf[0] = '%'; + for (k = 1; k < fltFmtStrLen - 1; ++k) { + // convert wchar to char + fltFmtBuf[k] = static_cast(pFltFmt[k]); // copy the format string + } + fltFmtBuf[k] = '\0'; + } +#ifdef SECUREC_COMPATIBLE_LINUX_FORMAT + if (formatAttr.flags & SECUREC_FLAG_LONG_DOUBLE) { + long double tmp = (long double)va_arg(arglist, long double); + // call system sprintf to format float value + if (formatAttr.dynWidth && formatAttr.dynPrecision) { + textLen = SecIndirectSprintf(formatBuf.str, reinterpret_cast(fltFmtStr), + formatAttr.fldWidth, formatAttr.precision, tmp); + } else if (formatAttr.dynWidth) { + textLen = SecIndirectSprintf(formatBuf.str, + reinterpret_cast(fltFmtStr), formatAttr.fldWidth, tmp); + } else if (formatAttr.dynPrecision) { + textLen = SecIndirectSprintf(formatBuf.str, + reinterpret_cast(fltFmtStr), formatAttr.precision, tmp); + } else { + textLen = SecIndirectSprintf(formatBuf.str, + reinterpret_cast(fltFmtStr), tmp); + } + } else #endif - { - double tmp = (double)va_arg(arglist, double); - if (formatAttr.dynWidth && formatAttr.dynPrecision) { - textLen = SecIndirectSprintf(formatBuf.str, (char *)fltFmtStr, formatAttr.fldWidth, - formatAttr.precision, tmp); - } else if (formatAttr.dynWidth) { - textLen = SecIndirectSprintf(formatBuf.str, (char *)fltFmtStr, formatAttr.fldWidth, - tmp); - } else if (formatAttr.dynPrecision) { - textLen = SecIndirectSprintf(formatBuf.str, (char *)fltFmtStr, formatAttr.precision, - tmp); - } else { - textLen = SecIndirectSprintf(formatBuf.str, (char *)fltFmtStr, tmp); + { + double tmp = static_cast(va_arg(arglist, double)); + if (formatAttr.dynWidth && formatAttr.dynPrecision) { + textLen = SecIndirectSprintf(formatBuf.str, + reinterpret_cast(fltFmtStr), + formatAttr.fldWidth, formatAttr.precision, tmp); + } else if (formatAttr.dynWidth) { + textLen = SecIndirectSprintf(formatBuf.str, + reinterpret_cast(fltFmtStr), formatAttr.fldWidth, tmp); + } else if (formatAttr.dynPrecision) { + textLen = SecIndirectSprintf(formatBuf.str, + reinterpret_cast(fltFmtStr), formatAttr.precision, tmp); + } else { + textLen = SecIndirectSprintf(formatBuf.str, + reinterpret_cast(fltFmtStr), tmp); + } + } + if (fltFmtHeap != nullptr) { + // if buffer is allocated on heap, free it + SECUREC_FREE(fltFmtHeap); + fltFmtHeap = nullptr; + /* to clear e438 last value assigned not used, + the compiler will optimize this code */ + (void)fltFmtHeap; + } + if (textLen < 0) { + // bufferSize is large enough,just validation the return value + noOutput = 1; + break; + } + // no padding ,this variable to calculate amount of padding + formatAttr.fldWidth = textLen; + // no padding ,this variable to calculate amount of padding + prefixLen = DEFAULT_PREFIX_LEN; + // clear all internal formatAttr.flags + formatAttr.flags = 0; + break; } } - - if (fltFmtHeap != NULL) { - /* if buffer is allocated on heap, free it */ - SECUREC_FREE(fltFmtHeap); - fltFmtHeap = NULL; - /* to clear e438 last value assigned not used , the compiler will optimize this code */ - (void)fltFmtHeap; - } - if (textLen < 0) { - /* bufferSize is large enough,just validation the return value */ - noOutput = 1; - break; - } - - formatAttr.fldWidth = textLen; /* no padding ,this variable to calculate amount of padding */ - prefixLen = 0; /* no padding ,this variable to calculate amount of padding */ - formatAttr.flags = 0; /* clear all internal formatAttr.flags */ - break; - } - } - - case SECUREC_CHAR('p'): - /* print a pointer */ + case SECUREC_CHAR('p'): + // print a pointer #if defined(SECUREC_COMPATIBLE_WIN_FORMAT) - formatAttr.flags &= ~SECUREC_FLAG_LEADZERO; + formatAttr.flags &= ~SECUREC_FLAG_LEADZERO; #else - formatAttr.flags |= SECUREC_FLAG_POINTER; + formatAttr.flags |= SECUREC_FLAG_POINTER; #endif - #ifdef SECUREC_ON_64BITS - formatAttr.flags |= SECUREC_FLAG_I64; /* converting an int64 */ + formatAttr.flags |= SECUREC_FLAG_I64; // converting an int64 #else - formatAttr.flags |= SECUREC_FLAG_LONG; /* converting a long */ + formatAttr.flags |= SECUREC_FLAG_LONG; // converting a long #endif - #if (defined(SECUREC_COMPATIBLE_LINUX_FORMAT) || defined(SECUREC_VXWORKS_PLATFORM)) && (!defined(SECUREC_ON_UNIX)) - #if defined(SECUREC_VXWORKS_PLATFORM) - formatAttr.precision = 1; + formatAttr.precision = NORMAL_PRECISION; #else - formatAttr.precision = 0; + formatAttr.precision = DEFAULT_PRECISION; #endif - formatAttr.flags |= SECUREC_FLAG_ALTERNATE; /* "0x" is not default prefix in UNIX */ - digits = itoaLowerDigits; - goto OUTPUT_HEX; + formatAttr.flags |= SECUREC_FLAG_ALTERNATE; // "0x" is not default prefix in UNIX + digits = itoaLowerDigits; + goto OUTPUT_HEX; #else -/* not linux vxwoks */ +// not linux vxwoks #if defined(_AIX) || defined(SECUREC_ON_SOLARIS) - formatAttr.precision = 1; + formatAttr.precision = NORMAL_PRECISION; #else - formatAttr.precision = 2 * sizeof(void *); + formatAttr.precision = PRECISION_MULTI_FACTOR * sizeof(void*); #endif - #endif - #if defined(SECUREC_ON_UNIX) - digits = itoaLowerDigits; - goto OUTPUT_HEX; + digits = itoaLowerDigits; + goto OUTPUT_HEX; #endif - - [[fallthrough]]; - case SECUREC_CHAR('X'): - /* unsigned upper hex output */ - digits = itoaUpperDigits; - goto OUTPUT_HEX; - case SECUREC_CHAR('x'): - /* unsigned lower hex output */ - digits = itoaLowerDigits; - + [[fallthrough]]; + case SECUREC_CHAR('X'): + // unsigned upper hex output + digits = itoaUpperDigits; + goto OUTPUT_HEX; + case SECUREC_CHAR('x'): + // unsigned lower hex output + digits = itoaLowerDigits; OUTPUT_HEX: - radix = 16; - if (formatAttr.flags & SECUREC_FLAG_ALTERNATE) { - /* alternate form means '0x' prefix */ - prefix[0] = SECUREC_CHAR('0'); - prefix[1] = (SecChar) (digits[16]); /* 'x' or 'X' */ - + radix = HEX; + if (formatAttr.flags & SECUREC_FLAG_ALTERNATE) { + // alternate form means '0x' prefix + prefix[0] = SECUREC_CHAR('0'); + prefix[1] = static_cast(digits[TWO_BYTES_BITS]); // 'x' or 'X' #if (defined(SECUREC_COMPATIBLE_LINUX_FORMAT) || defined(SECUREC_VXWORKS_PLATFORM)) - if (ch == 'p') { - prefix[1] = SECUREC_CHAR('x'); - } + if (ch == 'p') { + prefix[1] = SECUREC_CHAR('x'); + } #endif #if defined(_AIX) || defined(SECUREC_ON_SOLARIS) - if (ch == 'p') { - prefixLen = 0; - } else { - prefixLen = 2; - } + if (ch == 'p') { + prefixLen = DEFAULT_PREFIX_LEN; + } else { + prefixLen = FORMATTED_PREFIX_LEN; + } #else - prefixLen = 2; + prefixLen = FORMATTED_PREFIX_LEN; #endif - - } - goto OUTPUT_INT; - case SECUREC_CHAR('i'): /* fall-through */ /* FALLTHRU */ - case SECUREC_CHAR('d'): /* fall-through */ /* FALLTHRU */ - /* signed decimal output */ - formatAttr.flags |= SECUREC_FLAG_SIGNED; - [[fallthrough]]; - case SECUREC_CHAR('u'): - radix = 10; - goto OUTPUT_INT; - case SECUREC_CHAR('o'): - /* unsigned octal output */ - radix = 8; - if (formatAttr.flags & SECUREC_FLAG_ALTERNATE) { - /* alternate form means force a leading 0 */ - formatAttr.flags |= SECUREC_FLAG_FORCE_OCTAL; - } + } + goto OUTPUT_INT; + case SECUREC_CHAR('i'): // fall-through FALLTHRU + case SECUREC_CHAR('d'): // fall-through FALLTHRU + // signed decimal output + formatAttr.flags |= SECUREC_FLAG_SIGNED; + [[fallthrough]]; + case SECUREC_CHAR('u'): + radix = DECIMAL; + goto OUTPUT_INT; + case SECUREC_CHAR('o'): + // unsigned octal output + radix = OCTAL; + if (formatAttr.flags & SECUREC_FLAG_ALTERNATE) { + // alternate form means force a leading 0 + formatAttr.flags |= SECUREC_FLAG_FORCE_OCTAL; + } OUTPUT_INT: - { - - SecUnsignedInt64 number = 0; /* number to convert */ - SecInt64 l; /* temp long value */ - unsigned char tch; + { + SecUnsignedInt64 number = 0; // number to convert + SecInt64 l; // temp long value + unsigned char tch; #if defined(SECUREC_VXWORKS_VERSION_5_4) && !defined(SECUREC_ON_64BITS) - SecUnsignedInt32 digit = 0; /* ascii value of digit */ - SecUnsignedInt32 quotientHigh = 0; - SecUnsignedInt32 quotientLow = 0; + SecUnsignedInt32 digit = 0; // ascii value of digit + SecUnsignedInt32 quotientHigh = 0; + SecUnsignedInt32 quotientLow = 0; #endif - - /* read argument into variable l */ - if (formatAttr.flags & SECUREC_FLAG_I64) { - l = (SecInt64)va_arg(arglist, SecInt64); - } else if (formatAttr.flags & SECUREC_FLAG_LONGLONG) { - l = (SecInt64)va_arg(arglist, SecInt64); - } else + // read argument into variable l + if (formatAttr.flags & SECUREC_FLAG_I64) { + l = static_cast(va_arg(arglist, SecInt64)); + } else if (formatAttr.flags & SECUREC_FLAG_LONGLONG) { + l = static_cast(va_arg(arglist, SecInt64)); + } else #ifdef SECUREC_ON_64BITS - if (formatAttr.flags & SECUREC_FLAG_LONG) { - l = (long)va_arg(arglist, long); - } else -#endif /* SECUREC_ON_64BITS */ - if (formatAttr.flags & SECUREC_FLAG_CHAR) { - if (formatAttr.flags & SECUREC_FLAG_SIGNED) { - l = (char)va_arg(arglist, int); /* sign extend */ - if (l >= 128) { /* on some platform, char is always unsigned */ - SecUnsignedInt64 tmpL = (SecUnsignedInt64)l; - formatAttr.flags |= SECUREC_FLAG_NEGATIVE; - tch = (unsigned char)(~(tmpL)); - l = tch + 1; + if (formatAttr.flags & SECUREC_FLAG_LONG) { + l = static_cast(va_arg(arglist, long)); + } else +#endif // SECUREC_ON_64BITS + if (formatAttr.flags & SECUREC_FLAG_CHAR) { + if (formatAttr.flags & SECUREC_FLAG_SIGNED) { + l = static_cast(va_arg(arglist, int)); + // on some platform, char is always unsigned + if (l >= UNSIGNED_CHAR_BITS_BOUND) { + SecUnsignedInt64 tmpL = static_cast(l); + formatAttr.flags |= SECUREC_FLAG_NEGATIVE; + tch = static_cast(~(tmpL)); + l = tch + 1; + } + } else { + l = static_cast(va_arg(arglist, int)); + } + } else if (formatAttr.flags & SECUREC_FLAG_SHORT) { + if (formatAttr.flags & SECUREC_FLAG_SIGNED) { + l = static_cast(va_arg(arglist, int)); + } else { + l = static_cast(va_arg(arglist, int)); + } } - } else { - l = (unsigned char)va_arg(arglist, int); /* zero-extend */ - } - - } else if (formatAttr.flags & SECUREC_FLAG_SHORT) { - if (formatAttr.flags & SECUREC_FLAG_SIGNED) { - l = (short)va_arg(arglist, int); /* sign extend */ - } else { - l = (unsigned short)va_arg(arglist, int); /* zero-extend */ - } - - } #ifdef SECUREC_COMPATIBLE_LINUX_FORMAT - else if (formatAttr.flags & SECUREC_FLAG_PTRDIFF) { - l = (ptrdiff_t)va_arg(arglist, ptrdiff_t); /* sign extend */ - } else if (formatAttr.flags & SECUREC_FLAG_SIZE) { - if (formatAttr.flags & SECUREC_FLAG_SIGNED) { - /* No suitable macros were found to handle the branch */ - if (SecIsSameSize(sizeof(size_t), sizeof(long))) { - l = va_arg(arglist, long); /* sign extend */ - } else if (SecIsSameSize(sizeof(size_t), sizeof(long long))) { - l = va_arg(arglist, long long); /* sign extend */ - } else { - l = va_arg(arglist, int); /* sign extend */ + else if (formatAttr.flags & SECUREC_FLAG_PTRDIFF) { + l = (ptrdiff_t)va_arg(arglist, ptrdiff_t); + } else if (formatAttr.flags & SECUREC_FLAG_SIZE) { + if (formatAttr.flags & SECUREC_FLAG_SIGNED) { + // No suitable macros were found to handle the branch + if (SecIsSameSize(sizeof(size_t), sizeof(long))) { + l = va_arg(arglist, long); + } else if (SecIsSameSize(sizeof(size_t), sizeof(long long))) { + l = va_arg(arglist, long long); + } else { + l = va_arg(arglist, int); + } + } else { + l = static_cast(static_cast(va_arg(arglist, size_t))); + } + } else if (formatAttr.flags & SECUREC_FLAG_INTMAX) { + if (formatAttr.flags & SECUREC_FLAG_SIGNED) { + l = va_arg(arglist, SecInt64); + } else { + l = static_cast( + static_cast(va_arg(arglist, SecUnsignedInt64))); + } } - } else { - l = (SecInt64)(size_t)va_arg(arglist, size_t); /* sign extend */ - } - } else if (formatAttr.flags & SECUREC_FLAG_INTMAX) { - if (formatAttr.flags & SECUREC_FLAG_SIGNED) { - l = va_arg(arglist, SecInt64); /* sign extend */ - } else { - l = (SecInt64)(SecUnsignedInt64)va_arg(arglist, SecUnsignedInt64); /* sign extend */ - } - } #endif - else { - if (formatAttr.flags & SECUREC_FLAG_SIGNED) { - l = va_arg(arglist, int); /* sign extend */ - } else { - l = (unsigned int)va_arg(arglist, int); /* zero-extend */ - } - - } - /*if it's a private arg, just write to stream*/ - if (isPrivacy == 1) { - break; - } - - /* check for negative; copy into number */ - if ((formatAttr.flags & SECUREC_FLAG_SIGNED) && l < 0) { - number = (SecUnsignedInt64)(-l); - formatAttr.flags |= SECUREC_FLAG_NEGATIVE; - } else { - number = (SecUnsignedInt64)l; - } - - if (((formatAttr.flags & SECUREC_FLAG_I64) == 0) && + else { + if (formatAttr.flags & SECUREC_FLAG_SIGNED) { + l = va_arg(arglist, int); + } else { + l = static_cast(va_arg(arglist, int)); + } + } + // if it's a private arg, just write to stream + if (isPrivacy == 1) { + break; + } + // check for negative; copy into number + if ((formatAttr.flags & SECUREC_FLAG_SIGNED) && l < 0) { + number = static_cast(-l); + formatAttr.flags |= SECUREC_FLAG_NEGATIVE; + } else { + number = static_cast(l); + } + if (((formatAttr.flags & SECUREC_FLAG_I64) == 0) && #ifdef SECUREC_COMPATIBLE_LINUX_FORMAT - ((formatAttr.flags & SECUREC_FLAG_INTMAX) == 0) && + ((formatAttr.flags & SECUREC_FLAG_INTMAX) == 0) && #endif #ifdef SECUREC_ON_64BITS - ((formatAttr.flags & SECUREC_FLAG_PTRDIFF) == 0) && - ((formatAttr.flags & SECUREC_FLAG_SIZE) == 0) && -#if !defined(SECUREC_COMPATIBLE_WIN_FORMAT) /* on window 64 system sizeof long is 32bit */ - ((formatAttr.flags & SECUREC_FLAG_LONG) == 0) && + ((formatAttr.flags & SECUREC_FLAG_PTRDIFF) == 0) && + ((formatAttr.flags & SECUREC_FLAG_SIZE) == 0) && +#if !defined(SECUREC_COMPATIBLE_WIN_FORMAT) // on window 64 system sizeof long is 32bit + ((formatAttr.flags & SECUREC_FLAG_LONG) == 0) && #endif #endif - ((formatAttr.flags & SECUREC_FLAG_LONGLONG) == 0)) { - - number &= 0xffffffff; - } - - /* check precision value for default */ - if (formatAttr.precision < 0) { - formatAttr.precision = 1; /* default precision */ - } else { + ((formatAttr.flags & SECUREC_FLAG_LONGLONG) == 0)) { + number &= 0xffffffff; + } + // check precision value for default + if (formatAttr.precision < DEFAULT_PRECISION) { + formatAttr.precision = NORMAL_PRECISION; // default precision + } else { #if defined(SECUREC_COMPATIBLE_WIN_FORMAT) - formatAttr.flags &= ~SECUREC_FLAG_LEADZERO; + formatAttr.flags &= ~SECUREC_FLAG_LEADZERO; #else - if (!(formatAttr.flags & SECUREC_FLAG_POINTER)) { - formatAttr.flags &= ~SECUREC_FLAG_LEADZERO; - } + if (!(formatAttr.flags & SECUREC_FLAG_POINTER)) { + formatAttr.flags &= ~SECUREC_FLAG_LEADZERO; + } #endif - if (formatAttr.precision > SECUREC_MAX_PRECISION) { - formatAttr.precision = SECUREC_MAX_PRECISION; - } - } - - /* Check if data is 0; if so, turn off hex prefix,if 'p',add 0x prefix,else not add prefix */ - if (number == 0) { + if (formatAttr.precision > SECUREC_MAX_PRECISION) { + formatAttr.precision = SECUREC_MAX_PRECISION; + } + } + // Check if data is 0; if so, turn off hex prefix,if 'p',add 0x prefix,else not add prefix + if (number == 0) { #if !(defined(SECUREC_VXWORKS_PLATFORM)||defined(__hpux)) - prefixLen = 0; + prefixLen = DEFAULT_PREFIX_LEN; #else - if ((ch == 'p') && (formatAttr.flags & SECUREC_FLAG_ALTERNATE)) - prefixLen = 2; - else - prefixLen = 0; + if ((ch == 'p') && (formatAttr.flags & SECUREC_FLAG_ALTERNATE)) + prefixLen = FORMATTED_PREFIX_LEN; + else + prefixLen = DEFAULT_PREFIX_LEN; #endif - } - - /* Convert data to ASCII */ - formatBuf.str = &buffer.str[SECUREC_BUFFER_SIZE]; - - if (number > 0) { + } + // Convert data to ASCII + formatBuf.str = &buffer.str[SECUREC_BUFFER_SIZE]; + if (number > 0) { #ifdef SECUREC_ON_64BITS - switch (radix) { - /* the compiler will optimize each one */ - SECUREC_SPECIAL(number, 10); - break; - SECUREC_SPECIAL(number, 16); - break; - SECUREC_SPECIAL(number, 8); - break; - default: - break; - } -#else /* for 32 bits system */ - if (number <= 0xFFFFFFFFUL) { - /* in most case, the value to be converted is small value */ - SecUnsignedInt32 n32Tmp = (SecUnsignedInt32)number; - switch (radix) { - SECUREC_SPECIAL(n32Tmp, 16); - break; - SECUREC_SPECIAL(n32Tmp, 8); - break; - + SecurecSpecial(formatBuf, digits, number, radix); +#else // for 32 bits system + if (number <= 0xFFFFFFFFUL) { + // in most case, the value to be converted is small value + SecUnsignedInt32 n32Tmp = static_cast(number); + switch (radix) { + case HEX: + SecurecSpecial(formatBuf, digits, n32Tmp, HEX); + break; + case OCTAL: + SecurecSpecial(formatBuf, digits, n32Tmp, OCTAL); + break; #ifdef _AIX - /* the compiler will optimize div 10 */ - SECUREC_SPECIAL(n32Tmp, 10); - break; + // the compiler will optimize div 10 + case DECIMAL: + SecurecSpecial(formatBuf, digits, n32Tmp, DECIMAL); + break; #else - case 10: - { - /* fast div 10 */ - SecUnsignedInt32 q; - SecUnsignedInt32 r; - do { - *--formatBuf.str = digits[n32Tmp % 10]; - q = (n32Tmp >> 1) + (n32Tmp >> 2); - q = q + (q >> 4); - q = q + (q >> 8); - q = q + (q >> 16); - q = q >> 3; - r = n32Tmp - (((q << 2) + q) << 1); - n32Tmp = (r > 9) ? (q + 1) : q; - } while (n32Tmp != 0); - } - break; + case DECIMAL: + { + // fast div 10 + SecUnsignedInt32 q; + SecUnsignedInt32 r; + do { + *--formatBuf.str = digits[n32Tmp % DECIMAL]; + q = (n32Tmp >> ONE_BIT) + (n32Tmp >> TWO_BITS); + q = q + (q >> FOUR_BITS); + q = q + (q >> ONE_BYTE_BITS); + q = q + (q >> TWO_BYTES_BITS); + q = q >> THREE_BITS; + r = n32Tmp - (((q << TWO_BITS) + q) << ONE_BIT); + n32Tmp = (r >= DECIMAL) ? (q + 1) : q; + } while (n32Tmp != 0); + } + break; #endif - default: - break; - } /* end switch */ - } else { - /* the value to be converted is greater than 4G */ + default: + break; + } // end switch + } else { + // the value to be converted is greater than 4G #if defined(SECUREC_VXWORKS_VERSION_5_4) - do { - if (0 != SecU64Div32((SecUnsignedInt32)((number >> 16) >> 16), - (SecUnsignedInt32)number, - (SecUnsignedInt32)radix, "ientHigh, "ientLow, &digit)) { - noOutput = 1; - break; - } - *--formatBuf.str = digits[digit]; - - number = (SecUnsignedInt64)quotientHigh; - number = (number << 32) + quotientLow; - } while (number != 0); + do { + if (SecU64Div32(static_cast( + (number >> TWO_BYTES_BITS) >> TWO_BYTES_BITS), + static_cast(number), + static_cast(radix), + "ientHigh, "ientLow, &digit) != 0) { + noOutput = 1; + break; + } + *--formatBuf.str = digits[digit]; + number = static_cast(quotientHigh); + number = (number << FOUR_BYTES_BITS_COUNT) + quotientLow; + } while (number != 0); #else - switch (radix) { - /* the compiler will optimize div 10 */ - SECUREC_SPECIAL(number, 10); - break; - SECUREC_SPECIAL(number, 16); - break; - SECUREC_SPECIAL(number, 8); - break; - default: - break; - } + SecurecSpecial(formatBuf, digits, number, radix); #endif - } + } #endif - } /* END if (number > 0) */ - /* compute length of number,.if textLen > 0, then formatBuf.str must be in buffer.str */ - textLen = (int)((char *)&buffer.str[SECUREC_BUFFER_SIZE] - formatBuf.str); - if (formatAttr.precision > textLen) { - for (ii = 0; ii < formatAttr.precision - textLen; ++ii) { - *--formatBuf.str = '0'; + } // END if (number > 0) + // compute length of number,.if textLen > 0, then formatBuf.str must be in buffer.str + textLen = static_cast(reinterpret_cast( + &buffer.str[SECUREC_BUFFER_SIZE]) - formatBuf.str); + if (formatAttr.precision > textLen) { + for (int ii = 0; ii < formatAttr.precision - textLen; ++ii) { + *--formatBuf.str = '0'; + } + textLen = formatAttr.precision; + } + // Force a leading zero if FORCEOCTAL flag set + if ((formatAttr.flags & SECUREC_FLAG_FORCE_OCTAL) + && (textLen == 0 || formatBuf.str[0] != '0')) { + *--formatBuf.str = '0'; + ++textLen; // add a zero + } } - textLen = formatAttr.precision; - } - - /* Force a leading zero if FORCEOCTAL flag set */ - if ((formatAttr.flags & SECUREC_FLAG_FORCE_OCTAL) && (textLen == 0 || formatBuf.str[0] != '0')) { - *--formatBuf.str = '0'; - ++textLen; /* add a zero */ - } + break; + default: + break; } - break; - default: - break; - } - /*if it's a private arg, just write to stream*/ - if (isPrivacy == 1) { - SecWritePrivateStr(stream, &charsOut); - break; - } - - if (noOutput == 0) { - if (formatAttr.flags & SECUREC_FLAG_SIGNED) { - if (formatAttr.flags & SECUREC_FLAG_NEGATIVE) { - /* prefix is a '-' */ - prefix[0] = SECUREC_CHAR('-'); - prefixLen = 1; - } else if (formatAttr.flags & SECUREC_FLAG_SIGN) { - /* prefix is '+' */ - prefix[0] = SECUREC_CHAR('+'); - prefixLen = 1; - } else if (formatAttr.flags & SECUREC_FLAG_SIGN_SPACE) { - /* prefix is ' ' */ - prefix[0] = SECUREC_CHAR(' '); - prefixLen = 1; - } + // if it's a private arg, just write to stream + if (isPrivacy == 1) { + SecWritePrivateStr(stream, &charsOut, PRIVATE_STR_LEN); + break; } - + if (noOutput == 0) { + if (formatAttr.flags & SECUREC_FLAG_SIGNED) { + if (formatAttr.flags & SECUREC_FLAG_NEGATIVE) { + // prefix is a '-' + prefix[0] = SECUREC_CHAR('-'); + prefixLen = 1; + } else if (formatAttr.flags & SECUREC_FLAG_SIGN) { + // prefix is '+' + prefix[0] = SECUREC_CHAR('+'); + prefixLen = 1; + } else if (formatAttr.flags & SECUREC_FLAG_SIGN_SPACE) { + // prefix is ' ' + prefix[0] = SECUREC_CHAR(' '); + prefixLen = 1; + } + } #if defined(SECUREC_COMPATIBLE_LINUX_FORMAT) && (!defined(SECUREC_ON_UNIX)) - if ((formatAttr.flags & SECUREC_FLAG_POINTER) && (0 == textLen)) { - formatAttr.flags &= ~SECUREC_FLAG_LEADZERO; - formatBuf.str = &buffer.str[SECUREC_BUFFER_SIZE - 1]; - *formatBuf.str-- = '\0'; - *formatBuf.str-- = ')'; - *formatBuf.str-- = 'l'; - *formatBuf.str-- = 'i'; - *formatBuf.str-- = 'n'; - *formatBuf.str = '('; - textLen = 5; - } + if ((formatAttr.flags & SECUREC_FLAG_POINTER) && (textLen == 0)) { + formatAttr.flags &= ~SECUREC_FLAG_LEADZERO; + formatBuf.str = &buffer.str[SECUREC_BUFFER_SIZE - 1]; + *formatBuf.str-- = '\0'; + *formatBuf.str-- = ')'; + *formatBuf.str-- = 'l'; + *formatBuf.str-- = 'i'; + *formatBuf.str-- = 'n'; + *formatBuf.str = '('; + textLen = FORMATTED_TXT_LEN; + } #endif - - /* calculate amount of padding */ - padding = (formatAttr.fldWidth - textLen) - prefixLen; - - /* put out the padding, prefix, and text, in the correct order */ - - if (!(formatAttr.flags & (SECUREC_FLAG_LEFT | SECUREC_FLAG_LEADZERO)) && padding > 0) { - /* pad on left with blanks */ - if (SECUREC_IS_REST_BUF_ENOUGH(padding)) { - /* char * cast to wchar * */ - SECUREC_SAFE_PADDING(SECUREC_CHAR(' '), padding, stream, &charsOut); - } else { - SECUREC_WRITE_MULTI_CHAR(SECUREC_CHAR(' '), padding, stream, &charsOut); + // calculate amount of padding + padding = (formatAttr.fldWidth - textLen) - prefixLen; + // put out the padding, prefix, and text, in the correct order + if (!(formatAttr.flags & (SECUREC_FLAG_LEFT | SECUREC_FLAG_LEADZERO)) + && padding > 0) { + // pad on left with blanks + if (SecurecIsRestBufEnough(stream, padding)) { + // char * cast to wchar * + SecurecSafePadding(SECUREC_CHAR(' '), padding, stream, &charsOut); + } else { + SECUREC_WRITE_MULTI_CHAR(SECUREC_CHAR(' '), padding, stream, &charsOut); + } } - } - - /* write prefix */ - if (prefixLen > 0) { - SecChar *pPrefix = prefix; - if (SECUREC_IS_REST_BUF_ENOUGH(prefixLen)) { - /* max prefix len is 2, use loop copy */ /* char * cast to wchar * */ - SECUREC_SAFE_WRITE_PREFIX(pPrefix, prefixLen, stream, &charsOut); - } else { - SECUREC_WRITE_STRING(prefix, prefixLen, stream, &charsOut); + // write prefix + if (prefixLen > 0) { + SecChar *pPrefix = prefix; + if (SecurecIsRestBufEnough(stream, prefixLen)) { + // max prefix len is 2, use loop copy char * cast to wchar * + SecureSafeWritePrefix(pPrefix, prefixLen, stream, &charsOut); + } else { + SECUREC_WRITE_STRING(prefix, prefixLen, stream, &charsOut); + } } - } - - if ((formatAttr.flags & SECUREC_FLAG_LEADZERO) && !(formatAttr.flags & SECUREC_FLAG_LEFT) - && padding > 0) { - /* write leading zeros */ - if (SECUREC_IS_REST_BUF_ENOUGH(padding)) { - /* char * cast to wchar * */ - SECUREC_SAFE_PADDING(SECUREC_CHAR('0'), padding, stream, &charsOut); - } else { - SECUREC_WRITE_MULTI_CHAR(SECUREC_CHAR('0'), padding, stream, &charsOut); + if ((formatAttr.flags & SECUREC_FLAG_LEADZERO) + && !(formatAttr.flags & SECUREC_FLAG_LEFT) && padding > 0) { + // write leading zeros + if (SecurecIsRestBufEnough(stream, padding)) { + // char * cast to wchar * + SecurecSafePadding(SECUREC_CHAR('0'), padding, stream, &charsOut); + } else { + SECUREC_WRITE_MULTI_CHAR(SECUREC_CHAR('0'), padding, stream, &charsOut); + } } - } - - /* write text */ + // write text #ifndef SECUREC_FOR_WCHAR - if (formatAttr.bufferIsWide && (textLen > 0)) { - wchar_t *p = formatBuf.wStr; - int count = textLen; - while (count--) { - char tmpBuf[SECUREC_MB_LEN + 1]; - SECUREC_MASK_MSVC_CRT_WARNING - int retVal = wctomb(tmpBuf, *p++); - SECUREC_END_MASK_MSVC_CRT_WARNING - if (retVal <= 0) { - charsOut = -1; - break; + if (formatAttr.bufferIsWide && (textLen > 0)) { + wchar_t *p = formatBuf.wStr; + int count = textLen; + while (count--) { + char tmpBuf[SECUREC_MB_LEN + 1]; + SECUREC_MASK_MSVC_CRT_WARNING + int retVal = wctomb(tmpBuf, *p++); + SECUREC_END_MASK_MSVC_CRT_WARNING + if (retVal <= 0) { + charsOut = -1; + break; + } + SECUREC_WRITE_STRING(tmpBuf, retVal, stream, &charsOut); } - SECUREC_WRITE_STRING(tmpBuf, retVal, stream, &charsOut); - } - } else { - if (SECUREC_IS_REST_BUF_ENOUGH(textLen)) { - SECUREC_SAFE_WRITE_STR(formatBuf.str, textLen, stream, &charsOut); } else { - SECUREC_WRITE_STRING(formatBuf.str, textLen, stream, &charsOut); - } - } -#else /* SECUREC_FOR_WCHAR */ - if (formatAttr.bufferIsWide == 0 && textLen > 0) { - int count = textLen; - char *p = formatBuf.str; - - while (count > 0) { - wchar_t wchar = L'\0'; - int retVal = mbtowc(&wchar, p, (size_t)MB_CUR_MAX); - if (retVal <= 0) { - charsOut = -1; - break; + if (SecurecIsRestBufEnough(stream, textLen)) { + SecurecSafeWriteStr(formatBuf.str, textLen, stream, &charsOut); + } else { + SECUREC_WRITE_STRING(formatBuf.str, textLen, stream, &charsOut); } - SECUREC_WRITE_CHAR(wchar, stream, &charsOut); - p += retVal; - count -= retVal; } - } else { - if (SECUREC_IS_REST_BUF_ENOUGH(textLen)) { - SECUREC_SAFE_WRITE_STR(formatBuf.wStr, textLen, stream, &charsOut); /* char * cast to wchar * */ +#else // SECUREC_FOR_WCHAR + if (formatAttr.bufferIsWide == 0 && textLen > 0) { + int count = textLen; + char *p = formatBuf.str; + while (count > 0) { + wchar_t wchar = L'\0'; + int retVal = mbtowc(&wchar, p, (size_t)MB_CUR_MAX); + if (retVal <= 0) { + charsOut = -1; + break; + } + SECUREC_WRITE_CHAR(wchar, stream, &charsOut); + p += retVal; + count -= retVal; + } } else { - SECUREC_WRITE_STRING(formatBuf.wStr, textLen, stream, &charsOut); + if (SecurecIsRestBufEnough(stream, textLen)) { + SecurecSafeWriteStr(formatBuf.wStr, textLen, stream, &charsOut); + } else { + SECUREC_WRITE_STRING(formatBuf.wStr, textLen, stream, &charsOut); + } } - } -#endif /* SECUREC_FOR_WCHAR */ - - if (charsOut >= 0 && (formatAttr.flags & SECUREC_FLAG_LEFT) && padding > 0) { - /* pad on right with blanks */ - if (SECUREC_IS_REST_BUF_ENOUGH(padding)) { - /* char * cast to wchar * */ - SECUREC_SAFE_PADDING(SECUREC_CHAR(' '), padding, stream, &charsOut); - } else { - SECUREC_WRITE_MULTI_CHAR(SECUREC_CHAR(' '), padding, stream, &charsOut); +#endif // SECUREC_FOR_WCHAR + if (charsOut >= 0 && (formatAttr.flags & SECUREC_FLAG_LEFT) && padding > 0) { + // pad on right with blanks + if (SecurecIsRestBufEnuough(stream, padding)) { + // char * cast to wchar * + SecurecSafePadding(SECUREC_CHAR(' '), padding, stream, &charsOut); + } else { + SECUREC_WRITE_MULTI_CHAR(SECUREC_CHAR(' '), padding, stream, &charsOut); + } } + // we're done! } - - /* we're done! */ - } - if (floatBuf != NULL) { - SECUREC_FREE(floatBuf); - floatBuf = NULL; - } - break; - case STAT_INVALID: - return -1; - default: - return -1; /* input format is wrong, directly return */ + if (floatBuf != nullptr) { + SECUREC_FREE(floatBuf); + floatBuf = nullptr; + } + break; + case STAT_INVALID: + return -1; + default: + return -1; // input format is wrong, directly return } } - if (state != STAT_NORMAL && state != STAT_TYPE) { return -1; } - - return charsOut; /* the number of characters written */ -} /* arglist must not be declare as const */ -#endif /* OUTPUT_P_INL_2B263E9C_43D8_44BB_B17A_6D2033DECEE5 */ - + return charsOut; // the number of characters written +} // arglist must not be declare as const +#endif // OUTPUT_P_INL_2B263E9C_43D8_44BB_B17A_6D2033DECEE5 diff --git a/frameworks/native/seq_packet_socket_server.cpp b/frameworks/native/seq_packet_socket_server.cpp index f37e5aa..dc18b2c 100644 --- a/frameworks/native/seq_packet_socket_server.cpp +++ b/frameworks/native/seq_packet_socket_server.cpp @@ -40,8 +40,10 @@ int SeqPacketSocketServer::AcceptingLoop(AcceptingHandler func) int acceptedSockedFd = 0; while ((acceptedSockedFd = Accept()) > 0) { std::unique_ptr handler = std::make_unique(SOCK_SEQPACKET); - handler->setHandler(acceptedSockedFd); - func(std::move(handler)); + if (handler != nullptr) { + handler->setHandler(acceptedSockedFd); + func(std::move(handler)); + } } int acceptError = errno; #ifdef DEBUG diff --git a/frameworks/native/socket_client.cpp b/frameworks/native/socket_client.cpp index 6dc8aa4..d13bae0 100644 --- a/frameworks/native/socket_client.cpp +++ b/frameworks/native/socket_client.cpp @@ -34,7 +34,6 @@ SocketClient::SocketClient(std::string serverPath, uint32_t socketType) : Socket if (strcpy_s(serverAddr.sun_path, sizeof(serverAddr.sun_path), sockPath.c_str()) != EOK) { return; } - serverAddr.sun_path[sizeof(serverAddr.sun_path) - 1] = '\0'; } int SocketClient::Connect() diff --git a/frameworks/native/socket_server.cpp b/frameworks/native/socket_server.cpp index 63b447a..cf9b53a 100644 --- a/frameworks/native/socket_server.cpp +++ b/frameworks/native/socket_server.cpp @@ -41,7 +41,6 @@ SocketServer::SocketServer(const std::string& _socketName, uint32_t socketType) if (strcpy_s(serverAddr.sun_path, sizeof(serverAddr.sun_path), sockPath.c_str()) != EOK) { return; } - serverAddr.sun_path[sizeof(serverAddr.sun_path) - 1] = '\0'; } int SocketServer::Init() diff --git a/frameworks/native/vsnprintf_s_p.cpp b/frameworks/native/vsnprintf_s_p.cpp index e9199c2..bd4eca9 100644 --- a/frameworks/native/vsnprintf_s_p.cpp +++ b/frameworks/native/vsnprintf_s_p.cpp @@ -30,14 +30,14 @@ #if defined(_DEBUG) || defined(DEBUG) #if defined(SECUREC_ERROR_HANDLER_BY_ASSERT) - #define SECUREC_ERROR_INVALID_PARAMTER(msg) assert( msg "invalid argument" == NULL) - #define SECUREC_ERROR_INVALID_RANGE(msg) assert( msg "invalid dest buffer size" == NULL) + #define SECUREC_ERROR_INVALID_PARAMTER(msg) assert( msg "invalid argument" == nullptr) + #define SECUREC_ERROR_INVALID_RANGE(msg) assert( msg "invalid dest buffer size" == nullptr) #elif defined(SECUREC_ERROR_HANDLER_BY_PRINTF) #if SECUREC_IN_KERNEL - #define SECUREC_ERROR_INVALID_PARAMTER(msg) printk( "%s invalid argument\n",msg) + #define SECUREC_ERROR_INVALID_PARAMTER(msg) printk( "%s invalid argument\n", msg) #define SECUREC_ERROR_INVALID_RANGE(msg) printk( "%s invalid dest buffer size\n", msg) #else - #define SECUREC_ERROR_INVALID_PARAMTER(msg) printf( "%s invalid argument\n",msg) + #define SECUREC_ERROR_INVALID_PARAMTER(msg) printf( "%s invalid argument\n", msg) #define SECUREC_ERROR_INVALID_RANGE(msg) printf( "%s invalid dest buffer size\n", msg) #endif #elif defined(SECUREC_ERROR_HANDLER_BY_FILE_LOG) @@ -55,10 +55,10 @@ #endif #define SECUREC_PRINTF_TRUNCATE (-2) -typedef struct { +using SecPrintfStream = struct { int count; char *cur; -} SecPrintfStream; +}; #ifdef SECUREC_STACK_SIZE_LESS_THAN_1K /* SECUREC_BUFFER_SIZE Can not be less than 23 , @@ -108,7 +108,7 @@ typedef struct { #endif /* put a char to output */ -#define SECUREC_PUTC(_c,_stream) ((--(_stream)->count >= 0) ? ((*(_stream)->cur++ = (char)(_c)) & 0xff) : EOF) +#define SECUREC_PUTC(_c, _stream) ((--(_stream)->count >= 0) ? ((*(_stream)->cur++ = (char)(_c)) & 0xff) : EOF) /* to clear e835 */ #define SECUREC_PUTC_ZERO(_stream) ((--(_stream)->count >= 0) ? ((*(_stream)->cur++ = (char)('\0'))) : EOF) @@ -131,7 +131,7 @@ typedef enum { #endif #ifndef SECUREC_FREE -#define SECUREC_FREE(x) free((void *)(x)) +#define SECUREC_FREE(x) free(reinterpret_cast(x)) #endif #else @@ -219,9 +219,9 @@ int vsnprintfp_s(char *strDest, size_t destMax, size_t count, int priv, const c { int retVal; - if (format == NULL || strDest == NULL || destMax == 0 || destMax > SECUREC_STRING_MAX_LEN || + if (format == nullptr || strDest == nullptr || destMax == 0 || destMax > SECUREC_STRING_MAX_LEN || (count > (SECUREC_STRING_MAX_LEN - 1) && count != (size_t)-1)) { - if (strDest != NULL && destMax > 0) { + if (strDest != nullptr && destMax > 0) { strDest[0] = '\0'; } SECUREC_ERROR_INVALID_PARAMTER("vsnprintfp_s"); diff --git a/interfaces/js/kits/napi/src/common/napi/n_class.cpp b/interfaces/js/kits/napi/src/common/napi/n_class.cpp index 45b22b2..c646236 100644 --- a/interfaces/js/kits/napi/src/common/napi/n_class.cpp +++ b/interfaces/js/kits/napi/src/common/napi/n_class.cpp @@ -55,4 +55,4 @@ napi_value NClass::InstantiateClass(napi_env env, string className, vector DefineClass(napi_env env, @@ -49,7 +49,7 @@ public: return nullptr; } T *t = nullptr; - napi_status status = napi_unwrap(env, objStat, (void **)&t); + napi_status status = napi_unwrap(env, objStat, reinterpret_cast(&t)); if (status != napi_ok) { return nullptr; } @@ -80,4 +80,4 @@ private: } // namespace HiviewDFX } // namespace OHOS -#endif // HIVIEWDFX_NAPI_NCALSS \ No newline at end of file +#endif // HIVIEWDFX_NAPI_NCALSS diff --git a/interfaces/js/kits/napi/src/common/napi/n_exporter.h b/interfaces/js/kits/napi/src/common/napi/n_exporter.h index 03ee878..f0b3fc8 100644 --- a/interfaces/js/kits/napi/src/common/napi/n_exporter.h +++ b/interfaces/js/kits/napi/src/common/napi/n_exporter.h @@ -27,11 +27,11 @@ namespace OHOS { namespace HiviewDFX { class NExporter { public: - NExporter() : exports_(nullptr, nullptr) {}; + NExporter() : exports_(nullptr, nullptr) {} virtual ~NExporter() = default; - NExporter(napi_env env, napi_value exports) : exports_(env, exports) {}; + NExporter(napi_env env, napi_value exports) : exports_(env, exports) {} virtual bool Export(napi_env env, napi_value exports) = 0; @@ -43,4 +43,4 @@ protected: } // namespace HiviewDFX } // namespace OHOS -#endif // HIVIEWDFX_NAPI_EXPOTER \ No newline at end of file +#endif // HIVIEWDFX_NAPI_EXPOTER diff --git a/interfaces/js/kits/napi/src/common/napi/n_func_arg.cpp b/interfaces/js/kits/napi/src/common/napi/n_func_arg.cpp index 3c40bc9..fbdfaf8 100644 --- a/interfaces/js/kits/napi/src/common/napi/n_func_arg.cpp +++ b/interfaces/js/kits/napi/src/common/napi/n_func_arg.cpp @@ -45,6 +45,9 @@ napi_value NFuncArg::GetThisVar(void) const napi_value NFuncArg::GetArg(size_t argPos) const { + if (argv_ == nullptr) { + return nullptr; + } return (argPos < GetArgc()) ? argv_[argPos] : nullptr; } @@ -56,6 +59,9 @@ napi_value NFuncArg::operator[](size_t argPos) const bool NFuncArg::InitArgs(std::function argcChecker) { SetArgc(0); + if (argv_ == nullptr) { + return false; + } argv_.reset(); size_t argc; @@ -66,7 +72,9 @@ bool NFuncArg::InitArgs(std::function argcChecker) } if (argc) { argv_ = make_unique(argc); - status = napi_get_cb_info(env_, info_, &argc, argv_.get(), &thisVar, nullptr); + if (argv_ != nullptr) { + status = napi_get_cb_info(env_, info_, &argc, argv_.get(), &thisVar, nullptr); + } if (status != napi_ok) { return false; } @@ -92,11 +100,11 @@ bool NFuncArg::InitArgs(size_t minArgc, size_t maxArgc) { return InitArgs([minArgc, maxArgc, this]() { size_t realArgc = GetArgc(); - if (minArgc > realArgc || maxArgc < realArgc) { + if ((minArgc > realArgc) || (maxArgc < realArgc)) { return false; } return true; }); } } // namespace HiviewDFX -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/js/kits/napi/src/common/napi/n_func_arg.h b/interfaces/js/kits/napi/src/common/napi/n_func_arg.h index 91b6649..877347f 100644 --- a/interfaces/js/kits/napi/src/common/napi/n_func_arg.h +++ b/interfaces/js/kits/napi/src/common/napi/n_func_arg.h @@ -91,4 +91,4 @@ private: } // namespace HiviewDFX } // namespace OHOS -#endif // HIVIEWDFX_NAPI_ARG \ No newline at end of file +#endif // HIVIEWDFX_NAPI_ARG diff --git a/interfaces/js/kits/napi/src/common/napi/n_val.cpp b/interfaces/js/kits/napi/src/common/napi/n_val.cpp index e97f317..d91860f 100644 --- a/interfaces/js/kits/napi/src/common/napi/n_val.cpp +++ b/interfaces/js/kits/napi/src/common/napi/n_val.cpp @@ -38,10 +38,7 @@ bool NVal::TypeIs(napi_valuetype expType) const napi_valuetype valueType; napi_typeof(env_, val_, &valueType); - if (expType != valueType) { - return false; - } - return true; + return (expType == valueType); } tuple NVal::IsArray() const @@ -61,7 +58,9 @@ tuple, size_t> NVal::ToUTF8String() const size_t bufLen = strLen + 1; unique_ptr str = make_unique(bufLen); - status = napi_get_value_string_utf8(env_, val_, str.get(), bufLen, &strLen); + if (str != nullptr) { + status = napi_get_value_string_utf8(env_, val_, str.get(), bufLen, &strLen); + } return make_tuple(status == napi_ok, move(str), strLen); } @@ -75,7 +74,9 @@ tuple, size_t> NVal::ToUTF16String() const } auto str = make_unique(++strLen); - status = napi_get_value_string_utf16(env_, val_, str.get(), strLen, nullptr); + if (str != nullptr) { + status = napi_get_value_string_utf16(env_, val_, str.get(), strLen, nullptr); + } if (status != napi_ok) { return { false, nullptr, 0 }; } @@ -146,7 +147,8 @@ tuple NVal::ToTypedArray() const size_t byte_offset; size_t length; void *data = nullptr; - napi_status status = napi_get_typedarray_info(env_, val_, &type, &length, (void **) &data, &in_array_buffer, + napi_status status = napi_get_typedarray_info(env_, val_, + &type, &length, reinterpret_cast(&data), &in_array_buffer, &byte_offset); return make_tuple(status == napi_ok, type, data, length); } @@ -169,7 +171,8 @@ tuple NVal::ToTypedArrayInfo size_t length; void *data = nullptr; napi_status status = - napi_get_typedarray_info(env_, val_, &type, &length, (void **)&data, &in_array_buffer, &byte_offset); + napi_get_typedarray_info(env_, val_, &type, &length, + reinterpret_cast(&data), &in_array_buffer, &byte_offset); return make_tuple(status == napi_ok, data, length, byte_offset, type); } @@ -316,4 +319,4 @@ napi_property_descriptor NVal::DeclareNapiGetterSetter(const char *name, napi_ca return {(name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr}; } } // namespace HiviewDFX -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/js/kits/napi/src/common/napi/n_val.h b/interfaces/js/kits/napi/src/common/napi/n_val.h index e2ed44d..e682c6f 100644 --- a/interfaces/js/kits/napi/src/common/napi/n_val.h +++ b/interfaces/js/kits/napi/src/common/napi/n_val.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef HIVIEWDFX_NAPI_VAL #define HIVIEWDFX_NAPI_VAL @@ -113,4 +114,4 @@ public: } // namespace HiviewDFX } // namespace OHOS -#endif // HIVIEWDFX_NAPI_VAL \ No newline at end of file +#endif // HIVIEWDFX_NAPI_VAL diff --git a/interfaces/js/kits/napi/src/common/napi/uni_header.h b/interfaces/js/kits/napi/src/common/napi/uni_header.h index d000d78..4692c56 100644 --- a/interfaces/js/kits/napi/src/common/napi/uni_header.h +++ b/interfaces/js/kits/napi/src/common/napi/uni_header.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef INTERFACES_JS_KITS_NAPI_SRC_COMMON_NAPI_UNI_HEADER_H #define INTERFACES_JS_KITS_NAPI_SRC_COMMON_NAPI_UNI_HEADER_H @@ -22,4 +23,4 @@ #include "napi/native_api.h" #include "napi/native_node_api.h" -#endif // INTERFACES_JS_KITS_NAPI_SRC_COMMON_NAPI_UNI_HEADER_H \ No newline at end of file +#endif // INTERFACES_JS_KITS_NAPI_SRC_COMMON_NAPI_UNI_HEADER_H diff --git a/interfaces/js/kits/napi/src/common/napi/util.h b/interfaces/js/kits/napi/src/common/napi/util.h index b78a313..f103410 100644 --- a/interfaces/js/kits/napi/src/common/napi/util.h +++ b/interfaces/js/kits/napi/src/common/napi/util.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef HIVIEW_NAPI_UTIL #define HIVIEW_NAPI_UTIL #include @@ -124,4 +125,4 @@ ReturnT unpack_caller(FuncType& func, VecType& args) return details::do_call(func, args, BuildIndices()); } } // namespace util -#endif // HIVIEW_NAPI_UTIL \ No newline at end of file +#endif // HIVIEW_NAPI_UTIL diff --git a/interfaces/js/kits/napi/src/hilog/include/context/hilog_napi.h b/interfaces/js/kits/napi/src/hilog/include/context/hilog_napi.h index 12a876b..21f3bc0 100644 --- a/interfaces/js/kits/napi/src/hilog/include/context/hilog_napi.h +++ b/interfaces/js/kits/napi/src/hilog/include/context/hilog_napi.h @@ -26,11 +26,11 @@ public: inline static const std::string className = "hilog"; bool Export(napi_env env, napi_value exports) override; std::string GetClassName() override; - HilogNapi(napi_env env, napi_value exports) : NExporter(env, exports) {}; - explicit HilogNapi() {}; + HilogNapi(napi_env env, napi_value exports) : NExporter(env, exports) {} + explicit HilogNapi() {} ~HilogNapi() override {}; }; } // namespace HiviewDFX } // namespace OHOS -#endif // HIVIEWDFX_NAPI_HILOG \ No newline at end of file +#endif // HIVIEWDFX_NAPI_HILOG diff --git a/interfaces/js/kits/napi/src/hilog/include/context/hilog_napi_base.h b/interfaces/js/kits/napi/src/hilog/include/context/hilog_napi_base.h index 5faccaf..b061282 100644 --- a/interfaces/js/kits/napi/src/hilog/include/context/hilog_napi_base.h +++ b/interfaces/js/kits/napi/src/hilog/include/context/hilog_napi_base.h @@ -43,4 +43,4 @@ private: } #endif -#endif // HIVIEWDFX_NAPI_HILOG_BASE \ No newline at end of file +#endif // HIVIEWDFX_NAPI_HILOG_BASE diff --git a/interfaces/js/kits/napi/src/hilog/module.cpp b/interfaces/js/kits/napi/src/hilog/module.cpp index b9074bc..014ba27 100644 --- a/interfaces/js/kits/napi/src/hilog/module.cpp +++ b/interfaces/js/kits/napi/src/hilog/module.cpp @@ -25,10 +25,13 @@ namespace HiviewDFX { static napi_value Export(napi_env env, napi_value exports) { std::vector> products; - products.emplace_back(make_unique(env, exports)); - for (auto &&product : products) { - if (!product->Export(env, exports)) { - return nullptr; + auto product = make_unique(env, exports); + if (product != nullptr) { + products.emplace_back(); + for (auto &&product : products) { + if (!product->Export(env, exports)) { + return nullptr; + } } } return exports; @@ -36,4 +39,4 @@ static napi_value Export(napi_env env, napi_value exports) NAPI_MODULE(hilog, Export) } // namespace HiviewDFX -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/js/kits/napi/src/hilog/src/hilog_napi.cpp b/interfaces/js/kits/napi/src/hilog/src/hilog_napi.cpp index 3a0a77e..2d9b6af 100644 --- a/interfaces/js/kits/napi/src/hilog/src/hilog_napi.cpp +++ b/interfaces/js/kits/napi/src/hilog/src/hilog_napi.cpp @@ -62,4 +62,4 @@ string HilogNapi::GetClassName() #ifdef __cplusplus } -#endif \ No newline at end of file +#endif diff --git a/interfaces/js/kits/napi/src/hilog/src/hilog_napi_base.cpp b/interfaces/js/kits/napi/src/hilog/src/hilog_napi_base.cpp index 79e99ee..a20518d 100644 --- a/interfaces/js/kits/napi/src/hilog/src/hilog_napi_base.cpp +++ b/interfaces/js/kits/napi/src/hilog/src/hilog_napi_base.cpp @@ -65,7 +65,7 @@ void ParseLogContent(string& formatStr, vector& params, string& logConte if (formatStr.substr(pos + PROPERTY_POS, PRIVATE_LEN) == "private") { pos += (PRIVATE_LEN + PROPERTY_POS); if (priv) { - showPriv = true ; + showPriv = true; } } } @@ -234,7 +234,7 @@ napi_value HilogNapiBase::HilogImpl(napi_env env, napi_callback_info info, int l if (!res) { for (size_t i = MIN_NUMBER; i < funcArg.GetArgc(); i++) { napi_value argsVal = funcArg[i]; - parseNapiValue(env, info, argsVal, params); + (void)parseNapiValue(env, info, argsVal, params); } } else { if (funcArg.GetArgc() != MIN_NUMBER + 1) { @@ -254,7 +254,7 @@ napi_value HilogNapiBase::HilogImpl(napi_env env, napi_callback_info info, int l if (eleStatus != napi_ok) { return nullptr; } - parseNapiValue(env, info, element, params); + (void)parseNapiValue(env, info, element, params); } } ParseLogContent(fmtString, params, logContent); @@ -267,4 +267,4 @@ napi_value HilogNapiBase::HilogImpl(napi_env env, napi_callback_info info, int l #ifdef __cplusplus } -#endif \ No newline at end of file +#endif diff --git a/interfaces/native/innerkits/include/hilog/log.h b/interfaces/native/innerkits/include/hilog/log.h index 45e604a..f905b40 100644 --- a/interfaces/native/innerkits/include/hilog/log.h +++ b/interfaces/native/innerkits/include/hilog/log.h @@ -12,11 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#ifndef HIVIEWDFX_HILOG_H -#define HIVIEWDFX_HILOG_H - -#include "hilog/log_c.h" -#include "hilog/log_cpp.h" - -#endif // HIVIEWDFX_HILOG_H \ No newline at end of file + +#ifndef HIVIEWDFX_HILOG_H +#define HIVIEWDFX_HILOG_H + +#include "hilog/log_c.h" +#include "hilog/log_cpp.h" + +#endif // HIVIEWDFX_HILOG_H diff --git a/interfaces/native/innerkits/include/hilog/log_cpp.h b/interfaces/native/innerkits/include/hilog/log_cpp.h index 3bc9f9b..ff48162 100644 --- a/interfaces/native/innerkits/include/hilog/log_cpp.h +++ b/interfaces/native/innerkits/include/hilog/log_cpp.h @@ -19,15 +19,13 @@ #include "hilog/log_c.h" #ifdef __cplusplus - namespace OHOS { namespace HiviewDFX { - -typedef struct HiLogLabel { +using HiLogLabel = struct { LogType type; unsigned int domain; const char *tag; -} HiLogLabel; +}; class HiLog final { public: @@ -37,10 +35,7 @@ public: static int Error(const HiLogLabel &label, const char *fmt, ...) __attribute__((__format__(os_log, 2, 3))); static int Fatal(const HiLogLabel &label, const char *fmt, ...) __attribute__((__format__(os_log, 2, 3))); }; - } // namespace HiviewDFX } // namespace OHOS - #endif // __cplusplus - -#endif // HIVIEWDFX_HILOG_CPP_H \ No newline at end of file +#endif // HIVIEWDFX_HILOG_CPP_H diff --git a/services/hilogd/cmd_executor.cpp b/services/hilogd/cmd_executor.cpp index 58b1ebe..10fe3e7 100644 --- a/services/hilogd/cmd_executor.cpp +++ b/services/hilogd/cmd_executor.cpp @@ -85,8 +85,10 @@ void CmdExecutor::MainLoop() if (acceptResult > 0) { int acceptedSockedFd = acceptResult; std::unique_ptr handler = std::make_unique(SOCK_SEQPACKET); - handler->setHandler(acceptedSockedFd); - OnAcceptedConnection(std::move(handler)); + if (handler != nullptr) { + handler->setHandler(acceptedSockedFd); + OnAcceptedConnection(std::move(handler)); + } } else { std::cerr << "Socket accept failed: "; HilogPrintError(errno); @@ -99,9 +101,11 @@ void CmdExecutor::OnAcceptedConnection(std::unique_ptr handler) { std::lock_guard lg(m_clientAccess); auto newVal = std::make_unique(); - newVal->m_stopThread.store(false); - newVal->m_clientThread = std::thread(&CmdExecutor::ClientEventLoop, this, std::move(handler)); - m_clients.push_back(std::move(newVal)); + if (newVal != nullptr) { + newVal->m_stopThread.store(false); + newVal->m_clientThread = std::thread(&CmdExecutor::ClientEventLoop, this, std::move(handler)); + m_clients.push_back(std::move(newVal)); + } } void CmdExecutor::ClientEventLoop(std::unique_ptr handler) diff --git a/services/hilogd/etc/hilog.para b/services/hilogd/etc/hilog.para old mode 100755 new mode 100644 diff --git a/services/hilogd/etc/hilog.para.dac b/services/hilogd/etc/hilog.para.dac old mode 100755 new mode 100644 diff --git a/services/hilogd/etc/hilog_domains.conf b/services/hilogd/etc/hilog_domains.conf old mode 100755 new mode 100644 diff --git a/services/hilogd/flow_control_init.cpp b/services/hilogd/flow_control_init.cpp index 3d0540c..6eecc9c 100644 --- a/services/hilogd/flow_control_init.cpp +++ b/services/hilogd/flow_control_init.cpp @@ -30,6 +30,8 @@ namespace OHOS { namespace HiviewDFX { static const int DOMAIN_FILTER = 0x00fffff; static const int DOMAIN_FILTER_SUBSYSTEM = 8; +constexpr int FLOW_CTL_NORAML = 0; +constexpr int FLOW_CTL_FAILED = -1; using DomainInfo = struct { std::string domain; @@ -160,15 +162,18 @@ int32_t InitDomainFlowCtrl() int FlowCtrlDomain(HilogMsg* hilogMsg) { + if (hilogMsg == nullptr) { + return FLOW_CTL_FAILED; + } if (hilogMsg->type == LOG_APP || !IsDomainSwitchOn() || IsDebugOn()) { - return 0; + return FLOW_CTL_NORAML; } LogTimeStamp tsNow(0, 0); std::unordered_map::iterator it; uint32_t domain = hilogMsg->domain; uint32_t domainId = (domain & DOMAIN_FILTER) >> DOMAIN_FILTER_SUBSYSTEM; auto logLen = hilogMsg->len - sizeof(HilogMsg) - 1 - 1; /* quota length exclude '\0' of tag and log content */ - int ret = 0; + int ret = FLOW_CTL_NORAML; it = g_domainMap.find(domainId); if (it != g_domainMap.end()) { LogTimeStamp tsNow(CLOCK_MONOTONIC); @@ -176,11 +181,11 @@ int FlowCtrlDomain(HilogMsg* hilogMsg) if ((tsNow -= it->second->startTime) < LogTimeStamp(1)) { if (it->second->sumLen <= it->second->domainQuota) { /* under quota */ it->second->sumLen += logLen; - ret = 0; + ret = FLOW_CTL_NORAML; } else { /* over quota */ IncreaseDropped(domainId, hilogMsg->type); it->second->dropped++; - ret = -1; + ret = FLOW_CTL_FAILED; } } else { /* new statistic period */ it->second->startTime = tsNow; @@ -192,5 +197,5 @@ int FlowCtrlDomain(HilogMsg* hilogMsg) return ret; } -} -} +} // namespace HiviewDFX +} // namespace OHOS diff --git a/services/hilogd/include/cmd_executor.h b/services/hilogd/include/cmd_executor.h index 1ae86b7..05c8de4 100644 --- a/services/hilogd/include/cmd_executor.h +++ b/services/hilogd/include/cmd_executor.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef CMD_EXECUTOR_H #define CMD_EXECUTOR_H @@ -32,7 +33,7 @@ struct ClientThread { class CmdExecutor { public: - CmdExecutor(HilogBuffer& buffer) : m_hilogBuffer(buffer) {} + explicit CmdExecutor(HilogBuffer& buffer) : m_hilogBuffer(buffer) {} ~CmdExecutor(); void MainLoop(); private: diff --git a/services/hilogd/include/flow_control_init.h b/services/hilogd/include/flow_control_init.h index 4278202..fbfbf13 100644 --- a/services/hilogd/include/flow_control_init.h +++ b/services/hilogd/include/flow_control_init.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef FLOW_CONTROL_CONFIG_H #define FLOW_CONTROL_CONFIG_H diff --git a/services/hilogd/include/kmsg_parser.h b/services/hilogd/include/kmsg_parser.h index 4aa1d3f..11a90f4 100644 --- a/services/hilogd/include/kmsg_parser.h +++ b/services/hilogd/include/kmsg_parser.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef KMSG_PARSER_H #define KMSG_PARSER_H @@ -29,4 +30,3 @@ public: } // namespace HiviewDFX } // namespace OHOS #endif - diff --git a/services/hilogd/include/log_buffer.h b/services/hilogd/include/log_buffer.h index 46919c1..e0058b7 100644 --- a/services/hilogd/include/log_buffer.h +++ b/services/hilogd/include/log_buffer.h @@ -52,6 +52,7 @@ public: int32_t ClearStatisticInfoByDomain(uint32_t domain); static bool LogMatchFilter(const LogFilterExt& filter, const HilogData& logData); + private: struct BufferReader { LogMsgContainer::iterator m_pos; diff --git a/services/hilogd/include/log_collector.h b/services/hilogd/include/log_collector.h index aa55b2f..0679dbe 100644 --- a/services/hilogd/include/log_collector.h +++ b/services/hilogd/include/log_collector.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef LOG_COLLECTOR_H #define LOG_COLLECTOR_H #include @@ -23,7 +24,7 @@ namespace OHOS { namespace HiviewDFX { class LogCollector { public: - LogCollector(HilogBuffer& buffer) : m_hilogBuffer(buffer) {} + explicit LogCollector(HilogBuffer& buffer) : m_hilogBuffer(buffer) {} void InsertDropInfo(const HilogMsg &msg, int droppedCount); size_t InsertLogToBuffer(const HilogMsg& msg); #ifndef __RECV_MSG_WITH_UCRED_ diff --git a/services/hilogd/include/log_compress.h b/services/hilogd/include/log_compress.h index 95f87ed..1799ce7 100644 --- a/services/hilogd/include/log_compress.h +++ b/services/hilogd/include/log_compress.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef HILOG_COMPRESS_H #define HILOG_COMPRESS_H @@ -26,11 +27,10 @@ namespace OHOS { namespace HiviewDFX { -typedef struct { +using LogPersisterBuffer = struct { char content[MAX_PERSISTER_BUFFER_SIZE]; uint32_t offset; -} LogPersisterBuffer; - +}; class LogCompress { public: @@ -51,7 +51,7 @@ private: static const uint16_t CHUNK = 16384; char buffIn[CHUNK] = {0}; char buffOut[CHUNK] = {0}; - + z_stream cStream; }; @@ -66,6 +66,6 @@ private: ZSTD_CCtx* cctx; #endif }; -} -} +} // namespace HiviewDFX +} // namespace OHOS #endif /* HILOG_COMPRESS_H */ diff --git a/services/hilogd/include/log_data.h b/services/hilogd/include/log_data.h index 2d1c649..ccac055 100644 --- a/services/hilogd/include/log_data.h +++ b/services/hilogd/include/log_data.h @@ -64,8 +64,8 @@ struct HilogData { tag = nullptr; content = nullptr; } - HilogData() : len(0), tag(nullptr), content(nullptr) {}; - HilogData(const HilogMsg& msg) + HilogData() : len(0), tag(nullptr), content(nullptr) {} + explicit HilogData(const HilogMsg& msg) : len(0), version(msg.version), type(msg.type), level(msg.level), tag_len(msg.tag_len), tv_sec(msg.tv_sec), tv_nsec(msg.tv_nsec), pid(msg.pid), tid(msg.tid), domain(msg.domain), tag(nullptr), content(nullptr) diff --git a/services/hilogd/include/log_kmsg.h b/services/hilogd/include/log_kmsg.h index ce4fc09..ae699b8 100644 --- a/services/hilogd/include/log_kmsg.h +++ b/services/hilogd/include/log_kmsg.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef LOG_KMSG_H #define LOG_KMSG_H @@ -22,7 +23,7 @@ namespace OHOS { namespace HiviewDFX { class LogKmsg { public: - LogKmsg(HilogBuffer& hilogBuffer) : hilogBuffer(hilogBuffer) {}; + explicit LogKmsg(HilogBuffer& hilogBuffer) : hilogBuffer(hilogBuffer) {} ~LogKmsg(); ssize_t LinuxReadOneKmsg(KmsgParser& parser); int LinuxReadAllKmsg(); @@ -35,4 +36,3 @@ private: } // namespace HiviewDFX } // namespace OHOS #endif - diff --git a/services/hilogd/include/log_persister.h b/services/hilogd/include/log_persister.h index 1f1eab1..5416d7b 100644 --- a/services/hilogd/include/log_persister.h +++ b/services/hilogd/include/log_persister.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef _HILOG_PERSISTER_H #define _HILOG_PERSISTER_H @@ -48,11 +49,12 @@ public: int Init(const InitData& initData); int Deinit(); - + void Start(); void Stop(); - + void FillInfo(LogPersistQueryResult &response); + private: struct BaseData { uint32_t id; @@ -63,7 +65,7 @@ private: std::chrono::seconds newLogTimeout; }; - LogPersister(HilogBuffer &buffer); + explicit LogPersister(HilogBuffer &buffer); static bool CheckRegistered(uint32_t id, const std::string& logPath); static std::shared_ptr GetLogPersisterById(uint32_t id); diff --git a/services/hilogd/include/log_persister_rotator.h b/services/hilogd/include/log_persister_rotator.h index b2654b9..022bd4f 100644 --- a/services/hilogd/include/log_persister_rotator.h +++ b/services/hilogd/include/log_persister_rotator.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef _HILOG_PERSISTER_ROTATOR_H #define _HILOG_PERSISTER_ROTATOR_H #include @@ -23,12 +24,12 @@ #include "log_filter.h" namespace OHOS { namespace HiviewDFX { -typedef struct { +using PersistRecoveryInfo = struct { uint32_t index; uint16_t types; uint8_t levels; LogPersistStartMsg msg; -} PersistRecoveryInfo; +}; static constexpr const char* AUXILLARY_PERSISTER_PREFIX = "persisterInfo_"; @@ -43,6 +44,7 @@ public: void FinishInput(); void SetFileIndex(uint32_t index, bool forceRotate); + private: void RemoveOldFile(); bool IsOldFile(const std::string& logName, const int index); @@ -59,7 +61,7 @@ private: std::string m_fileNameSuffix; uint32_t m_currentLogFileIdx = 0; std::fstream m_currentLogOutput; - + uint32_t m_id = 0; std::fstream m_infoFile; std::string m_infoFilePath; diff --git a/services/hilogd/include/service_controller.h b/services/hilogd/include/service_controller.h index 158e122..64beca5 100644 --- a/services/hilogd/include/service_controller.h +++ b/services/hilogd/include/service_controller.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef LOG_QUERIER_H #define LOG_QUERIER_H @@ -38,6 +39,7 @@ public: ~ServiceController(); void CommunicationLoop(const std::atomic& stopLoop); + private: void SetFilters(const PacketBuf& rawData); diff --git a/services/hilogd/kmsg_parser.cpp b/services/hilogd/kmsg_parser.cpp index bcad6e4..72baa05 100644 --- a/services/hilogd/kmsg_parser.cpp +++ b/services/hilogd/kmsg_parser.cpp @@ -44,6 +44,16 @@ constexpr int DEC = 10; #undef LOG_INFO #undef LOG_DEBUG +using Priority = enum { + PV0, + PV1, + PV2, + PV3, + PV4, + PV5, + PV6 +}; + static void ParseHeader(std::string& str, uint16_t* level, uint64_t* timestamp) { static const std::string pattern = "(\\d+),(\\d+),(\\d+),(\\S);"; @@ -88,19 +98,19 @@ static uint16_t KmsgLevelMap(uint16_t prio) { uint16_t level; switch (prio) { - case 0: - case 1: - case 2: + case Priority::PV0: + case Priority::PV1: + case Priority::PV2: level = LOG_FATAL; break; - case 3: + case Priority::PV3: level = LOG_ERROR; break; - case 4: - case 5: + case Priority::PV4: + case Priority::PV5: level = LOG_WARN; break; - case 6: + case Priority::PV6: level = LOG_INFO; break; default: @@ -178,4 +188,3 @@ std::optional KmsgParser::ParseKmsg(const std::vector& km } } // namespace HiviewDFX } // namespace OHOS - diff --git a/services/hilogd/log_buffer.cpp b/services/hilogd/log_buffer.cpp index 4b38c1f..0ec0154 100644 --- a/services/hilogd/log_buffer.cpp +++ b/services/hilogd/log_buffer.cpp @@ -175,7 +175,9 @@ HilogBuffer::ReaderId HilogBuffer::CreateBufReader(std::function onNewDa { std::unique_lock lock(m_logReaderMtx); auto reader = std::make_shared(); - reader->m_onNewDataCallback = onNewDataCallback; + if (reader != nullptr) { + reader->m_onNewDataCallback = onNewDataCallback; + } ReaderId id = reinterpret_cast(reader.get()); m_logReaders.insert(std::make_pair(id, reader)); return id; diff --git a/services/hilogd/log_collector.cpp b/services/hilogd/log_collector.cpp index 8cca61c..0d46870 100644 --- a/services/hilogd/log_collector.cpp +++ b/services/hilogd/log_collector.cpp @@ -51,7 +51,7 @@ void LogCollector::InsertDropInfo(const HilogMsg &msg, int droppedCount) if (memcpy_s(dropMsg->tag, remainSize, tag.data(), tag.size())) { std::cerr << "Can't copy tag info of Drop Info message\n"; } - + remainSize -= tag.size(); auto logTextPtr = dropMsg->tag + tag.size(); // log text is behind tag data if (memcpy_s(logTextPtr, remainSize, dropLog.data(), dropLog.size() + 1)) { diff --git a/services/hilogd/log_compress.cpp b/services/hilogd/log_compress.cpp index d64d4f5..f43dfa5 100644 --- a/services/hilogd/log_compress.cpp +++ b/services/hilogd/log_compress.cpp @@ -57,27 +57,31 @@ int ZlibCompress::Compress(const LogPersisterBuffer &inBuffer, LogPersisterBuffe do { bool flag = read - src_pos < toRead; if (flag) { - memset_s(buffIn, CHUNK, 0, CHUNK); + if (memset_s(buffIn, CHUNK, 0, CHUNK) != 0) { + return -1; + } if (memmove_s(buffIn, CHUNK, inBuffer.content + src_pos, read - src_pos) != 0) { return -1; } cStream.avail_in = read - src_pos; src_pos += read - src_pos; } else { - memset_s(buffIn, CHUNK, 0, CHUNK); + if (memset_s(buffIn, CHUNK, 0, CHUNK) != 0) { + return -1; + } if (memmove_s(buffIn, CHUNK, inBuffer.content + src_pos, toRead) != 0) { return -1; - }; + } src_pos += toRead; cStream.avail_in = toRead; } flush = flag ? Z_FINISH : Z_NO_FLUSH; - cStream.next_in = (Bytef *)buffIn; + cStream.next_in = reinterpret_cast(buffIn); /* run deflate() on input until output buffer not full, finish compression if all of source has been read in */ do { cStream.avail_out = CHUNK; - cStream.next_out = (Bytef *)buffOut; + cStream.next_out = reinterpret_cast(buffOut); if (deflate(&cStream, flush) == Z_STREAM_ERROR) { return -1; } @@ -124,14 +128,18 @@ int ZstdCompress::Compress(const LogPersisterBuffer &inBuffer, LogPersisterBuffe do { bool flag = read - src_pos < toRead; if (flag) { - memset_s(buffIn, CHUNK, 0, CHUNK); + if (memset_s(buffIn, CHUNK, 0, CHUNK) != 0) { + return -1; + } if (memmove_s(buffIn, CHUNK, inBuffer.content + src_pos, read - src_pos) != 0) { return -1; } input = {buffIn, read - src_pos, 0}; src_pos += read - src_pos; } else { - memset_s(buffIn, CHUNK, 0, CHUNK); + if (memset_s(buffIn, CHUNK, 0, CHUNK) != 0) { + return -1; + } if (memmove_s(buffIn, CHUNK, inBuffer.content + src_pos, toRead) != 0) { return -1; } @@ -143,7 +151,7 @@ int ZstdCompress::Compress(const LogPersisterBuffer &inBuffer, LogPersisterBuffe do { ZSTD_outBuffer output = {buffOut, CHUNK, 0}; size_t const remaining = ZSTD_compressStream2(cctx, &output, &input, mode); - if (memmove_s(zdata + dst_pos, zdlen, (Bytef *)buffOut, output.pos) != 0) { + if (memmove_s(zdata + dst_pos, zdlen, reinterpret_cast(buffOut), output.pos) != 0) { return -1; } dst_pos += output.pos; diff --git a/services/hilogd/log_kmsg.cpp b/services/hilogd/log_kmsg.cpp index a96c4f9..5d68a60 100644 --- a/services/hilogd/log_kmsg.cpp +++ b/services/hilogd/log_kmsg.cpp @@ -62,6 +62,9 @@ int LogKmsg::LinuxReadAllKmsg() return -1; } std::unique_ptr parser = std::make_unique(); + if (parser == nullptr) { + return -1; + } while (true) { ssize_t sz = LinuxReadOneKmsg(*parser); if (sz < 0) { @@ -100,4 +103,3 @@ LogKmsg::~LogKmsg() } } // namespace HiviewDFX } // namespace OHOS - diff --git a/services/hilogd/log_persister.cpp b/services/hilogd/log_persister.cpp index 8bd8610..856bd6b 100644 --- a/services/hilogd/log_persister.cpp +++ b/services/hilogd/log_persister.cpp @@ -44,7 +44,8 @@ namespace OHOS { namespace HiviewDFX { -static constexpr int DEFAULT_LOG_LEVEL = 1<(m_baseData.logPath, m_baseData.id, m_baseData.maxLogFileNum, fileSuffix); if (!m_fileRotator) { @@ -242,8 +243,8 @@ int LogPersister::PrepareUncompressedFile(const std::string& parentPath, bool re fflush(plainTextFile); fsync(fileno(plainTextFile)); } - m_mappedPlainLogFile = (LogPersisterBuffer *)mmap(nullptr, sizeof(LogPersisterBuffer), PROT_READ | PROT_WRITE, - MAP_SHARED, fileno(plainTextFile), 0); + m_mappedPlainLogFile = reinterpret_cast(mmap(nullptr, sizeof(LogPersisterBuffer), + PROT_READ | PROT_WRITE, MAP_SHARED, fileno(plainTextFile), 0)); if (fclose(plainTextFile)) { std::cerr << "File: " << plainTextFile << " can't be closed. "; HilogPrintError(errno); @@ -253,7 +254,7 @@ int LogPersister::PrepareUncompressedFile(const std::string& parentPath, bool re HilogPrintError(errno); return RET_FAIL; } - if (restore == true) { + if (restore) { #ifdef DEBUG std::cout << __PRETTY_FUNCTION__ << " Recovered persister, Offset=" << m_mappedPlainLogFile->offset << "\n"; #endif @@ -262,7 +263,7 @@ int LogPersister::PrepareUncompressedFile(const std::string& parentPath, bool re if (compressionResult != 0) { std::cerr << __PRETTY_FUNCTION__ << " Compression error. Result:" << compressionResult << "\n"; return RET_FAIL; - }; + } WriteCompressedLogs(); } else { m_mappedPlainLogFile->offset = 0; @@ -365,7 +366,7 @@ int LogPersister::WriteLogData(const HilogData& logData) if (compressionResult != 0) { std::cerr << __PRETTY_FUNCTION__ << " Compression error. Result:" << compressionResult << "\n"; return RET_FAIL; - }; + } // Write compressed buffor and clear counters WriteCompressedLogs(); // Try again write data that wasn't written at the beginning diff --git a/services/hilogd/log_persister_rotator.cpp b/services/hilogd/log_persister_rotator.cpp index 3f8e0cc..0e43bb4 100644 --- a/services/hilogd/log_persister_rotator.cpp +++ b/services/hilogd/log_persister_rotator.cpp @@ -31,7 +31,7 @@ namespace HiviewDFX { uint64_t GenerateHash(const PersistRecoveryInfo &info) { uint64_t ret {BASIS}; - const char *p = (char *)&info; + const char *p = reinterpret_cast(const_cast(&info)); unsigned long i = 0; while (i < sizeof(PersistRecoveryInfo)) { ret ^= *(p + i); @@ -62,10 +62,7 @@ bool LogPersisterRotator::IsOldFile(const std::string& logName, const int index) LogPersisterRotator::LogPersisterRotator(const std::string& logsPath, uint32_t id, uint32_t maxFiles, const std::string& fileNameSuffix) - : m_maxLogFileNum(maxFiles) - , m_logsPath(logsPath) - , m_fileNameSuffix(fileNameSuffix) - , m_id(id) + : m_maxLogFileNum(maxFiles), m_logsPath(logsPath), m_fileNameSuffix(fileNameSuffix), m_id(id) { } @@ -109,7 +106,7 @@ int LogPersisterRotator::Input(const char *buf, uint32_t length) std::cout << __PRETTY_FUNCTION__ << " Log location: " << m_logsPath << " idx: " << m_currentLogFileIdx << "/" << m_maxLogFileNum - << " buf: " << (void*) buf << " len: " << length + << " buf: " << reinterpret_cast(const_cast(buf)) << " len: " << length << " needRotate: " << (m_needRotate ? 'T' : 'F') << "\n"; if (length <= 0 || buf == nullptr) { return ERR_LOG_PERSIST_COMPRESS_BUFFER_EXP; @@ -127,10 +124,10 @@ int LogPersisterRotator::Input(const char *buf, uint32_t length) void LogPersisterRotator::RemoveOldFile() { - DIR *dir; + DIR *dir = nullptr; struct dirent *ent = nullptr; - if ((dir = opendir(HILOG_FILE_DIR)) != NULL) { - while ((ent = readdir(dir)) != NULL) { + if ((dir = opendir(HILOG_FILE_DIR)) != nullptr) { + while ((ent = readdir(dir)) != nullptr) { size_t length = strlen(ent->d_name); std::string pPath(ent->d_name, length); if (IsOldFile(pPath, m_currentLogFileIdx)) { @@ -139,7 +136,9 @@ void LogPersisterRotator::RemoveOldFile() } } } - closedir(dir); + if (dir != nullptr) { + closedir(dir); + } } void LogPersisterRotator::Rotate() diff --git a/services/hilogd/main.cpp b/services/hilogd/main.cpp index 3dc165f..1418918 100644 --- a/services/hilogd/main.cpp +++ b/services/hilogd/main.cpp @@ -196,9 +196,9 @@ int HilogdEntry() auto cgroupWriteTask = std::async(std::launch::async, [&hilogBuffer]() { prctl(PR_SET_NAME, "hilogd.cgroup_set"); string myPid = to_string(getpid()); - WriteStringToFile(myPid, SYSTEM_BG_STUNE); - WriteStringToFile(myPid, SYSTEM_BG_CPUSET); - WriteStringToFile(myPid, SYSTEM_BG_BLKIO); + (void)WriteStringToFile(myPid, SYSTEM_BG_STUNE); + (void)WriteStringToFile(myPid, SYSTEM_BG_CPUSET); + (void)WriteStringToFile(myPid, SYSTEM_BG_BLKIO); }); CmdExecutor cmdExecutor(hilogBuffer); @@ -210,6 +210,6 @@ int HilogdEntry() int main() { - OHOS::HiviewDFX::HilogdEntry(); + (void)OHOS::HiviewDFX::HilogdEntry(); return 0; } diff --git a/services/hilogd/service_controller.cpp b/services/hilogd/service_controller.cpp index c7982ab..f13be17 100644 --- a/services/hilogd/service_controller.cpp +++ b/services/hilogd/service_controller.cpp @@ -79,7 +79,9 @@ inline bool IsLogTypeForbidden(uint16_t queryTypes) int StartPersistStoreJob(const LogPersister::InitData& initData, HilogBuffer& hilogBuffer) { std::shared_ptr persister = LogPersister::CreateLogPersister(hilogBuffer); - + if (persister == nullptr) { + return RET_FAIL; + } int persistRes = persister->Init(initData); if (persistRes != RET_SUCCESS) { if (persistRes == ERR_LOG_PERSIST_TASK_FAIL) { @@ -589,7 +591,7 @@ int ServiceController::WriteV(const iovec* vec, size_t len) uint32_t offset = 0; for (uint32_t i = 0; i < len; ++i) { - auto src_address = (char*)vec[i].iov_base; + auto src_address = reinterpret_cast(vec[i].iov_base); std::copy(src_address, src_address + vec[i].iov_len, dataBuf.data() + offset); offset += vec[i].iov_len; } diff --git a/services/hilogtool/include/hilogtool.h b/services/hilogtool/include/hilogtool.h index ef74cc9..5f943bd 100644 --- a/services/hilogtool/include/hilogtool.h +++ b/services/hilogtool/include/hilogtool.h @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef HILOGTOOL_H #define HILOGTOOL_H @@ -20,7 +21,7 @@ namespace HiviewDFX { #define DOMAIN_NUMBER_BASE (16) #define DOMAIN_MAX_SCOPE 0xDFFFFFF -typedef struct { +using HilogArgs = struct { uint16_t noBlockMode; uint8_t nPid; uint8_t nNoPid; @@ -62,7 +63,7 @@ typedef struct { std::string flowQuotaArgs; std::string pidArgs; std::string algorithmArgs; -} HilogArgs; +}; } // namespace HiviewDFX } // namespace OHOS #endif diff --git a/services/hilogtool/include/log_display.h b/services/hilogtool/include/log_display.h index b92025b..742e5ae 100644 --- a/services/hilogtool/include/log_display.h +++ b/services/hilogtool/include/log_display.h @@ -27,7 +27,7 @@ int32_t ControlCmdResult(const char* message); std::string ParseErrorCode(ErrorCode errorCode); void HilogShowLog(uint32_t showFormat, HilogDataMessage* contentOut, const HilogArgs* context, vector& tailBuffer); -HilogShowFormat HilogFormat (const char* formatArg); +HilogShowFormat HilogFormat(const char* formatArg); } // namespace HiviewDFX } // namespace OHOS #endif diff --git a/services/hilogtool/log_controller.cpp b/services/hilogtool/log_controller.cpp index 9addb78..52a6f2e 100644 --- a/services/hilogtool/log_controller.cpp +++ b/services/hilogtool/log_controller.cpp @@ -33,7 +33,8 @@ namespace OHOS { namespace HiviewDFX { using namespace std; - +constexpr int BIT_INIT_VAL = 0b01; +constexpr uint16_t INVALD_LOG_TYPE = 0xffff; const int LOG_PERSIST_FILE_SIZE = 4 * ONE_MB; const int LOG_PERSIST_FILE_NUM = 10; const uint32_t DEFAULT_JOBID = 1; @@ -85,7 +86,7 @@ uint16_t GetLogType(const string& logTypeStr) } else if (logTypeStr == "kmsg") { logType = LOG_KMSG; } else { - return 0xffff; + return INVALD_LOG_TYPE; } return logType; } @@ -145,7 +146,7 @@ uint16_t GetLogLevel(const std::string& logLevelStr, std::string& logLevel) logLevel = "F"; return LOG_FATAL; } - return 0xffff; + return INVALD_LOG_TYPE; } string SetDefaultLogType(const std::string& logTypeStr) @@ -165,12 +166,15 @@ void NextRequestOp(SeqPacketSocketClient& controller, uint16_t sendId) NextRequest nextRequest = {{0}}; SetMsgHead(&nextRequest.header, NEXT_REQUEST, sizeof(NextRequest)-sizeof(MessageHeader)); nextRequest.sendId = sendId; - controller.WriteAll((char*)&nextRequest, sizeof(NextRequest)); + controller.WriteAll(reinterpret_cast(&nextRequest), sizeof(NextRequest)); } void LogQueryRequestOp(SeqPacketSocketClient& controller, const HilogArgs* context) { LogQueryRequest logQueryRequest = {{0}}; + if (context == nullptr) { + return; + } logQueryRequest.levels = context->levels; logQueryRequest.types = context->types; logQueryRequest.nPid = context->nPid; @@ -207,7 +211,7 @@ void LogQueryRequestOp(SeqPacketSocketClient& controller, const HilogArgs* conte } SetMsgHead(&logQueryRequest.header, LOG_QUERY_REQUEST, sizeof(LogQueryRequest)-sizeof(MessageHeader)); logQueryRequest.header.version = 0; - controller.WriteAll((char*)&logQueryRequest, sizeof(LogQueryRequest)); + controller.WriteAll(reinterpret_cast(&logQueryRequest), sizeof(LogQueryRequest)); } void LogQueryResponseOp(SeqPacketSocketClient& controller, char* recvBuffer, uint32_t bufLen, @@ -215,7 +219,13 @@ void LogQueryResponseOp(SeqPacketSocketClient& controller, char* recvBuffer, uin { static std::vector tailBuffer; LogQueryResponse* rsp = reinterpret_cast(recvBuffer); + if (rsp == nullptr || context == nullptr) { + return; + } HilogDataMessage* data = &(rsp->data); + if (data == nullptr) { + return; + } if (data->sendId != SENDIDN) { HilogShowLog(format, data, context, tailBuffer); } @@ -229,6 +239,9 @@ void LogQueryResponseOp(SeqPacketSocketClient& controller, char* recvBuffer, uin return; } MessageHeader* msgHeader = &(rsp->header); + if (msgHeader == nullptr) { + return; + } if (msgHeader->msgType == NEXT_RESPONSE) { switch (data->sendId) { case SENDIDN: @@ -253,8 +266,9 @@ void LogQueryResponseOp(SeqPacketSocketClient& controller, char* recvBuffer, uin } } } -int32_t BufferSizeOp(SeqPacketSocketClient& controller, uint8_t msgCmd, const std::string& logTypeStr, - const std::string& buffSizeStr) + +int32_t BufferSizeOp(SeqPacketSocketClient& controller, uint8_t msgCmd, + const std::string& logTypeStr, const std::string& buffSizeStr) { char msgToSend[MSG_MAX_LEN] = {0}; vector vecLogType; @@ -266,13 +280,19 @@ int32_t BufferSizeOp(SeqPacketSocketClient& controller, uint8_t msgCmd, const st switch (msgCmd) { case MC_REQ_BUFFER_SIZE: { BufferSizeRequest* pBuffSizeReq = reinterpret_cast(msgToSend); + if (pBuffSizeReq == nullptr) { + return RET_FAIL; + } BuffSizeMsg* pBuffSizeMsg = reinterpret_cast(&pBuffSizeReq->buffSizeMsg); + if (pBuffSizeMsg == nullptr) { + return RET_FAIL; + } if (logTypeNum * sizeof(BuffSizeMsg) + sizeof(MessageHeader) > MSG_MAX_LEN) { return RET_FAIL; } for (iter = 0; iter < logTypeNum; iter++) { pBuffSizeMsg->logType = GetLogType(vecLogType[iter]); - if (pBuffSizeMsg->logType == 0xffff) { + if (pBuffSizeMsg->logType == INVALD_LOG_TYPE) { cout << ParseErrorCode(ERR_LOG_TYPE_INVALID) << endl; return RET_FAIL; } @@ -285,13 +305,19 @@ int32_t BufferSizeOp(SeqPacketSocketClient& controller, uint8_t msgCmd, const st case MC_REQ_BUFFER_RESIZE: { BufferResizeRequest* pBuffResizeReq = reinterpret_cast(msgToSend); + if (pBuffResizeReq == nullptr) { + return RET_FAIL; + } BuffResizeMsg* pBuffResizeMsg = reinterpret_cast(&pBuffResizeReq->buffResizeMsg); + if (pBuffResizeMsg == nullptr) { + return RET_FAIL; + } if (logTypeNum * sizeof(BuffResizeMsg) + sizeof(MessageHeader) > MSG_MAX_LEN) { return RET_FAIL; } for (iter = 0; iter < logTypeNum; iter++) { pBuffResizeMsg->logType = GetLogType(vecLogType[iter]); - if (pBuffResizeMsg->logType == 0xffff) { + if (pBuffResizeMsg->logType == INVALD_LOG_TYPE) { cout << ParseErrorCode(ERR_LOG_TYPE_INVALID) << endl; return RET_FAIL; } @@ -319,7 +345,7 @@ int32_t StatisticInfoOp(SeqPacketSocketClient& controller, uint8_t msgCmd, uint32_t domain; if (domainStr == "") { domain = 0xffffffff; - if (logType == 0xffff) { + if (logType == INVALD_LOG_TYPE) { cout << ParseErrorCode(ERR_LOG_TYPE_INVALID) << endl; return RET_FAIL; } @@ -336,7 +362,7 @@ int32_t StatisticInfoOp(SeqPacketSocketClient& controller, uint8_t msgCmd, staInfoQueryReq.logType = logType; staInfoQueryReq.domain = domain; SetMsgHead(&staInfoQueryReq.msgHeader, msgCmd, sizeof(StatisticInfoQueryRequest) - sizeof(MessageHeader)); - controller.WriteAll((char*)&staInfoQueryReq, sizeof(StatisticInfoQueryRequest)); + controller.WriteAll(reinterpret_cast(&staInfoQueryReq), sizeof(StatisticInfoQueryRequest)); break; } case MC_REQ_STATISTIC_INFO_CLEAR: { @@ -344,7 +370,7 @@ int32_t StatisticInfoOp(SeqPacketSocketClient& controller, uint8_t msgCmd, staInfoClearReq.logType = logType; staInfoClearReq.domain = domain; SetMsgHead(&staInfoClearReq.msgHeader, msgCmd, sizeof(StatisticInfoClearRequest) - sizeof(MessageHeader)); - controller.WriteAll((char*)&staInfoClearReq, sizeof(StatisticInfoClearRequest)); + controller.WriteAll(reinterpret_cast(&staInfoClearReq), sizeof(StatisticInfoClearRequest)); break; } default: @@ -363,6 +389,9 @@ int32_t LogClearOp(SeqPacketSocketClient& controller, uint8_t msgCmd, const std: Split(logType, " ", vecLogType); logTypeNum = vecLogType.size(); LogClearRequest* pLogClearReq = reinterpret_cast(msgToSend); + if (pLogClearReq == nullptr) { + return RET_FAIL; + } LogClearMsg* pLogClearMsg = reinterpret_cast(&pLogClearReq->logClearMsg); if (!pLogClearMsg) { cout << ParseErrorCode(ERR_MEM_ALLOC_FAIL) << endl; @@ -374,7 +403,7 @@ int32_t LogClearOp(SeqPacketSocketClient& controller, uint8_t msgCmd, const std: } for (iter = 0; iter < logTypeNum; iter++) { pLogClearMsg->logType = GetLogType(vecLogType[iter]); - if (pLogClearMsg->logType == 0xffff) { + if (pLogClearMsg->logType == INVALD_LOG_TYPE) { cout << ParseErrorCode(ERR_LOG_TYPE_INVALID) << endl; return RET_FAIL; } @@ -396,6 +425,9 @@ int32_t LogPersistOp(SeqPacketSocketClient& controller, uint8_t msgCmd, LogPersi int ret = 0; uint32_t fileSizeDefault = LOG_PERSIST_FILE_SIZE; uint32_t fileNumDefault = LOG_PERSIST_FILE_NUM; + if (logPersistParam == nullptr) { + return RET_FAIL; + } string logType = SetDefaultLogType(logPersistParam->logTypeStr); Split(logType, " ", vecLogType); Split(logPersistParam->jobIdStr, " ", vecJobId); @@ -412,13 +444,13 @@ int32_t LogPersistOp(SeqPacketSocketClient& controller, uint8_t msgCmd, LogPersi } for (iter = 0; iter < logTypeNum; iter++) { uint16_t tmpType = GetLogType(vecLogType[iter]); - if (tmpType == 0xffff) { + if (tmpType == INVALD_LOG_TYPE) { cout << ParseErrorCode(ERR_LOG_TYPE_INVALID) << endl; return RET_FAIL; } - pLogPersistStartMsg->logType = (0b01 << tmpType) | pLogPersistStartMsg->logType; + pLogPersistStartMsg->logType = (BIT_INIT_VAL << tmpType) | pLogPersistStartMsg->logType; } - if (pLogPersistStartMsg->logType == (0b01 << LOG_KMSG)) { + if (pLogPersistStartMsg->logType == (BIT_INIT_VAL << LOG_KMSG)) { pLogPersistStartMsg->jobId = (logPersistParam->jobIdStr == "") ? DEFAULT_KMSG_JOBID : static_cast(stoi(logPersistParam->jobIdStr)); } else { @@ -450,8 +482,14 @@ int32_t LogPersistOp(SeqPacketSocketClient& controller, uint8_t msgCmd, LogPersi case MC_REQ_LOG_PERSIST_STOP: { LogPersistStopRequest* pLogPersistStopReq = reinterpret_cast(msgToSend); + if (pLogPersistStopReq == nullptr) { + return RET_FAIL; + } LogPersistStopMsg* pLogPersistStopMsg = reinterpret_cast(&pLogPersistStopReq->logPersistStopMsg); + if (pLogPersistStopMsg == nullptr) { + return RET_FAIL; + } if (logPersistParam->jobIdStr == "") { pLogPersistStopMsg->jobId = JOB_ID_ALL; SetMsgHead(&pLogPersistStopReq->msgHeader, msgCmd, sizeof(LogPersistStopMsg)); @@ -474,16 +512,21 @@ int32_t LogPersistOp(SeqPacketSocketClient& controller, uint8_t msgCmd, LogPersi case MC_REQ_LOG_PERSIST_QUERY: { LogPersistQueryRequest* pLogPersistQueryReq = reinterpret_cast(msgToSend); + if (pLogPersistQueryReq == nullptr) { + return RET_FAIL; + } LogPersistQueryMsg* pLogPersistQueryMsg = reinterpret_cast(&pLogPersistQueryReq->logPersistQueryMsg); - + if (pLogPersistQueryMsg == nullptr) { + return RET_FAIL; + } for (iter = 0; iter < logTypeNum; iter++) { uint16_t tmpType = GetLogType(vecLogType[iter]); - if (tmpType == 0xffff) { + if (tmpType == INVALD_LOG_TYPE) { cout << ParseErrorCode(ERR_LOG_TYPE_INVALID) << endl; return RET_FAIL; } - pLogPersistQueryMsg->logType = (0b01 << tmpType) | pLogPersistQueryMsg->logType; + pLogPersistQueryMsg->logType = (BIT_INIT_VAL << tmpType) | pLogPersistQueryMsg->logType; } SetMsgHead(&pLogPersistQueryReq->msgHeader, msgCmd, sizeof(LogPersistQueryMsg)); controller.WriteAll(msgToSend, sizeof(LogPersistQueryRequest)); @@ -508,6 +551,9 @@ int32_t SetPropertiesOp(SeqPacketSocketClient& controller, uint8_t operationType uint32_t domainNum, tagNum; uint32_t iter; string key, value; + if (propertyParm == nullptr) { + return RET_FAIL; + } Split(propertyParm->domainStr, " ", vecDomain); Split(propertyParm->tagStr, " ", vecTag); domainNum = vecDomain.size(); @@ -546,7 +592,7 @@ int32_t SetPropertiesOp(SeqPacketSocketClient& controller, uint8_t operationType std::string keyPre = GetPropertyName(PROP_DOMAIN_LOG_LEVEL); for (iter = 0; iter < domainNum; iter++) { key = keyPre + vecDomain[iter]; - if (GetLogLevel(propertyParm->logLevelStr, value) == 0xffff) { + if (GetLogLevel(propertyParm->logLevelStr, value) == INVALD_LOG_TYPE) { continue; } PropertySet(key.c_str(), value.c_str()); @@ -556,7 +602,7 @@ int32_t SetPropertiesOp(SeqPacketSocketClient& controller, uint8_t operationType std::string keyPre = GetPropertyName(PROP_TAG_LOG_LEVEL); for (iter = 0; iter < tagNum; iter++) { key = keyPre + vecTag[iter]; - if (GetLogLevel(propertyParm->logLevelStr, value) == 0xffff) { + if (GetLogLevel(propertyParm->logLevelStr, value) == INVALD_LOG_TYPE) { continue; } PropertySet(key.c_str(), value.c_str()); @@ -564,7 +610,7 @@ int32_t SetPropertiesOp(SeqPacketSocketClient& controller, uint8_t operationType } } else { key = GetPropertyName(PROP_GLOBAL_LOG_LEVEL); - if (GetLogLevel(propertyParm->logLevelStr, value) == 0xffff) { + if (GetLogLevel(propertyParm->logLevelStr, value) == INVALD_LOG_TYPE) { return RET_FAIL; } PropertySet(key.c_str(), value.c_str()); diff --git a/services/hilogtool/log_display.cpp b/services/hilogtool/log_display.cpp index 4e0a76a..8c17cd1 100644 --- a/services/hilogtool/log_display.cpp +++ b/services/hilogtool/log_display.cpp @@ -82,6 +82,9 @@ string ParseErrorCode(ErrorCode errorCode) hash_t Hash(char const *str) { hash_t ret {BASIS}; + if (str == nullptr) { + return ret; + } while (*str) { ret ^= *str; ret *= PRIME; @@ -91,6 +94,9 @@ hash_t Hash(char const *str) } constexpr hash_t HashCompileTime(char const *str, hash_t lastValue = BASIS) { + if (str == nullptr) { + return lastValue; + } return *str ? HashCompileTime(str + 1, (*str ^ lastValue) * PRIME) : lastValue; } constexpr unsigned long long operator "" _hash(char const *p, size_t) @@ -178,18 +184,24 @@ string GetByteLenStr(uint64_t buffSize) */ int32_t ControlCmdResult(const char* message) { - MessageHeader* msgHeader = (MessageHeader*)message; + if (message == nullptr) { + return RET_FAIL; + } + MessageHeader* msgHeader = + reinterpret_cast(const_cast(message)); uint8_t msgCmd = msgHeader->msgType; uint16_t msgLen = msgHeader->msgLen; string outputStr = ""; uint32_t resultLen = 0; switch (msgCmd) { case MC_RSP_BUFFER_SIZE: { - BufferSizeResponse* pBuffSizeRsp = (BufferSizeResponse*)message; + BufferSizeResponse* pBuffSizeRsp = + reinterpret_cast(const_cast(message)); if (!pBuffSizeRsp) { return RET_FAIL; } - BuffSizeResult* pBuffSizeRst = (BuffSizeResult*)&pBuffSizeRsp->buffSizeRst; + BuffSizeResult* pBuffSizeRst = + reinterpret_cast(&pBuffSizeRsp->buffSizeRst); while (pBuffSizeRst && resultLen < msgLen) { if (pBuffSizeRst->result < 0) { outputStr += GetLogTypeStr(pBuffSizeRst->logType); @@ -208,11 +220,13 @@ int32_t ControlCmdResult(const char* message) break; } case MC_RSP_BUFFER_RESIZE: { - BufferResizeResponse* pBuffResizeRsp = (BufferResizeResponse*)message; + BufferResizeResponse* pBuffResizeRsp = + reinterpret_cast(const_cast(message)); if (!pBuffResizeRsp) { return RET_FAIL; } - BuffResizeResult* pBuffResizeRst = (BuffResizeResult*)&pBuffResizeRsp->buffResizeRst; + BuffResizeResult* pBuffResizeRst = + reinterpret_cast(&pBuffResizeRsp->buffResizeRst); while (pBuffResizeRst && resultLen < msgLen) { if (pBuffResizeRst->result < 0) { outputStr += GetLogTypeStr(pBuffResizeRst->logType); @@ -231,7 +245,8 @@ int32_t ControlCmdResult(const char* message) break; } case MC_RSP_STATISTIC_INFO_QUERY: { - StatisticInfoQueryResponse* staInfoQueryRsp = (StatisticInfoQueryResponse*)message; + StatisticInfoQueryResponse* staInfoQueryRsp = + reinterpret_cast(const_cast(message)); string logOrDomain; if (!staInfoQueryRsp) { return RET_FAIL; @@ -261,7 +276,8 @@ int32_t ControlCmdResult(const char* message) break; } case MC_RSP_STATISTIC_INFO_CLEAR: { - StatisticInfoClearResponse* staInfoClearRsp = (StatisticInfoClearResponse*)message; + StatisticInfoClearResponse* staInfoClearRsp = + reinterpret_cast(const_cast(message)); string logOrDomain; if (!staInfoClearRsp) { return RET_FAIL; @@ -282,11 +298,12 @@ int32_t ControlCmdResult(const char* message) break; } case MC_RSP_LOG_CLEAR: { - LogClearResponse* pLogClearRsp = (LogClearResponse*)message; + LogClearResponse* pLogClearRsp = + reinterpret_cast(const_cast(message)); if (!pLogClearRsp) { - RET_FAIL; + return RET_FAIL; } - LogClearResult* pLogClearRst = (LogClearResult*)&pLogClearRsp->logClearRst; + LogClearResult* pLogClearRst = reinterpret_cast(&pLogClearRsp->logClearRst); while (pLogClearRst && resultLen < msgLen) { if (pLogClearRst->result < 0) { outputStr += GetLogTypeStr(pLogClearRst->logType); @@ -304,12 +321,13 @@ int32_t ControlCmdResult(const char* message) break; } case MC_RSP_LOG_PERSIST_START: { - LogPersistStartResponse* pLogPersistStartRsp = (LogPersistStartResponse*)message; + LogPersistStartResponse* pLogPersistStartRsp = + reinterpret_cast(const_cast(message)); if (!pLogPersistStartRsp) { return RET_FAIL; } LogPersistStartResult* pLogPersistStartRst = - (LogPersistStartResult*)&pLogPersistStartRsp->logPersistStartRst; + reinterpret_cast(&pLogPersistStartRsp->logPersistStartRst); while (pLogPersistStartRst && resultLen < msgLen) { if (pLogPersistStartRst->result < 0) { outputStr += "Persist task [jobid:"; @@ -327,11 +345,13 @@ int32_t ControlCmdResult(const char* message) break; } case MC_RSP_LOG_PERSIST_STOP: { - LogPersistStopResponse* pLogPersistStopRsp = (LogPersistStopResponse*)message; + LogPersistStopResponse* pLogPersistStopRsp = + reinterpret_cast(const_cast(message)); if (!pLogPersistStopRsp) { return RET_FAIL; } - LogPersistStopResult* pLogPersistStopRst = (LogPersistStopResult*)&pLogPersistStopRsp->logPersistStopRst; + LogPersistStopResult* pLogPersistStopRst = + reinterpret_cast(&pLogPersistStopRsp->logPersistStopRst); while (pLogPersistStopRst && resultLen < msgLen) { if (pLogPersistStopRst->result < 0) { outputStr += "Persist task [jobid:"; @@ -349,12 +369,13 @@ int32_t ControlCmdResult(const char* message) break; } case MC_RSP_LOG_PERSIST_QUERY: { - LogPersistQueryResponse* pLogPersistQueryRsp = (LogPersistQueryResponse*)message; + LogPersistQueryResponse* pLogPersistQueryRsp = + reinterpret_cast(const_cast(message)); if (!pLogPersistQueryRsp) { return RET_FAIL; } LogPersistQueryResult* pLogPersistQueryRst = - (LogPersistQueryResult*)&pLogPersistQueryRsp->logPersistQueryRst; + reinterpret_cast(&pLogPersistQueryRsp->logPersistQueryRst); while (pLogPersistQueryRst && resultLen < msgLen) { if (pLogPersistQueryRst->result < 0) { outputStr = "Persist task [logtype:"; @@ -387,10 +408,12 @@ int32_t ControlCmdResult(const char* message) return 0; } -HilogShowFormat HilogFormat (const char* formatArg) +HilogShowFormat HilogFormat(const char* formatArg) { static HilogShowFormat format; - + if (formatArg == nullptr) { + exit(1); + } switch (Hash(formatArg)) { case "color"_hash: format = COLOR_SHOWFORMAT; @@ -433,29 +456,29 @@ bool HilogMatchByRegex(string context, string regExpArg) { smatch regExpSmatch; regex regExp(regExpArg); - if (regex_search(context, regExpSmatch, regExp)) { - return false; - } else { - return true; - } + return regex_search(context, regExpSmatch, regExp); } void HilogShowLog(uint32_t showFormat, HilogDataMessage* data, const HilogArgs* context, vector& tailBuffer) { + if (data == nullptr) { + return; + } if (data->sendId == SENDIDN) { return; } - if (data->length == 0) { std::cout << ParseErrorCode(ERR_LOG_CONTENT_NULL) << endl; return; } - static int printHeadCnt = 0; HilogShowFormatBuffer showBuffer; const char* content = data->data + data->tag_len; + if (context == nullptr) { + return; + } if (context->headLines) { if (printHeadCnt++ >= context->headLines) { exit(1); @@ -463,7 +486,7 @@ void HilogShowLog(uint32_t showFormat, HilogDataMessage* data, const HilogArgs* } if (context->regexArgs != "") { string str = content; - if (HilogMatchByRegex(str, context->regexArgs)) { + if (!HilogMatchByRegex(str, context->regexArgs)) { return; } } @@ -480,24 +503,27 @@ void HilogShowLog(uint32_t showFormat, HilogDataMessage* data, const HilogArgs* const char *dataBegin = data->data + offset; char *dataPos = data->data + offset; while (*dataPos != 0) { - if (*dataPos == '\n') { - if (dataPos != dataBegin) { - *dataPos = 0; - showBuffer.tag_len = offset; - showBuffer.data = data->data; - HilogShowBuffer(buffer, MAX_LOG_LEN + MAX_LOG_LEN, showBuffer, showFormat); - if (context->tailLines) { - tailBuffer.emplace_back(buffer); - return; - } else { - cout << buffer << endl; - } - offset += dataPos - dataBegin + 1; - } else { - offset++; - } + if (*dataPos != '\n') { + dataPos++; + continue; + } + if (dataPos == dataBegin) { + offset++; dataBegin = dataPos + 1; + dataPos++; + continue; + } + *dataPos = 0; + showBuffer.tag_len = offset; + showBuffer.data = data->data; + HilogShowBuffer(buffer, MAX_LOG_LEN + MAX_LOG_LEN, showBuffer, showFormat); + if (context->tailLines) { + tailBuffer.emplace_back(buffer); + return; } + cout << buffer << endl; + offset += dataPos - dataBegin + 1; + dataBegin = dataPos + 1; dataPos++; } if (dataPos != dataBegin) { diff --git a/services/hilogtool/main.cpp b/services/hilogtool/main.cpp index 27ef4e1..0a0e7a1 100644 --- a/services/hilogtool/main.cpp +++ b/services/hilogtool/main.cpp @@ -33,14 +33,12 @@ namespace OHOS { namespace HiviewDFX { using namespace std; -constexpr int DEFAULT_LOG_TYPE = 1<, --level=\n" " Outputs logs at a specific level.\n" " -t , --type=\n" @@ -110,9 +108,12 @@ static void Helper() " \n Types, levels, domains, tags support exclusion query.\n" " Exclusion query can be done with parameters starting with \"^\" and delimiter \",\".\n" " Example: \"-t ^core,app\" excludes logs with types core and app.\n" - " Could be used along with other parameters.\n", - MAX_DOMAINS, MAX_TAGS, MAX_PIDS - ); + " Could be used along with other parameters.\n"; + +static void Helper() +{ + (void)fprintf(stderr, "Usage: [options]\n"); + (void)fprintf(stderr, GUIDANCE_DESCRIPTION, MAX_DOMAINS, MAX_TAGS, MAX_PIDS); } static uint16_t GetTypes(HilogArgs context, const string& typesArgs, bool exclude = false) @@ -182,7 +183,7 @@ int HilogEntry(int argc, char* argv[]) for (int argsCount = 0; argsCount < argc; argsCount++) { args.push_back(argv[argsCount]); } - if (argc == 2 && !args[1].compare("--help")) { + if (argc == PARAMS_COUNT_TWO && !args[1].compare("--help")) { Helper(); exit(0); } @@ -230,10 +231,10 @@ int HilogEntry(int argc, char* argv[]) context.regexArgs = optarg; break; case 'a': - context.headLines = static_cast(atoi(optarg)); + context.headLines = static_cast(strtol(optarg, nullptr, DECIMAL)); break; case 'z': - context.tailLines = static_cast(atoi(optarg)); + context.tailLines = static_cast(strtol(optarg, nullptr, DECIMAL)); context.noBlockMode = 1; break; case 't': @@ -246,22 +247,19 @@ int HilogEntry(int argc, char* argv[]) while (indexType < argc) { string types(argv[indexType]); indexType++; - if (!strstr(types.c_str(), "-")) { - if (types.front() == '^') { - vector v(sregex_token_iterator(types.begin() + 1, types.end(), delimiter, -1), - sregex_token_iterator()); - for (auto s : v) { - context.noTypes = GetTypes(context, s, true); - } + if (strstr(types.c_str(), "-")) { + break; + } + int offset = 0; + offset += ((types.front() == '^') ? 1 : 0); + vector v(sregex_token_iterator(types.begin() + offset, types.end(), delimiter, -1), + sregex_token_iterator()); + for (auto s : v) { + if (offset == 1) { + context.noTypes = GetTypes(context, s, true); } else { - vector v(sregex_token_iterator(types.begin(), types.end(), delimiter, -1), - sregex_token_iterator()); - for (auto s : v) { - context.types = GetTypes(context, s); - } + context.types = GetTypes(context, s); } - } else { - break; } } if (context.types != 0 && context.noTypes != 0) { @@ -274,22 +272,19 @@ int HilogEntry(int argc, char* argv[]) while (indexLevel < argc) { string levels(argv[indexLevel]); indexLevel++; - if (!strstr(levels.c_str(), "-")) { - if (levels.front() == '^') { - vector v(sregex_token_iterator(levels.begin() + 1, levels.end(), delimiter, -1), - sregex_token_iterator()); - for (auto s : v) { - context.noLevels = GetLevels(context, s, true); - } + if (strstr(levels.c_str(), "-")) { + break; + } + int offset = 0; + offset += ((levels.front() == '^') ? 1 : 0); + vector v(sregex_token_iterator(levels.begin() + offset, levels.end(), delimiter, -1), + sregex_token_iterator()); + for (auto s : v) { + if (offset == 1) { + context.noLevels = GetLevels(context, s, true); } else { - vector v(sregex_token_iterator(levels.begin(), levels.end(), delimiter, -1), - sregex_token_iterator()); - for (auto s : v) { - context.levels = GetLevels(context, s); - } + context.levels = GetLevels(context, s); } - } else { - break; } } if (context.levels != 0 && context.noLevels != 0) { @@ -350,34 +345,26 @@ int HilogEntry(int argc, char* argv[]) } std::string domains(argv[indexDomain]); indexDomain++; - if (!strstr(domains.c_str(), "-")) { - char* endptr = nullptr; - if (domains.front() == '^') { - vector v(sregex_token_iterator(domains.begin() + 1, domains.end(), delimiter, -1), - sregex_token_iterator()); - for (auto s: v) { - strtoul(s.c_str(), &endptr, DOMAIN_NUMBER_BASE); - if (*endptr != '\0') { - cout << ParseErrorCode(ERR_QUERY_DOMAIN_INVALID) << endl; - exit(RET_FAIL); - } - context.noDomains[context.nNoDomain++] = s; - } + if (strstr(domains.c_str(), "-")) { + break; + } + char* endptr = nullptr; + int offset = 0; + offset += ((domains.front() == '^') ? 1 : 0); + vector v(sregex_token_iterator(domains.begin() + 1, domains.end(), delimiter, -1), + sregex_token_iterator()); + for (auto s: v) { + strtoul(s.c_str(), &endptr, DOMAIN_NUMBER_BASE); + (*endptr != '\0') ? + ({ cout << ParseErrorCode(ERR_QUERY_DOMAIN_INVALID) << endl; + exit(RET_FAIL); }) : + ({}); + if (offset == 1) { + context.noDomains[context.nNoDomain++] = s; } else { - vector v(sregex_token_iterator(domains.begin(), domains.end(), delimiter, -1), - sregex_token_iterator()); - for (auto s: v) { - strtoul(s.c_str(), &endptr, DOMAIN_NUMBER_BASE); - if (*endptr != '\0') { - cout << ParseErrorCode(ERR_QUERY_DOMAIN_INVALID) << endl; - exit(RET_FAIL); - } - context.domains[context.nDomain++] = s; - context.domainArgs += (s + " "); - } + context.domains[context.nDomain++] = s; + context.domainArgs += (s + " "); } - } else { - break; } } break; @@ -399,23 +386,20 @@ int HilogEntry(int argc, char* argv[]) } std::string tags(argv[indexTag]); indexTag++; - if (!strstr(tags.c_str(), "-")) { - if (tags.front() == '^') { - vector v(sregex_token_iterator(tags.begin() + 1, tags.end(), delimiter, -1), - sregex_token_iterator()); - for (auto s: v) { - context.noTags[context.nNoTag++] = s; - } + if (strstr(tags.c_str(), "-")) { + break; + } + int offset = 0; + offset += ((tags.front() == '^') ? 1 : 0); + vector v(sregex_token_iterator(tags.begin() + offset, tags.end(), delimiter, -1), + sregex_token_iterator()); + for (auto s: v) { + if (offset == 1) { + context.noTags[context.nNoTag++] = s; } else { - vector v(sregex_token_iterator(tags.begin(), tags.end(), delimiter, -1), - sregex_token_iterator()); - for (auto s: v) { - context.tags[context.nTag++] = s; - context.tagArgs += (s + " "); - } + context.tags[context.nTag++] = s; + context.tagArgs += (s + " "); } - } else { - break; } } if (context.nTag != 0 && context.nNoTag != 0) { @@ -441,23 +425,20 @@ int HilogEntry(int argc, char* argv[]) } std::string pids(argv[indexPid]); indexPid++; - if (!strstr(pids.c_str(), "-")) { - if (pids.front() == '^') { - vector v(sregex_token_iterator(pids.begin() + 1, pids.end(), delimiter, -1), - sregex_token_iterator()); - for (auto s: v) { - context.noPids[context.nNoPid++] = s; - } + if (strstr(pids.c_str(), "-")) { + break; + } + int offset = 0; + offset += ((pids.front() == '^') ? 1 : 0); + vector v(sregex_token_iterator(pids.begin() + offset, pids.end(), delimiter, -1), + sregex_token_iterator()); + for (auto s: v) { + if (offset == 1) { + context.noPids[context.nNoPid++] = s; } else { - vector v(sregex_token_iterator(pids.begin(), pids.end(), delimiter, -1), - sregex_token_iterator()); - for (auto s: v) { - context.pids[context.nPid++] = s; - context.pidArgs += s + " "; - } + context.pids[context.nPid++] = s; + context.pidArgs += s + " "; } - } else { - break; } } if (context.nPid != 0 && context.nNoPid != 0) { @@ -633,6 +614,6 @@ int HilogEntry(int argc, char* argv[]) int main(int argc, char* argv[]) { - OHOS::HiviewDFX::HilogEntry(argc, argv); + (void)OHOS::HiviewDFX::HilogEntry(argc, argv); return 0; } diff --git a/test/moduletest/common/hilog_base_ndk_test.cpp b/test/moduletest/common/hilog_base_ndk_test.cpp index 97a7611..42e6463 100644 --- a/test/moduletest/common/hilog_base_ndk_test.cpp +++ b/test/moduletest/common/hilog_base_ndk_test.cpp @@ -94,15 +94,15 @@ static std::string PopenToString(const std::string &command) class HiLogBaseNDKTest : public testing::Test { public: - static void SetUpTestCase() {}; - static void TearDownTestCase() {}; + static void SetUpTestCase() {} + static void TearDownTestCase() {} void SetUp(); - void TearDown() {}; + void TearDown() {} }; void HiLogBaseNDKTest::SetUp() { - PopenToString("hilog -r"); + (void)PopenToString("hilog -r"); } static std::string RandomStringGenerator(uint32_t logLen = 16) diff --git a/test/moduletest/common/hilog_ndk_test.cpp b/test/moduletest/common/hilog_ndk_test.cpp index 266db8b..b9c05d1 100644 --- a/test/moduletest/common/hilog_ndk_test.cpp +++ b/test/moduletest/common/hilog_ndk_test.cpp @@ -107,15 +107,15 @@ static std::string PopenToString(const std::string &command) class HiLogNDKTest : public testing::Test { public: - static void SetUpTestCase() {}; - static void TearDownTestCase() {}; + static void SetUpTestCase() {} + static void TearDownTestCase() {} void SetUp(); - void TearDown() {}; + void TearDown() {} }; void HiLogNDKTest::SetUp() { - PopenToString("hilog -r"); + (void)PopenToString("hilog -r"); } static std::string RandomStringGenerator() -- Gitee