From 4056bc9ba47426306a5cb8644dfdfa26e990959f Mon Sep 17 00:00:00 2001 From: sun_fan Date: Wed, 21 Jul 2021 01:01:47 +0800 Subject: [PATCH 1/3] init: modify static check Signed-off-by: sun_fan --- services/BUILD.gn | 4 +- services/{ => cmds}/reboot/BUILD.gn | 0 services/{ => cmds}/reboot/init_cmd_reboot.c | 0 services/cmds/service_control/BUILD.gn | 27 +++ .../cmds/service_control/service_control.c | 92 ++++++++ services/include/init_cmds.h | 8 +- services/include/init_service_manager.h | 3 +- services/log/init_log.c | 6 +- services/param/cmd/param_get.c | 2 +- services/param/manager/param_manager.c | 2 +- services/param/manager/param_trie.c | 2 +- services/param/trigger/trigger_processor.c | 9 +- services/src/init_capability.c | 9 +- services/src/init_cmds.c | 207 ++++++++++++------ services/src/init_import.c | 4 +- services/src/init_read_cfg.c | 11 +- services/src/init_reboot.c | 18 +- services/src/init_service.c | 11 +- services/src/init_service_manager.c | 70 ++++-- services/src/init_service_socket.c | 28 ++- services/src/init_signal_handler.c | 11 - services/src/init_utils.c | 26 ++- services/src/main.c | 4 +- services/test/unittest/common/BUILD.gn | 1 + .../test/unittest/common/cmd_func_test.cpp | 5 +- 25 files changed, 413 insertions(+), 147 deletions(-) rename services/{ => cmds}/reboot/BUILD.gn (100%) mode change 100644 => 100755 rename services/{ => cmds}/reboot/init_cmd_reboot.c (100%) mode change 100644 => 100755 create mode 100755 services/cmds/service_control/BUILD.gn create mode 100755 services/cmds/service_control/service_control.c diff --git a/services/BUILD.gn b/services/BUILD.gn index e69a8ef12..d1a1f0bdc 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -57,6 +57,7 @@ if (defined(ohos_lite)) { ldflags = [] if (ohos_kernel_type == "liteos_a") { include_dirs += [ + "//kernel/liteos_a/syscall", "//base/startup/init_lite/interfaces/kits", "//base/startup/init_lite/initsync/include", ] @@ -152,7 +153,8 @@ if (defined(ohos_lite)) { "//base/startup/init_lite/services/param:paramclient", "//base/startup/init_lite/services/param:paramservice", "//base/startup/init_lite/services/param:setparam", - "//base/startup/init_lite/services/reboot:reboot", + "//base/startup/init_lite/services/cmds/reboot:reboot", + "//base/startup/init_lite/services/cmds/service_control:service_control", ] } diff --git a/services/reboot/BUILD.gn b/services/cmds/reboot/BUILD.gn old mode 100644 new mode 100755 similarity index 100% rename from services/reboot/BUILD.gn rename to services/cmds/reboot/BUILD.gn diff --git a/services/reboot/init_cmd_reboot.c b/services/cmds/reboot/init_cmd_reboot.c old mode 100644 new mode 100755 similarity index 100% rename from services/reboot/init_cmd_reboot.c rename to services/cmds/reboot/init_cmd_reboot.c diff --git a/services/cmds/service_control/BUILD.gn b/services/cmds/service_control/BUILD.gn new file mode 100755 index 000000000..5b4aa7a02 --- /dev/null +++ b/services/cmds/service_control/BUILD.gn @@ -0,0 +1,27 @@ +# Copyright (c) 2020 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. +import("//build/ohos.gni") + +ohos_executable("service_control") { + sources = [ "service_control.c" ] + include_dirs = [ + "//base/startup/init_lite/services/include/param", + "//base/startup/init_lite/services/include", + ] + deps = [ + "//base/startup/init_lite/services/param:paramclient", + "//third_party/bounds_checking_function:libsec_static", + ] + install_enable = true + part_name = "init" +} diff --git a/services/cmds/service_control/service_control.c b/services/cmds/service_control/service_control.c new file mode 100755 index 000000000..1d5872f59 --- /dev/null +++ b/services/cmds/service_control/service_control.c @@ -0,0 +1,92 @@ +/* +* 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 +#include +#include "sys_param.h" +#include "securec.h" + +#define SERVICE_START_NUMBER 2 +#define SERVICE_CONTROL_NUMBER 3 +#define CONTROL_SERVICE_POS 2 +#define SERVICE_CONTROL_MAX_SIZE 50 + +static void ServiceControlUsage() +{ + printf("Please input correct params, example:\n"); + printf(" start_service serviceName\n"); + printf(" stop_service serviceName\n"); + printf(" service_control start serviceName\n"); + printf(" service_control stop serviceName\n"); + return; +} + +static void ServiceControl(int argc, char** argv) +{ + if (argc != SERVICE_CONTROL_NUMBER) { + ServiceControlUsage(); + return; + } + char serviceCtl[SERVICE_CONTROL_MAX_SIZE]; + if (strcmp(argv[1], "start") == 0) { + if (strncpy_s(serviceCtl, sizeof(serviceCtl), "ohos.ctl.start", sizeof(serviceCtl) - 1) != EOK) { + printf("strncpy_s failed.\n"); + return; + } + } else if (strcmp(argv[1], "stop") == 0) { + if (strncpy_s(serviceCtl, sizeof(serviceCtl), "ohos.ctl.stop", sizeof(serviceCtl) - 1) != EOK) { + printf("strncpy_s failed.\n"); + return; + } + } else { + ServiceControlUsage(); + return; + } + if (SystemSetParameter(serviceCtl, argv[CONTROL_SERVICE_POS]) != 0) { + printf("%s service:%s failed.\n", argv[1], argv[CONTROL_SERVICE_POS]); + return; + } + return; +} + +int main(int argc, char** argv) +{ + if (argc != SERVICE_START_NUMBER && argc != SERVICE_CONTROL_NUMBER) { + ServiceControlUsage(); + return -1; + } + + char serviceCtl[SERVICE_CONTROL_MAX_SIZE]; + if (strcmp(argv[0], "start_service") == 0) { + if (strncpy_s(serviceCtl, sizeof(serviceCtl), "ohos.ctl.start", sizeof(serviceCtl) - 1) != EOK) { + printf("strncpy_s failed.\n"); + return -1; + } + } else if (strcmp(argv[0], "stop_service") == 0) { + if (strncpy_s(serviceCtl, sizeof(serviceCtl), "ohos.ctl.stop", sizeof(serviceCtl) - 1) != EOK) { + printf("strncpy_s failed.\n"); + return -1; + } + } else { + ServiceControl(argc, argv); + return 0; + } + + if (SystemSetParameter(serviceCtl, argv[1]) != 0) { + printf("%s service:%s failed.\n", argv[0], argv[1]); + return -1; + } + return 0; +} diff --git a/services/include/init_cmds.h b/services/include/init_cmds.h index bdf88120d..469ef4fb2 100644 --- a/services/include/init_cmds.h +++ b/services/include/init_cmds.h @@ -33,6 +33,10 @@ extern "C" { #define MAX_PARAM_VALUE_LEN 96 // Limit max length of parameter name to 96 #define MAX_PARAM_NAME_LEN 96 +#else +// For lite ohos, do not support parameter operation +#define MAX_PARAM_VALUE_LEN 0 +#define MAX_PARAM_NAME_LEN 0 #endif // one cmd line @@ -46,10 +50,8 @@ struct CmdArgs { char **argv; }; -#ifndef OHOS_LITE int GetParamValue(char *symValue, char *paramValue, unsigned int paramLen); -#endif -struct CmdArgs* GetCmd(const char *cmdContent, const char *delim); +struct CmdArgs* GetCmd(const char *cmdContent, const char *delim, int argsCount); void FreeCmd(struct CmdArgs **cmd); void ParseCmdLine(const char* cmdStr, CmdLine* resCmd); diff --git a/services/include/init_service_manager.h b/services/include/init_service_manager.h index ae3e7c579..3e680d3a9 100644 --- a/services/include/init_service_manager.h +++ b/services/include/init_service_manager.h @@ -43,8 +43,9 @@ void StopAllServices(); void StopAllServicesBeforeReboot(); void ReapServiceByPID(int pid); void ParseAllServices(const cJSON* fileRoot); +#ifdef OHOS_SERVICE_DUMP void DumpAllServices(); - +#endif #ifdef __cplusplus #if __cplusplus } diff --git a/services/log/init_log.c b/services/log/init_log.c index f4cf63178..678b7f35c 100644 --- a/services/log/init_log.c +++ b/services/log/init_log.c @@ -70,10 +70,14 @@ void InitLog(const char *tag, InitLogLevel logLevel, const char *fileName, int l if (logLevel < g_logLevel) { return; } - // 可以替换stdout这个为对应的文件句柄 + time_t logTime; time(&logTime); struct tm *t = gmtime(&logTime); + if (t == NULL) { + printf("time is NULL.\n"); + return; + } fprintf(stdout, "[%d-%d-%d %d:%d:%d][pid=%d][%s:%d][%s][%s] ", (t->tm_year + BASE_YEAR), (t->tm_mon + 1), t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, getpid(), fileName, line, tag, LOG_LEVEL_STR[logLevel]); diff --git a/services/param/cmd/param_get.c b/services/param/cmd/param_get.c index bba06fcdf..7ae0ddd9d 100644 --- a/services/param/cmd/param_get.c +++ b/services/param/cmd/param_get.c @@ -47,7 +47,7 @@ int main(int argc, char* argv[]) u_int32_t size = BUFFER_SIZE; int ret = SystemGetParameter(argv[1], value, &size); if (ret == 0) { - printf("getparam %s %s \n", argv[1], value); + printf("%s \n", value); } else { printf("getparam %s %s fail\n", argv[1], value); } diff --git a/services/param/manager/param_manager.c b/services/param/manager/param_manager.c index f5afb967e..dcf3c3793 100644 --- a/services/param/manager/param_manager.c +++ b/services/param/manager/param_manager.c @@ -249,7 +249,7 @@ int ReadParamValue(ParamWorkSpace *workSpace, ParamHandle handle, char *value, u } if (value == NULL) { - *len = DATA_ENTRY_DATA_LEN(entry);; + *len = DATA_ENTRY_DATA_LEN(entry) + 1; return 0; } diff --git a/services/param/manager/param_trie.c b/services/param/manager/param_trie.c index cfe7ee753..116bdf300 100644 --- a/services/param/manager/param_trie.c +++ b/services/param/manager/param_trie.c @@ -489,7 +489,7 @@ int UpdateDataValue(DataEntry *entry, const char *value) u_int32_t valueLen = strlen(value); u_int32_t oldLen = DATA_ENTRY_DATA_LEN(entry); if (oldLen < PARAM_VALUE_LEN_MAX && valueLen < PARAM_VALUE_LEN_MAX) { - PARAM_LOGE("Old value %s new value %s", entry->data + keyLen + 1, value); + PARAM_LOGD("Old value %s new value %s", entry->data + keyLen + 1, value); ret = memcpy_s(entry->data + keyLen + 1, PARAM_VALUE_LEN_MAX, value, valueLen + 1); PARAM_CHECK(ret == 0, return PARAM_CODE_INVALID_VALUE, "Failed to copy value"); u_int32_t dataLength = keyLen << TRIE_SERIAL_KEY_LEN_OFFSET | valueLen << TRIE_SERIAL_DATA_LEN_OFFSET; diff --git a/services/param/trigger/trigger_processor.c b/services/param/trigger/trigger_processor.c index 7b97f3d2c..9ea89cbed 100644 --- a/services/param/trigger/trigger_processor.c +++ b/services/param/trigger/trigger_processor.c @@ -25,6 +25,9 @@ #define LABEL "Trigger" #define MAX_TRIGGER_COUNT_RUN_ONCE 20 #define SYS_POWER_CTRL "sys.powerctrl=" +#define OHOS_CTL_START "ohos.ctl.start=" +#define OHOS_CTL_STOP "ohos.ctl.stop=" + static TriggerWorkSpace g_triggerWorkSpace = {}; static int DoCmdExecute(TriggerNode *trigger, const char *cmdName, const char *command) @@ -129,6 +132,10 @@ static void SendTriggerEvent(TriggerDataEvent *event) } else { PARAM_LOGE("SendTriggerEvent cmd %s not found", event->content); } + } else if (strncmp(event->content, OHOS_CTL_START, strlen(OHOS_CTL_START)) == 0) { + DoCmdByName("start ", event->content + strlen(OHOS_CTL_START)); + } else if (strncmp(event->content, OHOS_CTL_STOP, strlen(OHOS_CTL_STOP)) == 0) { + DoCmdByName("stop ", event->content + strlen(OHOS_CTL_STOP)); } else { uv_queue_work(uv_default_loop(), &event->request, ProcessEvent, ProcessAfterEvent); event = NULL; @@ -141,7 +148,7 @@ static void SendTriggerEvent(TriggerDataEvent *event) void PostParamTrigger(const char *name, const char *value) { PARAM_CHECK(name != NULL && value != NULL, return, "Invalid param"); - PARAM_LOGI("PostParamTrigger %s ", name); + PARAM_LOGD("PostParamTrigger %s ", name); int contentLen = strlen(name) + strlen(value) + 2; TriggerDataEvent *event = (TriggerDataEvent *)malloc(sizeof(TriggerDataEvent) + contentLen); PARAM_CHECK(event != NULL, return, "Failed to alloc memory"); diff --git a/services/src/init_capability.c b/services/src/init_capability.c index ca9365bdf..58884ef31 100644 --- a/services/src/init_capability.c +++ b/services/src/init_capability.c @@ -89,6 +89,10 @@ static int GetServiceStringCaps(const cJSON* filedJ, Service* curServ) break; } char* fieldStr = cJSON_GetStringValue(cJSON_GetArrayItem(filedJ, i)); + if (fieldStr == NULL) { + INIT_LOGE("fieldStr is NULL"); + break; + } int mapSize = sizeof(g_capStrCapNum) / sizeof(struct CapStrCapNum); // search int j = 0; for (; j < mapSize; j++) { @@ -114,6 +118,10 @@ static int GetServiceStringCaps(const cJSON* filedJ, Service* curServ) int GetServiceCaps(const cJSON* curArrItem, Service* curServ) { + if (curServ == NULL || curArrItem == NULL) { + INIT_LOGE("GetServiceCaps failed, curServ or curArrItem is NULL."); + return SERVICE_FAILURE; + } curServ->servPerm.capsCnt = 0; curServ->servPerm.caps = NULL; cJSON* filedJ = cJSON_GetObjectItem(curArrItem, "caps"); @@ -145,7 +153,6 @@ int GetServiceCaps(const cJSON* curArrItem, Service* curServ) cJSON* capJ = cJSON_GetArrayItem(filedJ, i); if (!cJSON_IsNumber(capJ) || cJSON_GetNumberValue(capJ) < 0) { // resources will be released by function: ReleaseServiceMem - INIT_LOGI("service=%s, Capbility is not a number or < 0, error.", curServ->name); break; } curServ->servPerm.caps[i] = (unsigned int)cJSON_GetNumberValue(capJ); diff --git a/services/src/init_cmds.c b/services/src/init_cmds.c index e4bb8c67f..5799bf86d 100644 --- a/services/src/init_cmds.c +++ b/services/src/init_cmds.c @@ -50,7 +50,7 @@ #define LOADCFG_MAX_FILE_LEN 51200 // loadcfg, max file size is 50K #define LOADCFG_MAX_LOOP 20 // loadcfg, to prevent to be trapped in infite loop #define OCTAL_TYPE 8 // 8 means octal to decimal -#define MAX_BUFFER 256 +#define MAX_BUFFER 256UL #define AUTHORITY_MAX_SIZE 128 #define WAIT_MAX_COUNT 10 #define MAX_EACH_CMD_LENGTH 30 @@ -141,47 +141,96 @@ int GetParamValue(char *symValue, char *paramValue, unsigned int paramLen) return -1; } } +#else +// For ite ohos, do not support parameter operation. just do string copy +inline int GetParamValue(char *symValue, char *paramValue, unsigned int paramLen) +{ + return strncpy_s(paramValue, paramLen, symValue, strlen(symValue)) == EOK ? 0 : -1; +} #endif -struct CmdArgs* GetCmd(const char *cmdContent, const char *delim) +struct CmdArgs* GetCmd(const char *cmdContent, const char *delim, int argsCount) { + INIT_CHECK_ONLY_RETURN(cmdContent != NULL, return NULL); struct CmdArgs *ctx = (struct CmdArgs *)malloc(sizeof(struct CmdArgs)); INIT_CHECK_ONLY_RETURN(ctx != NULL, return NULL); - ctx->argv = (char**)malloc(sizeof(char*) * MAX_CMD_NAME_LEN); + if (argsCount > SPACES_CNT_IN_CMD_MAX) { + INIT_LOGW("Too much arguments for command, max number is %d", SPACES_CNT_IN_CMD_MAX); + argsCount = SPACES_CNT_IN_CMD_MAX; + } + ctx->argv = (char**)malloc(sizeof(char*) * (size_t)argsCount + 1); INIT_CHECK_ONLY_RETURN(ctx->argv != NULL, FreeCmd(&ctx); return NULL); char tmpCmd[MAX_BUFFER]; - INIT_CHECK_ONLY_RETURN(strncpy_s(tmpCmd, strlen(cmdContent) + 1, cmdContent, strlen(cmdContent)) == EOK, + size_t cmdLength = strlen(cmdContent); + + if (cmdLength > MAX_BUFFER - 1) { + INIT_LOGE("command line is too larget, should not bigger than %d. ignore...\n", MAX_BUFFER); + FreeCmd(&ctx); + return NULL; + } + + INIT_CHECK_ONLY_RETURN(strncpy_s(tmpCmd, MAX_BUFFER - 1, cmdContent, cmdLength) == EOK, FreeCmd(&ctx); return NULL); tmpCmd[strlen(cmdContent)] = '\0'; - char *buffer = NULL; - char *token = strtok_r(tmpCmd, delim, &buffer); + char *p = tmpCmd; + char *token = NULL; + size_t allocSize = 0; + + // Skip lead whitespaces + while (isspace(*p)) { + p++; + } ctx->argc = 0; - while (token != NULL) { -#ifndef OHOS_LITE - ctx->argv[ctx->argc] = calloc(sizeof(char *), MAX_EACH_CMD_LENGTH + MAX_PARAM_VALUE_LEN); - INIT_CHECK_ONLY_RETURN(ctx->argv[ctx->argc] != NULL, FreeCmd(&ctx); return NULL); - INIT_CHECK_ONLY_RETURN(GetParamValue(token, ctx->argv[ctx->argc], MAX_EACH_CMD_LENGTH + MAX_PARAM_VALUE_LEN) == 0, - FreeCmd(&ctx); - return NULL); -#else - ctx->argv[ctx->argc] = calloc(sizeof(char *), MAX_EACH_CMD_LENGTH); + token = strstr(p, delim); + if (token == NULL) { // No whitespaces + // Make surce there is enough memory to store parameter value + allocSize = (size_t)(cmdLength + MAX_PARAM_VALUE_LEN); + ctx->argv[ctx->argc] = calloc(sizeof(char), allocSize); INIT_CHECK_ONLY_RETURN(ctx->argv[ctx->argc] != NULL, FreeCmd(&ctx); return NULL); - INIT_CHECK_ONLY_RETURN(strncpy_s(ctx->argv[ctx->argc], strlen(cmdContent) + 1, token, strlen(token)) == EOK, - FreeCmd(&ctx); - return NULL); -#endif - if (ctx->argc > MAX_CMD_NAME_LEN - 1) { - INIT_LOGE("GetCmd failed, max cmd number is 10."); - FreeCmd(&ctx); - return NULL; - } - token = strtok_r(NULL, delim, &buffer); + INIT_CHECK_ONLY_RETURN(GetParamValue(p, ctx->argv[ctx->argc], allocSize) == 0, + FreeCmd(&ctx); return NULL); ctx->argc += 1; + ctx->argv[ctx->argc] = NULL; + return ctx; + } + + int index = ctx->argc; + while (token != NULL) { + // Too more arguments, treat rest of data as one argument + if (index == (argsCount -1)) { + break; + } + *token = '\0'; // replace it with '\0'; + allocSize = (size_t)((p - token) + MAX_PARAM_VALUE_LEN); + ctx->argv[index] = calloc(sizeof(char), allocSize); + INIT_CHECK_ONLY_RETURN(ctx->argv[index] != NULL, FreeCmd(&ctx); return NULL); + INIT_CHECK_ONLY_RETURN(GetParamValue(p, ctx->argv[index], allocSize) == 0, + FreeCmd(&ctx); return NULL); + p = token + 1; // skip '\0' + // Skip lead whitespaces + while (isspace(*p)) { + p++; + } + index++; + token = strstr(p, delim); + } + + ctx->argc = index; + if (p < tmpCmd + cmdLength) { + // no more white space or encounter max argument count + size_t restSize = tmpCmd + cmdLength - p; + allocSize = restSize + MAX_PARAM_VALUE_LEN; + ctx->argv[index] = calloc(sizeof(char), allocSize); + INIT_CHECK_ONLY_RETURN(ctx->argv[index] != NULL, FreeCmd(&ctx); return NULL); + INIT_CHECK_ONLY_RETURN(GetParamValue(p, ctx->argv[index], allocSize) == 0, + FreeCmd(&ctx); return NULL); + ctx->argc = index + 1; } + ctx->argv[ctx->argc] = NULL; return ctx; } @@ -258,11 +307,12 @@ static void DoCopy(const char* cmdContent) int dstFd = -1; int rdLen = 0; int rtLen = 0; + int argsCount = 2; char buf[MAX_COPY_BUF_SIZE] = {0}; mode_t mode = 0; struct stat fileStat = {0}; - struct CmdArgs *ctx = GetCmd(cmdContent, " "); - if (ctx == NULL || ctx->argv == NULL || ctx->argc != DEFAULT_COPY_ARGS_CNT) { + struct CmdArgs *ctx = GetCmd(cmdContent, " ", argsCount); + if (ctx == NULL || ctx->argv == NULL || ctx->argv[0] == NULL || ctx->argc != DEFAULT_COPY_ARGS_CNT) { INIT_LOGE("DoCopy failed."); goto out; } @@ -290,8 +340,9 @@ out: static void DoChown(const char* cmdContent) { // format: chown owner group /xxx/xxx/xxx - struct CmdArgs *ctx = GetCmd(cmdContent, " "); - if (ctx == NULL || ctx->argv == NULL || ctx->argc != 3) { + const int argsCount = 3; + struct CmdArgs *ctx = GetCmd(cmdContent, " ", argsCount); + if (ctx == NULL || ctx->argv == NULL || ctx->argc != argsCount) { INIT_LOGE("DoChown failed."); goto out; } @@ -324,7 +375,8 @@ out: static void DoMkDir(const char* cmdContent) { // format: mkdir /xxx/xxx/xxx or mkdir /xxx/xxx/xxx mode owner group - struct CmdArgs *ctx = GetCmd(cmdContent, " "); + const int argsCount = 4; + struct CmdArgs *ctx = GetCmd(cmdContent, " ", argsCount); if (ctx == NULL || ctx->argv == NULL || ctx->argc < 1) { INIT_LOGE("DoMkDir failed."); goto out; @@ -341,8 +393,8 @@ static void DoMkDir(const char* cmdContent) if (chmod(ctx->argv[0], mode) != 0) { INIT_LOGE("DoMkDir failed for %s, err %d.", cmdContent, errno); } - int ownerPos = 2; - int groupPos = 3; + const int ownerPos = 2; + const int groupPos = 3; char chownCmdContent[AUTHORITY_MAX_SIZE] = { 0 }; if (snprintf_s(chownCmdContent, AUTHORITY_MAX_SIZE, AUTHORITY_MAX_SIZE - 1, "%s %s %s", ctx->argv[ownerPos], ctx->argv[groupPos], ctx->argv[0]) == -1) { @@ -359,8 +411,9 @@ out: static void DoChmod(const char* cmdContent) { // format: chmod xxxx /xxx/xxx/xxx - struct CmdArgs *ctx = GetCmd(cmdContent, " "); - if (ctx == NULL || ctx->argv == NULL || ctx->argc != 2) { + int argsCount = 2; + struct CmdArgs *ctx = GetCmd(cmdContent, " ", argsCount); + if (ctx == NULL || ctx->argv == NULL || ctx->argc != argsCount) { INIT_LOGE("DoChmod failed."); goto out; } @@ -552,7 +605,7 @@ static void DoInsmodInternal(const char *fileName, char *secondPtr, char *restPt } } } - if (!fileName) { + if (fileName == NULL) { return; } char *realPath = (char *)calloc(MAX_BUFFER, sizeof(char)); @@ -560,6 +613,10 @@ static void DoInsmodInternal(const char *fileName, char *secondPtr, char *restPt return; } realPath = realpath(fileName, realPath); + if (realPath == NULL) { + free(realPath); + return; + } int fd = open(realPath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC); if (fd < 0) { INIT_LOGE("failed to open %s: %d", realPath, errno); @@ -596,7 +653,7 @@ static void DoInsmod(const char *cmdContent) return; } - if (memcpy_s(line, count, cmdContent, count) != EOK) { + if (memcpy_s(line, count + 1, cmdContent, count) != EOK) { INIT_LOGE("DoInsmod memcpy failed"); free(line); return; @@ -626,8 +683,9 @@ static void DoInsmod(const char *cmdContent) static void DoSetParam(const char* cmdContent) { - struct CmdArgs *ctx = GetCmd(cmdContent, " "); - if (ctx == NULL || ctx->argv == NULL || ctx->argc != 2) { + int argsCount = 2; + struct CmdArgs *ctx = GetCmd(cmdContent, " ", argsCount); + if (ctx == NULL || ctx->argv == NULL || ctx->argc != argsCount) { INIT_LOGE("DoSetParam failed."); goto out; } @@ -675,7 +733,10 @@ static void DoLoadCfg(const char *path) INIT_LOGE("CheckCfg file %s Failed", path); return; } - + if (path == NULL) { + INIT_LOGE("CheckCfg path is NULL."); + return; + } fp = fopen(path, "r"); if (fp == NULL) { INIT_LOGE("open cfg error = %d", errno); @@ -711,15 +772,14 @@ static void DoLoadCfg(const char *path) static void DoWrite(const char *cmdContent) { // format: write path content - struct CmdArgs *ctx = GetCmd(cmdContent, " "); - int writeCmdNumber = 2; - if (ctx == NULL || ctx->argv == NULL || ctx->argc != writeCmdNumber) { + const int argsCount = 2; + struct CmdArgs *ctx = GetCmd(cmdContent, " ", argsCount); + if (ctx == NULL || ctx->argv == NULL || ctx->argv[0] == NULL || ctx->argc != argsCount) { INIT_LOGE("DoWrite: invalid arguments"); goto out; } - int fd = open(ctx->argv[0], O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC, S_IRWXU | - S_IRGRP | S_IROTH); + int fd = open(ctx->argv[0], O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC, S_IRWXU | S_IRGRP | S_IROTH); if (fd == -1) { INIT_LOGE("DoWrite: open %s failed: %d", ctx->argv[0], errno); goto out; @@ -740,7 +800,7 @@ out: static void DoRmdir(const char *cmdContent) { // format: rmdir path - struct CmdArgs *ctx = GetCmd(cmdContent, " "); + struct CmdArgs *ctx = GetCmd(cmdContent, " ", 1); if (ctx == NULL || ctx->argv == NULL || ctx->argc != 1) { INIT_LOGE("DoRmdir: invalid arguments"); goto out; @@ -764,17 +824,17 @@ static void DoSetrlimit(const char *cmdContent) "RLIMIT_MSGQUEUE", "RLIMIT_NICE", "RLIMIT_RTPRIO", "RLIMIT_RTTIME", "RLIM_NLIMITS" }; // format: setrlimit resource curValue maxValue - struct CmdArgs *ctx = GetCmd(cmdContent, " "); - int setrlimitCmdNumber = 3; - int rlimMaxPos = 2; - if (ctx == NULL || ctx->argv == NULL || ctx->argc != setrlimitCmdNumber) { + const int argsCount = 3; + struct CmdArgs *ctx = GetCmd(cmdContent, " ", argsCount); + const int rlimMaxPos = 2; + if (ctx == NULL || ctx->argv == NULL || ctx->argc != argsCount) { INIT_LOGE("DoSetrlimit: invalid arguments"); goto out; } struct rlimit limit; - limit.rlim_cur = atoi(ctx->argv[1]); - limit.rlim_max = atoi(ctx->argv[rlimMaxPos]); + limit.rlim_cur = (rlim_t)atoi(ctx->argv[1]); + limit.rlim_max = (rlim_t )atoi(ctx->argv[rlimMaxPos]); int rcs = -1; for (unsigned int i = 0 ; i < sizeof(resource) / sizeof(char*); ++i) { if (strcmp(ctx->argv[0], resource[i]) == 0) { @@ -798,7 +858,7 @@ out: static void DoRm(const char *cmdContent) { // format: rm /xxx/xxx/xxx - struct CmdArgs *ctx = GetCmd(cmdContent, " "); + struct CmdArgs *ctx = GetCmd(cmdContent, " ", 1); if (ctx == NULL || ctx->argv == NULL || ctx->argc != 1) { INIT_LOGE("DoRm: invalid arguments"); goto out; @@ -816,9 +876,9 @@ out: static void DoExport(const char *cmdContent) { // format: export xxx /xxx/xxx/xxx - struct CmdArgs *ctx = GetCmd(cmdContent, " "); - int exportCmdNumber = 2; - if (ctx == NULL || ctx->argv == NULL || ctx->argc != exportCmdNumber) { + const int argsCount = 2; + struct CmdArgs *ctx = GetCmd(cmdContent, " ", argsCount); + if (ctx == NULL || ctx->argv == NULL || ctx->argc != argsCount) { INIT_LOGE("DoExport: invalid arguments"); goto out; } @@ -841,8 +901,9 @@ static void DoExec(const char *cmdContent) return; } if (pid == 0) { - struct CmdArgs *ctx = GetCmd(cmdContent, " "); - if (ctx == NULL || ctx->argv == NULL) { + int argsCount = 10; + struct CmdArgs *ctx = GetCmd(cmdContent, " ", argsCount); + if (ctx == NULL || ctx->argv == NULL || ctx->argv[0] == NULL) { INIT_LOGE("DoExec: invalid arguments"); _exit(0x7f); } @@ -864,9 +925,9 @@ static void DoExec(const char *cmdContent) static void DoSymlink(const char *cmdContent) { // format: symlink /xxx/xxx/xxx /xxx/xxx/xxx - struct CmdArgs *ctx = GetCmd(cmdContent, " "); - int symlinkCmdNumber = 2; - if (ctx == NULL || ctx->argv == NULL || ctx->argc != symlinkCmdNumber) { + const int argsCount = 2; + struct CmdArgs *ctx = GetCmd(cmdContent, " ", argsCount); + if (ctx == NULL || ctx->argv == NULL || ctx->argc != argsCount) { INIT_LOGE("DoSymlink: invalid arguments."); goto out; } @@ -901,15 +962,15 @@ static mode_t GetDeviceMode(const char *deviceStr) static void DoMakeNode(const char *cmdContent) { // format: mknod path b 0644 1 9 - struct CmdArgs *ctx = GetCmd(cmdContent, " "); - int mkNodeCmdNumber = 5; - int deviceTypePos = 1; - int authorityPos = 2; - int majorDevicePos = 3; - int minorDevicePos = 4; - int decimal = 10; - int octal = 8; - if (ctx == NULL || ctx->argv == NULL || ctx->argc != mkNodeCmdNumber) { + const int argsCount = 5; + struct CmdArgs *ctx = GetCmd(cmdContent, " ", argsCount); + const int deviceTypePos = 1; + const int authorityPos = 2; + const int majorDevicePos = 3; + const int minorDevicePos = 4; + const int decimal = 10; + const int octal = 8; + if (ctx == NULL || ctx->argv == NULL || ctx->argc != argsCount) { INIT_LOGE("DoMakeNode: invalid arguments"); goto out; } @@ -936,10 +997,10 @@ out: static void DoMakeDevice(const char *cmdContent) { // format: makedev major minor - struct CmdArgs *ctx = GetCmd(cmdContent, " "); - int makeDevCmdNumber = 2; - int decimal = 10; - if (ctx == NULL || ctx->argv == NULL || ctx->argc != makeDevCmdNumber) { + const int argsCount = 2; + struct CmdArgs *ctx = GetCmd(cmdContent, " ", argsCount); + const int decimal = 10; + if (ctx == NULL || ctx->argv == NULL || ctx->argc != argsCount) { INIT_LOGE("DoMakedevice: invalid arugments"); goto out; } diff --git a/services/src/init_import.c b/services/src/init_import.c index 1e705bd79..08fd54d7f 100644 --- a/services/src/init_import.c +++ b/services/src/init_import.c @@ -22,8 +22,6 @@ #include "init_read_cfg.h" #include "securec.h" -#define IMPORT_ARR_NAME_IN_JSON "import" - #ifndef OHOS_LITE static int ExtractCfgFile(char **cfgFile, char *content) { @@ -41,7 +39,7 @@ static int ExtractCfgFile(char **cfgFile, char *content) void ParseAllImports(cJSON *root) { - cJSON *importAttr = cJSON_GetObjectItemCaseSensitive(root, IMPORT_ARR_NAME_IN_JSON); + cJSON *importAttr = cJSON_GetObjectItemCaseSensitive(root, "import"); char *cfgFile = NULL; if (!cJSON_IsArray(importAttr)) { return; diff --git a/services/src/init_read_cfg.c b/services/src/init_read_cfg.c index a1621ffe7..751a02a6c 100644 --- a/services/src/init_read_cfg.c +++ b/services/src/init_read_cfg.c @@ -44,13 +44,17 @@ #define FILE_NAME_MAX_SIZE 100 static void ParseInitCfgContents(cJSON *root) { + if (root == NULL) { + INIT_LOGE("ParseInitCfgContents root is NULL"); + return; + } // parse services ParseAllServices(root); #ifdef OHOS_LITE // parse jobs ParseAllJobs(root); #else - ParseTriggerConfig(root); + ParseTriggerConfig(root); #endif // parse imports @@ -129,9 +133,10 @@ void InitReadCfg() ParseInitCfg(INIT_CONFIGURATION_FILE); ParseOtherCfgs(); INIT_LOGI("Parse init config file done."); - +#ifdef OHOS_SERVICE_DUMP DumpAllServices(); - // DumpAllJobs(); +#endif + #ifdef OHOS_LITE // do jobs DoJob("pre-init"); diff --git a/services/src/init_reboot.c b/services/src/init_reboot.c index f6466d477..38ea5fb73 100644 --- a/services/src/init_reboot.c +++ b/services/src/init_reboot.c @@ -23,6 +23,7 @@ #include #include #include +#include "securec.h" #include "init_service.h" #include "init_service_manager.h" #include "init_log.h" @@ -38,6 +39,10 @@ struct RBMiscUpdateMessage { static bool RBMiscWriteUpdaterMessage(const char *path, struct RBMiscUpdateMessage *boot) { + if (path == NULL || boot == NULL) { + INIT_LOGE("path or boot is NULL."); + return false; + } FILE* fp = fopen(path, "rb+"); if (fp == NULL) { INIT_LOGE("open %s failed", path); @@ -57,6 +62,10 @@ static bool RBMiscWriteUpdaterMessage(const char *path, struct RBMiscUpdateMessa static bool RBMiscReadUpdaterMessage(const char *path, struct RBMiscUpdateMessage *boot) { + if (path == NULL || boot == NULL) { + INIT_LOGE("path or boot is NULL."); + return false; + } FILE* fp = fopen(path, "rb"); if (fp == NULL) { INIT_LOGE("open %s failed", path); @@ -75,7 +84,8 @@ static bool RBMiscReadUpdaterMessage(const char *path, struct RBMiscUpdateMessag static int GetMountStatusForMountPoint(const char *mountPoint) { - char buffer[512]; + const int bufferMaxSize = 512; + char buffer[bufferMaxSize]; size_t n; const char *mountFile = "/proc/mounts"; FILE *fp = fopen(mountFile, "r"); @@ -129,12 +139,12 @@ void DoReboot(const char *value) } StopAllServicesBeforeReboot(); - if (GetMountStatusForMountPoint("/vendor")) { + if (GetMountStatusForMountPoint("/vendor") != 0) { if (umount("/vendor") != 0) { INIT_LOGE("DoReboot umount vendor failed! errno = %d.", errno); } } - if (GetMountStatusForMountPoint("/data")) { + if (GetMountStatusForMountPoint("/data") != 0) { if (umount("/data") != 0) { INIT_LOGE("DoReboot umount data failed! errno = %d.", errno); } @@ -161,7 +171,7 @@ void DoReboot(const char *value) if (strlen(valueData) > strlen("updater:") && strncmp(valueData, "updater:", strlen("updater:")) == 0) { const char *p = valueData + strlen("updater:"); - if (snprintf(msg.update, MAX_UPDATE_SIZE, "%s", p) > MAX_UPDATE_SIZE) { + if (snprintf_s(msg.update, MAX_UPDATE_SIZE, MAX_UPDATE_SIZE - 1, "%s", p) == -1) { INIT_LOGE("DoReboot updater: RBMiscWriteUpdaterMessage error"); return; } diff --git a/services/src/init_service.c b/services/src/init_service.c index 2c014b1c4..592d98b12 100644 --- a/services/src/init_service.c +++ b/services/src/init_service.c @@ -159,7 +159,10 @@ int ServiceStart(Service *service) INIT_LOGE("start service %s invalid.", service->name); return SERVICE_FAILURE; } - + if (service->pathArgs == NULL) { + INIT_LOGE("start service pathArgs is NULL."); + return SERVICE_FAILURE; + } struct stat pathStat = {0}; service->attribute &= (~(SERVICE_ATTR_NEED_RESTART | SERVICE_ATTR_NEED_STOP)); if (stat(service->pathArgs[0], &pathStat) != 0) { @@ -189,7 +192,7 @@ int ServiceStart(Service *service) } char pidString[MAX_PID_STRING_LENGTH]; // writepid pid_t childPid = getpid(); - if (snprintf(pidString, MAX_PID_STRING_LENGTH, "%d", childPid) <= 0) { + if (snprintf_s(pidString, MAX_PID_STRING_LENGTH, MAX_PID_STRING_LENGTH - 1, "%d", childPid) < 0) { INIT_LOGE("start service writepid sprintf failed."); _exit(0x7f); // 0x7f: user specified } @@ -271,6 +274,9 @@ int ServiceStop(Service *service) // the service need to be restarted, if it crashed more than 4 times in 4 minutes void CheckCritical(Service *service) { + if (service == NULL) { + return; + } if (service->attribute & SERVICE_ATTR_CRITICAL) { // critical // crash time and count check time_t curTime = time(NULL); @@ -303,6 +309,7 @@ static int ExecRestartCmd(const Service *service) DoCmd(&service->onRestart->cmdLine[i]); } free(service->onRestart->cmdLine); + service->onRestart->cmdLine = NULL; free(service->onRestart); return SERVICE_SUCCESS; } diff --git a/services/src/init_service_manager.c b/services/src/init_service_manager.c index 73927627e..adae7d45d 100644 --- a/services/src/init_service_manager.c +++ b/services/src/init_service_manager.c @@ -38,28 +38,41 @@ static Service* g_services = NULL; static int g_servicesCnt = 0; +#ifdef OHOS_SERVICE_DUMP void DumpAllServices() { + if (g_services == NULL) { + return; + } INIT_LOGD("Ready to dump all services:"); INIT_LOGD("total service number: %d", g_servicesCnt); for (int i = 0; i < g_servicesCnt; i++) { INIT_LOGD("\tservice name: [%s]", g_services[i].name); INIT_LOGD("\tpath :"); for (int j = 0; j < g_services[i].pathArgsCnt; j++) { - INIT_LOGD(" %s", g_services[i].pathArgs[j]); + if (g_services[i].pathArgs[j] != NULL) { + INIT_LOGD(" %s", g_services[i].pathArgs[j]); + } } } INIT_LOGD("Dump all services finished"); } +#endif void RegisterServices(Service* services, int servicesCnt) { + if (services == NULL) { + return; + } g_services = services; g_servicesCnt += servicesCnt; } static void ReleaseServiceMem(Service* curServ) { + if (curServ == NULL) { + return; + } if (curServ->pathArgs != NULL) { for (int i = 0; i < curServ->pathArgsCnt; ++i) { if (curServ->pathArgs[i] != NULL) { @@ -77,7 +90,6 @@ static void ReleaseServiceMem(Service* curServ) curServ->servPerm.caps = NULL; } curServ->servPerm.capsCnt = 0; - for (int i = 0; i < MAX_WRITEPID_FILES; i++) { if (curServ->writepidFiles[i] != NULL) { free(curServ->writepidFiles[i]); @@ -154,8 +166,8 @@ static cJSON* GetArrItem(const cJSON* fileRoot, int* arrSize, const char* arrNam static int GetWritepidStrings(const cJSON *curArrItem, Service *curServ) // writepid { int writepidCnt = 0; - cJSON* filedJ = GetArrItem(curArrItem, &writepidCnt, "writepid"); - if (writepidCnt <= 0) { // not item is ok. + cJSON *filedJ = GetArrItem(curArrItem, &writepidCnt, "writepid"); + if ((writepidCnt <= 0) || (filedJ == NULL)) { // not item is ok. return SERVICE_SUCCESS; } @@ -191,7 +203,7 @@ static int GetWritepidStrings(const cJSON *curArrItem, Service *curServ) static int GetGidOneItem(const cJSON *curArrItem, Service *curServ) // gid one item { - cJSON* filedJ = cJSON_GetObjectItem(curArrItem, GID_STR_IN_CFG); + cJSON *filedJ = cJSON_GetObjectItem(curArrItem, GID_STR_IN_CFG); if (filedJ == NULL) { return SERVICE_SUCCESS; // not found } @@ -203,7 +215,10 @@ static int GetGidOneItem(const cJSON *curArrItem, Service *curServ) // gi } if (cJSON_IsString(filedJ)) { - char* fieldStr = cJSON_GetStringValue(filedJ); + char *fieldStr = cJSON_GetStringValue(filedJ); + if (fieldStr == NULL) { + return SERVICE_FAILURE; + } gid_t gID = DecodeUid(fieldStr); if (gID == (gid_t)(-1)) { INIT_LOGE("GetGidOneItem, DecodeUid %s error.", fieldStr); @@ -230,8 +245,8 @@ static int GetGidOneItem(const cJSON *curArrItem, Service *curServ) // gi static int GetGidArray(const cJSON *curArrItem, Service *curServ) // gid array { int gIDCnt = 0; - cJSON* filedJ = GetArrItem(curArrItem, &gIDCnt, GID_STR_IN_CFG); // "gid" must have 1 item. - if (gIDCnt <= 0) { // not a array, but maybe a item? + cJSON *filedJ = GetArrItem(curArrItem, &gIDCnt, GID_STR_IN_CFG); // "gid" must have 1 item. + if ((gIDCnt <= 0) && (filedJ == NULL)) { // not a array, but maybe a item? return GetGidOneItem(curArrItem, curServ); } @@ -254,7 +269,7 @@ static int GetGidArray(const cJSON *curArrItem, Service *curServ) // gid INIT_LOGE("GetGidArray, parse item[%d] as string, error.", i); break; } - char* fieldStr = cJSON_GetStringValue(cJSON_GetArrayItem(filedJ, i)); + char *fieldStr = cJSON_GetStringValue(cJSON_GetArrayItem(filedJ, i)); gid_t gID = DecodeUid(fieldStr); if ((gID) == (gid_t)(-1)) { INIT_LOGE("GetGidArray, DecodeUid item[%d] error.", i); @@ -398,13 +413,16 @@ static int GetServiceNumber(const cJSON* curArrItem, Service* curServ, const cha static int GetUidStringNumber(const cJSON *curArrItem, Service *curServ) { - cJSON* filedJ = cJSON_GetObjectItem(curArrItem, UID_STR_IN_CFG); + cJSON *filedJ = cJSON_GetObjectItem(curArrItem, UID_STR_IN_CFG); if (filedJ == NULL) { return SERVICE_SUCCESS; // uID not found, but ok. } if (cJSON_IsString(filedJ)) { - char* fieldStr = cJSON_GetStringValue(filedJ); + char *fieldStr = cJSON_GetStringValue(filedJ); + if (fieldStr == NULL) { + return SERVICE_FAILURE; + } int uID = DecodeUid(fieldStr); if (uID < 0) { INIT_LOGE("GetUidStringNumber, DecodeUid %s error.", fieldStr); @@ -474,6 +492,7 @@ static int ParseServiceSocket(char **opt, const int optNum, struct ServiceSocket int ret = memcpy_s(sockopt->name, MAX_SOCK_NAME_LEN, opt[SERVICE_SOCK_NAME], MAX_SOCK_NAME_LEN - 1); if (ret != 0) { free(sockopt->name); + sockopt->name = NULL; return -1; } sockopt->next = NULL; @@ -542,8 +561,11 @@ static int GetServiceSocket(const cJSON* curArrItem, Service* curServ) static int GetServiceOnRestart(const cJSON* curArrItem, Service* curServ) { cJSON* filedJ = cJSON_GetObjectItem(curArrItem, "onrestart"); + if (filedJ == NULL) { + return SERVICE_SUCCESS; // onrestart not found, but ok. + } if (!cJSON_IsArray(filedJ)) { - return SERVICE_FAILURE; + return SERVICE_FAILURE; } int cmdCnt = cJSON_GetArraySize(filedJ); if (cmdCnt <= 0) { @@ -563,6 +585,7 @@ static int GetServiceOnRestart(const cJSON* curArrItem, Service* curServ) cJSON* cmdJ = cJSON_GetArrayItem(filedJ, i); if (!cJSON_IsString(cmdJ) || !cJSON_GetStringValue(cmdJ)) { free(curServ->onRestart->cmdLine); + curServ->onRestart->cmdLine = NULL; free(curServ->onRestart); curServ->onRestart = NULL; return SERVICE_FAILURE; @@ -618,7 +641,9 @@ void ParseAllServices(const cJSON* fileRoot) servArrSize, MAX_SERVICES_CNT_IN_FILE); return; } - + if ((g_servicesCnt + servArrSize) <= 0) { + return; + } Service* retServices = (Service*)realloc(g_services, sizeof(Service) * (g_servicesCnt + servArrSize)); if (retServices == NULL) { INIT_LOGE("ParseAllServices, realloc for %s arr failed! %d.", SERVICES_ARR_NAME_IN_JSON, servArrSize); @@ -663,15 +688,12 @@ void ParseAllServices(const cJSON* fileRoot) tmp[i].attribute & SERVICE_ATTR_DISABLED ? 1 : 0); } if (GetServiceSocket(curItem, &tmp[i]) != SERVICE_SUCCESS) { - INIT_LOGE("GetServiceSocket fail "); if (tmp[i].socketCfg != NULL) { FreeServiceSocket(tmp[i].socketCfg); tmp[i].socketCfg = NULL; } } - if (GetServiceOnRestart(curItem, &tmp[i]) != SERVICE_SUCCESS) { - INIT_LOGE("GetServiceOnRestart fail "); - } + GetServiceOnRestart(curItem, &tmp[i]); } // Increase service counter. RegisterServices(retServices, servArrSize); @@ -679,7 +701,7 @@ void ParseAllServices(const cJSON* fileRoot) static int FindServiceByName(const char* servName) { - if (servName == NULL) { + if ((servName == NULL) || (g_services == NULL)) { return -1; } @@ -726,6 +748,10 @@ void StopServiceByName(const char* servName) void StopAllServices() { + if (g_services == NULL) { + return; + } + for (int i = 0; i < g_servicesCnt; i++) { if (ServiceStop(&g_services[i]) != SERVICE_SUCCESS) { INIT_LOGE("StopAllServices, service %s stop failed!", g_services[i].name); @@ -735,6 +761,10 @@ void StopAllServices() void StopAllServicesBeforeReboot() { + if (g_services == NULL) { + return; + } + for (int i = 0; i < g_servicesCnt; i++) { g_services[i].attribute |= SERVICE_ATTR_INVALID; if (ServiceStop(&g_services[i]) != SERVICE_SUCCESS) { @@ -745,6 +775,10 @@ void StopAllServicesBeforeReboot() void ReapServiceByPID(int pid) { + if (g_services == NULL) { + return; + } + for (int i = 0; i < g_servicesCnt; i++) { if (g_services[i].pid == pid) { #ifdef OHOS_LITE diff --git a/services/src/init_service_socket.c b/services/src/init_service_socket.c index 630ff2e98..9e663adc3 100644 --- a/services/src/init_service_socket.c +++ b/services/src/init_service_socket.c @@ -24,9 +24,12 @@ #include #include #include "init_log.h" +#include "securec.h" #define HOS_SOCKET_DIR "/dev/unix/socket" #define HOS_SOCKET_ENV_PREFIX "OHOS_SOCKET_" +#define MAX_SOCKET_ENV_PREFIX_LEN 64 +#define MAX_SOCKET_FD_LEN 16 static int CreateSocket(struct ServiceSocket *sockopt) { @@ -46,8 +49,10 @@ static int CreateSocket(struct ServiceSocket *sockopt) struct sockaddr_un addr; bzero(&addr,sizeof(addr)); addr.sun_family = AF_UNIX; - snprintf(addr.sun_path, sizeof(addr.sun_path), HOS_SOCKET_DIR"/%s", - sockopt->name); + if (snprintf_s(addr.sun_path, sizeof(addr.sun_path), sizeof(addr.sun_path) - 1, HOS_SOCKET_DIR"/%s", + sockopt->name) < 0) { + return -1; + } if (access(addr.sun_path, F_OK)) { INIT_LOGE("%s already exist, remove it", addr.sun_path); if (unlink(addr.sun_path) != 0) { @@ -89,10 +94,18 @@ static int CreateSocket(struct ServiceSocket *sockopt) static int SetSocketEnv(int fd, char *name) { - char pubName[64] = {0}; - char val[16] = {0}; - snprintf(pubName, sizeof(pubName), HOS_SOCKET_ENV_PREFIX"%s", name); - snprintf(val, sizeof(val), "%d", fd); + if (name == NULL) { + return -1; + } + char pubName[MAX_SOCKET_ENV_PREFIX_LEN] = {0}; + char val[MAX_SOCKET_FD_LEN] = {0}; + if (snprintf_s(pubName, MAX_SOCKET_ENV_PREFIX_LEN, MAX_SOCKET_ENV_PREFIX_LEN - 1, + HOS_SOCKET_ENV_PREFIX"%s", name) < 0) { + return -1; + } + if (snprintf_s(val, MAX_SOCKET_FD_LEN, MAX_SOCKET_FD_LEN - 1, "%d", fd) < 0) { + return -1; + } int ret = setenv(pubName, val, 1); if (ret < 0) { INIT_LOGE("setenv fail %d ", errno); @@ -113,6 +126,9 @@ int DoCreateSocket(struct ServiceSocket *sockopt) if (fd < 0) { return -1; } + if (tmpSock->name == NULL) { + return -1; + } int ret = SetSocketEnv(fd, tmpSock->name); if (ret < 0) { return -1; diff --git a/services/src/init_signal_handler.c b/services/src/init_signal_handler.c index 2f2d10c7a..ffe8e55ea 100644 --- a/services/src/init_signal_handler.c +++ b/services/src/init_signal_handler.c @@ -77,12 +77,6 @@ static void SigHandler(int sig) StopAllServices(); break; } - case SIGINT: -#ifndef OHOS_LITE - StopParamService(); -#endif - exit(0); - break; default: INIT_LOGI("SigHandler, unsupported signal %d.", sig); break; @@ -103,7 +97,6 @@ void SignalInitModule() #else // L2 or above, use signal event in libuv uv_signal_t g_sigchldHandler; uv_signal_t g_sigtermHandler; -uv_signal_t g_sigintHandler; static void UVSignalHandler(uv_signal_t* handle, int signum) { @@ -114,7 +107,6 @@ void SignalInitModule() { int ret = uv_signal_init(uv_default_loop(), &g_sigchldHandler); ret |= uv_signal_init(uv_default_loop(), &g_sigtermHandler); - ret |= uv_signal_init(uv_default_loop(), &g_sigintHandler); if (ret != 0) { INIT_LOGW("initialize signal handler failed"); return; @@ -126,8 +118,5 @@ void SignalInitModule() if (uv_signal_start(&g_sigtermHandler, UVSignalHandler, SIGTERM) != 0) { INIT_LOGW("start SIGTERM handler failed"); } - if (uv_signal_start(&g_sigintHandler, UVSignalHandler, SIGINT) != 0) { - INIT_LOGW("start SIGTERM handler failed"); - } } #endif diff --git a/services/src/init_utils.c b/services/src/init_utils.c index 86ec49766..cea23f6b9 100644 --- a/services/src/init_utils.c +++ b/services/src/init_utils.c @@ -47,6 +47,9 @@ int DecodeUid(const char *name) { + if (name == NULL) { + return -1; + } bool digitFlag = true; for (unsigned int i = 0; i < strlen(name); ++i) { if (isalpha(name[i])) { @@ -63,7 +66,7 @@ int DecodeUid(const char *name) return result; } else { struct passwd *pwd = getpwnam(name); - if (!pwd) { + if (pwd == NULL) { return -1; } return pwd->pw_uid; @@ -72,6 +75,9 @@ int DecodeUid(const char *name) void CheckAndCreateDir(const char *fileName) { + if (fileName == NULL || *fileName == '\0') { + return; + } char *path = strndup(fileName, strrchr(fileName, '/') - fileName); if (path != NULL && access(path, F_OK) != 0) { mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); @@ -99,7 +105,7 @@ char* ReadFileToBuf(const char *configFile) INIT_LOGE("Open %s failed. err = %d", configFile, errno); break; } - buffer = (char*)malloc(fileStat.st_size + 1); + buffer = (char*)malloc((size_t)(fileStat.st_size + 1)); if (buffer == NULL) { INIT_LOGE("Failed to allocate memory for config file, err = %d", errno); break; @@ -127,17 +133,13 @@ int SplitString(char *srcPtr, char **dstPtr, int maxNum) } char *buf = NULL; dstPtr[0] = strtok_r(srcPtr, " ", &buf); - int i = 0; - while (dstPtr[i] != NULL && (i < maxNum)) { - i++; - dstPtr[i] = strtok_r(NULL, " ", &buf); - } - dstPtr[i] = "\0"; - int num = i; - for (int j = 0; j < num; j++) { - INIT_LOGI("dstPtr[%d] is %s ", j, dstPtr[j]); + int counter = 0; + while (dstPtr[counter] != NULL && (counter < maxNum)) { + counter++; + dstPtr[counter] = strtok_r(NULL, " ", &buf); } - return num; + dstPtr[counter] = NULL; + return counter; } void WaitForFile(const char *source, unsigned int maxCount) diff --git a/services/src/main.c b/services/src/main.c index 433e4f0ad..619eb911c 100644 --- a/services/src/main.c +++ b/services/src/main.c @@ -52,11 +52,11 @@ static void PrintSysInfo() } #ifdef OHOS_DEBUG -static long TimeDiffMs(struct timespec* tmBefore, struct timespec* tmAfter) +static long TimeDiffMs(const struct timespec* tmBefore, const struct timespec* tmAfter) { if (tmBefore != NULL && tmAfter != NULL) { long timeUsed = (tmAfter->tv_sec - tmBefore->tv_sec) * 1000 + // 1 s = 1000 ms - (tmAfter->tv_nsec - tmBefore->tv_nsec) / 1000000; // 1 ms = 1000000 ns + (tmAfter->tv_nsec - tmBefore->tv_nsec) / 1000000L; // 1 ms = 1000000 ns return timeUsed; } return -1; diff --git a/services/test/unittest/common/BUILD.gn b/services/test/unittest/common/BUILD.gn index 04b2edbc2..9b9c379ec 100644 --- a/services/test/unittest/common/BUILD.gn +++ b/services/test/unittest/common/BUILD.gn @@ -63,6 +63,7 @@ if (defined(ohos_lite)) { ] if (ohos_kernel_type == "liteos_a") { include_dirs += [ + "//kernel/liteos_a/syscall", "//base/startup/init_lite/interfaces/kits", "//base/startup/init_lite/initsync/include", ] diff --git a/services/test/unittest/common/cmd_func_test.cpp b/services/test/unittest/common/cmd_func_test.cpp index 7e3cc721b..b1c8b0525 100644 --- a/services/test/unittest/common/cmd_func_test.cpp +++ b/services/test/unittest/common/cmd_func_test.cpp @@ -522,7 +522,7 @@ static char* ReadFileToBuf() break; } - buffer = (char*)malloc(fileStat.st_size + 1); + buffer = (char *)malloc((size_t)fileStat.st_size + 1); if (buffer == nullptr) { break; } @@ -895,11 +895,12 @@ HWTEST_F(StartupInitUTest, cmdFuncDoLoadCfgTest_003, TestSize.Level1) } do { - size = fread(buf, 1, CAT_BUF_SIZE, fd); + size = fread(buf, 1, CAT_BUF_SIZE - 1, fd); if (size < 0) { EXPECT_TRUE(size >= 0); break; } + buf[CAT_BUF_SIZE - 1] = 0; if (strstr(buf, "zpfs") != nullptr) { hasZpfs = true; break; -- Gitee From bc9685c15812288ef2593cb776b36ce2e2707e4b Mon Sep 17 00:00:00 2001 From: zhong_ning Date: Wed, 21 Jul 2021 10:10:28 +0800 Subject: [PATCH 2/3] init : fix code style Signed-off-by: zhong_ning --- services/cmds/reboot/init_cmd_reboot.c | 10 ++++++---- services/cmds/service_control/service_control.c | 10 +++++----- services/src/init_cmds.c | 7 +++---- services/src/init_service_manager.c | 2 +- services/src/init_service_socket.c | 4 ++-- services/test/unittest/common/cmd_func_test.cpp | 2 +- 6 files changed, 18 insertions(+), 17 deletions(-) diff --git a/services/cmds/reboot/init_cmd_reboot.c b/services/cmds/reboot/init_cmd_reboot.c index e43bdb154..6e032e7fe 100755 --- a/services/cmds/reboot/init_cmd_reboot.c +++ b/services/cmds/reboot/init_cmd_reboot.c @@ -18,20 +18,22 @@ #include #include "init_reboot.h" +#define REBOOT_CMD_NUMBER 2 + int main(int argc, char* argv[]) { - if (argc > 2) { + if (argc > REBOOT_CMD_NUMBER) { printf("usage: reboot shutdown\n reboot updater\n reboot updater[:options]\n reboot\n"); return 0; } - if (argc == 2 && strcmp(argv[1], "shutdown") != 0 && + if (argc == REBOOT_CMD_NUMBER && strcmp(argv[1], "shutdown") != 0 && strcmp(argv[1], "updater") != 0 && - strncmp(argv[1], "updater:", strlen("updater:")) != 0 ) { + strncmp(argv[1], "updater:", strlen("updater:")) != 0) { printf("usage: reboot shutdown\n reboot updater\n reboot updater[:options]\n reboot\n"); return 0; } int ret = 0; - if (argc == 2) { + if (argc == REBOOT_CMD_NUMBER) { ret = DoReboot(argv[1]); } else { ret = DoReboot("NoArgument"); diff --git a/services/cmds/service_control/service_control.c b/services/cmds/service_control/service_control.c index 1d5872f59..320e15553 100755 --- a/services/cmds/service_control/service_control.c +++ b/services/cmds/service_control/service_control.c @@ -15,8 +15,8 @@ #include #include -#include "sys_param.h" #include "securec.h" +#include "sys_param.h" #define SERVICE_START_NUMBER 2 #define SERVICE_CONTROL_NUMBER 3 @@ -71,13 +71,13 @@ int main(int argc, char** argv) char serviceCtl[SERVICE_CONTROL_MAX_SIZE]; if (strcmp(argv[0], "start_service") == 0) { if (strncpy_s(serviceCtl, sizeof(serviceCtl), "ohos.ctl.start", sizeof(serviceCtl) - 1) != EOK) { - printf("strncpy_s failed.\n"); - return -1; + printf("strncpy_s failed.\n"); + return -1; } } else if (strcmp(argv[0], "stop_service") == 0) { if (strncpy_s(serviceCtl, sizeof(serviceCtl), "ohos.ctl.stop", sizeof(serviceCtl) - 1) != EOK) { - printf("strncpy_s failed.\n"); - return -1; + printf("strncpy_s failed.\n"); + return -1; } } else { ServiceControl(argc, argv); diff --git a/services/src/init_cmds.c b/services/src/init_cmds.c index 5799bf86d..d11e0ec35 100644 --- a/services/src/init_cmds.c +++ b/services/src/init_cmds.c @@ -145,7 +145,7 @@ int GetParamValue(char *symValue, char *paramValue, unsigned int paramLen) // For ite ohos, do not support parameter operation. just do string copy inline int GetParamValue(char *symValue, char *paramValue, unsigned int paramLen) { - return strncpy_s(paramValue, paramLen, symValue, strlen(symValue)) == EOK ? 0 : -1; + return (strncpy_s(paramValue, paramLen, symValue, strlen(symValue)) == EOK) ? 0 : -1; } #endif @@ -164,7 +164,6 @@ struct CmdArgs* GetCmd(const char *cmdContent, const char *delim, int argsCount) char tmpCmd[MAX_BUFFER]; size_t cmdLength = strlen(cmdContent); - if (cmdLength > MAX_BUFFER - 1) { INIT_LOGE("command line is too larget, should not bigger than %d. ignore...\n", MAX_BUFFER); FreeCmd(&ctx); @@ -201,7 +200,7 @@ struct CmdArgs* GetCmd(const char *cmdContent, const char *delim, int argsCount) int index = ctx->argc; while (token != NULL) { // Too more arguments, treat rest of data as one argument - if (index == (argsCount -1)) { + if (index == (argsCount - 1)) { break; } *token = '\0'; // replace it with '\0'; @@ -834,7 +833,7 @@ static void DoSetrlimit(const char *cmdContent) struct rlimit limit; limit.rlim_cur = (rlim_t)atoi(ctx->argv[1]); - limit.rlim_max = (rlim_t )atoi(ctx->argv[rlimMaxPos]); + limit.rlim_max = (rlim_t)atoi(ctx->argv[rlimMaxPos]); int rcs = -1; for (unsigned int i = 0 ; i < sizeof(resource) / sizeof(char*); ++i) { if (strcmp(ctx->argv[0], resource[i]) == 0) { diff --git a/services/src/init_service_manager.c b/services/src/init_service_manager.c index adae7d45d..53b14e99e 100644 --- a/services/src/init_service_manager.c +++ b/services/src/init_service_manager.c @@ -693,7 +693,7 @@ void ParseAllServices(const cJSON* fileRoot) tmp[i].socketCfg = NULL; } } - GetServiceOnRestart(curItem, &tmp[i]); + (void)GetServiceOnRestart(curItem, &tmp[i]); } // Increase service counter. RegisterServices(retServices, servArrSize); diff --git a/services/src/init_service_socket.c b/services/src/init_service_socket.c index 9e663adc3..18fd117eb 100644 --- a/services/src/init_service_socket.c +++ b/services/src/init_service_socket.c @@ -50,7 +50,7 @@ static int CreateSocket(struct ServiceSocket *sockopt) bzero(&addr,sizeof(addr)); addr.sun_family = AF_UNIX; if (snprintf_s(addr.sun_path, sizeof(addr.sun_path), sizeof(addr.sun_path) - 1, HOS_SOCKET_DIR"/%s", - sockopt->name) < 0) { + sockopt->name) < 0) { return -1; } if (access(addr.sun_path, F_OK)) { @@ -100,7 +100,7 @@ static int SetSocketEnv(int fd, char *name) char pubName[MAX_SOCKET_ENV_PREFIX_LEN] = {0}; char val[MAX_SOCKET_FD_LEN] = {0}; if (snprintf_s(pubName, MAX_SOCKET_ENV_PREFIX_LEN, MAX_SOCKET_ENV_PREFIX_LEN - 1, - HOS_SOCKET_ENV_PREFIX"%s", name) < 0) { + HOS_SOCKET_ENV_PREFIX"%s", name) < 0) { return -1; } if (snprintf_s(val, MAX_SOCKET_FD_LEN, MAX_SOCKET_FD_LEN - 1, "%d", fd) < 0) { diff --git a/services/test/unittest/common/cmd_func_test.cpp b/services/test/unittest/common/cmd_func_test.cpp index b1c8b0525..8189e0ede 100644 --- a/services/test/unittest/common/cmd_func_test.cpp +++ b/services/test/unittest/common/cmd_func_test.cpp @@ -522,7 +522,7 @@ static char* ReadFileToBuf() break; } - buffer = (char *)malloc((size_t)fileStat.st_size + 1); + buffer = static_castmalloc((size_t)fileStat.st_size + 1); if (buffer == nullptr) { break; } -- Gitee From 417facdc05c54953708432d12658b477f260f7a7 Mon Sep 17 00:00:00 2001 From: zhong_ning Date: Wed, 21 Jul 2021 10:31:02 +0800 Subject: [PATCH 3/3] fix code style Signed-off-by: zhong_ning --- services/test/unittest/common/cmd_func_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/test/unittest/common/cmd_func_test.cpp b/services/test/unittest/common/cmd_func_test.cpp index 8189e0ede..7121262dc 100644 --- a/services/test/unittest/common/cmd_func_test.cpp +++ b/services/test/unittest/common/cmd_func_test.cpp @@ -522,7 +522,7 @@ static char* ReadFileToBuf() break; } - buffer = static_castmalloc((size_t)fileStat.st_size + 1); + buffer = static_cast(malloc((size_t)fileStat.st_size + 1)); if (buffer == nullptr) { break; } -- Gitee