提交 d823b120 编写于 作者: C cheng_jinsong 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/startup_init_lite into slot

Signed-off-by: Ncheng_jinsong <chengjinsong2@huawei.com>
......@@ -18,6 +18,7 @@
#endif
#include "param_comm.h"
#include "securec.h"
#include "sysparam_errno.h"
#ifdef __cplusplus
#if __cplusplus
......@@ -28,7 +29,7 @@ extern "C" {
int AclGetDevUdid(char *udid, int size)
{
if (udid == nullptr || size < UDID_LEN) {
return -1;
return SYSPARAM_INVALID_INPUT;
}
(void)memset_s(udid, size, 0, size);
#ifdef PARAM_FEATURE_DEVICEINFO
......
......@@ -23,6 +23,7 @@
#include "string_ex.h"
#include "system_ability_definition.h"
#include "param_comm.h"
#include "sysparam_errno.h"
using std::u16string;
namespace OHOS {
......@@ -35,15 +36,15 @@ REGISTER_SYSTEM_ABILITY_BY_ID(DeviceInfoService, SYSPARAM_DEVICE_SERVICE_ID, tru
int32_t DeviceInfoStub::OnRemoteRequest(uint32_t code,
MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
std::u16string myDescripter = IDeviceInfo::GetDescriptor();
std::u16string remoteDescripter = data.ReadInterfaceToken();
DINFO_CHECK(myDescripter == remoteDescripter, return ERR_INVALD_DESC, "Invalid remoteDescripter");
std::u16string myDescriptor = IDeviceInfo::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
DINFO_CHECK(myDescriptor == remoteDescriptor, return ERR_FAIL, "Invalid remoteDescriptor");
int ret = ERR_FAIL;
switch (code) {
case COMMAND_GET_UDID: {
if (!CheckPermission(data, PERMISSION_UDID)) {
return ERR_FAIL;
return SYSPARAM_PERMISSION_DENIED;
}
char localDeviceInfo[UDID_LEN] = {0};
ret = GetDevUdid_(localDeviceInfo, UDID_LEN);
......@@ -53,7 +54,7 @@ int32_t DeviceInfoStub::OnRemoteRequest(uint32_t code,
}
case COMMAND_GET_SERIAL_ID: {
if (!CheckPermission(data, PERMISSION_UDID)) {
return ERR_FAIL;
return SYSPARAM_PERMISSION_DENIED;
}
const char *serialNumber = GetSerial_();
DINFO_CHECK(serialNumber != nullptr, break, "Failed to get serialNumber");
......
......@@ -33,7 +33,6 @@ public:
static constexpr int COMMAND_GET_UDID = MIN_TRANSACTION_ID + 0;
static constexpr int COMMAND_GET_SERIAL_ID = MIN_TRANSACTION_ID + 1;
static constexpr int ERR_FAIL = -1;
static constexpr int ERR_INVALD_DESC = -1;
const std::string PERMISSION_UDID = "ohos.permission.sec.ACCESS_UDID";
};
} // namespace device_info
......
......@@ -123,7 +123,6 @@ static int SendCmdMessage(const CmdAgent *agent, uint16_t type, const char *cmd,
BEGET_LOGE("[control_fd] Invalid parameter");
return -1;
}
int ret = 0;
BufferHandle handle = NULL;
uint32_t bufferSize = sizeof(CmdMessage) + strlen(cmd) + PTY_PATH_SIZE + 1;
handle = LE_CreateBuffer(LE_GetDefaultLoop(), bufferSize);
......@@ -132,7 +131,7 @@ static int SendCmdMessage(const CmdAgent *agent, uint16_t type, const char *cmd,
CmdMessage *message = (CmdMessage *)buff;
message->msgSize = bufferSize;
message->type = type;
ret = strcpy_s(message->ptyName, PTY_PATH_SIZE - 1, ptyName);
int ret = strcpy_s(message->ptyName, PTY_PATH_SIZE - 1, ptyName);
BEGET_ERROR_CHECK(ret == 0, LE_FreeBuffer(LE_GetDefaultLoop(), agent->task, handle);
return -1, "[control_fd] Failed to copy pty name %s", ptyName);
ret = strcpy_s(message->cmd, bufferSize - sizeof(CmdMessage) - PTY_PATH_SIZE, cmd);
......@@ -198,5 +197,6 @@ void CmdClientInit(const char *socketPath, uint16_t type, const char *cmd)
return;
}
LE_RunLoop(LE_GetDefaultLoop());
LE_CloseLoop(LE_GetDefaultLoop());
BEGET_LOGI("Cmd Client exit ");
}
......@@ -42,7 +42,7 @@ static void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint3
// parse msg to exec
CmdMessage *msg = (CmdMessage *)buffer;
if ((msg->type < 0) || (msg->type >= ACTION_MAX) || (msg->cmd[0] == '\0') || (msg->ptyName[0] == '\0')) {
if ((msg->type >= ACTION_MAX) || (msg->cmd[0] == '\0') || (msg->ptyName[0] == '\0')) {
BEGET_LOGE("[control_fd] Received msg is invaild");
return;
}
......@@ -61,7 +61,9 @@ static void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint3
(void)dup2(fd, STDOUT_FILENO);
(void)dup2(fd, STDERR_FILENO); // Redirect fd to 0, 1, 2
(void)close(fd);
g_controlFdFunc(msg->type, msg->cmd, NULL);
if (g_controlFdFunc != NULL) {
g_controlFdFunc(msg->type, msg->cmd, NULL);
}
exit(0);
} else if (agent->pid < 0) {
BEGET_LOGE("[control_fd] Failed fork service");
......
......@@ -50,6 +50,7 @@ static unsigned int ConvertFlags(char *flagBuffer)
{"check", FS_MANAGER_CHECK},
{"wait", FS_MANAGER_WAIT},
{"required", FS_MANAGER_REQUIRED},
{"nofail", FS_MANAGER_NOFAIL},
};
BEGET_CHECK_RETURN_VALUE(flagBuffer != NULL && *flagBuffer != '\0', 0); // No valid flags.
......@@ -328,7 +329,7 @@ int GetBlockDeviceByMountPoint(const char *mountPoint, const Fstab *fstab, char
}
FstabItem *item = FindFstabItemForMountPoint(*fstab, mountPoint);
if (item == NULL) {
BEGET_LOGE("Failed to get fstab item from point \" %s \"", mountPoint);
BEGET_LOGE("Failed to get fstab item from mount point \" %s \"", mountPoint);
return -1;
}
if (strncpy_s(deviceName, nameLen, item->deviceName, strlen(item->deviceName)) != 0) {
......@@ -398,7 +399,6 @@ static unsigned long ParseDefaultMountFlag(const char *str)
static bool IsFscryptOption(const char *option)
{
BEGET_LOGI("IsFscryptOption start");
if (!option) {
return false;
}
......@@ -433,7 +433,7 @@ int LoadFscryptPolicy(char *buf, size_t size)
BEGET_LOGE("LoadFscryptPolicy:buf or fscrypt policy is empty");
return -ENOMEM;
}
if (size <= 0) {
if (size == 0) {
BEGET_LOGE("LoadFscryptPloicy:size is invalid");
return -EINVAL;
}
......@@ -510,7 +510,7 @@ int GetBlockDevicePath(const char *partName, char *path, size_t size)
BEGET_CHECK_RETURN_VALUE(fstab != NULL, -1);
int ret = GetBlockDeviceByMountPoint(partName, fstab, path, size);
BEGET_INFO_CHECK(ret == 0, ret = GetBlockDeviceByName(partName, fstab, path, size),
"mount point not found, try to get it by device name");
"Mount point not found, try to get path by device name.");
ReleaseFstab(fstab);
return ret;
}
......@@ -533,9 +533,8 @@ static int ParseRequiredMountInfo(const char *item, Fstab *fstab)
BEGET_CHECK(!(item == NULL || *item == '\0' || fstab == NULL), return -1);
char *p = NULL;
const char *q = item;
if ((p = strstr(item, "=")) != NULL) {
q = item + strlen(OHOS_REQUIRED_MOUNT_PREFIX); // Get partition name
const char *q = item + strlen(OHOS_REQUIRED_MOUNT_PREFIX); // Get partition name
BEGET_CHECK(!(q == NULL || *q == '\0' || (p - q) <= 0), return -1);
BEGET_ERROR_CHECK(strncpy_s(partName, NAME_SIZE -1, q, p - q) == EOK,
return -1, "Failed to copy required partition name");
......
......@@ -42,11 +42,10 @@ const off_t PARTITION_ACTIVE_SLOT_SIZE = 4;
bool IsSupportedFilesystem(const char *fsType)
{
static const char *supportedFilesystem[] = {"ext4", "f2fs", NULL};
bool supported = false;
int index = 0;
if (fsType != NULL) {
static const char *supportedFilesystem[] = {"ext4", "f2fs", NULL};
int index = 0;
while (supportedFilesystem[index] != NULL) {
if (strcmp(supportedFilesystem[index++], fsType) == 0) {
supported = true;
......@@ -62,6 +61,7 @@ static int ExecCommand(int argc, char **argv)
if (argc == 0 || argv == NULL || argv[0] == NULL) {
return -1;
}
BEGET_LOGI("Execute %s begin", argv[0]);
pid_t pid = fork();
if (pid < 0) {
BEGET_LOGE("Fork new process to format failed: %d", errno);
......@@ -76,6 +76,7 @@ static int ExecCommand(int argc, char **argv)
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
BEGET_LOGE("Command %s failed with status %d", argv[0], WEXITSTATUS(status));
}
BEGET_LOGI("Execute %s end", argv[0]);
return WEXITSTATUS(status);
}
......@@ -90,8 +91,8 @@ int DoFormat(const char *devPath, const char *fsType)
return -1;
}
int ret = 0;
char blockSizeBuffer[BLOCK_SIZE_BUFFER] = {0};
if (strcmp(fsType, "ext4") == 0) {
char blockSizeBuffer[BLOCK_SIZE_BUFFER] = {0};
const unsigned int blockSize = 4096;
if (snprintf_s(blockSizeBuffer, BLOCK_SIZE_BUFFER, BLOCK_SIZE_BUFFER - 1, "%u", blockSize) == -1) {
BEGET_LOGE("Failed to build block size buffer");
......@@ -171,7 +172,7 @@ static int DoResizeF2fs(const char* device, const unsigned long long size)
}
int ret = 0;
if (size <= 0) {
if (size == 0) {
char *cmd[] = {
file, (char *)device, NULL
};
......@@ -193,7 +194,6 @@ static int DoResizeF2fs(const char* device, const unsigned long long size)
char **argv = (char **)cmd;
ret = ExecCommand(argc, argv);
}
BEGET_LOGI("resize.f2fs is ending.");
return ret;
}
......@@ -210,7 +210,6 @@ static int DoFsckF2fs(const char* device)
};
int argc = ARRAY_LENGTH(cmd);
char **argv = (char **)cmd;
BEGET_LOGI("fsck.f2fs is ending.");
return ExecCommand(argc, argv);
}
......@@ -223,7 +222,7 @@ static int DoResizeExt(const char* device, const unsigned long long size)
}
int ret = 0;
if (size <= 0) {
if (size == 0) {
char *cmd[] = {
file, "-f", (char *)device, NULL
};
......@@ -243,7 +242,6 @@ static int DoResizeExt(const char* device, const unsigned long long size)
char **argv = (char **)cmd;
ret = ExecCommand(argc, argv);
}
BEGET_LOGI("resize2fs is ending.");
return ret;
}
......@@ -260,7 +258,6 @@ static int DoFsckExt(const char* device)
};
int argc = ARRAY_LENGTH(cmd);
char **argv = (char **)cmd;
BEGET_LOGI("e2fsck is ending.");
return ExecCommand(argc, argv);
}
......@@ -288,15 +285,8 @@ static int Mount(const char *source, const char *target, const char *fsType,
}
}
errno = 0;
while ((rc = mount(source, target, fsType, flags, data)) != 0) {
if (errno == EAGAIN) {
BEGET_LOGE("Mount %s to %s failed. try again", source, target);
continue;
}
if (errno == EBUSY) {
rc = 0;
}
break;
if ((rc = mount(source, target, fsType, flags, data)) != 0) {
BEGET_WARNING_CHECK(errno != EBUSY, rc = 0, "Mount %s to %s busy, ignore", source, target);
}
return rc;
}
......@@ -407,7 +397,12 @@ int MountOneItem(FstabItem *item)
int rc = Mount(item->deviceName, item->mountPoint, item->fsType, mountFlags, fsSpecificData);
if (rc != 0) {
BEGET_LOGE("Mount %s to %s failed %d", item->deviceName, item->mountPoint, errno);
if (FM_MANAGER_NOFAIL_ENABLED(item->fsManagerFlags)) {
BEGET_LOGE("Mount no fail device %s to %s failed, err = %d", item->deviceName, item->mountPoint, errno);
} else {
BEGET_LOGW("Mount %s to %s failed, err = %d. Ignore failure", item->deviceName, item->mountPoint, errno);
rc = 0;
}
} else {
BEGET_LOGI("Mount %s to %s successful", item->deviceName, item->mountPoint);
}
......
......@@ -29,6 +29,7 @@ extern "C" {
#define FS_MANAGER_CHECK 0x00000001
#define FS_MANAGER_WAIT 0x00000002
#define FS_MANAGER_REQUIRED 0x00000004
#define FS_MANAGER_NOFAIL 0x00000008
#define NAME_SIZE 32
#define MAX_SLOT 2
......@@ -38,6 +39,7 @@ extern "C" {
#define FM_MANAGER_CHECK_ENABLED(fsMgrFlags) FS_MANAGER_FLAGS_ENABLED((fsMgrFlags), CHECK)
#define FM_MANAGER_WAIT_ENABLED(fsMgrFlags) FS_MANAGER_FLAGS_ENABLED((fsMgrFlags), WAIT)
#define FM_MANAGER_REQUIRED_ENABLED(fsMgrFlags) FS_MANAGER_FLAGS_ENABLED((fsMgrFlags), REQUIRED)
#define FM_MANAGER_NOFAIL_ENABLED(fsMgrFlags) FS_MANAGER_FLAGS_ENABLED((fsMgrFlags), NOFAIL)
typedef enum MountStatus {
MOUNT_ERROR = -1,
......
......@@ -20,8 +20,8 @@
namespace OHOS {
namespace system {
int GetStringParameter(const std::string key, std::string &value, const std::string def = "");
int GetIntParameter(const std::string key, int def);
int GetStringParameter(const std::string &key, std::string &value, const std::string def = "");
int GetIntParameter(const std::string &key, int def);
}
}
......
......@@ -28,6 +28,13 @@ enum OHOSStartUpSysParamErrorCode {
EC_FAILURE = -1, /* Execution failed */
EC_INVALID = -9, /* Invalid argument */
EC_SYSTEM_ERR = -10, /* system error */
SYSPARAM_INVALID_INPUT = -401, /*Input parameter is missing or invalid*/
SYSPARAM_NOT_FOUND = -14700101, /*System parameter can not be found.*/
SYSPARAM_INVALID_VALUE = -14700102, /*System parameter value is invalid*/
SYSPARAM_PERMISSION_DENIED = -14700103, /*System permission operation permission denied*/
SYSPARAM_SYSTEM_ERROR = -14700104, /* System internal error including out of memory, deadlock etc.*/
SYSPARAM_WAIT_TIMEOUT = -14700105, /* System wait parameter value change time out.*/
};
#ifdef __cplusplus
......
......@@ -42,6 +42,7 @@ void PluginExecCmdByName(const char *name, const char *cmdContent);
void PluginExecCmdByCmdIndex(int index, const char *cmdContent);
int PluginExecCmd(const char *name, int argc, const char **argv);
const char *PluginGetCmdIndex(const char *cmdStr, int *index);
const char *GetPluginCmdNameByIndex(int index);
int AddCmdExecutor(const char *cmdName, CmdExecutor execCmd);
......
......@@ -81,7 +81,7 @@ typedef struct tagMODULE_ITEM {
void *handle;
} MODULE_ITEM;
static void moduleDestroy(ListNode *node)
static void ModuleDestroy(ListNode *node)
{
MODULE_ITEM *module;
......@@ -95,7 +95,7 @@ static void moduleDestroy(ListNode *node)
static MODULE_INSTALL_ARGS *currentInstallArgs = NULL;
static void *moduleInstall(MODULE_ITEM *module, int argc, const char *argv[])
static void *ModuleInstall(MODULE_ITEM *module, int argc, const char *argv[])
{
void *handle;
char path[PATH_MAX];
......@@ -115,14 +115,21 @@ static void *moduleInstall(MODULE_ITEM *module, int argc, const char *argv[])
return NULL;
}
}
BEGET_LOGV("moduleInstall path %s", path);
BEGET_LOGV("Module install path %s", path);
currentInstallArgs = &(module->moduleMgr->installArgs);
handle = dlopen(path, RTLD_LAZY | RTLD_GLOBAL);
currentInstallArgs = NULL;
BEGET_CHECK_ONLY_ELOG(handle != NULL, "moduleInstall path %s fail %d", path, errno);
BEGET_CHECK_ONLY_ELOG(handle != NULL, "ModuleInstall path %s fail %d", path, errno);
return handle;
}
static int ModuleCompare(ListNode *node, void *data)
{
MODULE_ITEM *module = (MODULE_ITEM *)node;
return strcmp(module->name, (char *)data);
}
/*
* 用于扫描安装指定目录下所有的插件。
*/
......@@ -133,6 +140,10 @@ int ModuleMgrInstall(MODULE_MGR *moduleMgr, const char *moduleName,
BEGET_LOGV("ModuleMgrInstall moduleName %s", moduleName);
// Get module manager
BEGET_CHECK(!(moduleMgr == NULL || moduleName == NULL), return -1);
module = (MODULE_ITEM *)OH_ListFind(&(moduleMgr->modules), (void *)moduleName, ModuleCompare);
BEGET_ERROR_CHECK(module == NULL, return 0, "%s module already exists", moduleName);
// Create module item
module = (MODULE_ITEM *)malloc(sizeof(MODULE_ITEM));
BEGET_CHECK(module != NULL, return -1);
......@@ -142,15 +153,15 @@ int ModuleMgrInstall(MODULE_MGR *moduleMgr, const char *moduleName,
module->name = strdup(moduleName);
if (module->name == NULL) {
moduleDestroy((ListNode *)module);
ModuleDestroy((ListNode *)module);
return -1;
}
// Install
module->handle = moduleInstall(module, argc, argv);
module->handle = ModuleInstall(module, argc, argv);
if (module->handle == NULL) {
BEGET_LOGE("Failed to install module %s", moduleName);
moduleDestroy((ListNode *)module);
ModuleDestroy((ListNode *)module);
return -1;
}
......@@ -165,7 +176,7 @@ const MODULE_INSTALL_ARGS *ModuleMgrGetArgs(void)
return currentInstallArgs;
}
static int stringEndsWith(const char *srcStr, const char *endStr)
static int StringEndsWith(const char *srcStr, const char *endStr)
{
int srcStrLen = strlen(srcStr);
int endStrLen = strlen(endStr);
......@@ -177,10 +188,9 @@ static int stringEndsWith(const char *srcStr, const char *endStr)
return -1;
}
static void scanModules(MODULE_MGR *moduleMgr, const char *path)
static void ScanModules(MODULE_MGR *moduleMgr, const char *path)
{
int end;
int ret;
DIR *dir;
struct dirent *file;
......@@ -197,17 +207,17 @@ static void scanModules(MODULE_MGR *moduleMgr, const char *path)
}
// Must be ended with MODULE_SUFFIX_D
end = stringEndsWith(file->d_name, MODULE_SUFFIX_D);
end = StringEndsWith(file->d_name, MODULE_SUFFIX_D);
if (end <= 0) {
continue;
}
file->d_name[end] = '\0';
BEGET_LOGV("scanModules module %s", file->d_name);
BEGET_LOGV("Scan module with name %s", file->d_name);
if (strncmp(file->d_name, "lib", strlen("lib")) == 0) {
ret = ModuleMgrInstall(moduleMgr, file->d_name + strlen("lib"), 0, NULL);
ModuleMgrInstall(moduleMgr, file->d_name + strlen("lib"), 0, NULL);
} else {
ret = ModuleMgrInstall(moduleMgr, file->d_name, 0, NULL);
ModuleMgrInstall(moduleMgr, file->d_name, 0, NULL);
}
}
......@@ -226,18 +236,18 @@ MODULE_MGR *ModuleMgrScan(const char *modulePath)
BEGET_CHECK(moduleMgr != NULL, return NULL);
if (modulePath[0] == '/') {
scanModules(moduleMgr, modulePath);
ScanModules(moduleMgr, modulePath);
} else if (InUpdaterMode() == 1) {
BEGET_CHECK(snprintf_s(path, sizeof(path), sizeof(path) - 1,
"/%s/%s", MODULE_LIB_NAME, modulePath) > 0, return NULL);
scanModules(moduleMgr, path);
ScanModules(moduleMgr, path);
} else {
BEGET_CHECK(snprintf_s(path, sizeof(path), sizeof(path) - 1,
"%s/%s", MODULE_LIB_NAME, modulePath) > 0, return NULL);
CfgFiles *files = GetCfgFiles(path);
for (int i = MAX_CFG_POLICY_DIRS_CNT - 1; files && i >= 0; i--) {
if (files->paths[i]) {
scanModules(moduleMgr, files->paths[i]);
ScanModules(moduleMgr, files->paths[i]);
}
}
FreeCfgFiles(files);
......@@ -245,13 +255,6 @@ MODULE_MGR *ModuleMgrScan(const char *modulePath)
return moduleMgr;
}
static int moduleCompare(ListNode *node, void *data)
{
MODULE_ITEM *module = (MODULE_ITEM *)node;
return strcmp(module->name, (char *)data);
}
/*
* 卸载指定插件。
*/
......@@ -261,18 +264,18 @@ void ModuleMgrUninstall(MODULE_MGR *moduleMgr, const char *name)
BEGET_CHECK(moduleMgr != NULL, return);
// Uninstall all modules if no name specified
if (name == NULL) {
OH_ListRemoveAll(&(moduleMgr->modules), moduleDestroy);
OH_ListRemoveAll(&(moduleMgr->modules), ModuleDestroy);
return;
}
BEGET_LOGV("ModuleMgrUninstall moduleName %s", name);
// Find module by name
module = (MODULE_ITEM *)OH_ListFind(&(moduleMgr->modules), (void *)name, moduleCompare);
module = (MODULE_ITEM *)OH_ListFind(&(moduleMgr->modules), (void *)name, ModuleCompare);
BEGET_ERROR_CHECK(module != NULL, return, "Can not find module %s", name);
// Remove from the list
OH_ListRemove((ListNode *)module);
// Destroy the module
moduleDestroy((ListNode *)module);
ModuleDestroy((ListNode *)module);
}
int ModuleMgrGetCnt(const MODULE_MGR *moduleMgr)
......@@ -286,7 +289,7 @@ typedef struct tagMODULE_TRAVERSAL_ARGS {
OhosModuleTraversal traversal;
} MODULE_TRAVERSAL_ARGS;
static int moduleTraversalProc(ListNode *node, void *cookie)
static int ModuleTraversalProc(ListNode *node, void *cookie)
{
MODULE_ITEM *module;
MODULE_TRAVERSAL_ARGS *args;
......@@ -321,5 +324,5 @@ void ModuleMgrTraversal(const MODULE_MGR *moduleMgr, void *cookie, OhosModuleTra
args.cookie = cookie;
args.traversal = traversal;
OH_ListTraversal((ListNode *)(&(moduleMgr->modules)), (void *)(&args), moduleTraversalProc, 0);
OH_ListTraversal((ListNode *)(&(moduleMgr->modules)), (void *)(&args), ModuleTraversalProc, 0);
}
......@@ -47,16 +47,8 @@ static int DoReboot_(const char *option)
ret = snprintf_s(value, MAX_REBOOT_OPTION_SIZE, MAX_REBOOT_OPTION_SIZE - 1, "reboot,%s", option);
BEGET_ERROR_CHECK(ret >= 0, return -1, "Failed to copy boot option \" %s \"", option);
if (strcmp(option, DEVICE_CMD_SUSPEND) == 0) {
ret = SystemSetParameter(STARTUP_DEVICE_CTL, DEVICE_CMD_STOP);
BEGET_ERROR_CHECK(ret == 0, return -1, "Failed to set stop param");
} else if (strcmp(option, DEVICE_CMD_FREEZE) == 0) {
ret = SystemSetParameter(STARTUP_DEVICE_CTL, DEVICE_CMD_STOP);
BEGET_ERROR_CHECK(ret == 0, return -1, "Failed to set stop param");
} else {
ret = SystemSetParameter(STARTUP_DEVICE_CTL, DEVICE_CMD_STOP);
BEGET_ERROR_CHECK(ret == 0, return -1, "Failed to set stop param");
}
ret = SystemSetParameter(STARTUP_DEVICE_CTL, DEVICE_CMD_STOP);
BEGET_ERROR_CHECK(ret == 0, return -1, "Failed to set stop param");
ret = SystemSetParameter(DOREBOOT_PARAM, value);
BEGET_ERROR_CHECK(ret == 0, return -1, "Set parameter to trigger reboot command \" %s \" failed", value);
return 0;
......@@ -65,7 +57,11 @@ static int DoReboot_(const char *option)
int DoReboot(const char *option)
{
// check if param set ok
#ifndef STARTUP_INIT_TEST
const int maxCount = 10;
#else
const int maxCount = 1;
#endif
int count = 0;
DoReboot_(option);
while (count < maxCount) {
......
......@@ -16,7 +16,10 @@ import("//build/ohos.gni")
config("exported_header_files") {
visibility = [ ":*" ]
include_dirs = [ "//base/startup/init/interfaces/innerkits/sandbox/include" ]
include_dirs = [
"//base/startup/init/interfaces/innerkits/sandbox/include",
"//base/customization/config_policy/interfaces/inner_api/include",
]
}
ohos_static_library("sandbox") {
......
......@@ -21,33 +21,33 @@ extern "C" {
#endif
#include <stdbool.h>
#include "init_utils.h"
#include "list.h"
typedef struct {
typedef enum SandboxTag {
SANDBOX_TAG_MOUNT_PATH = 0,
SANDBOX_TAG_MOUNT_FILE,
SANDBOX_TAG_SYMLINK
} SandboxTag;
typedef struct MountList {
char *source; // source 目录,一般是全局的fs 目录
char *target; // 沙盒化后的目录
unsigned long flags;
bool ignoreErrors;
} mount_t;
typedef struct MountList {
mount_t *info;
struct MountList *next;
SandboxTag tag;
struct ListNode node;
} mountlist_t;
typedef struct {
typedef struct LinkList {
char *target;
char *linkName;
} linker_t;
typedef struct LinkList {
linker_t *info;
struct LinkList *next;
struct ListNode node;
} linklist_t;
typedef struct {
mountlist_t *pathMounts;
mountlist_t *fileMounts;
linklist_t *links;
ListNode pathMountsHead;
ListNode fileMountsHead;
ListNode linksHead;
char *rootPath; // /mnt/sandbox/system|vendor|xxx
char name[MAX_BUFFER_LEN]; // name of sandbox. i.e system, chipset etc.
bool isCreated; // sandbox already created or not
......
......@@ -28,14 +28,12 @@
static int GetControlFromEnv(const char *path, int length)
{
BEGET_CHECK_RETURN_VALUE(path != NULL && length > 0, -1);
BEGET_LOGI("GetControlFromEnv path is %s ", path);
const char *val = getenv(path);
BEGET_ERROR_CHECK(val != NULL, return -1, "GetControlFromEnv val is null %d", errno);
BEGET_ERROR_CHECK(val != NULL, return -1, "Get environment from %s failed", path);
errno = 0;
int fd = strtol(val, NULL, N_DEC);
BEGET_CHECK_RETURN_VALUE(errno == 0, -1);
BEGET_LOGI("GetControlFromEnv fd is %d ", fd);
BEGET_ERROR_CHECK(fcntl(fd, F_GETFD) >= 0, return -1, "GetControlFromEnv errno %d ", errno);
BEGET_ERROR_CHECK(errno == 0, return -1, "Failed strtol err=%d", errno);
BEGET_ERROR_CHECK(fcntl(fd, F_GETFD) >= 0, return -1, "Failed fcntl err=%d ", errno);
return fd;
}
......@@ -45,26 +43,23 @@ int GetControlSocket(const char *name)
char path[MAX_SOCKET_ENV_PREFIX_LEN] = {0};
BEGET_CHECK_RETURN_VALUE(snprintf_s(path, sizeof(path), sizeof(path) - 1, OHOS_SOCKET_ENV_PREFIX"%s",
name) != -1, -1);
BEGET_LOGI("GetControlSocket path is %s ", path);
int fd = GetControlFromEnv(path, MAX_SOCKET_ENV_PREFIX_LEN);
BEGET_ERROR_CHECK(fd >= 0, return -1, "GetControlFromEnv fail ");
BEGET_ERROR_CHECK(fd >= 0, return -1, "Get control fd from environment failed");
int addrFamily = 0;
socklen_t afLen = sizeof(addrFamily);
int ret = getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &addrFamily, &afLen);
BEGET_ERROR_CHECK(ret == 0, return -1, "get socket option fail, errno %d ", errno);
BEGET_LOGI("socket %s fd %d address family %d", name, fd, addrFamily);
BEGET_ERROR_CHECK(ret == 0, return -1, "Get socket option fail, err=%d ", errno);
if (addrFamily != AF_UNIX) {
return fd;
}
struct sockaddr_un addr;
socklen_t addrlen = sizeof(addr);
ret = getsockname(fd, (struct sockaddr*)&addr, &addrlen);
BEGET_ERROR_CHECK(ret >= 0, return -1, "GetControlSocket errno %d ", errno);
BEGET_ERROR_CHECK(ret >= 0, return -1, "Failed getsockname err=%d ", errno);
char sockDir[MAX_SOCKET_DIR_LEN] = {0};
BEGET_CHECK_RETURN_VALUE(snprintf_s(sockDir, sizeof(sockDir), sizeof(sockDir) - 1, OHOS_SOCKET_DIR"/%s",
name) != -1, -1);
BEGET_LOGI("sockDir %s ", sockDir);
BEGET_LOGI("addr.sun_path %s ", addr.sun_path);
BEGET_LOGV("Compary sockDir %s and addr.sun_path %s", sockDir, addr.sun_path);
if (strncmp(sockDir, addr.sun_path, strlen(sockDir)) == 0) {
return fd;
}
......
......@@ -32,6 +32,35 @@
#include "securec.h"
#include "beget_ext.h"
INIT_LOCAL_API int GetSystemError(int err)
{
switch(err) {
case 0:
return 0;
case PARAM_CODE_INVALID_PARAM:
case PARAM_CODE_INVALID_NAME:
case PARAM_CODE_READ_ONLY:
return EC_INVALID;
case PARAM_CODE_INVALID_VALUE:
return SYSPARAM_INVALID_VALUE;
case PARAM_CODE_NOT_FOUND:
case PARAM_CODE_NODE_EXIST:
return SYSPARAM_NOT_FOUND;
case DAC_RESULT_FORBIDED:
return SYSPARAM_PERMISSION_DENIED;
case PARAM_CODE_REACHED_MAX:
case PARAM_CODE_FAIL_CONNECT:
case PARAM_CODE_INVALID_SOCKET:
case PARAM_CODE_NOT_SUPPORT:
return SYSPARAM_SYSTEM_ERROR;
case PARAM_CODE_TIMEOUT:
return SYSPARAM_WAIT_TIMEOUT;
default:
return SYSPARAM_SYSTEM_ERROR;
}
return 0;
}
INIT_LOCAL_API int IsValidParamValue(const char *value, uint32_t len)
{
if ((value == NULL) || (strlen(value) + 1 > len)) {
......@@ -48,7 +77,10 @@ INIT_LOCAL_API int GetParameter_(const char *key, const char *def, char *value,
uint32_t size = len;
int ret = SystemGetParameter(key, NULL, &size);
if (ret != 0) {
if (def == NULL || strlen(def) > len) {
if (def == NULL) {
return GetSystemError(ret);
}
if (strlen(def) > len) {
return EC_INVALID;
}
ret = strcpy_s(value, len, def);
......@@ -56,8 +88,10 @@ INIT_LOCAL_API int GetParameter_(const char *key, const char *def, char *value,
} else if (size > len) {
return EC_INVALID;
}
size = len;
return (SystemGetParameter(key, value, &size) == 0) ? EC_SUCCESS : EC_FAILURE;
ret = SystemGetParameter(key, value, &size);
return GetSystemError(ret);
}
INIT_LOCAL_API const char *GetProperty(const char *key, const char **paramHolder)
......
......@@ -40,6 +40,7 @@ INIT_LOCAL_API int GetDevUdid_(char *udid, int size);
INIT_LOCAL_API int IsValidParamValue(const char *value, uint32_t len);
INIT_LOCAL_API const char *GetFullName_(void);
INIT_LOCAL_API int GetSystemError(int err);
#ifdef __cplusplus
#if __cplusplus
}
......
......@@ -99,7 +99,7 @@ bool GetBoolParameter(const std::string& key, bool def)
return def;
}
int GetStringParameter(const std::string key, std::string &value, const std::string def)
int GetStringParameter(const std::string &key, std::string &value, const std::string def)
{
uint32_t size = 0;
int ret = SystemReadParam(key.c_str(), NULL, &size);
......@@ -163,7 +163,7 @@ std::string GetDeviceType(void)
{"fitnessWatch", "liteWearable"},
};
static const char *productType = nullptr;
const char *type = GetProperty("const.build.devicetype", &productType);
const char *type = GetProperty("const.product.devicetype", &productType);
if (type == nullptr) {
type = GetProperty("const.build.characteristics", &productType);
}
......@@ -173,7 +173,7 @@ std::string GetDeviceType(void)
return std::string(type);
}
int GetIntParameter(const std::string key, int def)
int GetIntParameter(const std::string &key, int def)
{
return GetIntParameter(key, def, INT_MIN, INT_MAX);
}
......
......@@ -28,7 +28,8 @@
int WaitParameter(const char *key, const char *value, int timeout)
{
BEGET_CHECK(!(key == NULL || value == NULL), return EC_INVALID);
return SystemWaitParameter(key, value, timeout);
int ret = SystemWaitParameter(key, value, timeout);
return GetSystemError(ret);
}
uint32_t FindParameter(const char *key)
......@@ -56,7 +57,10 @@ int GetParameterName(uint32_t handle, char *name, uint32_t len)
return EC_INVALID;
}
int ret = SystemGetParameterName(handle, name, len);
return (ret != 0) ? EC_FAILURE : strlen(name);
if (ret == 0) {
return strlen(name);
}
return GetSystemError(ret);
}
int GetParameterValue(uint32_t handle, char *value, uint32_t len)
......@@ -66,7 +70,10 @@ int GetParameterValue(uint32_t handle, char *value, uint32_t len)
}
uint32_t size = len;
int ret = SystemGetParameterValue(handle, value, &size);
return (ret != 0) ? EC_FAILURE : strlen(value);
if (ret == 0) {
return strlen(value);
}
return GetSystemError(ret);
}
int GetParameter(const char *key, const char *def, char *value, uint32_t len)
......@@ -84,17 +91,13 @@ int SetParameter(const char *key, const char *value)
return EC_INVALID;
}
int ret = SystemSetParameter(key, value);
if (ret == PARAM_CODE_INVALID_NAME || ret == DAC_RESULT_FORBIDED ||
ret == PARAM_CODE_INVALID_PARAM || ret == PARAM_CODE_INVALID_VALUE) {
return EC_INVALID;
}
return (ret == 0) ? EC_SUCCESS : EC_FAILURE;
return GetSystemError(ret);
}
const char *GetDeviceType(void)
{
static const char *productType = NULL;
const char *deviceType = GetProperty("const.build.devicetype", &productType);
const char *deviceType = GetProperty("const.product.devicetype", &productType);
if (deviceType != NULL) {
return deviceType;
}
......@@ -320,14 +323,14 @@ int32_t GetIntParameter(const char *key, int32_t def)
{
char value[MAX_INT_LEN] = {0};
int ret = GetParameter(key, "0", value, sizeof(value));
if (ret != 0) {
if (ret < 0) {
return def;
}
long long int result = 0;
if (StringToLL(value, &result) != 0) {
return def;
}
if (result <= INT32_MIN && result >= INT32_MAX) {
if (result <= INT32_MIN || result >= INT32_MAX) {
return def;
}
return (int32_t)result;
......@@ -337,7 +340,7 @@ uint32_t GetUintParameter(const char *key, uint32_t def)
{
char value[MAX_INT_LEN] = {0};
int ret = GetParameter(key, "0", value, sizeof(value));
if (ret != 0) {
if (ret < 0) {
return def;
}
unsigned long long int result = 0;
......
......@@ -24,6 +24,7 @@ group("kitsgroup") {
deps += [
"jskits:deviceinfo",
"jskits:systemparameter",
"jskits:systemparameterv9",
]
}
}
......
......@@ -49,3 +49,22 @@ ohos_shared_library("systemparameter") {
subsystem_name = "startup"
part_name = "init"
}
ohos_shared_library("systemparameterv9") {
include_dirs = [
"src",
"//third_party/libuv/include",
]
sources = [ "src_v9/native_parameters_js.cpp" ]
deps = [
"//base/startup/init/interfaces/innerkits:libbeget_proxy",
"//base/startup/init/interfaces/innerkits:libbegetutil",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module"
subsystem_name = "startup"
part_name = "init"
}
/*
* 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 "native_parameters_js.h"
#include "sysparam_errno.h"
static constexpr int ARGC_NUMBER = 2;
static constexpr int ARGC_THREE_NUMBER = 3;
static constexpr int MAX_NAME_LENGTH = 128;
static constexpr int MAX_VALUE_LENGTH = PARAM_CONST_VALUE_LEN_MAX;
using StorageAsyncContext = struct StorageAsyncContext {
napi_env env = nullptr;
napi_async_work work = nullptr;
char key[MAX_NAME_LENGTH] = { 0 };
size_t keyLen = 0;
char value[MAX_VALUE_LENGTH] = { 0 };
size_t valueLen = 0;
napi_deferred deferred = nullptr;
napi_ref callbackRef = nullptr;
int status = -1;
std::string getValue;
};
using StorageAsyncContextPtr = StorageAsyncContext *;
static int GetErrorInfo(int status, std::string &errMsg)
{
switch(status) {
case EC_FAILURE:
case EC_SYSTEM_ERR:
case SYSPARAM_SYSTEM_ERROR:
errMsg = "System internal error including out of memory, deadlock etc";
return -SYSPARAM_SYSTEM_ERROR;
case EC_INVALID:
case SYSPARAM_INVALID_INPUT:
errMsg = "Input parameter is missing or invalid";
return -SYSPARAM_INVALID_INPUT;
case SYSPARAM_PERMISSION_DENIED:
errMsg = "System permission operation permission denied";
return -SYSPARAM_PERMISSION_DENIED;
case SYSPARAM_NOT_FOUND:
errMsg = "System parameter can not be found";
return -SYSPARAM_NOT_FOUND;
case SYSPARAM_INVALID_VALUE:
errMsg = "System parameter value is invalid";
return -SYSPARAM_INVALID_VALUE;
default:
errMsg = "System internal error including out of memory, deadlock etc";
return -SYSPARAM_SYSTEM_ERROR;
}
return 0;
}
static napi_value BusinessErrorCreate(napi_env env, int status)
{
std::string errMsg = "";
int ret = GetErrorInfo(status, errMsg);
PARAM_JS_LOGV("BusinessErrorCreate status %d err %d msg: %s", status, ret, errMsg.c_str());
napi_value code = nullptr;
napi_create_int32(env, ret, &code);
napi_value msg = nullptr;
napi_create_string_utf8(env, errMsg.c_str(), NAPI_AUTO_LENGTH, &msg);
napi_value businessError = nullptr;
napi_create_error(env, nullptr, msg, &businessError);
napi_set_named_property(env, businessError, "code", code);
return businessError;
}
#define PARAM_NAPI_ASSERT(env, assertion, result, info) \
do { \
if (!(assertion)) { \
napi_value d_err = BusinessErrorCreate(env, result); \
napi_throw(env, d_err); \
return nullptr; \
} \
} while (0)
static int GetParamString(napi_env env, napi_value arg, char *buffer, size_t maxBuff, size_t *keySize)
{
(void)napi_get_value_string_utf8(env, arg, nullptr, maxBuff - 1, keySize);
if (*keySize >= maxBuff || *keySize == 0) {
return SYSPARAM_INVALID_INPUT;
}
(void)napi_get_value_string_utf8(env, arg, buffer, maxBuff - 1, keySize);
return 0;
}
static void SetCallbackWork(napi_env env, StorageAsyncContextPtr asyncContext)
{
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSStartupSet", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(
env, nullptr, resource,
[](napi_env env, void *data) {
StorageAsyncContext *asyncContext = (StorageAsyncContext *)data;
asyncContext->status = SetParameter(asyncContext->key, asyncContext->value);
PARAM_JS_LOGV("JSApp set status: %d, key: '%s', value: '%s'.",
asyncContext->status, asyncContext->key, asyncContext->value);
},
[](napi_env env, napi_status status, void *data) {
StorageAsyncContext *asyncContext = (StorageAsyncContext *)data;
napi_value result[ARGC_NUMBER] = { 0 };
if (asyncContext->status == 0) {
napi_get_undefined(env, &result[0]);
napi_get_undefined(env, &result[1]);
} else {
result[0] = BusinessErrorCreate(env, asyncContext->status);
napi_get_undefined(env, &result[1]);
}
if (asyncContext->deferred) {
if (asyncContext->status == 0) {
napi_resolve_deferred(env, asyncContext->deferred, result[1]);
} else {
napi_reject_deferred(env, asyncContext->deferred, result[0]);
}
} else {
napi_value callback = nullptr;
napi_value callResult = nullptr;
napi_get_reference_value(env, asyncContext->callbackRef, &callback);
napi_call_function(env, nullptr, callback, ARGC_NUMBER, result, &callResult);
napi_delete_reference(env, asyncContext->callbackRef);
}
napi_delete_async_work(env, asyncContext->work);
delete asyncContext;
},
(void *)asyncContext, &asyncContext->work);
napi_queue_async_work(env, asyncContext->work);
}
static napi_value Set(napi_env env, napi_callback_info info)
{
size_t argc = ARGC_THREE_NUMBER;
napi_value argv[ARGC_THREE_NUMBER] = { nullptr };
napi_value thisVar = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, &argc, argv, &thisVar, &data);
PARAM_NAPI_ASSERT(env, argc >= ARGC_NUMBER, SYSPARAM_INVALID_INPUT, "requires 2 parameter");
StorageAsyncContextPtr asyncContext = new StorageAsyncContext();
asyncContext->env = env;
for (size_t i = 0; i < argc; i++) {
napi_valuetype valueType = napi_null;
napi_typeof(env, argv[i], &valueType);
int ret = 0;
if (i == 0 && valueType == napi_string) {
ret = GetParamString(env, argv[i], asyncContext->key, MAX_NAME_LENGTH, &asyncContext->keyLen);
} else if (i == 1 && valueType == napi_string) {
ret = GetParamString(env, argv[i], asyncContext->value, MAX_VALUE_LENGTH, &asyncContext->valueLen);
} else if (i == ARGC_NUMBER && valueType == napi_function) {
napi_create_reference(env, argv[i], 1, &asyncContext->callbackRef);
} else {
delete asyncContext;
ret = SYSPARAM_INVALID_INPUT;
}
if (ret != 0) {
ret = (i == 1) ? SYSPARAM_INVALID_VALUE : ret;
napi_value err = BusinessErrorCreate(env, ret);
napi_throw(env, err);
return nullptr;
}
}
PARAM_JS_LOGV("JSApp set key: %s(%d), value: %s(%d).",
asyncContext->key, asyncContext->keyLen, asyncContext->value, asyncContext->valueLen);
napi_value result = nullptr;
if (asyncContext->callbackRef == nullptr) {
napi_create_promise(env, &asyncContext->deferred, &result);
} else {
napi_get_undefined(env, &result);
}
SetCallbackWork(env, asyncContext);
return result;
}
static napi_value SetSync(napi_env env, napi_callback_info info)
{
size_t argc = ARGC_NUMBER;
napi_value args[ARGC_NUMBER] = { nullptr };
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
PARAM_NAPI_ASSERT(env, argc == ARGC_NUMBER, SYSPARAM_INVALID_INPUT, "Wrong number of arguments");
napi_valuetype valuetype0 = napi_null;
NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0));
napi_valuetype valuetype1 = napi_null;
NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1));
PARAM_NAPI_ASSERT(env, valuetype0 == napi_string && valuetype1 == napi_string,
SYSPARAM_INVALID_INPUT, "Wrong argument type. string expected.");
size_t keySize = 0;
std::vector<char> keyBuf(MAX_NAME_LENGTH, 0);
int ret = GetParamString(env, args[0], keyBuf.data(), MAX_NAME_LENGTH, &keySize);
if (ret != 0) {
napi_value err = BusinessErrorCreate(env, SYSPARAM_INVALID_INPUT);
napi_throw(env, err);
return nullptr;
}
std::vector<char> value(MAX_VALUE_LENGTH, 0);
size_t valueSize = 0;
ret = GetParamString(env, args[1], value.data(), MAX_VALUE_LENGTH, &valueSize);
if (ret != 0) {
napi_value err = BusinessErrorCreate(env, SYSPARAM_INVALID_VALUE);
napi_throw(env, err);
return nullptr;
}
ret = SetParameter(keyBuf.data(), value.data());
PARAM_JS_LOGV("JSApp SetSync result:%d, key: '%s'.", ret, keyBuf.data());
napi_value napiValue = nullptr;
if (ret != 0) { // set failed
napi_value err = BusinessErrorCreate(env, ret);
napi_throw(env, err);
} else {
napi_get_undefined(env, &napiValue);
}
return napiValue;
}
static napi_value GetSync(napi_env env, napi_callback_info info)
{
size_t argc = ARGC_NUMBER;
napi_value args[ARGC_NUMBER] = { nullptr };
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
PARAM_NAPI_ASSERT(env, argc == 1 || argc == ARGC_NUMBER, SYSPARAM_INVALID_INPUT, "Wrong number of arguments");
napi_valuetype valuetype0 = napi_null;
NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0));
PARAM_NAPI_ASSERT(env, valuetype0 == napi_string,
SYSPARAM_INVALID_INPUT, "Wrong argument type. Numbers expected.");
if (argc == ARGC_NUMBER) {
napi_valuetype valuetype1 = napi_null;
NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1));
PARAM_NAPI_ASSERT(env, valuetype1 == napi_string,
SYSPARAM_INVALID_INPUT, "Wrong argument type. string expected.");
}
size_t keySize = 0;
std::vector<char> keyBuf(MAX_NAME_LENGTH, 0);
int ret = GetParamString(env, args[0], keyBuf.data(), MAX_NAME_LENGTH, &keySize);
if (ret != 0) {
napi_value err = BusinessErrorCreate(env, SYSPARAM_INVALID_INPUT);
napi_throw(env, err);
return nullptr;
}
std::vector<char> defValue(MAX_VALUE_LENGTH, 0);
size_t valueSize = 0;
if (argc == ARGC_NUMBER) {
ret = GetParamString(env, args[1], defValue.data(), MAX_VALUE_LENGTH, &valueSize);
if (ret != 0) {
napi_value err = BusinessErrorCreate(env, SYSPARAM_INVALID_INPUT);
napi_throw(env, err);
return nullptr;
}
}
std::vector<char> value(MAX_VALUE_LENGTH, 0);
ret = GetParameter(keyBuf.data(), (valueSize == 0) ? nullptr : defValue.data(), value.data(), MAX_VALUE_LENGTH);
PARAM_JS_LOGV("JSApp get status: %d, key: '%s', value: '%s', defValue: '%s'.",
ret, keyBuf.data(), value.data(), defValue.data());
if (ret < 0) {
napi_value err = BusinessErrorCreate(env, ret);
napi_throw(env, err);
return nullptr;
}
napi_value napiValue = nullptr;
NAPI_CALL(env, napi_create_string_utf8(env, value.data(), strlen(value.data()), &napiValue));
return napiValue;
}
static void GetCallbackWork(napi_env env, StorageAsyncContextPtr asyncContext)
{
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSStartupGet", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(
env, nullptr, resource,
[](napi_env env, void *data) {
StorageAsyncContext *asyncContext = (StorageAsyncContext *)data;
std::vector<char> value(MAX_VALUE_LENGTH, 0);
asyncContext->status = GetParameter(asyncContext->key,
(asyncContext->valueLen == 0) ? nullptr : asyncContext->value, value.data(), MAX_VALUE_LENGTH);
asyncContext->getValue = std::string(value.begin(), value.end());
PARAM_JS_LOGV("JSApp get asyncContext status: %d, key: '%s', value: '%s', defValue: '%s'.",
asyncContext->status, asyncContext->key, asyncContext->getValue.c_str(), asyncContext->value);
},
[](napi_env env, napi_status status, void *data) {
StorageAsyncContext *asyncContext = (StorageAsyncContext *)data;
napi_value result[ARGC_NUMBER] = { 0 };
if (asyncContext->status > 0) {
napi_get_undefined(env, &result[0]);
napi_create_string_utf8(env,
asyncContext->getValue.c_str(), strlen(asyncContext->getValue.c_str()), &result[1]);
} else {
result[0] = BusinessErrorCreate(env, asyncContext->status);
napi_get_undefined(env, &result[1]);
}
if (asyncContext->deferred) {
if (asyncContext->status > 0) {
napi_resolve_deferred(env, asyncContext->deferred, result[1]);
} else {
napi_reject_deferred(env, asyncContext->deferred, result[0]);
}
} else {
napi_value callback = nullptr;
napi_value callResult = nullptr;
napi_get_reference_value(env, asyncContext->callbackRef, &callback);
napi_call_function(env, nullptr, callback, ARGC_NUMBER, result, &callResult);
napi_delete_reference(env, asyncContext->callbackRef);
}
napi_delete_async_work(env, asyncContext->work);
delete asyncContext;
},
(void *)asyncContext, &asyncContext->work);
napi_queue_async_work(env, asyncContext->work);
}
static napi_value Get(napi_env env, napi_callback_info info)
{
size_t argc = ARGC_THREE_NUMBER;
napi_value argv[ARGC_THREE_NUMBER] = { nullptr };
napi_value thisVar = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, &argc, argv, &thisVar, &data);
PARAM_NAPI_ASSERT(env, argc >= 1, SYSPARAM_INVALID_INPUT, "requires 1 parameter");
StorageAsyncContextPtr asyncContext = new StorageAsyncContext();
asyncContext->env = env;
for (size_t i = 0; i < argc; i++) {
napi_valuetype valueType = napi_null;
napi_typeof(env, argv[i], &valueType);
int ret = 0;
if (i == 0 && valueType == napi_string) {
ret = GetParamString(env, argv[i], asyncContext->key, MAX_NAME_LENGTH, &asyncContext->keyLen);
} else if (i == 1 && valueType == napi_string) {
ret = GetParamString(env, argv[i], asyncContext->value, MAX_VALUE_LENGTH, &asyncContext->valueLen);
} else if (i == 1 && valueType == napi_function) {
napi_create_reference(env, argv[i], 1, &asyncContext->callbackRef);
break;
} else if (i == ARGC_NUMBER && valueType == napi_function) {
napi_create_reference(env, argv[i], 1, &asyncContext->callbackRef);
} else {
delete asyncContext;
ret = SYSPARAM_INVALID_INPUT;
}
if (ret != 0) {
ret = (i == 1) ? SYSPARAM_INVALID_VALUE : ret;
napi_value err = BusinessErrorCreate(env, ret);
napi_throw(env, err);
return nullptr;
}
}
PARAM_JS_LOGV("JSApp Get key: '%s'(%d), def value: '%s'(%d).",
asyncContext->key, asyncContext->keyLen, asyncContext->value, asyncContext->valueLen);
napi_value result = nullptr;
if (asyncContext->callbackRef == nullptr) {
napi_create_promise(env, &asyncContext->deferred, &result);
} else {
napi_get_undefined(env, &result);
}
GetCallbackWork(env, asyncContext);
return result;
}
EXTERN_C_START
/*
* Module init
*/
static napi_value Init(napi_env env, napi_value exports)
{
/*
* Attribute definition
*/
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("set", Set),
DECLARE_NAPI_FUNCTION("setSync", SetSync),
DECLARE_NAPI_FUNCTION("get", Get),
DECLARE_NAPI_FUNCTION("getSync", GetSync),
#ifdef PARAM_SUPPORT_WAIT
DECLARE_NAPI_FUNCTION("wait", ParamWait),
DECLARE_NAPI_FUNCTION("getWatcher", GetWatcher)
#endif
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc));
#ifdef PARAM_SUPPORT_WAIT
return RegisterWatcher(env, exports);
#else
return exports;
#endif
}
EXTERN_C_END
/*
* Module definition
*/
static napi_module _module = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = NULL,
.nm_register_func = Init,
.nm_modname = "systemParameterV9",
.nm_priv = ((void *)0),
.reserved = { 0 }
};
/*
* Module registration function
*/
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&_module);
}
......@@ -20,6 +20,7 @@ import argparse
import os
import sys
def decode_cfg_line(data):
data.replace('\n', '').replace('\r', '')
data = data.strip()
......@@ -30,17 +31,19 @@ def decode_cfg_line(data):
return "", ""
return strs[0].strip(), strs[1].strip()
def get_param_from_cfg(cfg_name):
dict = {}
data_dict = {}
with open(cfg_name) as afile:
data = afile.readline()
while data:
name, value = decode_cfg_line(data)
if len(name) != 0 and len(value) != 0:
dict[name] = value
print("sample file name={%s %s}"%(name, value))
data_dict[name] = value
print("sample file name={%s %s}" % (name, value))
data = afile.readline()
return dict
return data_dict
def decode_code_line(data):
data.replace('\n', '').replace('\r', '')
......@@ -53,21 +56,23 @@ def decode_code_line(data):
strs = data.split(',')
if len(strs) <= 1:
return "", ""
return strs[0].strip(), data[len(strs[0]) + 1: ].strip()
return strs[0].strip(), data[len(strs[0]) + 1:].strip()
def get_param_from_c_code(code_name):
dict = {}
data_dict = {}
with open(code_name, "r+") as afile:
data = afile.readline()
while data:
name, value = decode_code_line(data)
if len(name) != 0 and len(value) != 0:
dict[name] = value
data_dict[name] = value
data = afile.readline()
afile.truncate(0)
return dict
return data_dict
def write_map_to_code(code_name, dict):
def write_map_to_code(code_name, data_dict):
try:
with open(code_name, "w") as f:
# start with 0
......@@ -91,13 +96,13 @@ def write_map_to_code(code_name, dict):
f.write(os.linesep + os.linesep)
# write data
f.write('static Node g_paramDefCfgNodes[] = {' + os.linesep)
for name, value in dict.items():
for name, value in data_dict.items():
if (value.startswith("\"")):
str = " PARAM_MAP({0}, {1})".format(name, value)
f.write(str + os.linesep)
tmp_str = " PARAM_MAP({0}, {1})".format(name, value)
f.write(tmp_str + os.linesep)
else:
str = " PARAM_MAP({0}, \"{1}\")".format(name, value)
f.write(str + os.linesep)
tmp_str = " PARAM_MAP({0}, \"{1}\")".format(name, value)
f.write(tmp_str + os.linesep)
f.write('};' + os.linesep + os.linesep)
#end
......@@ -110,19 +115,21 @@ def write_map_to_code(code_name, dict):
f.write(os.linesep)
f.truncate()
except IOError:
print("Error: open or write file %s fail"%{code_name})
print("Error: open or write file %s fail" % {code_name})
return 0
def add_to_code_dict(code_dict, cfg_dict, high = True):
def add_to_code_dict(code_dict, cfg_dict, high=True):
for name, value in cfg_dict.items():
# check if name exit
has_key = name in code_dict #code_dict.has_key(name)
has_key = name in code_dict
if has_key and high:
code_dict[name] = value
elif not has_key:
code_dict[name] = value
return code_dict
def main():
parser = argparse.ArgumentParser(
description='A common change param.para file to h.')
......
......@@ -123,8 +123,11 @@ if (defined(ohos_lite)) {
if (enable_ohos_startup_init_feature_ab_partition) {
sources += [ "partitionslot.cpp" ]
external_deps +=
[ "drivers_interface_partitionslot:libpartitionslot_proxy_1.0" ]
include_dirs += [ "//drivers/hdf_core/adapter/uhdf2/include" ]
external_deps += [
"drivers_interface_partitionslot:libpartitionslot_proxy_1.0",
"hdf_core:libhdi",
]
symlink_target_name += [ "partitionslot" ]
}
......
......@@ -37,6 +37,7 @@ static int main_cmd(BShellHandle shell, int argc, char **argv)
}
size_t serviceNameLen = strlen(argv[1]) + strlen(argv[2]) + 2; // 2 is \0 and #
char *cmd = (char *)calloc(1, serviceNameLen);
BEGET_ERROR_CHECK(cmd != NULL, return 0, "failed to allocate cmd memory");
BEGET_ERROR_CHECK(sprintf_s(cmd, serviceNameLen, "%s#%s", argv[1], argv[2]) >= 0, free(cmd);
return 0, "dump service arg create failed");
CmdClientInit(INIT_CONTROL_FD_SOCKET_PATH, ACTION_DUMP, cmd);
......
......@@ -64,7 +64,7 @@ static void ClearLogo(int fd)
static void WriteLogoContent(int fd, const std::string &logoPath, uint32_t size)
{
if (fd < 0 || logoPath.empty() || size <= 0) {
if (fd < 0 || logoPath.empty() || size == 0) {
std::cout << "path is null or size illegal\n";
return;
}
......
......@@ -16,22 +16,51 @@
#include <iostream>
#include "begetctl.h"
#include "hdi/idevmgr_hdi.h"
#include "v1_0/ipartition_slot.h"
using namespace OHOS::HDI::Partitionslot::V1_0;
using OHOS::HDI::DeviceManager::V1_0::IDeviceManager;
static const int32_t PARTITION_ARGC = 2;
static int LoadDevice()
{
auto devmgr = IDeviceManager::Get();
if (devmgr != nullptr) {
return devmgr->LoadDevice("partition_slot_service");
} else {
std::cout << "Get devmgr failed" << std::endl;
return -1;
}
}
static void UnloadDevice()
{
auto devmgr = IDeviceManager::Get();
if (devmgr != nullptr) {
devmgr->UnloadDevice("partition_slot_service");
} else {
std::cout << "Get devmgr failed" << std::endl;
}
}
static int GetSlot(BShellHandle handle, int32_t argc, char *argv[])
{
if (LoadDevice() != 0) {
std::cout << "Load partitionslot device failed" << std::endl;
return -1;
}
std::cout << "Command: partitionslot getslot" << std::endl;
sptr<IPartitionSlot> partitionslot = IPartitionSlot::Get();
int bootSlots = 0;
int currentSlot = 0;
if (partitionslot == nullptr) {
return 0;
std::cout << "Get partitionslot failed" << std::endl;
return -1;
}
partitionslot->GetCurrentSlot(currentSlot, bootSlots);
std::cout << "The number of slots: " << bootSlots << "," << "current slot: " << currentSlot << std::endl;
UnloadDevice();
return 0;
}
......@@ -39,17 +68,23 @@ static int GetSuffix(BShellHandle handle, int32_t argc, char *argv[])
{
if (argc != PARTITION_ARGC) {
BShellCmdHelp(handle, argc, argv);
return 0;
return -1;
}
if (LoadDevice() != 0) {
std::cout << "Load partitionslot device failed" << std::endl;
return -1;
}
std::cout << "Command: partitionslot getsuffix" << std::endl;
int slot = atoi(argv[1]);
std::string suffix = "";
sptr<IPartitionSlot> partitionslot = IPartitionSlot::Get();
if (partitionslot == nullptr) {
return 0;
std::cout << "Get partitionslot failed" << std::endl;
return -1;
}
partitionslot->GetSlotSuffix(slot, suffix);
std::cout << "The slot " << slot << " matches with suffix: " << suffix << std::endl;
UnloadDevice();
return 0;
}
......@@ -57,16 +92,22 @@ static int SetActiveSlot(BShellHandle handle, int32_t argc, char *argv[])
{
if (argc != PARTITION_ARGC) {
BShellCmdHelp(handle, argc, argv);
return 0;
return -1;
}
if (LoadDevice() != 0) {
std::cout << "Load partitionslot device failed" << std::endl;
return -1;
}
std::cout << "Command: partitionslot setactive" << std::endl;
int slot = atoi(argv[1]);
sptr<IPartitionSlot> partitionslot = IPartitionSlot::Get();
if (partitionslot == nullptr) {
return 0;
std::cout << "Get partitionslot failed" << std::endl;
return -1;
}
partitionslot->SetActiveSlot(slot);
std::cout << "Set active slot: " << slot << std::endl;
UnloadDevice();
return 0;
}
......@@ -74,16 +115,22 @@ static int SetUnbootSlot(BShellHandle handle, int32_t argc, char *argv[])
{
if (argc != PARTITION_ARGC) {
BShellCmdHelp(handle, argc, argv);
return 0;
return -1;
}
if (LoadDevice() != 0) {
std::cout << "Load partitionslot device failed" << std::endl;
return -1;
}
std::cout << "Command: partitionslot setunboot" << std::endl;
int slot = atoi(argv[1]);
sptr<IPartitionSlot> partitionslot = IPartitionSlot::Get();
if (partitionslot == nullptr) {
return 0;
std::cout << "Get partitionslot failed" << std::endl;
return -1;
}
partitionslot->SetSlotUnbootable(slot);
std::cout << "Set unboot slot: " << slot << std::endl;
UnloadDevice();
return 0;
}
......
......@@ -74,7 +74,7 @@ static void RunSandbox(const std::string &sandboxName)
static void EnterShell()
{
char *argv[] = { const_cast<char *>("sh"), NULL };
char *argv[] = { const_cast<char *>("sh"), nullptr };
char *envp[] = { nullptr };
if (execve("/system/bin/sh", argv, envp) != 0) {
std::cout << "execve sh failed! err = "<< errno << std::endl;
......@@ -94,14 +94,14 @@ static void EnterExec(const std::string &processName)
const std::string sep = " ";
OHOS::SplitStr(tmpName, sep, vtr, true, false);
if ((vtr.size() > MAX_PROCESS_ARGC) || (vtr.size() <= 0)) {
if ((vtr.size() > MAX_PROCESS_ARGC) || (vtr.size() == 0)) {
std::cout << "Service parameters is error." << std::endl;
return;
}
char *argv[MAX_PROCESS_ARGC] = {};
std::vector<std::string>::iterator it;
int i = 0;
for (it = vtr.begin(); it != vtr.end(); it++) {
for (it = vtr.begin(); it != vtr.end(); ++it) {
argv[i] = (char *)(*it).c_str();
std::cout << std::string(argv[i]) << std::endl;
i++;
......
......@@ -36,9 +36,9 @@ char *BShellEnvErrString(BShellHandle handle, int32_t err)
return shellErrString[i].desc;
}
}
BSH_CHECK(handle != NULL, return "System unknow err", "Invalid shell env");
BSH_CHECK(handle != NULL, return "System unknown err", "Invalid shell env");
BShellEnv *shell = (BShellEnv *)handle;
int len = sprintf_s(shell->data, sizeof(shell->data) - 1, "System unknow err 0x%08x", err);
int len = sprintf_s(shell->data, sizeof(shell->data) - 1, "System unknown err 0x%08x", err);
if (len <= 0) {
BSH_LOGE("Write shell data size failed.");
}
......@@ -561,7 +561,7 @@ static const char *GetRealCmdName(const char *name)
}
i++;
}
if ((last != 0) && (name + last != NULL)) {
if (last != 0) {
return name + last + 1;
} else {
return name;
......
......@@ -160,12 +160,6 @@ if (defined(ohos_lite)) {
subsystem_name = "startup"
}
ohos_prebuilt_etc("charge.group") {
source = "//base/startup/init/services/etc/device.charge.group.cfg"
part_name = "init"
subsystem_name = "startup"
}
ohos_prebuilt_etc("syscap.para") {
source = "${preloader_output_dir}/system/etc/param/syscap.para"
module_install_dir = "etc/param/"
......@@ -224,7 +218,6 @@ if (defined(ohos_lite)) {
group("etc_files") {
deps = [
":boot.group",
":charge.group",
":chipset-sandbox.json",
":console.cfg",
":features.json",
......
{
"jobs": [
"param:sys.usb.config=hdc && param:sys.usb.configfs=1",
"param:sys.usb.ffs.ready=1 && param:sys.usb.config=hdc && param:sys.usb.configfs=1",
"boot && param:persist.sys.usb.config=*",
"param:sys.usb.config=none && param:sys.usb.configfs=0",
"boot && param:const.debuggable=1",
"param:sys.usb.config=none && param:sys.usb.configfs=1",
"load_persist_props_action"
],
"services": [
"ueventd",
"console",
"hdcd",
"charger",
"misc"
],
"groups": [
]
}
\ No newline at end of file
......@@ -17,8 +17,8 @@ vpn:x:1016:
keystore:x:1017:
usb:x:1018:
drm:x:1019:
gps:x:1020:
location_host:x:1021:
gps:x:1021:
location_host:x:1022:
media_rw:x:1023:
dsoftbus:x:1024:
nfc:x:1027:
......@@ -32,7 +32,7 @@ uiserver:x:1048:
servicectrl:x:1050:root,shell,system,samgr,hdf_devmgr
powerctrl:x:1051:root,shell,system,update,power_host
bootctrl:x:1052:root,shell,system
deviceprivate:x:1053:root,shell,system,samgr,hdf_devmgr,deviceinfo,dsoftbus,dms,account,useriam,access_token
deviceprivate:x:1053:root,shell,system,samgr,hdf_devmgr,deviceinfo,dsoftbus,dms,account,useriam,access_token,device_manager,foundation,dbms,deviceauth,huks_server
hiview:x:1201:
hidumper_service:x:1212:
shell:x:2000:
......@@ -81,14 +81,13 @@ vendor_mpp_driver:x:3061:
device_manager:x:3062:
deviceauth:x:3333:
huks_server:x:3510:
cert_manager_server:x:3515:
dms:x:5522:
foundation:x:5523:
quickfixserver:x:5524;
samgr:x:5555:
update:x:6666:
charger:x:6667:
battery_stats:x:6668:
thermal:x:6669:
sensor:x:6688:
input:x:6696:
msdp:x:6699:
......
......@@ -139,11 +139,7 @@
"mkdir /data/service/el2/0/hmdfs 0711 system system",
"mkdir /data/chipset/el2/0 0711 root root",
"mkdir /storage/media 0711 root root",
"copy /data/system/entropy.dat /dev/urandom",
"mkdir /data/misc 01771 system misc",
"mkdir /data/misc/wifi 0770 wifi wifi",
"mkdir /data/misc/wifi/sockets 0770 wifi wifi",
"mkdir /data/misc/wifi/wpa_supplicant 0770 wifi wifi",
"mkdir /data/local 0751 root root",
"mkdir /data/vendor 0771 root root",
"mkdir /data/local/tmp 0771 shell shell",
......@@ -152,9 +148,6 @@
"mkdir /data/app 0771 system system",
"mkdir /data/nfc 0770 nfc nfc",
"mkdir /data/nfc/param 0770 nfc nfc",
"mkdir /data/system 0775 system system",
"mkdir /data/misc_de 01771 system misc",
"mkdir /data/misc_ce 01771 system misc",
"setparam sys.use_memfd false",
"chown root system /dev/fscklogs/log",
"chmod 0770 /dev/fscklogs/log",
......
......@@ -28,6 +28,7 @@
"uid" : "system",
"gid" : "system"
}],
"apl" : "normal",
"permission" : [
"ohos.permission.CHANGE_ABILITY_ENABLED_STATE",
"ohos.permission.DUMP",
......@@ -40,7 +41,16 @@
"ohos.permission.START_ABILITIES_FROM_BACKGROUND",
"ohos.permission.PERMISSION_USED_STATS"
],
"permission_acls" : ["ohos.permission.DUMP"],
"permission_acls" : [
"ohos.permission.CHANGE_ABILITY_ENABLED_STATE",
"ohos.permission.DUMP",
"ohos.permission.GET_BUNDLE_INFO_PRIVILEGED",
"ohos.permission.INSTALL_BUNDLE",
"ohos.permission.LISTEN_BUNDLE_CHANGE",
"ohos.permission.REMOVE_CACHE_FILES",
"ohos.permission.START_ABILITIES_FROM_BACKGROUND",
"ohos.permission.PERMISSION_USED_STATS"
],
"sandbox" : 0,
"start-mode" : "condition",
"secon" : "u:r:hdcd:s0",
......
......@@ -129,9 +129,6 @@
"mkdir /data/app-staging 0750 system system",
"copy /data/system/entropy.dat /dev/urandom",
"mkdir /data/misc 01771 system misc",
"mkdir /data/misc/wifi 0770 wifi wifi",
"mkdir /data/misc/wifi/sockets 0770 wifi wifi",
"mkdir /data/misc/wifi/wpa_supplicant 0770 wifi wifi",
"mkdir /data/local 0751 root root",
"mkdir /data/preloads 0775 system system",
"mkdir /data/vendor 0771 root root",
......
......@@ -19,7 +19,7 @@ const.allow.mock.location=0
const.debuggable=1
const.build.characteristics=default
const.product.model=ohos
const.product.name="OpenHarmony 2.0 Canary"
const.product.name="OpenHarmony 3.2"
persist.sys.usb.config=hdc
const.sandbox=enable
const.product.devicetype=default
......@@ -30,7 +30,7 @@ const.build.product=default
const.product.hardwareversion=default
const.product.bootloader.version=bootloader
const.product.cpu.abilist=default
const.product.software.version=OpenHarmony 3.2.7.5
const.product.software.version=OpenHarmony 3.2.8.1
const.product.incremental.version=default
const.product.firstapiversion=1
const.product.build.type=default
......
......@@ -16,8 +16,8 @@ vpn:x:1016:1016:::/bin/false
keystore:x:1017:1017:::/bin/false
usb:x:1018:1018:::/bin/false
drm:x:1019:1019:::/bin/false
gps:x:1020:1020:::/bin/false
location_host:x:1021:1021:::/bin/false
gps:x:1021:1021:::/bin/false
location_host:x:1022:1022:::/bin/false
media_rw:x:1023:1023:::/bin/false
dsoftbus:x:1024:1024:::/bin/false
nfc:x:1027:1027:::/bin/false
......@@ -77,6 +77,7 @@ vendor_mpp_driver:x:3061:3061:::/bin/false
device_manager:x:3062:3062:::/bin/false
deviceauth:x:3333:3333:::/bin/false
huks_server:x:3510:3510:::/bin/false
cert_manager_server:x:3515:3515:::/bin/false
dms:x:5522:5522:::/bin/false
foundation:x:5523:5523:::/bin/false
quickfixserver:x:5524:5524:::/bin/false
......@@ -84,8 +85,6 @@ samgr:x:5555:5555:::/bin/false
dbms:x:6000:6000:::/bin/false
update:x:6666:6666:::/bin/false
charger:x:6667:6667:::/bin/false
battery_stats:x:6668:6668:::/bin/false
thermal:x:6669:6669:::/bin/false
sensor:x:6688:6688:::/bin/false
input:x:6696:6696:::/bin/false
msdp:x:6699:6699:::/bin/false
......
......@@ -2,4 +2,7 @@ root:x:0:
bin:x:2:
system:x:1000:
servicectrl:x:1050:root,shell,system,samgr,hdf_devmgr
shell:x:2000:
\ No newline at end of file
shell:x:2000:
faultloggerd:x:1202:root,system
watchdog:x:2001:root
ueventd:x:2002:root
......@@ -11,7 +11,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
const.ohos.releasetype=Beta
const.ohos.apiversion=6
const.ohos.version.security_patch=2021-09-01
const.ohos.fullname=OpenHarmony-1.0.1.0
\ No newline at end of file
const.ohos.releasetype=Beta3
const.ohos.apiversion=9
const.ohos.version.security_patch=2022-09-01
const.ohos.fullname=OpenHarmony-3.2.8.1
\ No newline at end of file
......@@ -2,3 +2,6 @@ root:x:0:0:::/bin/false
bin:x:2:2:::/bin/false
system:x:1000:1000:::/bin/false
shell:x:2000:2000:::/bin/false
faultloggerd:x:1202:1202:::/bin/false
watchdog:x:2001:2001:::/bin/false
ueventd:x:2002:2002:::/bin/false
......@@ -51,6 +51,7 @@ typedef enum {
PARAM_CODE_READ_ONLY,
PARAM_CODE_FAIL_CONNECT,
PARAM_CODE_NODE_EXIST, // 9
PARAM_CODE_INVALID_SOCKET,
DAC_RESULT_INVALID_PARAM = 1000,
DAC_RESULT_FORBIDED,
PARAM_CODE_MAX
......
......@@ -17,7 +17,10 @@
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include "cJSON.h"
#ifdef __cplusplus
#if __cplusplus
......@@ -68,6 +71,11 @@ struct CmdTable {
void (*DoFuncion)(const struct CmdArgs *ctx);
};
typedef struct INIT_TIMING_STAT {
struct timespec startTime;
struct timespec endTime;
} INIT_TIMING_STAT;
int GetParamValue(const char *symValue, unsigned int symLen, char *paramValue, unsigned int paramLen);
const struct CmdArgs *GetCmdArg(const char *cmdContent, const char *delim, int argsCount);
void FreeCmdArg(struct CmdArgs *cmd);
......@@ -84,6 +92,7 @@ void ExecCmd(const struct CmdTable *cmd, const char *cmdContent);
int SetFileCryptPolicy(const char *dir);
void OpenHidebug(const char *name);
long long InitDiffTime(INIT_TIMING_STAT *stat);
#ifdef __cplusplus
#if __cplusplus
}
......
......@@ -44,7 +44,7 @@ int DoJobNow(const char *jobName);
#define INIT_CONFIGURATION_FILE "/etc/init.without_two_stages.cfg"
#endif
#define OTHER_CFG_PATH "/system/etc/init"
#define OTHER_CHARGE_PATH "/system/etc/charge"
#define OTHER_CHARGE_PATH "/vendor/etc/charger"
#define MAX_PATH_ARGS_CNT 20
void ReadConfig(void);
......
......@@ -50,6 +50,8 @@ extern "C" {
#define SERVICE_ATTR_NEEDWAIT 0x400 // service should execute waitpid while stopping
#define SERVICE_ATTR_WITHOUT_SANDBOX 0x800 // make service not enter sandbox
#define SERVICE_ATTR_NOTIFY_STATE 0x1000 // service notify state
#define MAX_SERVICE_NAME 32
#define MAX_APL_NAME 32
#define MAX_ENV_NAME 64
......@@ -155,7 +157,7 @@ typedef struct Service_ {
size_t fdCount;
TimerHandle timer;
ServiceJobs serviceJobs;
cpu_set_t cpuSet;
cpu_set_t *cpuSet;
struct ListNode extDataNode;
} Service;
#pragma pack()
......
......@@ -111,7 +111,7 @@ int GetServiceCaps(const cJSON *curArrItem, Service *service)
caps = (unsigned int)cJSON_GetNumberValue(capJson);
} else if (cJSON_IsString(capJson)) {
capStr = cJSON_GetStringValue(capJson);
if (capStr == NULL || strlen(capStr) <= 0) { // check all errors
if (capStr == NULL || strlen(capStr) == 0) { // check all errors
INIT_LOGE("service=%s, parse item[%d] as string, error.", service->name, i);
break;
}
......
......@@ -316,7 +316,7 @@ static void DoMkDir(const struct CmdArgs *ctx)
}
mode_t mode = DEFAULT_DIR_MODE;
if (mkdir(ctx->argv[0], mode) != 0 && errno != EEXIST) {
INIT_LOGE("DoMkDir, failed for '%s', err %d.", ctx->argv[0], errno);
INIT_LOGE("Create directory '%s' failed, err=%d.", ctx->argv[0], errno);
return;
}
......@@ -338,7 +338,7 @@ static void DoMkDir(const struct CmdArgs *ctx)
}
ret = SetFileCryptPolicy(ctx->argv[0]);
if (ret != 0) {
INIT_LOGW("failed to set file fscrypt");
INIT_LOGW("Failed to set file fscrypt");
}
return;
......@@ -354,7 +354,7 @@ static void DoChmod(const struct CmdArgs *ctx)
}
if (chmod(ctx->argv[1], mode) != 0) {
INIT_LOGE("Failed to change mode \" %s \" mode to %04o, err = %d", ctx->argv[1], mode, errno);
INIT_LOGE("Failed to change mode \" %s \" to %04o, err=%d", ctx->argv[1], mode, errno);
}
}
......@@ -525,21 +525,21 @@ static void DoSetrlimit(const struct CmdArgs *ctx)
INIT_LOGE("DoSetrlimit failed, resources :%s not support.", ctx->argv[0]);
return;
}
INIT_CHECK_ONLY_ELOG(setrlimit(rcs, &limit) == 0, "DoSetrlimit failed : %d", errno);
INIT_CHECK_ONLY_ELOG(setrlimit(rcs, &limit) == 0, "Failed setrlimit err=%d", errno);
return;
}
static void DoRm(const struct CmdArgs *ctx)
{
// format: rm /xxx/xxx/xxx
INIT_CHECK_ONLY_ELOG(unlink(ctx->argv[0]) != -1, "DoRm: unlink %s failed: %d.", ctx->argv[0], errno);
INIT_CHECK_ONLY_ELOG(unlink(ctx->argv[0]) != -1, "Failed unlink %s err=%d.", ctx->argv[0], errno);
return;
}
static void DoExport(const struct CmdArgs *ctx)
{
// format: export xxx /xxx/xxx/xxx
INIT_CHECK_ONLY_ELOG(setenv(ctx->argv[0], ctx->argv[1], 1) == 0, "DoExport: set %s with %s failed: %d",
INIT_CHECK_ONLY_ELOG(setenv(ctx->argv[0], ctx->argv[1], 1) == 0, "Failed setenv %s with %s err=%d.",
ctx->argv[0], ctx->argv[1], errno);
return;
}
......@@ -693,17 +693,33 @@ int GetCmdLinesFromJson(const cJSON *root, CmdLines **cmdLines)
return 0;
}
long long InitDiffTime(INIT_TIMING_STAT *stat)
{
long long diff = (long long)((stat->endTime.tv_sec - stat->startTime.tv_sec) * 1000000); // 1000000 1000ms
if (stat->endTime.tv_nsec > stat->startTime.tv_nsec) {
diff += (stat->endTime.tv_nsec - stat->startTime.tv_nsec) / 1000; // 1000 ms
} else {
diff -= (stat->startTime.tv_nsec - stat->endTime.tv_nsec) / 1000; // 1000 ms
}
return diff;
}
void DoCmdByName(const char *name, const char *cmdContent)
{
if (name == NULL || cmdContent == NULL) {
return;
}
INIT_TIMING_STAT cmdTimer;
(void)clock_gettime(CLOCK_MONOTONIC, &cmdTimer.startTime);
const struct CmdTable *cmd = GetCmdByName(name);
if (cmd != NULL) {
ExecCmd(cmd, cmdContent);
return;
} else {
PluginExecCmdByName(name, cmdContent);
}
PluginExecCmdByName(name, cmdContent);
(void)clock_gettime(CLOCK_MONOTONIC, &cmdTimer.endTime);
long long diff = InitDiffTime(&cmdTimer);
INIT_LOGV("Execute command \"%s %s\" took %lld ms", name, cmdContent, diff / 1000); // 1000 is convert us to ms
}
void DoCmdByIndex(int index, const char *cmdContent)
......@@ -712,16 +728,28 @@ void DoCmdByIndex(int index, const char *cmdContent)
return;
}
int cmdCnt = 0;
INIT_TIMING_STAT cmdTimer;
(void)clock_gettime(CLOCK_MONOTONIC, &cmdTimer.startTime);
const struct CmdTable *commCmds = GetCommCmdTable(&cmdCnt);
const char *cmdName = NULL;
if (index < cmdCnt) {
cmdName = commCmds[index].name;
ExecCmd(&commCmds[index], cmdContent);
return;
}
int number = 0;
const struct CmdTable *cmds = GetCmdTable(&number);
if (index < (cmdCnt + number)) {
ExecCmd(&cmds[index - cmdCnt], cmdContent);
return;
} else {
int number = 0;
const struct CmdTable *cmds = GetCmdTable(&number);
if (index < (cmdCnt + number)) {
cmdName = cmds[index - cmdCnt].name;
ExecCmd(&cmds[index - cmdCnt], cmdContent);
} else {
PluginExecCmdByCmdIndex(index, cmdContent);
cmdName = GetPluginCmdNameByIndex(index);
if (cmdName == NULL) {
cmdName = "Unknown";
}
}
}
PluginExecCmdByCmdIndex(index, cmdContent);
(void)clock_gettime(CLOCK_MONOTONIC, &cmdTimer.endTime);
long long diff = InitDiffTime(&cmdTimer);
INIT_LOGV("Execute command \"%s %s\" took %lld ms", cmdName, cmdContent, diff / 1000); // 1000 is convert us to ms
}
......@@ -264,15 +264,15 @@ static void PublishHoldFds(Service *service)
static int BindCpuCore(Service *service)
{
if (service == NULL) {
if (service == NULL || service->cpuSet == NULL) {
return SERVICE_SUCCESS;
}
if (CPU_COUNT(&service->cpuSet) == 0) {
if (CPU_COUNT(service->cpuSet) == 0) {
return SERVICE_SUCCESS;
}
#ifndef __LITEOS_A__
int pid = getpid();
INIT_ERROR_CHECK(sched_setaffinity(pid, sizeof(service->cpuSet), &service->cpuSet) == 0,
INIT_ERROR_CHECK(sched_setaffinity(pid, sizeof(cpu_set_t), service->cpuSet) == 0,
return SERVICE_FAILURE, "%s set affinity between process(pid=%d) with CPU's core failed", service->name, pid);
INIT_LOGI("%s set affinity between process(pid=%d) with CPU's core successfully", service->name, pid);
#endif
......@@ -295,13 +295,13 @@ static int InitServiceProperties(Service *service)
{
INIT_ERROR_CHECK(service != NULL, return -1, "Invalid parameter.");
SetServiceEnterSandbox(service->pathArgs.argv[0], service->attribute);
INIT_CHECK_ONLY_ELOG(SetAccessToken(service) == SERVICE_SUCCESS, "access token failed %s", service->name);
INIT_CHECK_ONLY_ELOG(SetAccessToken(service) == SERVICE_SUCCESS,
"Set service %s access token failed", service->name);
// deal start job
if (service->serviceJobs.jobsName[JOB_ON_START] != NULL) {
DoJobNow(service->serviceJobs.jobsName[JOB_ON_START]);
}
ClearEnvironment(service);
if (!IsOnDemandService(service)) {
INIT_ERROR_CHECK(CreateServiceSocket(service) >= 0, return -1,
"service %s exit! create socket failed!", service->name);
......@@ -321,7 +321,7 @@ static int InitServiceProperties(Service *service)
// permissions
INIT_ERROR_CHECK(SetPerms(service) == SERVICE_SUCCESS, return -1,
"service %s exit! set perms failed! err %d.", service->name, errno);
// write pid
INIT_ERROR_CHECK(WritePid(service) == SERVICE_SUCCESS, return -1,
"service %s exit! write pid failed!", service->name);
......@@ -350,7 +350,7 @@ void EnterServiceSandbox(Service *service)
int ServiceStart(Service *service)
{
INIT_ERROR_CHECK(service != NULL, return SERVICE_FAILURE, "start service failed! null ptr.");
INIT_ERROR_CHECK(service->pid <= 0, return SERVICE_SUCCESS, "service : %s had started already.", service->name);
INIT_ERROR_CHECK(service->pid <= 0, return SERVICE_SUCCESS, "Service %s already started", service->name);
INIT_ERROR_CHECK(service->pathArgs.count > 0,
return SERVICE_FAILURE, "start service %s pathArgs is NULL.", service->name);
......@@ -382,7 +382,7 @@ int ServiceStart(Service *service)
INIT_LOGE("start service %s fork failed!", service->name);
return SERVICE_FAILURE;
}
INIT_LOGI("service %s starting pid %d", service->name, pid);
INIT_LOGI("Service %s(pid %d) started", service->name, pid);
service->pid = pid;
NotifyServiceChange(service, SERVICE_STARTED);
return SERVICE_SUCCESS;
......
......@@ -34,7 +34,7 @@ static void ParseInitCfgContents(const char *cfgName, const cJSON *root)
int ParseInitCfg(const char *configFile, void *context)
{
UNUSED(context);
INIT_LOGI("ParseInitCfg %s", configFile);
INIT_LOGV("Parse init configs from %s", configFile);
static const char *excludeCfg[] = {
"/system/etc/init/weston.cfg"
};
......
......@@ -49,7 +49,6 @@ static int ParseGroupCfgItem(cJSON *root, int type, const char *itemName)
{
int itemNumber = 0;
cJSON *json = GetArrayItem(root, &itemNumber, itemName);
INIT_LOGI("ParseGroupCfgItem %s itemNumber %d", itemName, itemNumber);
if (json == NULL) {
return 0;
}
......@@ -189,7 +188,7 @@ void InitServiceSpace(void)
int ret = GetProcCmdlineValue(BOOT_GROUP_NAME, data,
g_initWorkspace.groupModeStr, sizeof(g_initWorkspace.groupModeStr));
if (ret != 0) {
INIT_LOGE("%s", "Failed to get boot group");
INIT_LOGV("Failed to get boot group");
if (GetBootModeFromMisc() == GROUP_CHARGE) {
strcpy_s(g_initWorkspace.groupModeStr, sizeof(g_initWorkspace.groupModeStr), "device.charge.group");
}
......
......@@ -39,7 +39,7 @@ static int CreateFile(ServiceFile *file)
INIT_ERROR_CHECK(strncpy_s(path, strlen(file->fileName) + 1, file->fileName, strlen(file->fileName)) >= 0,
return -1, "Failed strncpy_s err=%d", errno);
}
INIT_LOGI("File path =%s . file flags =%d, file perm =%u ", path, file->flags, file->perm);
INIT_LOGV("File path =%s . file flags =%d, file perm =%u ", path, file->flags, file->perm);
if (file->fd >= 0) {
close(file->fd);
file->fd = -1;
......@@ -64,7 +64,6 @@ static int SetFileEnv(int fd, const char *pathName)
char val[MAX_FILE_FD_LEN] = { 0 };
INIT_ERROR_CHECK(snprintf_s(val, sizeof(val), sizeof(val) - 1, "%d", fd) >= 0, return -1,
"Failed snprintf_s err=%d", errno);
INIT_LOGE("Set file env pubName =%s, val =%s.", pubName, val);
int ret = setenv(pubName, val, 1);
INIT_ERROR_CHECK(ret >= 0, return -1, "Failed setenv err=%d ", errno);
fcntl(fd, F_SETFD, 0);
......
......@@ -95,7 +95,7 @@ Service *AddService(const char *name)
node->data.service = service;
service->name = node->name;
service->status = SERVICE_IDLE;
CPU_ZERO(&service->cpuSet);
service->cpuSet = NULL;
OH_ListInit(&service->extDataNode);
g_serviceSpace.serviceCount++;
INIT_LOGV("AddService %s", node->name);
......@@ -150,6 +150,10 @@ void ReleaseService(Service *service)
}
service->serviceJobs.jobsName[i] = NULL;
}
if (service->cpuSet != NULL) {
free(service->cpuSet);
service->cpuSet = NULL;
}
#ifndef OHOS_LITE
// clear ext data
SERVICE_INFO_CTX ctx = {0};
......@@ -213,7 +217,7 @@ static int GetServiceArgs(const cJSON *argJson, const char *name, int maxCount,
INIT_ERROR_CHECK(curParam != NULL, return SERVICE_FAILURE, "Invalid arg %d", i);
INIT_ERROR_CHECK(strlen(curParam) <= MAX_ONE_ARG_LEN, return SERVICE_FAILURE, "Arg %s is tool long", curParam);
args->argv[i] = strdup(curParam);
INIT_ERROR_CHECK(args->argv[i] != NULL, return SERVICE_FAILURE, "Failed to dupstring %s", curParam);
INIT_ERROR_CHECK(args->argv[i] != NULL, return SERVICE_FAILURE, "Failed to duplicate argument %s", curParam);
}
return SERVICE_SUCCESS;
}
......@@ -265,13 +269,13 @@ static int GetServiceGids(const cJSON *curArrItem, Service *curServ)
free(curServ->servPerm.gIDArray);
}
curServ->servPerm.gIDArray = (gid_t *)malloc(sizeof(gid_t) * gidCount);
INIT_ERROR_CHECK(curServ->servPerm.gIDArray != NULL, return SERVICE_FAILURE, "Failed to malloc");
INIT_ERROR_CHECK(curServ->servPerm.gIDArray != NULL, return SERVICE_FAILURE, "Failed to malloc err=%d", errno);
curServ->servPerm.gIDCnt = gidCount;
gid_t gid;
if (!cJSON_IsArray(arrItem)) {
int ret = GetGid(arrItem, &gid, curServ);
INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to gid");
INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Parse service %s gid failed.", curServ->name);
curServ->servPerm.gIDArray[0] = gid;
return SERVICE_SUCCESS;
}
......@@ -280,7 +284,7 @@ static int GetServiceGids(const cJSON *curArrItem, Service *curServ)
cJSON *item = cJSON_GetArrayItem(arrItem, i);
int ret = GetGid(item, &gid, curServ);
if (ret != 0) {
INIT_LOGE("parse service %s %d gid failed skip this", curServ->name, i);
INIT_LOGW("Parse service %s gid failed from item %s.", curServ->name, cJSON_Print(item));
continue;
}
curServ->servPerm.gIDArray[gidArrayIndex++] = gid;
......@@ -684,6 +688,11 @@ static int GetCpuArgs(const cJSON *argJson, const char *name, Service *service)
int count = cJSON_GetArraySize(obj);
int cpus = -1;
int cpuNumMax = sysconf(_SC_NPROCESSORS_CONF);
if (count > 0 && service->cpuSet == NULL) {
service->cpuSet = malloc(sizeof(cpu_set_t));
INIT_ERROR_CHECK(service->cpuSet != NULL, return SERVICE_FAILURE, "Failed to malloc for cpuset");
}
CPU_ZERO(service->cpuSet);
for (int i = 0; i < count; ++i) {
cJSON *item = cJSON_GetArrayItem(obj, i);
INIT_ERROR_CHECK(item != NULL, return SERVICE_FAILURE, "prase invalid");
......@@ -692,10 +701,10 @@ static int GetCpuArgs(const cJSON *argJson, const char *name, Service *service)
INIT_LOGW("%s core number %d of CPU cores does not exist", service->name, cpus);
continue;
}
if (CPU_ISSET(cpus, &service->cpuSet)) {
if (CPU_ISSET(cpus, service->cpuSet)) {
continue;
}
CPU_SET(cpus, &service->cpuSet);
CPU_SET(cpus, service->cpuSet);
}
return SERVICE_SUCCESS;
}
......@@ -836,6 +845,8 @@ int ParseOneService(const cJSON *curItem, Service *service)
INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get disabled flag for service %s", service->name);
ret = GetServiceAttr(curItem, service, CONSOLE_STR_IN_CFG, SERVICE_ATTR_CONSOLE, NULL);
INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get console for service %s", service->name);
ret = GetServiceAttr(curItem, service, "notify-state", SERVICE_ATTR_NOTIFY_STATE, NULL);
INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get notify-state for service %s", service->name);
ParseOneServiceArgs(curItem, service);
ret = GetServiceSandbox(curItem, service);
......@@ -990,14 +1001,14 @@ void ParseAllServices(const cJSON *fileRoot)
continue;
}
Service *service = GetServiceByName(fieldStr);
if (service != NULL) {
INIT_LOGE("Service \' %s \' already exist", fieldStr);
continue;
}
service = AddService(fieldStr);
if (service == NULL) {
INIT_LOGE("Failed to create service name %s", fieldStr);
continue;
service = AddService(fieldStr);
if (service == NULL) {
INIT_LOGE("Failed to add service name %s", fieldStr);
continue;
}
} else {
INIT_LOGI("Service %s already exists, updating.", fieldStr);
}
service->pid = -1;
int ret = ParseOneService(curItem, service);
......@@ -1071,7 +1082,7 @@ static Service *GetServiceByExtServName(const char *fullServName)
void StartServiceByName(const char *servName)
{
INIT_LOGI("StartServiceByName Service %s", servName);
INIT_LOGI("Start service %s", servName);
Service *service = GetServiceByName(servName);
if (service == NULL) {
service = GetServiceByExtServName(servName);
......@@ -1094,7 +1105,7 @@ void StopServiceByName(const char *servName)
INIT_ERROR_CHECK(service != NULL, return, "Cannot find service %s.", servName);
if (ServiceStop(service) != SERVICE_SUCCESS) {
INIT_LOGE("Service %s start failed!", servName);
INIT_LOGE("Service %s stop failed!", servName);
}
return;
}
......
......@@ -123,8 +123,8 @@ static int SetSocketOptionAndBind(ServiceSocket *sockopt)
static int CreateSocket(ServiceSocket *sockopt)
{
INIT_ERROR_CHECK(sockopt != NULL, return SERVICE_FAILURE, "Invalid socket opt");
INIT_LOGI("name: %s, family: %d, type: %u, protocol: %d, perm: %u, uid: %u, gid: %u, option: %u",
INIT_ERROR_CHECK(sockopt != NULL, return SERVICE_FAILURE, "Invalid socket options");
INIT_LOGV("Socket name: %s, family: %d, type: %u, protocol: %d, perm: %u, uid: %u, gid: %u, option: %u",
sockopt->name, sockopt->family, sockopt->type, sockopt->protocol,
sockopt->perm, sockopt->uid, sockopt->gid, sockopt->option);
if (sockopt->sockFd >= 0) {
......@@ -192,7 +192,7 @@ int SocketAddWatcher(ServiceWatcher *watcherHandle, Service *service, int fd)
info.events = Event_Read;
info.processEvent = ProcessWatchEvent_;
int ret = LE_StartWatcher(LE_GetDefaultLoop(), &handle, &info, service);
INIT_LOGI("Start to monitor socket, fd:%d service name:%s", fd, service->name);
INIT_LOGI("Watcher socket fd %d for service %s", fd, service->name);
*watcherHandle = (ServiceWatcher)handle;
return ret;
}
......
......@@ -74,7 +74,6 @@ static void DoLoadCfg(const struct CmdArgs *ctx)
{
char buf[LOADCFG_BUF_SIZE] = { 0 };
size_t maxLoop = 0;
int len;
if (!CheckValidCfg(ctx->argv[0])) {
INIT_LOGE("CheckCfg file %s Failed", ctx->argv[0]);
return;
......@@ -90,7 +89,7 @@ static void DoLoadCfg(const struct CmdArgs *ctx)
while (fgets(buf, LOADCFG_BUF_SIZE - 1, fp) != NULL && maxLoop < LOADCFG_MAX_LOOP) {
maxLoop++;
len = strlen(buf);
int len = strlen(buf);
if (len < 1) {
continue;
}
......@@ -122,14 +121,22 @@ const struct CmdTable *GetCmdTable(int *number)
void PluginExecCmdByName(const char *name, const char *cmdContent)
{
}
void PluginExecCmdByCmdIndex(int index, const char *cmdContent)
{
}
const char *PluginGetCmdIndex(const char *cmdStr, int *index)
{
return NULL;
}
const char *GetPluginCmdNameByIndex(int index)
{
return NULL;
}
int SetFileCryptPolicy(const char *dir)
{
return 0;
}
\ No newline at end of file
}
......@@ -66,21 +66,8 @@ int ServiceExec(const Service *service)
{
INIT_ERROR_CHECK(service != NULL && service->pathArgs.count > 0,
return SERVICE_FAILURE, "Exec service failed! null ptr.");
INIT_LOGI("service->name is %s ", service->name);
char sockEnvName[MAX_ENV_NAME] = {0};
char sockEnvValue[MAX_ENV_NAME] = {0};
if (service->socketCfg != NULL) {
INIT_ERROR_CHECK(snprintf_s(sockEnvName, MAX_ENV_NAME, MAX_ENV_NAME - 1, "OHOS_SOCKET_%s",
service->socketCfg->name) != -1,
return SERVICE_FAILURE, "format socket env name failed!");
INIT_ERROR_CHECK(snprintf_s(sockEnvValue, MAX_ENV_NAME, MAX_ENV_NAME - 1, "%d",
service->socketCfg->sockFd) != -1,
return SERVICE_FAILURE, "format socket env value failed!");
}
INIT_CHECK_ONLY_ELOG(setenv(sockEnvName, sockEnvValue, 1) == 0, "DoExport: set %s with %s failed: %d",
sockEnvName, sockEnvValue, errno);
if (execv(service->pathArgs.argv[0], service->pathArgs.argv) != 0) {
INIT_LOGE("service %s execv failed! err %d.", service->name, errno);
INIT_LOGE("Service %s execv failed! err=%d.", service->name, errno);
return errno;
}
return SERVICE_SUCCESS;
......
......@@ -135,23 +135,20 @@ static void SendFdsInfo(int sock, Service *service)
static void HandlerGetFds(int sock, Service *service)
{
const char *errorInfo = NULL;
if (sock < 0 || service == NULL) {
INIT_LOGE("Get fd from init with invalid parameter");
errorInfo = "Invalid parameter";
SendErrorInfo(sock, "Invalid parameter", "");
return;
}
if (service->fds == NULL || service->fdCount == 0) {
INIT_LOGE("Service \' %s \' does not have any held fds", service->name);
errorInfo = "Service without any fds";
SendErrorInfo(sock, "Service without any fds", service->name);
return;
}
if (errorInfo != NULL) {
SendErrorInfo(sock, errorInfo, service->name);
} else {
// Send fds back to service
SendFdsInfo(sock, service);
}
// Send fds back to service
SendFdsInfo(sock, service);
}
static int CheckFdHolderPermission(Service *service, pid_t requestPid)
......
......@@ -46,11 +46,6 @@
#include "fd_holder_internal.h"
#include "bootstage.h"
typedef struct HOOK_TIMING_STAT {
struct timespec startTime;
struct timespec endTime;
} HOOK_TIMING_STAT;
static int FdHolderSockInit(void)
{
int sock = -1;
......@@ -206,6 +201,7 @@ static void StartInitSecondStage(void)
KeyCtrlGetKeyringId(KEY_SPEC_SESSION_KEYRING, 1);
#ifndef DISABLE_INIT_TWO_STAGES
INIT_LOGI("Start init second stage.");
SwitchRoot("/usr");
// Execute init second stage
char * const args[] = {
......@@ -227,9 +223,10 @@ void SystemPrepare(void)
LogInit();
// Make sure init log always output to /dev/kmsg.
EnableDevKmsg();
INIT_LOGI("Start init first stage.");
// Only ohos normal system support
// two stages of init.
// If we are in updater mode, only one stage of init,
// If we are in updater mode, only one stage of init.
if (InUpdaterMode() == 0) {
StartInitSecondStage();
}
......@@ -252,25 +249,24 @@ HOOK_MGR *GetBootStageHookMgr()
return bootStageHookMgr;
}
HOOK_TIMING_STAT g_bootJob = {0};
static long long InitDiffTime(HOOK_TIMING_STAT *stat)
INIT_TIMING_STAT g_bootJob = {0};
static void RecordInitBootEvent(const char *initBootEvent)
{
long long diff = (long long)((stat->endTime.tv_sec - stat->startTime.tv_sec) * 1000000); // 1000000 1000ms
if (stat->endTime.tv_nsec > stat->startTime.tv_nsec) {
diff += (stat->endTime.tv_nsec - stat->startTime.tv_nsec) / 1000; // 1000 ms
} else {
diff -= (stat->startTime.tv_nsec - stat->endTime.tv_nsec) / 1000; // 1000 ms
}
return diff;
const char *bootEventArgv[] = {"init", initBootEvent};
PluginExecCmd("bootevent", ARRAY_LENGTH(bootEventArgv), bootEventArgv);
return;
}
static void BootStateChange(int start, const char *content)
{
if (start == 0) {
clock_gettime(CLOCK_MONOTONIC, &(g_bootJob.startTime));
RecordInitBootEvent(content);
INIT_LOGI("boot job %s start.", content);
} else {
clock_gettime(CLOCK_MONOTONIC, &(g_bootJob.endTime));
RecordInitBootEvent(content);
long long diff = InitDiffTime(&g_bootJob);
INIT_LOGI("boot job %s finish diff %lld us.", content, diff);
}
......@@ -297,19 +293,35 @@ static void InitLoadParamFiles(void)
static void InitPreHook(const HOOK_INFO *hookInfo, void *executionContext)
{
HOOK_TIMING_STAT *stat = (HOOK_TIMING_STAT *)executionContext;
INIT_TIMING_STAT *stat = (INIT_TIMING_STAT *)executionContext;
clock_gettime(CLOCK_MONOTONIC, &(stat->startTime));
}
static void InitPostHook(const HOOK_INFO *hookInfo, void *executionContext, int executionRetVal)
{
HOOK_TIMING_STAT *stat = (HOOK_TIMING_STAT *)executionContext;
INIT_TIMING_STAT *stat = (INIT_TIMING_STAT *)executionContext;
clock_gettime(CLOCK_MONOTONIC, &(stat->endTime));
long long diff = InitDiffTime(stat);
INIT_LOGI("Executing hook [%d:%d:%p] cost [%lld]us, return %d.",
hookInfo->stage, hookInfo->prio, hookInfo->hook, diff, executionRetVal);
}
static void InitSysAdj(void)
{
const char* path = "/proc/self/oom_score_adj";
const char* content = "-1000";
int fd = open(path, O_RDWR);
if (fd == -1) {
return;
}
if (write(fd, content, strlen(content)) < 0) {
close(fd);
return;
}
close(fd);
return;
}
static void TriggerServices(int startMode)
{
int index = 0;
......@@ -352,15 +364,17 @@ static void TriggerServices(int startMode)
void SystemConfig(void)
{
HOOK_TIMING_STAT timingStat;
INIT_TIMING_STAT timingStat;
InitSysAdj();
HOOK_EXEC_OPTIONS options;
options.flags = 0;
options.preHook = InitPreHook;
options.postHook = InitPostHook;
InitServiceSpace();
HookMgrExecute(GetBootStageHookMgr(), INIT_GLOBAL_INIT, (void *)&timingStat, (void *)&options);
RecordInitBootEvent("init.prepare");
HookMgrExecute(GetBootStageHookMgr(), INIT_PRE_PARAM_SERVICE, (void *)&timingStat, (void *)&options);
InitParamService();
......@@ -371,7 +385,9 @@ void SystemConfig(void)
// load SELinux context and policy
// Do not move position!
PluginExecCmdByName("loadSelinuxPolicy", "");
RecordInitBootEvent("init.prepare");
RecordInitBootEvent("init.ParseCfg");
LoadSpecialParam();
// parse parameters
......@@ -380,6 +396,7 @@ void SystemConfig(void)
// read config
HookMgrExecute(GetBootStageHookMgr(), INIT_PRE_CFG_LOAD, (void *)&timingStat, (void *)&options);
ReadConfig();
RecordInitBootEvent("init.ParseCfg");
INIT_LOGI("boot parse config file done.");
HookMgrExecute(GetBootStageHookMgr(), INIT_POST_CFG_LOAD, (void *)&timingStat, (void *)&options);
......
......@@ -29,7 +29,7 @@ static int g_cmdId = 0;
int AddCmdExecutor(const char *cmdName, CmdExecutor execCmd)
{
INIT_ERROR_CHECK(cmdName != NULL, return -1, "Invalid input param");
INIT_LOGI("AddCmdExecutor '%s'", cmdName);
INIT_LOGV("Add command '%s' executor.", cmdName);
PluginCmd *cmd = NULL;
InitGroupNode *groupNode = GetGroupNode(NODE_TYPE_CMDS, cmdName);
if (groupNode == NULL) {
......@@ -144,20 +144,39 @@ static int CompareCmdId(const HashNode *node, const void *key)
return cmd->cmdId - *(int *)key;
}
void PluginExecCmdByCmdIndex(int index, const char *cmdContent)
static PluginCmd *GetPluginCmdByIndex(int index)
{
int hashCode = ((index >> 16) & 0x0000ffff) - 1; // 16 left shift
int cmdId = (index & 0x0000ffff);
HashNode *node = OH_HashMapFind(GetGroupHashMap(NODE_TYPE_CMDS),
hashCode, (const void *)&cmdId, CompareCmdId);
if (node == NULL) {
return;
return NULL;
}
InitGroupNode *groupNode = HASHMAP_ENTRY(node, InitGroupNode, hashNode);
if (groupNode == NULL || groupNode->data.cmd == NULL) {
return NULL;
}
return groupNode->data.cmd;
}
const char *GetPluginCmdNameByIndex(int index)
{
PluginCmd *cmd = GetPluginCmdByIndex(index);
if (cmd == NULL) {
return NULL;
}
return cmd->name;
}
void PluginExecCmdByCmdIndex(int index, const char *cmdContent)
{
PluginCmd *cmd = GetPluginCmdByIndex(index);
if (cmd == NULL) {
INIT_LOGW("Cannot find plugin command with index %d", index);
return;
}
PluginCmd *cmd = groupNode->data.cmd;
INIT_LOGV("Command: %s cmdContent: %s", cmd->name, cmdContent);
PluginExecCmd_(cmd, cmdContent);
}
......@@ -186,6 +205,5 @@ const char *PluginGetCmdIndex(const char *cmdStr, int *index)
hashCode = (hashCode < 0) ? -hashCode : hashCode;
hashCode = hashCode % GROUP_HASHMAP_BUCKET;
*index = ((hashCode + 1) << 16) | cmd->cmdId; // 16 left shift
INIT_LOGI("PluginGetCmdIndex content: %s index %d", cmd->name, *index);
return cmd->name;
}
......@@ -92,7 +92,7 @@ int GetParamValue(const char *symValue, unsigned int symLen, char *paramValue, u
static void SyncExecCommand(int argc, char * const *argv)
{
INIT_CHECK(!(argc == 0 || argv == NULL || argv[0] == NULL), return);
INIT_LOGI("sync exec: %s", argv[0]);
INIT_LOGI("Sync exec: %s", argv[0]);
pid_t pid = fork();
INIT_ERROR_CHECK(!(pid < 0), return, "Fork new process to format failed: %d", errno);
if (pid == 0) {
......@@ -105,7 +105,7 @@ static void SyncExecCommand(int argc, char * const *argv)
INIT_LOGE("Failed to wait pid %d, errno %d", pid, errno);
return;
}
INIT_LOGI("sync exec: %s result %d %d", argv[0], WEXITSTATUS(status), WIFEXITED(status));
INIT_LOGI("Sync exec: %s result %d %d", argv[0], WEXITSTATUS(status), WIFEXITED(status));
return;
}
......@@ -196,8 +196,7 @@ static void DoLoadDefaultParams(const struct CmdArgs *ctx)
static void DoSyncExec(const struct CmdArgs *ctx)
{
// format: syncexec /xxx/xxx/xxx xxx
INIT_ERROR_CHECK(ctx != NULL && ctx->argv[0] != NULL, return,
"DoSyncExec: invalid arguments to exec \"%s\"", ctx->argv[0]);
INIT_ERROR_CHECK(ctx != NULL && ctx->argv[0] != NULL, return, "DoSyncExec: invalid arguments");
SyncExecCommand(ctx->argc, ctx->argv);
return;
}
......@@ -205,8 +204,7 @@ static void DoSyncExec(const struct CmdArgs *ctx)
static void DoExec(const struct CmdArgs *ctx)
{
// format: exec /xxx/xxx/xxx xxx
INIT_ERROR_CHECK(ctx != NULL && ctx->argv[0] != NULL, return,
"DoExec: invalid arguments to exec \"%s\"", ctx->argv[0]);
INIT_ERROR_CHECK(ctx != NULL && ctx->argv[0] != NULL, return, "DoExec: invalid arguments");
pid_t pid = fork();
INIT_ERROR_CHECK(pid >= 0, return, "DoExec: failed to fork child process to exec \"%s\"", ctx->argv[0]);
......@@ -424,17 +422,18 @@ static bool InitFscryptPolicy(void)
static void DoInitGlobalKey(const struct CmdArgs *ctx)
{
INIT_LOGV("Do init global key start");
if (ctx == NULL || ctx->argc != 1) {
INIT_LOGE("DoInitGlobalKey: para invalid");
INIT_LOGE("Parameter is invalid");
return;
}
const char *dataDir = "/data";
if (strncmp(ctx->argv[0], dataDir, strlen(dataDir)) != 0) {
INIT_LOGE("DoInitGlobalKey: not data partitation");
INIT_LOGE("Not data partitation");
return;
}
if (!InitFscryptPolicy()) {
INIT_LOGI("DoInitGlobalKey:init fscrypt failed,not enable fscrypt");
INIT_LOGW("Init fscrypt failed, not enable fscrypt");
return;
}
......@@ -451,7 +450,7 @@ static void DoInitGlobalKey(const struct CmdArgs *ctx)
static void DoInitMainUser(const struct CmdArgs *ctx)
{
if (ctx == NULL) {
INIT_LOGE("DoInitMainUser: para invalid");
INIT_LOGE("Do init main user: para invalid");
return;
}
......@@ -468,7 +467,7 @@ static void DoInitMainUser(const struct CmdArgs *ctx)
static void DoMkswap(const struct CmdArgs *ctx)
{
if (ctx == NULL) {
INIT_LOGE("DoMkswap: para invalid");
INIT_LOGE("Parameter is invalid");
return;
}
char *const argv[] = {
......@@ -483,7 +482,7 @@ static void DoMkswap(const struct CmdArgs *ctx)
static void DoSwapon(const struct CmdArgs *ctx)
{
if (ctx == NULL) {
INIT_LOGE("DoSwapon: para invalid");
INIT_LOGE("Parameter is invalid");
return;
}
char *const argv[] = {
......@@ -497,7 +496,7 @@ static void DoSwapon(const struct CmdArgs *ctx)
static void DoMkSandbox(const struct CmdArgs *ctx)
{
INIT_LOGI("DoMkSandbox: start");
INIT_LOGV("Do make sandbox start");
if ((ctx == NULL) || (ctx->argc != 1)) {
INIT_LOGE("Call DoMkSandbox with invalid arguments");
return;
......
......@@ -40,7 +40,7 @@ static bool g_enableSandbox = false;
void NotifyServiceChange(Service *service, int status)
{
INIT_LOGI("NotifyServiceChange %s %d to %d", service->name, service->status, status);
INIT_LOGV("Notify service %s change from %d to %d", service->name, service->status, status);
service->status = status;
INIT_CHECK(status != SERVICE_IDLE, return);
char paramName[PARAM_NAME_LEN_MAX] = { 0 };
......@@ -98,8 +98,11 @@ int SetAccessToken(const Service *service)
{
INIT_ERROR_CHECK(service != NULL, return SERVICE_FAILURE, "service is null");
int ret = SetSelfTokenID(service->tokenId);
INIT_LOGI("%s: token id %lld, set token id result %d", service->name, service->tokenId, ret);
return ret == 0 ? SERVICE_SUCCESS : SERVICE_FAILURE;
if (ret != 0) {
INIT_LOGV("Set service %s token id %lld failed.", service->name, service->tokenId);
return SERVICE_FAILURE;
}
return SERVICE_SUCCESS;
}
void GetAccessToken(void)
......@@ -125,7 +128,6 @@ void GetAccessToken(void)
service->name,
apl,
};
uint64_t tokenId = GetAccessTokenId(&nativeTokenInfoParams);
INIT_CHECK_ONLY_ELOG(tokenId != 0,
"Get totken id %lld of service \' %s \' failed", tokenId, service->name);
......
......@@ -35,15 +35,17 @@ static void ProcessSignal(const struct signalfd_siginfo *siginfo)
if (sigPID <= 0) {
break;
}
Service* service = GetServiceByPid(sigPID);
// check child process exit status
if (WIFSIGNALED(procStat)) {
INIT_LOGE("Child process %d exit with signal: %d", sigPID, WTERMSIG(procStat));
INIT_LOGE("Child process %s(pid %d) exit with code : %d",
service == NULL ? "Unknown" : service->name, sigPID, sigPID, WTERMSIG(procStat));
}
if (WIFEXITED(procStat)) {
INIT_LOGE("Child process %d exit with code : %d", sigPID, WEXITSTATUS(procStat));
INIT_LOGE("Child process %s(pid %d) exit with code : %d",
service == NULL ? "Unknown" : service->name, sigPID, WEXITSTATUS(procStat));
}
CmdServiceProcessDelClient(sigPID);
Service* service = GetServiceByPid(sigPID);
INIT_LOGI("SigHandler, SIGCHLD received, Service:%s pid:%d uid:%d status:%d.",
service == NULL ? "Unknown" : service->name,
sigPID, siginfo->ssi_uid, procStat);
......@@ -77,4 +79,4 @@ void SignalInit(void)
if (LE_AddSignal(LE_GetDefaultLoop(), g_sigHandle, SIGTERM) != 0) {
INIT_LOGW("start SIGTERM handler failed");
}
}
\ No newline at end of file
}
......@@ -25,6 +25,7 @@
#include "init_log.h"
#include "fs_manager/fs_manager.h"
#include "securec.h"
#include "init_utils.h"
static void FreeOldRoot(DIR *dir, dev_t dev)
{
......@@ -38,7 +39,7 @@ static void FreeOldRoot(DIR *dir, dev_t dev)
if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) {
continue;
}
isDir = false;
if (de->d_type == DT_DIR || de->d_type == DT_UNKNOWN) {
struct stat st = {};
if (fstatat(dfd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
......@@ -77,21 +78,14 @@ static void FreeOldRoot(DIR *dir, dev_t dev)
// all sub mount tree in the future.
static bool UnderBasicMountPoint(const char *path)
{
unsigned int i;
if (path == NULL || *path == '\0') {
return false;
}
size_t pathSize = strlen(path);
if (strncmp(path, "/dev", strlen("/dev")) == 0 && pathSize > strlen("/dev")) {
return true;
}
if (strncmp(path, "/sys", strlen("/sys")) == 0 && pathSize > strlen("/sys")) {
return true;
}
if (strncmp(path, "/proc", strlen("/proc")) == 0 && pathSize > strlen("/proc")) {
return true;
const char *basicMountPoint[] = {"/dev/", "/sys/", "/proc/"};
for (i = 0; i < ARRAY_LENGTH(basicMountPoint); i++) {
if (strncmp(path, basicMountPoint[i], strlen(basicMountPoint[i])) == 0)
return true;
}
return false;
}
......@@ -153,15 +147,9 @@ int SwitchRoot(const char *newRoot)
}
struct stat oldRootStat = {};
if (stat("/", &oldRootStat) != 0) {
INIT_LOGE("Failed to get old root \"/\" stat");
return -1;
}
INIT_ERROR_CHECK(stat("/", &oldRootStat) == 0, return -1, "Failed to get old root \"/\" stat");
DIR *oldRoot = opendir("/");
if (oldRoot == NULL) {
INIT_LOGE("Failed to open root dir \"/\"");
return -1;
}
INIT_ERROR_CHECK(oldRoot != NULL, return -1, "Failed to open root dir \"/\"");
struct stat newRootStat = {};
if (stat(newRoot, &newRootStat) != 0) {
INIT_LOGE("Failed to get new root \" %s \" stat", newRoot);
......
......@@ -27,7 +27,6 @@ if (defined(ohos_lite)) {
"_GNU_SOURCE",
"OHOS_LITE",
]
cflags = [ "-fPIC" ]
public_configs = [ ":exported_header_files" ]
if (ohos_kernel_type == "linux") {
......
......@@ -120,7 +120,7 @@ static void PrintLog(InitLogLevel logLevel, unsigned int domain, const char *tag
INIT_LOCAL_API void InitLog(int logLevel, unsigned int domain, const char *tag, const char *fmt, va_list vargs)
{
if (g_logLevel > logLevel) {
if ((int)g_logLevel > logLevel) {
return;
}
char tmpFmt[DEF_LOG_SIZE] = {0};
......@@ -128,7 +128,7 @@ INIT_LOCAL_API void InitLog(int logLevel, unsigned int domain, const char *tag,
tmpFmt[sizeof(tmpFmt) - 2] = '\n'; // 2 add \n to tail
tmpFmt[sizeof(tmpFmt) - 1] = '\0';
}
PrintLog(logLevel, domain, tag, tmpFmt);
PrintLog((InitLogLevel)logLevel, domain, tag, tmpFmt);
}
INIT_PUBLIC_API void EnableInitLog(InitLogLevel level)
......
......@@ -66,6 +66,7 @@ typedef void *BufferHandle;
LoopHandle LE_GetDefaultLoop(void);
LE_STATUS LE_CreateLoop(LoopHandle *loopHandle);
void LE_RunLoop(const LoopHandle loopHandle);
void LE_CloseLoop(const LoopHandle loopHandle);
void LE_StopLoop(const LoopHandle loopHandle);
void LE_CloseTask(const LoopHandle loopHandle, const TaskHandle taskHandle);
......
......@@ -115,7 +115,6 @@ static LE_STATUS RunLoop_(const EventLoop *loop)
break;
}
}
CloseLoop((EventLoop *)loop);
return LE_SUCCESS;
}
......
......@@ -152,6 +152,12 @@ void LE_RunLoop(const LoopHandle handle)
loop->runLoop(loop);
}
void LE_CloseLoop(const LoopHandle loopHandle)
{
LE_CHECK(loopHandle != NULL, return, "Invalid handle");
CloseLoop((EventLoop *)loopHandle);
}
void LE_StopLoop(const LoopHandle handle)
{
LE_CHECK(handle != NULL, return, "Invalid handle");
......
......@@ -28,7 +28,7 @@ static LE_STATUS SetTimer_(int tfd, uint64_t timeout)
struct itimerspec timeValue;
time_t sec = timeout / TIMEOUT_BASE;
timeValue.it_interval.tv_sec = sec;
long nsec = (timeout % TIMEOUT_BASE) * TIMEOUT_BASE;
long nsec = (timeout % TIMEOUT_BASE) * TIMEOUT_BASE * TIMEOUT_BASE;
timeValue.it_interval.tv_nsec = nsec;
timeValue.it_value.tv_sec = sec;
timeValue.it_value.tv_nsec = nsec;
......
......@@ -71,7 +71,7 @@ static void BootchartLogHeader(void)
struct tm *now = localtime(&tm);
PLUGIN_CHECK(now != NULL, return, "Failed to get local time");
size_t size = strftime(date, sizeof(date), "%F %T", now);
PLUGIN_CHECK(size >= 0, return, "Failed to strftime");
PLUGIN_CHECK(size > 0, return, "Failed to strftime");
struct utsname uts;
if (uname(&uts) == -1) {
return;
......@@ -224,12 +224,11 @@ static int DoBootchartStart(void)
PLUGIN_LOGI("bootcharting has been start");
return 0;
}
int ret = 0;
g_bootchartCtrl = malloc(sizeof(BootchartCtrl));
PLUGIN_CHECK(g_bootchartCtrl != NULL, return -1, "Failed to alloc mem for bootchart");
g_bootchartCtrl->bufferSize = DEFAULT_BUFFER;
ret = pthread_mutex_init(&(g_bootchartCtrl->mutex), NULL);
int ret = pthread_mutex_init(&(g_bootchartCtrl->mutex), NULL);
PLUGIN_CHECK(ret == 0, BootchartDestory();
return -1, "Failed to init mutex");
ret = pthread_cond_init(&(g_bootchartCtrl->cond), NULL);
......
......@@ -102,6 +102,34 @@ static int AddServiceBootEvent(const char *serviceName, const char *paramName)
return 0;
}
static void AddInitBootEvent(const char *bootEventName)
{
ListNode *found = NULL;
found = OH_ListFind(&bootEventList, (void *)bootEventName, ParseBooteventCompareProc);
if (found != NULL) {
INIT_CHECK_ONLY_RETURN(clock_gettime(CLOCK_MONOTONIC,
&(((BOOT_EVENT_PARAM_ITEM *)found)->timestamp[BOOTEVENT_READY])) == 0);
return;
}
BOOT_EVENT_PARAM_ITEM *item = malloc(sizeof(BOOT_EVENT_PARAM_ITEM));
if (item == NULL) {
return;
}
OH_ListInit(&item->node);
if (clock_gettime(CLOCK_MONOTONIC, &(item->timestamp[BOOTEVENT_FORK])) != 0) {
free(item);
return;
}
item->paramName = strdup(bootEventName);
if (item->paramName == NULL) {
free(item);
return;
}
OH_ListAddTail(&bootEventList, (ListNode *)&item->node);
return;
}
#define BOOT_EVENT_BOOT_COMPLETED "bootevent.boot.completed"
static void BootEventParaFireByName(const char *paramName)
......@@ -128,7 +156,7 @@ static void BootEventParaFireByName(const char *paramName)
return;
}
// All parameters are fired, set boot completed now ...
INIT_LOGI("All bootevents are fired, boot complete now ...");
INIT_LOGI("All boot events are fired, boot complete now ...");
SystemWriteParam(BOOT_EVENT_BOOT_COMPLETED, "true");
return;
}
......@@ -139,31 +167,31 @@ static void ServiceParseBootEventHook(SERVICE_PARSE_CTX *serviceParseCtx)
int cnt;
cJSON *bootEvents = cJSON_GetObjectItem(serviceParseCtx->serviceNode, BOOT_EVENT_FIELD_NAME);
// No bootevents in config file
// No boot events in config file
if (bootEvents == NULL) {
return;
}
SERVICE_INFO_CTX ctx = {0};
ctx.serviceName = serviceParseCtx->serviceName;
HookMgrExecute(GetBootStageHookMgr(), INIT_SERVICE_CLEAR, (void *)&ctx, NULL);
// Single bootevent in config file
// Single boot event in config file
if (!cJSON_IsArray(bootEvents)) {
if (AddServiceBootEvent(serviceParseCtx->serviceName,
cJSON_GetStringValue(bootEvents)) != 0) {
INIT_LOGI("Add service bootevent failed %s", serviceParseCtx->serviceName);
INIT_LOGI("Add service bootEvent failed %s", serviceParseCtx->serviceName);
return;
}
g_bootEventNum++;
return;
}
// Multiple bootevents in config file
// Multiple boot events in config file
cnt = cJSON_GetArraySize(bootEvents);
for (int i = 0; i < cnt; i++) {
cJSON *item = cJSON_GetArrayItem(bootEvents, i);
if (AddServiceBootEvent(serviceParseCtx->serviceName,
cJSON_GetStringValue(item)) != 0) {
INIT_LOGI("Add service bootevent failed %s", serviceParseCtx->serviceName);
INIT_LOGI("Add service bootEvent failed %s", serviceParseCtx->serviceName);
continue;
}
g_bootEventNum++;
......@@ -173,17 +201,21 @@ static void ServiceParseBootEventHook(SERVICE_PARSE_CTX *serviceParseCtx)
static int DoBootEventCmd(int id, const char *name, int argc, const char **argv)
{
PLUGIN_CHECK(argc >= 1, return -1, "Invalid parameter");
// argv[0] samgr.ready.true
BootEventParaFireByName(argv[0]);
if (strcmp(argv[0], "init") == 0) {
AddInitBootEvent(argv[1]);
} else {
// argv[0] samgr.ready.true
BootEventParaFireByName(argv[0]);
}
return 0;
}
static int AddItemToJson(cJSON *root, const char *name, double startime, int tid, double durTime)
static int AddItemToJson(cJSON *root, const char *name, double startTime, int tid, double durTime)
{
cJSON *obj = cJSON_CreateObject(); // release obj at traverse done
INIT_CHECK_RETURN_VALUE(obj != NULL, -1);
cJSON_AddStringToObject(obj, "name", name);
cJSON_AddNumberToObject(obj, "ts", startime);
cJSON_AddNumberToObject(obj, "ts", startTime);
cJSON_AddStringToObject(obj, "ph", "X");
cJSON_AddNumberToObject(obj, "pid", 0);
cJSON_AddNumberToObject(obj, "tid", tid);
......@@ -192,9 +224,9 @@ static int AddItemToJson(cJSON *root, const char *name, double startime, int tid
return 0;
}
static int BooteventTraversal(ListNode *node, void *root)
static int BootEventTraversal(ListNode *node, void *root)
{
static int tid = 1; // 1 bootevent start num
static int tid = 1; // 1 boot event start num
BOOT_EVENT_PARAM_ITEM *item = (BOOT_EVENT_PARAM_ITEM *)node;
double forkTime = item->timestamp[BOOTEVENT_FORK].tv_sec * SECTOMSEC +
(double)item->timestamp[BOOTEVENT_FORK].tv_nsec / MSECTONSEC;
......@@ -217,19 +249,26 @@ static int SaveServiceBootEvent(int id, const char *name, int argc, const char *
INIT_CHECK_RETURN_VALUE(nowTime > 0, -1);
struct tm *p = localtime(&nowTime);
INIT_CHECK_RETURN_VALUE(p != NULL, -1);
char booteventFileName[BOOT_EVENT_FILEPATH_MAX_LEN] = "";
INIT_CHECK_RETURN_VALUE(snprintf(booteventFileName, BOOT_EVENT_FILEPATH_MAX_LEN,
char bootEventFileName[BOOT_EVENT_FILEPATH_MAX_LEN] = "";
INIT_CHECK_RETURN_VALUE(snprintf(bootEventFileName, BOOT_EVENT_FILEPATH_MAX_LEN,
BOOTEVENT_OUTPUT_PATH"%d%d%d-%d%d.bootevent",
1900 + p->tm_year, p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min) >= 0, -1); // 1900 is start year
CheckAndCreatFile(booteventFileName, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
FILE *tmpFile = fopen(booteventFileName, "wr");
CheckAndCreatFile(bootEventFileName, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
FILE *tmpFile = fopen(bootEventFileName, "wr");
INIT_CHECK_RETURN_VALUE(tmpFile != NULL, -1);
cJSON *root = cJSON_CreateArray();
INIT_CHECK_RETURN_VALUE(root != NULL, -1);
OH_ListTraversal(&bootEventList, (void *)root, BooteventTraversal, 0);
if (root == NULL) {
(void)fclose(tmpFile);
return -1;
}
OH_ListTraversal(&bootEventList, (void *)root, BootEventTraversal, 0);
char *buff = cJSON_Print(root);
INIT_CHECK_RETURN_VALUE(buff != NULL, -1);
INIT_CHECK_RETURN_VALUE(fprintf(tmpFile, "%s\n", buff) >= 0, -1);
if (buff == NULL) {
cJSON_Delete(root);
(void)fclose(tmpFile);
return -1;
}
INIT_CHECK_ONLY_ELOG(fprintf(tmpFile, "%s\n", buff) >= 0, "save boot event file failed");
free(buff);
cJSON_Delete(root);
(void)fflush(tmpFile);
......@@ -258,16 +297,16 @@ static void DumpServiceBootEvent(SERVICE_INFO_CTX *serviceCtx)
return;
}
BOOT_EVENT_PARAM_ITEM *item = (BOOT_EVENT_PARAM_ITEM *)serviceExtData->data;
char booteventForkTimeStamp[BOOT_EVENT_TIMESTAMP_MAX_LEN] = "";
char booteventReadyTimeStamp[BOOT_EVENT_TIMESTAMP_MAX_LEN] = "";
INIT_CHECK_ONLY_RETURN(sprintf_s(booteventForkTimeStamp, BOOT_EVENT_TIMESTAMP_MAX_LEN, "%f",
char bootEventForkTimeStamp[BOOT_EVENT_TIMESTAMP_MAX_LEN] = "";
char bootEventReadyTimeStamp[BOOT_EVENT_TIMESTAMP_MAX_LEN] = "";
INIT_CHECK_ONLY_RETURN(sprintf_s(bootEventForkTimeStamp, BOOT_EVENT_TIMESTAMP_MAX_LEN, "%f",
item->timestamp[BOOTEVENT_FORK].tv_sec +
(double)item->timestamp[BOOTEVENT_FORK].tv_nsec / SECTONSEC) >= 0);
INIT_CHECK_ONLY_RETURN(sprintf_s(booteventReadyTimeStamp, BOOT_EVENT_TIMESTAMP_MAX_LEN, "%f",
INIT_CHECK_ONLY_RETURN(sprintf_s(bootEventReadyTimeStamp, BOOT_EVENT_TIMESTAMP_MAX_LEN, "%f",
(long)item->timestamp[BOOTEVENT_READY].tv_sec +
(double)item->timestamp[BOOTEVENT_READY].tv_nsec / SECTONSEC) >= 0);
printf("\t%-20.20s\t%-50s\t%-20.20s\t%-20.20s\n", serviceCtx->serviceName, item->paramName,
booteventForkTimeStamp, booteventReadyTimeStamp);
bootEventForkTimeStamp, bootEventReadyTimeStamp);
}
return;
}
......
......@@ -128,12 +128,12 @@ static void RebootAdpExit(void)
MODULE_CONSTRUCTOR(void)
{
PLUGIN_LOGI("RebootAdp init now ...");
PLUGIN_LOGI("Reboot adapter plug-in init now ...");
RebootAdpInit();
}
MODULE_DESTRUCTOR(void)
{
PLUGIN_LOGI("RebootAdp exit now ...");
PLUGIN_LOGI("Reboot adapter plug-in exit now ...");
RebootAdpExit();
}
......@@ -21,7 +21,7 @@ import argparse
import textwrap
import re
supported_parse_item = ['arch', 'labelName', 'priority', 'allowList', 'blockList', \
supported_parse_item = ['arch', 'labelName', 'priority', 'allowList', 'blockList', 'priorityWithArgs',\
'allowListWithArgs', 'headFiles', 'selfDefineSyscall', 'returnValue', 'mode']
function_name_nr_table_dict = {}
......@@ -30,9 +30,11 @@ BPF_JGE = 'BPF_JUMP(BPF_JMP|BPF_JGE|BPF_K, {}, {}, {}),'
BPF_JGT = 'BPF_JUMP(BPF_JMP|BPF_JGT|BPF_K, {}, {}, {}),'
BPF_JEQ = 'BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, {}, {}, {}),'
BPF_JSET = 'BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, {}, {}, {}),'
BPF_JA = 'BPF_JUMP(BPF_JMP|BPF_JA, {}, 0, 0),'
BPF_LOAD = 'BPF_STMT(BPF_LD|BPF_W|BPF_ABS, {}),'
BPF_LOAD_MEM = 'BPF_STMT(BPF_LD|BPF_MEM, {}),'
BPF_ST = 'BPF_STMT(BPF_ST, {}),'
BPF_AND = 'BPF_STMT(BPF_ALU|BPF_AND|BPF_K, {}),'
BPF_RET_VALUE = 'BPF_STMT(BPF_RET|BPF_K, {}),'
operation = ['<', '<=', '!=', '==', '>', '>=', '&']
......@@ -80,11 +82,13 @@ class SeccompPolicyParam:
self.priority = set()
self.allow_list = set()
self.blocklist = set()
self.priority_with_args = set()
self.allow_list_with_args = set()
self.head_files = set()
self.self_define_syscall = set()
self.final_allow_list = set()
self.final_priority = set()
self.final_priority_with_args = set()
self.final_allow_list_with_args = set()
self.return_value = ''
self.mode = 'DEFAULT'
......@@ -94,6 +98,7 @@ class SeccompPolicyParam:
'allowList': self.update_allow_list,
'blockList': self.update_blocklist,
'allowListWithArgs': self.update_allow_list_with_args,
'priorityWithArgs': self.update_priority_with_args,
'headFiles': self.update_head_files,
'selfDefineSyscall': self.update_self_define_syscall,
'returnValue': self.update_return_value,
......@@ -105,6 +110,7 @@ class SeccompPolicyParam:
self.allow_list.clear()
self.blocklist.clear()
self.allow_list_with_args.clear()
self.priority_with_args.clear()
if self.mode == 'ONLY_CHECK_ARGS':
self.final_allow_list.clear()
self.final_priority.clear()
......@@ -138,6 +144,14 @@ class SeccompPolicyParam:
return True
return False
def update_priority_with_args(self, function_name_with_args):
function_name = function_name_with_args[:function_name_with_args.find(':')]
function_name = function_name.strip()
if self.is_function_name_exist(function_name):
self.priority_with_args.add(function_name_with_args)
return True
return False
def update_allow_list_with_args(self, function_name_with_args):
function_name = function_name_with_args[:function_name_with_args.find(':')]
function_name = function_name.strip()
......@@ -182,12 +196,22 @@ class SeccompPolicyParam:
def update_final_list(self):
#remove duplicate function_name
self.allow_list_with_args = set(item for item in self.allow_list_with_args \
if item[:item.find(':')] not in self.blocklist)
self.priority_with_args = set(item
for item in self.priority_with_args
if item[:item.find(':')] not in self.blocklist)
priority_function_name_list_with_args = set(item[:item.find(':')] for item in self.priority_with_args)
self.allow_list_with_args = set(item
for item in self.allow_list_with_args
if item[:item.find(':')] not in self.blocklist and
item[:item.find(':')] not in priority_function_name_list_with_args)
function_name_list_with_args = set(item[:item.find(':')] for item in self.allow_list_with_args)
self.final_allow_list |= self.allow_list - self.blocklist - self.priority - function_name_list_with_args
self.final_priority |= self.priority - self.blocklist - function_name_list_with_args
self.final_allow_list |= self.allow_list - self.blocklist - self.priority - function_name_list_with_args - \
priority_function_name_list_with_args
self.final_priority |= self.priority - self.blocklist - function_name_list_with_args - \
priority_function_name_list_with_args
self.final_allow_list_with_args |= self.allow_list_with_args
self.final_priority_with_args |= self.priority_with_args
block_nr_list = self.function_name_to_nr(self.blocklist)
self.self_define_syscall = self.self_define_syscall - block_nr_list
self.clear_list()
......@@ -499,33 +523,96 @@ class GenBpfPolicy:
self.flag = False
return bpf_policy
arg_str = atom[0:3]
if atom[0] == '(':
bpf_policy += self.compile_mask_equal_atom(atom, cur_size)
else:
bpf_policy += self.compile_single_operation_atom(atom, cur_size)
return bpf_policy
def check_arg_str(self, arg_atom):
arg_str = arg_atom[0:3]
if arg_str != 'arg':
print('[ERROR] format ERROR, {} not start with arg'.format(atom))
print('[ERROR] format ERROR, {} is not equal to arg'.format(arg_atom))
self.flag = False
return bpf_policy
return -1, False
arg_id = int(atom[3])
arg_id = int(arg_atom[3])
if arg_id not in range(6):
print('[ERROR] arg num out of the scope 0~5')
self.flag = False
return bpf_policy
return -1, False
return arg_id, True
operation_str = atom[4:6]
def check_operation_str(self, operation_atom):
operation_str = operation_atom
if operation_str not in operation:
operation_str = atom[4]
operation_str = operation_atom[0]
if operation_str not in operation:
print('[ERROR] operation not in [<, <=, !=, ==, >, >=, &]')
self.flag = False
return bpf_policy
return '', False
return operation_str, True
#gen bpf (argn & mask) == value
def gen_mask_equal_bpf(self, arg_id, mask, value, cur_size):
bpf_policy = []
#high 4 bytes
bpf_policy.append(BPF_LOAD.format(20 + arg_id * 8))
bpf_policy.append(BPF_AND.format('((uint64_t)' + mask + ') >> 32'))
bpf_policy.append(BPF_JEQ.format('((uint64_t)' + value + ') >> 32', 0, cur_size + 3))
const_str = atom[4 + len(operation_str):]
#low 4 bytes
bpf_policy.append(BPF_LOAD.format(16 + arg_id * 8))
bpf_policy.append(BPF_AND.format(mask))
bpf_policy.append(BPF_JEQ.format(value, cur_size, cur_size + 1))
return bpf_policy
#parse (argn & mask) == value
def compile_mask_equal_atom(self, atom, cur_size):
bpf_policy = []
left_brace_pos = atom.find('(')
right_brace_pos = atom.rfind(')')
inside_brace_content = atom[left_brace_pos + 1: right_brace_pos]
outside_brace_content = atom[right_brace_pos + 1:]
arg_res = self.check_arg_str(inside_brace_content[0:4])
if not arg_res[1]:
return bpf_policy
operation_res_inside = self.check_operation_str(inside_brace_content[4:6])
if operation_res_inside[0] != '&' or not operation_res_inside[1]:
return bpf_policy
mask = inside_brace_content[4 + len(operation_res_inside[0]):]
operation_res_outside = self.check_operation_str(outside_brace_content[0:2])
if operation_res_outside[0] != '==' or not operation_res_outside[1]:
return bpf_policy
value = outside_brace_content[len(operation_res_outside[0]):]
return self.gen_mask_equal_bpf(arg_res[0], mask, value, cur_size)
def compile_single_operation_atom(self, atom, cur_size):
bpf_policy = []
arg_res = self.check_arg_str(atom[0:4])
if not arg_res[1]:
return bpf_policy
operation_res = self.check_operation_str(atom[4:6])
if not operation_res[1]:
return bpf_policy
const_str = atom[4 + len(operation_res[0]):]
if not const_str:
return bpf_policy
bpf_policy += self.load_arg(arg_id)
bpf_policy += self.operate_func_table.get(operation_str)(const_str, 0, cur_size + 1)
bpf_policy += self.load_arg(arg_res[0])
bpf_policy += self.operate_func_table.get(operation_res[0])(const_str, 0, cur_size + 1)
return bpf_policy
......@@ -549,6 +636,7 @@ class GenBpfPolicy:
and_cond_groups = operation_part.split('||')
for and_condition_group in and_cond_groups:
bpf_policy += self.parse_args_with_condition(and_condition_group)
bpf_policy.append(BPF_RET_VALUE.format(ret_str_to_bpf.get(self.return_value)))
return bpf_policy
def parse_else_part(self, else_part):
......@@ -562,7 +650,6 @@ class GenBpfPolicy:
group = group_info[0].split('elif')
for sub_group in group:
bpf_policy += self.parse_sub_group(sub_group)
bpf_policy.append(BPF_RET_VALUE.format(ret_str_to_bpf.get(self.return_value)))
self.parse_else_part(else_part)
bpf_policy.append(BPF_RET_VALUE.format(ret_str_to_bpf.get(self.return_value)))
syscall_nr = self.function_name_nr_table.get(function_name)
......@@ -599,8 +686,9 @@ class GenBpfPolicy:
#load arch
bpf_policy.append(BPF_LOAD.format(4))
if len(arches) == 2:
bpf_policy.append(BPF_JEQ.format('AUDIT_ARCH_AARCH64', 2, 0))
bpf_policy.append(BPF_JEQ.format('AUDIT_ARCH_ARM', skip_step, 0))
bpf_policy.append(BPF_JEQ.format('AUDIT_ARCH_AARCH64', 3, 0))
bpf_policy.append(BPF_JEQ.format('AUDIT_ARCH_ARM', 0, 1))
bpf_policy.append(BPF_JA.format(skip_step))
bpf_policy.append(BPF_RET_VALUE.format('SECCOMP_RET_KILL_PROCESS'))
elif 'arm' in arches:
bpf_policy.append(BPF_JEQ.format('AUDIT_ARCH_ARM', 1, 0))
......@@ -695,6 +783,8 @@ class SeccompPolicyParser:
if syscall_nr_allow_list or syscall_nr_priority:
self.bpf_generator.add_load_syscall_nr()
self.bpf_generator.gen_bpf_policy(syscall_nr_priority)
self.bpf_generator.gen_bpf_policy_with_args(self.cur_policy_param.final_priority_with_args, \
self.cur_policy_param.mode, self.cur_policy_param.return_value)
self.bpf_generator.gen_bpf_policy(syscall_nr_allow_list)
self.bpf_generator.gen_bpf_policy_with_args(self.cur_policy_param.final_allow_list_with_args, \
self.cur_policy_param.mode, self.cur_policy_param.return_value)
......
......@@ -91,9 +91,11 @@ bool SetSeccompPolicyWithName(const char *filterName)
strlen(filterName) + strlen(FILTER_NAME_FORMAT) - strlen("%s"), \
FILTER_NAME_FORMAT, filterName);
PLUGIN_CHECK(rc != -1, return false, "snprintf_s faiVribleName failed");
const char *filterLibRealPath = realpath(filterLibPath, NULL);
PLUGIN_CHECK(filterLibRealPath != NULL, return false, "format filter lib real path failed");
void *handler = dlopen(filterLibPath, RTLD_LAZY);
PLUGIN_CHECK(handler != NULL, return false, "dlopen %s failed", filterLibPath);
void *handler = dlopen(filterLibRealPath, RTLD_LAZY);
PLUGIN_CHECK(handler != NULL, return false, "dlopen %s failed", filterLibRealPath);
filterPtr = (struct sock_filter *)dlsym(handler, filterVaribleName);
PLUGIN_CHECK(filterPtr != NULL, dlclose(handler);
......
......@@ -161,6 +161,7 @@ prlimit64
cacheflush
set_tls
sched_setscheduler
mkdir
@allowListWithArgs
getrusage:if arg0 == RUSAGE_SELF || arg0 == RUSAGE_THREAD; return ALLOW; else return KILL_PROCESS;
......
......@@ -52,7 +52,7 @@ static int SetServiceContent(int id, const char *name, int argc, const char **ar
PLUGIN_LOGE("failed to set service %s's secon (%s).", argv[0], (char *)data->data);
_exit(PROCESS_EXIT_CODE);
} else {
PLUGIN_LOGI("Set content %s to %s.", (char *)data->data, argv[0]);
PLUGIN_LOGV("Set content %s to %s.", (char *)data->data, argv[0]);
}
} else {
PLUGIN_CHECK(!(setexeccon("u:r:limit_domain:s0") < 0), _exit(PROCESS_EXIT_CODE),
......@@ -95,12 +95,12 @@ static void SelinuxAdpExit(void)
MODULE_CONSTRUCTOR(void)
{
PLUGIN_LOGI("SelinuxAdp init now ...");
PLUGIN_LOGI("Selinux adapter plug-in init now ...");
SelinuxAdpInit();
}
MODULE_DESTRUCTOR(void)
{
PLUGIN_LOGI("SelinuxAdp exit now ...");
PLUGIN_LOGI("Selinux adapter plug-in exit now ...");
SelinuxAdpExit();
}
\ No newline at end of file
......@@ -195,7 +195,7 @@ static int DacGetParamSecurityLabel(const char *path)
ProcessParamFile(fileName, NULL);
}
}
PARAM_LOGI("DacGetParamSecurityLabel path %s %d", path, count);
PARAM_LOGV("Get parameter security label dac number is %d, from %s.", count, path);
free(fileName);
closedir(pDir);
return 0;
......
......@@ -42,7 +42,7 @@ static int LoadPersistParam()
if (fp == NULL) {
tmpPath = (updaterMode == 0) ? PARAM_PERSIST_SAVE_PATH : "/param/persist_parameters";
fp = fopen(tmpPath, "r");
PARAM_LOGI("LoadPersistParam open file %s", PARAM_PERSIST_SAVE_PATH);
PARAM_LOGI("Load persist param, from file %s", tmpPath);
}
PARAM_CHECK(fp != NULL, return -1, "No valid persist parameter file %s", PARAM_PERSIST_SAVE_PATH);
......
......@@ -32,6 +32,7 @@
#define CHECKER_LIB_NAME "/system/lib/libparaperm_checker.z.so"
#define CHECKER_UPDATER_LIB_NAME "/lib/libparaperm_checker.z.so"
#endif
typedef int (*SelinuxSetParamCheck)(const char *paraName, const char *destContext, const SrcInfo *info);
static int InitSelinuxOpsForInit(SelinuxSpace *selinuxSpace)
{
......@@ -202,7 +203,7 @@ static int SelinuxGetAllLabel(int readOnly)
if (readOnly == 0) {
SetSelinuxFileCon(WORKSPACE_NAME_DEF_SELINUX, WORKSPACE_NAME_DEF_SELINUX);
}
PARAM_LOGI("SelinuxGetAllLabel count %d", count);
PARAM_LOGV("Selinux get all label counts %d.", count);
return 0;
}
......@@ -295,9 +296,15 @@ static int UpdaterCheckParamPermission(const ParamSecurityLabel *srcLabel, const
static int OpenPermissionWorkSpace(const char *path)
{
static int loadLabels = 0;
UNUSED(path);
// open workspace by readonly
return SelinuxGetAllLabel(1);
int ret = 0;
if (loadLabels == 0) {
// open workspace by readonly
ret = SelinuxGetAllLabel(1);
}
loadLabels = 1;
return ret;
}
INIT_LOCAL_API int RegisterSecuritySelinuxOps(ParamSecurityOps *ops, int isInit)
......
......@@ -20,7 +20,7 @@
#include "param_manager.h"
#include "param_trie.h"
static ParamWorkSpace g_paramWorkSpace = {};
static ParamWorkSpace g_paramWorkSpace = {0};
PARAM_STATIC int WorkSpaceNodeCompare(const HashNode *node1, const HashNode *node2)
{
WorkSpace *workSpace1 = HASHMAP_ENTRY(node1, WorkSpace, hashNode);
......@@ -75,7 +75,7 @@ static int InitParamSecurity(ParamWorkSpace *workSpace,
}
ret = paramSecurityOps->securityCheckFilePermission(&workSpace->securityLabel, PARAM_STORAGE_PATH, op);
PARAM_CHECK(ret == 0, return PARAM_CODE_INVALID_NAME, "No permission to read file %s", PARAM_STORAGE_PATH);
PARAM_LOGI("InitParamSecurity %s success", paramSecurityOps->name);
PARAM_LOGI("Init parameter %s success", paramSecurityOps->name);
return 0;
}
......@@ -107,7 +107,6 @@ static int CheckNeedInit(int onlyRead, const PARAM_WORKSPACE_OPS *ops)
g_paramWorkSpace.ops.setfilecon = ops->setfilecon;
#endif
}
PARAM_LOGI("InitParamWorkSpace %x", g_paramWorkSpace.flags);
if (PARAM_TEST_FLAG(g_paramWorkSpace.flags, WORKSPACE_FLAGS_INIT)) {
return 0;
}
......@@ -169,7 +168,7 @@ INIT_INNER_API int InitParamWorkSpace(int onlyRead, const PARAM_WORKSPACE_OPS *o
// load user info for dac
LoadGroupUser();
// add default dac policy
ParamAuditData auditData = {};
ParamAuditData auditData = {0};
auditData.name = "#";
auditData.dacData.gid = DAC_DEFAULT_GROUP; // 2000 for shell
auditData.dacData.uid = DAC_DEFAULT_USER; // for root
......@@ -225,7 +224,7 @@ INIT_INNER_API ParamWorkSpace *GetParamWorkSpace(void)
int SystemReadParam(const char *name, char *value, uint32_t *len)
{
PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space");
PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Param workspace has not init.");
PARAM_CHECK(name != NULL && len != NULL && strlen(name) > 0, return -1, "The name or value is null");
ParamHandle handle = 0;
int ret = ReadParamWithCheck(name, DAC_READ, &handle);
......
......@@ -371,6 +371,7 @@ INIT_LOCAL_API int AddSecurityLabel(const ParamAuditData *auditData)
} else {
#ifdef STARTUP_INIT_TEST
ParamSecurityNode *label = (ParamSecurityNode *)GetTrieNode(workSpace, node->labelIndex);
PARAM_CHECK(label != NULL, return -1, "Failed to get trie node");
label->mode = auditData->dacData.mode;
label->uid = auditData->dacData.uid;
label->gid = auditData->dacData.gid;
......@@ -490,7 +491,7 @@ INIT_LOCAL_API int ReadParamValue(ParamHandle handle, char *value, uint32_t *len
PARAM_CHECK(length != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param");
ParamNode *entry = (ParamNode *)GetTrieNodeByHandle(handle);
if (entry == NULL) {
return -1;
return PARAM_CODE_NOT_FOUND;
}
if (value == NULL) {
*length = entry->valueLength + 1;
......@@ -515,7 +516,7 @@ INIT_LOCAL_API int ReadParamName(ParamHandle handle, char *name, uint32_t length
PARAM_CHECK(name != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param");
ParamNode *entry = (ParamNode *)GetTrieNodeByHandle(handle);
if (entry == NULL) {
return -1;
return PARAM_CODE_NOT_FOUND;
}
PARAM_CHECK(length > entry->keyLength, return -1, "Invalid param size %u %u", entry->keyLength, length);
int ret = ParamMemcpy(name, length, entry->data, entry->keyLength);
......
......@@ -22,12 +22,6 @@
#include <sys/types.h>
#ifdef PARAM_SUPPORT_SELINUX
#include "selinux_parameter.h"
#else
typedef struct ParamContextsList_ {
} ParamContextsList;
typedef struct SrcInfo {
} SrcInfo;
#endif
#include "beget_ext.h"
......@@ -100,9 +94,9 @@ typedef struct {
} ParamSecurityOps;
typedef int (*RegisterSecurityOpsPtr)(ParamSecurityOps *ops, int isInit);
typedef int (*SelinuxSetParamCheck)(const char *paraName, const char *destContext, const SrcInfo *info);
typedef struct SelinuxSpace_ {
void *selinuxHandle;
#ifdef PARAM_SUPPORT_SELINUX
void (*setSelinuxLogCallback)(void);
int (*setParamCheck)(const char *paraName, const char *destContext, const SrcInfo *info);
const char *(*getParamLabel)(const char *paraName);
......@@ -110,6 +104,7 @@ typedef struct SelinuxSpace_ {
int (*readParamCheck)(const char *paraName);
ParamContextsList *(*getParamList)(void);
void (*destroyParamList)(ParamContextsList **list);
#endif
} SelinuxSpace;
#ifdef PARAM_SUPPORT_SELINUX
INIT_LOCAL_API int RegisterSecuritySelinuxOps(ParamSecurityOps *ops, int isInit);
......
......@@ -23,9 +23,10 @@
int ConnectServer(int fd, const char *servername)
{
PARAM_CHECK(fd >= 0, return -1, "Invalid fd %d", fd);
PARAM_CHECK(servername != NULL, return -1, "Invalid servername");
int opt = 1;
int ret = setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &opt, sizeof(opt));
PARAM_CHECK(servername != NULL, return -1, "Invalid servername");
PARAM_CHECK(ret == 0, return -1, "Failed to set socket option");
struct sockaddr_un addr;
/* fill socket address structure with server's address */
ret = memset_s(&addr, sizeof(addr), 0, sizeof(addr));
......
......@@ -61,7 +61,7 @@ typedef struct {
uint32_t watcherId;
uint32_t waitId;
} id;
char key[PARAM_NAME_LEN_MAX];
char key[PARAM_NAME_LEN_MAX + 4];
char data[0];
} ParamMessage;
......@@ -84,8 +84,9 @@ int ParamServiceStop(void);
int ParamServiceStart(void);
int ParamTaskClose(const ParamTaskPtr stream);
int ParamServerCreate(ParamTaskPtr *server, const ParamStreamInfo *info);
int ParamStreamCreate(ParamTaskPtr *client, ParamTaskPtr server, const ParamStreamInfo *info, uint16_t userDataSize);
int ParamServerCreate(ParamTaskPtr *stream, const ParamStreamInfo *streamInfo);
int ParamStreamCreate(ParamTaskPtr *stream, ParamTaskPtr server,
const ParamStreamInfo *streamInfo, uint16_t userDataSize);
int ParamTaskSendMsg(const ParamTaskPtr stream, const ParamMessage *msg);
int ParamEventTaskCreate(ParamTaskPtr *stream, LE_ProcessAsyncEvent eventProcess);
......
......@@ -41,7 +41,7 @@ __attribute__((constructor)) static void ParameterInit(void)
if (getpid() == 1) {
return;
}
EnableInitLog(INIT_INFO);
EnableInitLog(INIT_ERROR);
PARAM_WORKSPACE_OPS ops = {0};
ops.updaterMode = 0;
#ifdef PARAM_BASE_LOG
......@@ -117,7 +117,7 @@ static int GetClientSocket(int timeout)
struct timeval time;
time.tv_sec = timeout;
time.tv_usec = 0;
int clientFd = socket(AF_UNIX, SOCK_STREAM, 0);
int clientFd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
PARAM_CHECK(clientFd >= 0, return -1, "Failed to create socket");
int ret = ConnectServer(clientFd, CLIENT_PIPE_NAME);
if (ret == 0) {
......@@ -132,11 +132,14 @@ static int GetClientSocket(int timeout)
static int StartRequest(int clientFd, ParamMessage *request, int timeout)
{
int ret = 0;
errno = 0;
ssize_t sendLen = send(clientFd, (char *)request, request->msgSize, 0);
PARAM_CHECK(sendLen >= 0, return PARAM_CODE_FAIL_CONNECT, "Failed to send message");
if (errno == EINVAL || errno == EACCES) {
return PARAM_CODE_INVALID_SOCKET;
}
PARAM_CHECK(sendLen >= 0, return PARAM_CODE_FAIL_CONNECT, "Failed to send message err: %d", errno);
PARAM_LOGV("sendMessage sendLen fd %d %zd", clientFd, sendLen);
ret = ReadMessage(clientFd, (char *)request, timeout);
int ret = ReadMessage(clientFd, (char *)request, timeout);
if (ret == 0) {
ret = ProcessRecvMsg(request);
}
......@@ -164,15 +167,25 @@ int SystemSetParameter(const char *name, const char *value)
request->id.msgId = atomic_fetch_add(&g_requestId, 1);
PARAM_LOGI("SystemSetParameter name %s msgid:%d ", name, request->id.msgId);
int fd = INVALID_SOCKET;
pthread_mutex_lock(&g_clientMutex);
if (g_clientFd == INVALID_SOCKET) {
g_clientFd = GetClientSocket(DEFAULT_PARAM_SET_TIMEOUT);
}
fd = g_clientFd;
ret = PARAM_CODE_INVALID_PARAM;
if (fd >= 0) {
ret = StartRequest(fd, request, DEFAULT_PARAM_SET_TIMEOUT);
int retryCount = 0;
while (retryCount < 2) { // max retry 2
if (g_clientFd == INVALID_SOCKET) {
g_clientFd = GetClientSocket(DEFAULT_PARAM_SET_TIMEOUT);
}
if (g_clientFd < 0) {
ret = DAC_RESULT_FORBIDED;
break;
}
ret = StartRequest(g_clientFd, request, DEFAULT_PARAM_SET_TIMEOUT);
if (ret == PARAM_CODE_INVALID_SOCKET) {
close(g_clientFd);
g_clientFd = INVALID_SOCKET;
retryCount++;
ret = DAC_RESULT_FORBIDED;
} else {
break;
}
}
PARAM_LOGI("SystemSetParameter name %s msgid:%d ret: %d ", name, request->id.msgId, ret);
pthread_mutex_unlock(&g_clientMutex);
......
......@@ -95,7 +95,7 @@ static int SendResponseMsg(ParamTaskPtr worker, const ParamMessage *msg, int res
response->result = result;
response->msg.msgSize = sizeof(ParamResponseMessage);
ParamTaskSendMsg(worker, (ParamMessage *)response);
PARAM_LOGI("SendResponseMsg msgId %d result %d", msg->id.msgId, result);
PARAM_LOGI("Send response msg msgId %d result %d", msg->id.msgId, result);
return 0;
}
......@@ -172,7 +172,7 @@ static int HandleParamSet(const ParamTaskPtr worker, const ParamMessage *msg)
srcLabel.cred.uid = cr.uid;
srcLabel.cred.pid = cr.pid;
srcLabel.cred.gid = cr.gid;
PARAM_LOGI("HandleParamSet msgId %d pid %d key: %s", msg->id.msgId, cr.pid, msg->key);
PARAM_LOGI("Handle set param msgId %d pid %d key: %s", msg->id.msgId, cr.pid, msg->key);
int ret = SystemSetParam(msg->key, valueContent->content, &srcLabel);
return SendResponseMsg(worker, msg, ret);
}
......@@ -364,7 +364,6 @@ static void LoadSelinuxLabel(void)
// load security label
#ifdef PARAM_SUPPORT_SELINUX
ParamSecurityOps *ops = GetParamSecurityOps(PARAM_SECURITY_SELINUX);
PARAM_LOGI("load selinux label %p", ops->securityGetLabel);
if (ops != NULL && ops->securityGetLabel != NULL) {
ops->securityGetLabel(NULL);
}
......
......@@ -108,10 +108,13 @@ static_library("param_init_lite") {
static_library("param_client_lite") {
sources = base_sources
include_dirs = param_include_dirs
cflags = [ "-fPIC" ]
defines = param_build_defines
public_configs = [ ":exported_header_files" ]
if (use_musl) {
defines += [ "PARAM_BASE" ]
}
if (ohos_kernel_type == "liteos_a") {
sources +=
[ "//base/startup/init/services/param/adapter/param_persistadp.c" ]
......
......@@ -19,7 +19,7 @@
static int g_flags = 0;
__attribute__((constructor)) static void ClientInit(void);
__attribute__((destructor)) static void ClientDeinit(void);
static void ClientDeinit(void);
static int InitParamClient(void)
{
......
......@@ -27,7 +27,7 @@
#include "utils_file.h"
// for linux, no mutex
static ParamMutex g_saveMutex = {};
static ParamMutex g_saveMutex = {0};
#ifdef PARAM_SUPPORT_POSIX
#define MODE_READ O_RDONLY
#define MODE_APPEND (O_RDWR | O_CREAT | O_APPEND)
......
......@@ -14,6 +14,7 @@
*/
#include "param_osadp.h"
#include "param_security.h"
#include "securec.h"
static int InitLocalSecurityLabel(ParamSecurityLabel *security, int isInit)
{
......@@ -59,9 +60,6 @@ static int DacCheckParamPermission(const ParamSecurityLabel *srcLabel, const cha
#if defined(__LITEOS_A__)
uid_t uid = getuid();
return uid <= SYS_UID_INDEX ? DAC_RESULT_PERMISSION : DAC_RESULT_FORBIDED;
#endif
#if defined(__LITEOS_M__)
return DAC_RESULT_PERMISSION;
#endif
return DAC_RESULT_PERMISSION;
}
......@@ -84,4 +82,4 @@ INIT_LOCAL_API int RegisterSecurityDacOps(ParamSecurityOps *ops, int isInit)
INIT_LOCAL_API void LoadGroupUser(void)
{
}
\ No newline at end of file
}
......@@ -24,6 +24,7 @@
#include <sys/shm.h>
#else
#include "los_task.h"
#include "los_mux.h"
#endif
#include <sys/stat.h>
#include <sys/time.h>
......@@ -318,4 +319,4 @@ INIT_LOCAL_API uint32_t Difftime(time_t curr, time_t base)
(void)base;
return 0;
#endif
}
\ No newline at end of file
}
......@@ -137,7 +137,6 @@ void LiteParamService(void)
InitParamService();
// get persist param
LoadPersistParams();
osThreadAttr_t attr;
attr.name = "ParamServiceTask";
attr.attr_bits = 0U;
......
......@@ -139,7 +139,7 @@ static int DumpTrieDataNodeTraversal(const WorkSpace *workSpace, const ParamTrie
ParamNode *entry = (ParamNode *)GetTrieNode(workSpace, current->dataIndex);
if (entry != NULL) {
PARAM_DUMP("\tparameter length info [%u, %u] \n\t param: %s \n",
entry->keyLength, entry->valueLength, (entry != NULL) ? entry->data : "null");
entry->keyLength, entry->valueLength, entry->data);
}
}
if (current->labelIndex != 0 && verbose) {
......@@ -300,7 +300,7 @@ INIT_LOCAL_API int GetServiceCtrlInfo(const char *name, const char *value, Servi
for (size_t i = 0; i < size; i++) {
if (strcmp(name, ctrlParam[i].name) == 0) {
uint32_t valueOffset = strlen(OHOS_SERVICE_CTRL_PREFIX) + strlen(ctrlParam[i].replace) + 1;
return CreateCtrlInfo(ctrlInfo, ctrlParam[i].cmd, valueOffset, 1,
return CreateCtrlInfo(ctrlInfo, ctrlParam[i].cmd, valueOffset, 1,
"%s%s.%s", OHOS_SERVICE_CTRL_PREFIX, ctrlParam[i].replace, value);
}
}
......@@ -309,14 +309,14 @@ INIT_LOCAL_API int GetServiceCtrlInfo(const char *name, const char *value, Servi
const ParamCmdInfo *installParam = GetServiceCtl(&size);
for (size_t i = 0; i < size; i++) {
if (strncmp(name, installParam[i].name, strlen(installParam[i].name)) == 0) {
return CreateCtrlInfo(ctrlInfo, installParam[i].cmd, strlen(name) + 1, 1, "%s.%s", name, value);
return CreateCtrlInfo(ctrlInfo, installParam[i].cmd, strlen(name) + 1, 1, "%s.%s", name, value);
}
}
}
const ParamCmdInfo *other = GetOtherSpecial(&size);
for (size_t i = 0; i < size; i++) {
if (strncmp(name, other[i].name, strlen(other[i].name)) == 0) {
return CreateCtrlInfo(ctrlInfo, other[i].cmd, strlen(other[i].name), 0, "%s.%s", name, value);
return CreateCtrlInfo(ctrlInfo, other[i].cmd, strlen(other[i].name), 0, "%s.%s", name, value);
}
}
return 0;
......@@ -348,7 +348,7 @@ INIT_LOCAL_API int CheckParameterSet(const char *name,
}
#if !(defined __LITEOS_A__ || defined __LITEOS_M__)
// do hook cmd
PARAM_LOGV("CheckParameterSet realKey %s cmd: '%s' value: %s",
PARAM_LOGV("Check parameter settings realKey %s cmd: '%s' value: %s",
serviceInfo->realKey, serviceInfo->cmdName, (char *)serviceInfo->realKey + serviceInfo->valueOffset);
DoCmdByName(serviceInfo->cmdName, (char *)serviceInfo->realKey + serviceInfo->valueOffset);
#endif
......@@ -365,7 +365,7 @@ int SystemGetParameterCommitId(ParamHandle handle, uint32_t *commitId)
ParamNode *entry = (ParamNode *)GetTrieNodeByHandle(handle);
if (entry == NULL) {
return -1;
return PARAM_CODE_NOT_FOUND;
}
*commitId = ReadCommitId(entry);
return 0;
......
......@@ -23,7 +23,7 @@
#include "param_osadp.h"
#include "securec.h"
static ParamPersistWorkSpace g_persistWorkSpace = {0, 0, NULL, 0, {}};
static ParamPersistWorkSpace g_persistWorkSpace = {0, 0, NULL, 0, {0}};
static int IsNeedToSave(const char *name)
{
#if defined(__LITEOS_M__) || defined(__LITEOS_A__)
......@@ -185,7 +185,6 @@ INIT_LOCAL_API int WritePersistParam(const char *name, const char *value)
// for linux, start timer after set persist parameter
// for liteos-a, start timer in init to check and save parameter
#ifdef PARAM_SUPPORT_REAL_CHECK
PARAM_LOGI("WritePersistParam start check ");
if (!PARAM_TEST_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_LOADED)) {
PARAM_LOGE("Can not save persist param before load %s ", name);
return 0;
......@@ -227,7 +226,7 @@ int LoadPersistParams(void)
}
#endif
if (g_persistWorkSpace.persistParamOps.load != NULL) {
ret = g_persistWorkSpace.persistParamOps.load();
(void)g_persistWorkSpace.persistParamOps.load();
PARAM_SET_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_LOADED);
}
// save new persist param
......@@ -242,4 +241,4 @@ int LoadPersistParams(void)
}
#endif
return 0;
}
\ No newline at end of file
}
......@@ -46,14 +46,14 @@ static int CommonDealFun(const char *name, const char *value, int res)
{
int ret = 0;
if (res == 0) {
PARAM_LOGI("Add param from cmdline %s %s", name, value);
PARAM_LOGV("Add param from cmdline %s %s", name, value);
ret = CheckParamName(name, 0);
PARAM_CHECK(ret == 0, return ret, "Invalid name %s", name);
PARAM_LOGV("**** name %s, value %s", name, value);
PARAM_CHECK(ret == 0, return ret, "Invalid param name %s", name);
PARAM_LOGV("Param name %s, value %s", name, value);
ret = WriteParam(name, value, NULL, 0);
PARAM_CHECK(ret == 0, return ret, "Failed to write param %s %s", name, value);
} else {
PARAM_LOGE("Can not find arrt %s", name);
PARAM_LOGE("Get %s parameter value is null.", name);
}
return ret;
}
......@@ -78,7 +78,7 @@ static int ReadSnFromFile(const char *name, const char *file)
PARAM_LOGV("**** name %s, value %s", name, data);
int ret = WriteParam(name, data, NULL, 0);
free(data);
PARAM_CHECK(ret == 0, return ret, "Failed to write param %s %s", name, data);
PARAM_CHECK(ret == 0, return ret, "Failed to write param %s", name);
return ret;
}
......@@ -113,7 +113,6 @@ static int SnDealFun(const char *name, const char *value, int res)
INIT_LOCAL_API int LoadParamFromCmdLine(void)
{
int ret;
static const cmdLineInfo cmdLines[] = {
{OHOS_BOOT"hardware", CommonDealFun
},
......@@ -133,6 +132,7 @@ INIT_LOCAL_API int LoadParamFromCmdLine(void)
return -1, "Failed to read file %s", BOOT_CMD_LINE);
for (size_t i = 0; i < ARRAY_LENGTH(cmdLines); i++) {
int ret = 0;
#ifdef BOOT_EXTENDED_CMDLINE
ret = GetParamValueFromBuffer(cmdLines[i].name, BOOT_EXTENDED_CMDLINE, value, PARAM_CONST_VALUE_LEN_MAX);
if (ret != 0) {
......@@ -182,7 +182,7 @@ static int LoadDefaultParam_(const char *fileName, uint32_t mode,
}
(void)fclose(fp);
free(buffer);
PARAM_LOGI("Load parameters success %s total %u", fileName, paramNum);
PARAM_LOGV("Load %u default parameters success from %s.", paramNum, fileName);
return 0;
}
......@@ -201,7 +201,7 @@ int LoadParamsFile(const char *fileName, bool onlyAdd)
int LoadDefaultParams(const char *fileName, uint32_t mode)
{
PARAM_CHECK(fileName != NULL, return -1, "Invalid filename for load");
PARAM_LOGI("load default parameters %s.", fileName);
PARAM_LOGI("Load default parameters from %s.", fileName);
struct stat st;
if ((stat(fileName, &st) == 0) && !S_ISDIR(st.st_mode)) {
(void)ProcessParamFile(fileName, &mode);
......
......@@ -187,7 +187,7 @@ static int ComputeSubCondition(const LogicCalculator *calculator, LogicData *dat
// check name
if ((calculator->inputName != NULL) && (strcmp(calculator->conditionName, calculator->inputName) == 0)) {
return CompareValue(calculator->conditionContent, calculator->inputContent);
} else if (calculator->conditionName != NULL && strlen(calculator->conditionName) > 0) {
} else if (strlen(calculator->conditionName) > 0) {
uint32_t len = SUPPORT_DATA_BUFFER_MAX;
ret = SystemReadParam(calculator->conditionName, calculator->readContent, &len);
if (ret != 0) {
......
......@@ -647,7 +647,7 @@ void InitTriggerHead(const TriggerWorkSpace *workSpace)
head->checkTriggerMatch = CheckParamMatch_;
head->checkCondition = CheckParamCondition_;
head->getCondition = GetTriggerCondition_;
// unknow trigger
// unknown trigger
head = (TriggerHeader *)&workSpace->triggerHead[TRIGGER_UNKNOW];
TriggerHeadSetDefault(head);
head->checkTriggerMatch = CheckUnknowMatch_;
......
......@@ -32,7 +32,7 @@ static TriggerWorkSpace g_triggerWorkSpace = {};
static int DoTriggerExecute_(const TriggerNode *trigger, const char *content, uint32_t size)
{
PARAM_CHECK(trigger != NULL, return -1, "Invalid trigger");
PARAM_LOGI("DoTriggerExecute_ trigger %s type: %d", GetTriggerName(trigger), trigger->type);
PARAM_LOGV("Do execute trigger %s type: %d", GetTriggerName(trigger), trigger->type);
PARAM_CHECK(trigger->type <= TRIGGER_UNKNOW, return -1, "Invalid trigger type %d", trigger->type);
CommandNode *cmd = GetNextCmdNode((JobNode *)trigger, NULL);
while (cmd != NULL) {
......@@ -53,7 +53,7 @@ static int DoTriggerCheckResult(TriggerNode *trigger, const char *content, uint3
return 0;
}
TRIGGER_SET_FLAG(trigger, TRIGGER_FLAGS_QUEUE);
PARAM_LOGI("Add trigger %s to execute queue", GetTriggerName(trigger));
PARAM_LOGV("Add trigger %s to execute queue", GetTriggerName(trigger));
ExecuteQueuePush(&g_triggerWorkSpace, trigger);
return 0;
}
......@@ -368,11 +368,11 @@ void DoTriggerExec(const char *triggerName)
PARAM_CHECK(triggerName != NULL, return, "Invalid param");
JobNode *trigger = GetTriggerByName(&g_triggerWorkSpace, triggerName);
if (trigger != NULL && !TRIGGER_IN_QUEUE((TriggerNode *)trigger)) {
PARAM_LOGI("DoTriggerExec trigger %s", trigger->name);
PARAM_LOGV("Trigger job %s", trigger->name);
TRIGGER_SET_FLAG((TriggerNode *)trigger, TRIGGER_FLAGS_QUEUE);
ExecuteQueuePush(&g_triggerWorkSpace, (TriggerNode *)trigger);
} else {
PARAM_LOGE("Can not find trigger %s", triggerName);
PARAM_LOGW("Can not find trigger %s", triggerName);
}
}
......
......@@ -261,16 +261,20 @@ void WatcherManagerKits::ParameterChangeListener::OnParameterChange(const std::s
} // namespace init_param
} // namespace OHOS
int SystemWatchParameter(const char *keyPrefix, ParameterChangePtr callback, void *context)
static int ParameterWatcherCheck(const char *keyPrefix)
{
WATCHER_CHECK(keyPrefix != nullptr, return PARAM_CODE_INVALID_PARAM, "Invalid prefix");
int ret = 0;
std::string key(keyPrefix);
if (key.rfind("*") == key.length() - 1) {
ret = WatchParamCheck(key.substr(0, key.length() - 1).c_str());
return WatchParamCheck(key.substr(0, key.length() - 1).c_str());
} else {
ret = WatchParamCheck(keyPrefix);
return WatchParamCheck(keyPrefix);
}
}
int SystemWatchParameter(const char *keyPrefix, ParameterChangePtr callback, void *context)
{
WATCHER_CHECK(keyPrefix != nullptr, return PARAM_CODE_INVALID_PARAM, "Invalid prefix");
int ret = ParameterWatcherCheck(keyPrefix);
if (ret != 0) {
return ret;
}
......@@ -286,13 +290,7 @@ int SystemWatchParameter(const char *keyPrefix, ParameterChangePtr callback, voi
int RemoveParameterWatcher(const char *keyPrefix, ParameterChgPtr callback, void *context)
{
WATCHER_CHECK(keyPrefix != nullptr, return PARAM_CODE_INVALID_PARAM, "Invalid prefix");
int ret = 0;
std::string key(keyPrefix);
if (key.rfind("*") == key.length() - 1) {
ret = WatchParamCheck(key.substr(0, key.length() - 1).c_str());
} else {
ret = WatchParamCheck(keyPrefix);
}
int ret = ParameterWatcherCheck(keyPrefix);
if (ret != 0) {
return ret;
}
......
......@@ -46,7 +46,7 @@ private:
: callback_(callback), context_(context) {}
~ParameterChangeListener() = default;
bool IsEqual(ParameterChangePtr callback, void *context)
bool IsEqual(ParameterChangePtr callback, void *context) const
{
return (callback == callback_ && context == context_);
}
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册