提交 72805afa 编写于 作者: 陈杰 提交者: Gitee

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

......@@ -13,14 +13,32 @@ init组件负责处理从内核加载第一个用户态进程开始,到第一
## 目录<a name="section15884114210197"></a>
```
base/startup/init_lite/ # init组件
base/startup/init_lite/ # init组件
├── device_info
├── initsync
├── interfaces # init提供的对外接口
├── scripts
├── services
├── begetctl # init归一化命令
├── etc # init配置文件目录(标准系统)
├── etc_lite # init配置文件目录(小型系统)
├── include # init头文件目录
├── init # init核心功能源码
├── log # init日志部件
├── loopevent # init提供的小型异步事件库
├── modules # 插件化模块
├── param # 系统参数部件
├── utils # init工具库
└── BUILD.gn
├── test # init组件测试用例源文件目录
├── ueventd # ueventd服务源码
├── watchdog # 看门狗服务源码
├── begetd.gni
├── bundle.json
├── LICENSE
└── services
├── include # init组件头文件目录
├── src # init组件源文件目录
├── etc # init配置文件目录(json格式,镜像烧写后部署于/etc/init.cfg)
└── test # init组件测试用例源文件目录
└── unittest
├── README_ZH.md
├── README.md
└── OAT.xml
device
└──hihope
......
......@@ -42,17 +42,16 @@
"//base/startup/init_lite/services/begetctl:begetctl_cmd",
"//base/startup/init_lite/services/modules:modules",
"//base/startup/init_lite/interfaces/innerkits:libbegetutil",
"//base/startup/init_lite/interfaces/kits/syscap:deviceinfo_ndk",
"//base/startup/init_lite/interfaces/innerkits:libbeget_proxy",
"//base/startup/init_lite/interfaces/innerkits/file:libfile",
"//base/startup/init_lite/interfaces/innerkits/socket:libsocket",
"//base/startup/init_lite/services/loopevent:loopevent",
"//base/startup/init_lite/services/init/module_engine:libinit_module_engine",
"//base/startup/init_lite/services/init/module_engine:libinit_stub_empty",
"//base/startup/init_lite/interfaces/innerkits/init_module_engine:init_module_engine",
"//base/startup/init_lite/device_info:device_info_group",
"//base/startup/init_lite/interfaces/innerkits/sandbox:libsandbox",
"//base/startup/init_lite/test/exec_test:exectest",
"//base/startup/init_lite/interfaces/innerkits/control_fd:libcontrolfd"
"//base/startup/init_lite/interfaces/innerkits/control_fd:libcontrolfd",
"//base/startup/init_lite/interfaces/kits:kitsgroup"
],
"inner_kits": [
{
......@@ -88,12 +87,12 @@
},
{
"header": {
"header_base": "//base/startup/init_lite/services/init/module_engine/include",
"header_base": "//base/startup/init_lite/interfaces/innerkits",
"header_files": [
"init_module_engine.h"
"init_module_engine/include/init_module_engine.h"
]
},
"name": "//base/startup/init_lite/services/init/module_engine:libinit_module_engine"
"name": "//base/startup/init_lite/interfaces/innerkits/init_module_engine:libinit_module_engine"
}
],
"test": [
......
......@@ -37,14 +37,11 @@ ohos_shared_library("deviceinfoservice") {
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/interfaces/innerkits/include/syspara",
"//base/startup/init_lite/interfaces/innerkits/syspara",
"//base/startup/init_lite/interfaces/hals",
]
deps = [
"//base/startup/init_lite/services/log:agent_log",
"//base/startup/init_lite/services/loopevent:loopevent",
"//base/startup/init_lite/services/param:param_client",
"//base/startup/init_lite/services/utils:libinit_tools",
"//base/startup/init_lite/services/utils:libinit_utils",
"//base/startup/init_lite/interfaces/innerkits:libbegetutil",
"//third_party/bounds_checking_function:libsec_shared",
"//third_party/openssl:libcrypto_shared",
]
......
......@@ -58,7 +58,6 @@ int32_t DeviceInfoStub::OnRemoteRequest(uint32_t code,
const char *serialNumber = GetSerial_();
DINFO_CHECK(serialNumber != nullptr, break, "Failed to get serialNumber");
reply.WriteString16(Str8ToStr16(serialNumber));
free((void *)serialNumber);
break;
}
default: {
......
......@@ -29,6 +29,20 @@ config("exported_header_files") {
]
}
include_common = [
"./include",
"//base/hiviewdfx/hilog_lite/interfaces/native/kits",
"//third_party/bounds_checking_function/include",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/include/param",
"//base/startup/init_lite/interfaces/innerkits/fd_holder",
"//base/startup/init_lite/services/param/include",
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/interfaces/innerkits/include/syspara",
"//base/startup/init_lite/interfaces/hals",
"//base/startup/init_lite/interfaces/innerkits/syspara",
]
if (defined(ohos_lite)) {
import("//build/lite/config/component/lite_component.gni")
import("//build/lite/ndk/ndk.gni")
......@@ -42,6 +56,7 @@ if (defined(ohos_lite)) {
"OHOS_LITE",
]
deps = []
include_dirs = include_common
if (enable_ohos_startup_init_feature_begetctl_liteos) {
sources += syspara_sources
defines += [ "LITEOS_SUPPORT" ]
......@@ -52,16 +67,7 @@ if (defined(ohos_lite)) {
public_configs = [ ":exported_header_files" ]
cflags = [ "-fPIC" ]
include_dirs = [
"./include",
"//base/hiviewdfx/hilog_lite/interfaces/native/kits",
"//third_party/bounds_checking_function/include",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/include/param",
"//base/startup/init_lite/interfaces/innerkits/fd_holder",
"//base/startup/init_lite/services/param/include",
"//base/startup/init_lite/interfaces/innerkits/include",
]
deps += [
"//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared",
"//base/startup/init_lite/services/utils:libinit_tools",
......@@ -91,16 +97,7 @@ if (defined(ohos_lite)) {
"__LITEOS_M__",
]
include_dirs = [
"./include",
"//base/hiviewdfx/hilog_lite/interfaces/native/kits",
"//third_party/bounds_checking_function/include",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/include/param",
"//base/startup/init_lite/interfaces/innerkits/fd_holder",
"//base/startup/init_lite/services/param/include",
"//base/startup/init_lite/interfaces/innerkits/include",
]
include_dirs = include_common
deps = [
"//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static",
"//base/startup/init_lite/services/utils:libinit_tools",
......@@ -172,15 +169,7 @@ if (defined(ohos_lite)) {
defines += [ "SUPPORT_64BIT" ]
}
include_dirs = [
"./include",
"//third_party/bounds_checking_function/include",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/include/param",
"//base/startup/init_lite/services/param/include",
"//base/startup/init_lite/interfaces/innerkits/fd_holder",
"//base/startup/init_lite/interfaces/innerkits/include",
]
include_dirs = include_common
deps = [
"//base/startup/init_lite/interfaces/innerkits/sandbox:libsandbox",
"//base/startup/init_lite/services/loopevent:loopevent",
......@@ -214,20 +203,12 @@ if (defined(ohos_lite)) {
"service_watcher/service_watcher.c",
]
include_dirs = [
"./include",
"//base/startup/init_lite/device_info",
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/interfaces/innerkits/syspara",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/include/param",
"//base/startup/init_lite/services/param/include",
"//third_party/bounds_checking_function/include",
]
include_dirs = include_common
deps = [
":libbegetutil",
"//base/startup/init_lite/services/utils:libinit_utils",
"//third_party/bounds_checking_function:libsec_shared",
"//third_party/openssl:libcrypto_shared",
]
if (enable_ohos_startup_init_feature_watcher) {
......@@ -241,12 +222,6 @@ if (defined(ohos_lite)) {
"//base/startup/init_lite/services/param/watcher/include",
"//base/startup/init_lite/services/log",
]
deps += [
"//base/startup/init_lite/services/param:param_client",
"//base/startup/init_lite/services/utils:libinit_tools",
"//base/startup/init_lite/services/utils:libinit_utils",
"//third_party/openssl:libcrypto_shared",
]
} else {
defines += [ "NO_PARAM_WATCHER" ]
}
......@@ -261,13 +236,6 @@ if (defined(ohos_lite)) {
sources += [
"//base/startup/init_lite/interfaces/innerkits/syspara/param_comm.c",
]
deps += [
"//base/startup/init_lite/services/loopevent:loopevent",
"//base/startup/init_lite/services/param:param_client",
"//base/startup/init_lite/services/utils:libinit_tools",
"//base/startup/init_lite/services/utils:libinit_utils",
"//third_party/openssl:libcrypto_shared",
]
}
external_deps = [
......@@ -283,6 +251,11 @@ if (defined(ohos_lite)) {
}
# For init only
config("libfsmanager_exported_configs") {
visibility = [ ":*" ]
include_dirs =
[ "//base/startup/init_lite/interfaces/innerkits/include/fs_manager" ]
}
ohos_static_library("libfsmanager_static") {
sources = fs_manager_sources
include_dirs = [
......@@ -292,6 +265,8 @@ if (defined(ohos_lite)) {
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/param/include",
]
public_configs = [ ":libfsmanager_exported_configs" ]
deps = [ "//base/startup/init_lite/services/log:init_log" ]
part_name = "init"
}
......@@ -310,16 +285,7 @@ if (defined(ohos_lite)) {
defines += [ "SUPPORT_64BIT" ]
}
include_dirs = [
"./include",
"//third_party/bounds_checking_function/include",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/include/param",
"//base/startup/init_lite/services/param/include",
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/interfaces/innerkits/include/syspara",
"//base/startup/init_lite/interfaces/innerkits/syspara",
]
include_dirs = include_common
deps = [
"//base/startup/init_lite/services/loopevent:loopevent",
"//base/startup/init_lite/services/param:param_client",
......
......@@ -17,6 +17,7 @@
#define CONTROL_FD_
#include <stdint.h>
#include <fcntl.h>
#include "loop_event.h"
#ifdef __cplusplus
......@@ -53,7 +54,7 @@ typedef enum {
typedef struct {
uint16_t msgSize;
uint16_t type;
uint32_t pid;
pid_t pid;
char fifoName[FIFO_PATH_SIZE];
char cmd[0];
} CmdMessage;
......
......@@ -118,17 +118,26 @@ static void CmdDisConnectComplete(const TaskHandle client)
static void CmdAgentInit(WatcherHandle handle, const char *path, bool read, ProcessWatchEvent func)
{
if (path == NULL) {
BEGET_LOGE("[control_fd] Invaild parameter");
return;
}
BEGET_LOGI("[control_fd] client open %s", (read ? "read" : "write"));
char *realPath = GetRealPath(path);
if (realPath == NULL) {
BEGET_LOGE("[control_fd] Failed get real path %s", path);
return;
}
if (read == true) {
g_FifoReadFd = open(path, O_RDONLY | O_TRUNC | O_NONBLOCK);
BEGET_ERROR_CHECK(g_FifoReadFd >= 0, return, "[control_fd] Failed to open fifo read");
g_FifoReadFd = open(realPath, O_RDONLY | O_TRUNC | O_NONBLOCK);
BEGET_ERROR_CHECK(g_FifoReadFd >= 0, free(realPath); return, "[control_fd] Failed to open fifo read");
BEGET_LOGI("[control_fd] g_FifoReadFd is %d", g_FifoReadFd);
} else {
g_FifoWriteFd = open(path, O_WRONLY | O_TRUNC);
BEGET_ERROR_CHECK(g_FifoWriteFd >= 0, return, "[control_fd] Failed to open fifo write");
g_FifoWriteFd = open(realPath, O_WRONLY | O_TRUNC);
BEGET_ERROR_CHECK(g_FifoWriteFd >= 0, free(realPath); return, "[control_fd] Failed to open fifo write");
BEGET_LOGI("[control_fd] g_FifoWriteFd is %d", g_FifoWriteFd);
}
free(realPath);
// start watcher for stdin
LE_WatchInfo info = {};
info.flags = 0;
......
......@@ -16,7 +16,6 @@
#include <stdbool.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/wait.h>
#include "beget_ext.h"
#include "control_fd.h"
......
......@@ -19,6 +19,7 @@
#include <string.h>
#include "list.h"
#include "beget_ext.h"
#include "hookmgr.h"
// Forward declaration
......@@ -58,17 +59,11 @@ static HOOK_MGR *defaultHookMgr = NULL;
static HOOK_MGR *getHookMgr(HOOK_MGR *hookMgr, int autoCreate)
{
if (hookMgr != NULL) {
return hookMgr;
}
BEGET_CHECK(hookMgr == NULL, return hookMgr);
// Use default HOOK_MGR if possible
if (defaultHookMgr != NULL) {
return defaultHookMgr;
}
BEGET_CHECK(defaultHookMgr == NULL, return defaultHookMgr);
if (!autoCreate) {
return NULL;
}
BEGET_CHECK(autoCreate, return NULL);
// Create default HOOK_MGR if not created
defaultHookMgr = HookMgrCreate("default");
......@@ -88,9 +83,7 @@ static void hookStageDestroy(ListNode *node)
{
HOOK_STAGE *stage;
if (node == NULL) {
return;
}
BEGET_CHECK(node != NULL, return);
stage = (HOOK_STAGE *)node;
ListRemoveAll(&(stage->hooks), NULL);
......@@ -103,19 +96,13 @@ static HOOK_STAGE *getHookStage(HOOK_MGR *hookMgr, int stage, int createIfNotFou
HOOK_STAGE *stageItem;
stageItem = (HOOK_STAGE *)ListFind(&(hookMgr->stages), (void *)(&stage), hookStageCompare);
if (stageItem != NULL) {
return stageItem;
}
BEGET_CHECK(stageItem == NULL, return stageItem);
if (!createIfNotFound) {
return NULL;
}
BEGET_CHECK(createIfNotFound, return NULL);
// Not found, create it
stageItem = (HOOK_STAGE *)malloc(sizeof(HOOK_STAGE));
if (stageItem == NULL) {
return NULL;
}
BEGET_CHECK(stageItem != NULL, return NULL);
stageItem->stage = stage;
ListInit(&(stageItem->hooks));
ListAddTail(&(hookMgr->stages), (ListNode *)stageItem);
......@@ -143,12 +130,8 @@ static int hookItemCompareValue(ListNode *node, void *data)
struct HOOKITEM_COMPARE_VAL *compareVal = (struct HOOKITEM_COMPARE_VAL *)data;
hookItem = (const HOOK_ITEM *)node;
if (hookItem->prio != compareVal->prio) {
return (hookItem->prio - compareVal->prio);
}
if (hookItem->hook == compareVal->hook) {
return 0;
}
BEGET_CHECK(hookItem->prio == compareVal->prio, return (hookItem->prio - compareVal->prio));
BEGET_CHECK(hookItem->hook != compareVal->hook, return 0);
return -1;
}
......@@ -162,15 +145,11 @@ static int addHookToStage(HOOK_STAGE *hookStage, int prio, OhosHook hook)
compareVal.prio = prio;
compareVal.hook = hook;
hookItem = (HOOK_ITEM *)ListFind(&(hookStage->hooks), (void *)(&compareVal), hookItemCompareValue);
if (hookItem != NULL) {
return 0;
}
BEGET_CHECK(hookItem == NULL, return 0);
// Create new item
hookItem = (HOOK_ITEM *)malloc(sizeof(HOOK_ITEM));
if (hookItem == NULL) {
return -1;
}
BEGET_CHECK(hookItem != NULL, return -1);
hookItem->prio = prio;
hookItem->hook = hook;
hookItem->stage = hookStage;
......@@ -183,21 +162,15 @@ static int addHookToStage(HOOK_STAGE *hookStage, int prio, OhosHook hook)
int HookMgrAdd(HOOK_MGR *hookMgr, int stage, int prio, OhosHook hook)
{
HOOK_STAGE *stageItem;
if (hook == NULL) {
return -1;
}
BEGET_CHECK(hook != NULL, return -1);
// Get HOOK_MGR
hookMgr = getHookMgr(hookMgr, true);
if (hookMgr == NULL) {
return -1;
}
BEGET_CHECK(hookMgr != NULL, return -1);
// Get HOOK_STAGE list
stageItem = getHookStage(hookMgr, stage, true);
if (stageItem == NULL) {
return -1;
}
BEGET_CHECK(stageItem != NULL, return -1);
// Add hook to stage
return addHookToStage(stageItem, prio, hook);
......@@ -208,9 +181,7 @@ static int hookTraversalDelProc(ListNode *node, void *cookie)
HOOK_ITEM *hookItem = (HOOK_ITEM *)node;
// Not equal, just return
if ((void *)hookItem->hook != cookie) {
return 0;
}
BEGET_CHECK((void *)hookItem->hook == cookie, return 0);
// Remove from the list
ListRemove(node);
......@@ -230,15 +201,11 @@ void HookMgrDel(HOOK_MGR *hookMgr, int stage, OhosHook hook)
// Get HOOK_MGR
hookMgr = getHookMgr(hookMgr, 0);
if (hookMgr == NULL) {
return;
}
BEGET_CHECK(hookMgr != NULL, return);
// Get HOOK_STAGE list
stageItem = getHookStage(hookMgr, stage, false);
if (stageItem == NULL) {
return;
}
BEGET_CHECK(stageItem != NULL, return);
if (hook != NULL) {
ListTraversal(&(stageItem->hooks), hook, hookTraversalDelProc, 0);
......@@ -289,15 +256,11 @@ int HookMgrExecute(HOOK_MGR *hookMgr, int stage, const HOOK_EXEC_ARGS *args)
// Get HOOK_MGR
hookMgr = getHookMgr(hookMgr, 0);
if (hookMgr == NULL) {
return -1;
}
BEGET_CHECK(hookMgr != NULL, return -1)
// Get HOOK_STAGE list
stageItem = getHookStage(hookMgr, stage, false);
if (stageItem == NULL) {
return -1;
}
BEGET_CHECK(stageItem != NULL, return -1);
flags = 0;
if (args != NULL) {
......@@ -313,13 +276,9 @@ HOOK_MGR *HookMgrCreate(const char *name)
{
HOOK_MGR *ret;
if (name == NULL) {
return NULL;
}
BEGET_CHECK(name != NULL, return NULL);
ret = (HOOK_MGR *)malloc(sizeof(HOOK_MGR));
if (ret == NULL) {
return NULL;
}
BEGET_CHECK(ret != NULL, return NULL);
ret->name = strdup(name);
if (ret->name == NULL) {
......@@ -333,9 +292,7 @@ HOOK_MGR *HookMgrCreate(const char *name)
void HookMgrDestroy(HOOK_MGR *hookMgr)
{
hookMgr = getHookMgr(hookMgr, 0);
if (hookMgr == NULL) {
return;
}
BEGET_CHECK(hookMgr != NULL, return);
ListRemoveAll(&(hookMgr->stages), hookStageDestroy);
......@@ -390,14 +347,10 @@ void HookMgrTraversal(HOOK_MGR *hookMgr, void *cookie, OhosHookTraversal travers
{
HOOK_TRAVERSAL_ARGS stageArgs;
if (traversal == NULL) {
return;
}
BEGET_CHECK(traversal != NULL, return);
hookMgr = getHookMgr(hookMgr, 0);
if (hookMgr == NULL) {
return;
}
BEGET_CHECK(hookMgr != NULL, return);
// Prepare common args
stageArgs.hookInfo.cookie = cookie;
......@@ -414,15 +367,11 @@ int HookMgrGetHooksCnt(HOOK_MGR *hookMgr, int stage)
HOOK_STAGE *stageItem;
hookMgr = getHookMgr(hookMgr, 0);
if (hookMgr == NULL) {
return 0;
}
BEGET_CHECK(hookMgr != NULL, return 0);
// Get HOOK_STAGE list
stageItem = getHookStage(hookMgr, stage, false);
if (stageItem == NULL) {
return 0;
}
BEGET_CHECK(stageItem != NULL, return 0);
return ListGetCnt(&(stageItem->hooks));
}
......@@ -433,9 +382,7 @@ int HookMgrGetHooksCnt(HOOK_MGR *hookMgr, int stage)
int HookMgrGetStagesCnt(HOOK_MGR *hookMgr)
{
hookMgr = getHookMgr(hookMgr, 0);
if (hookMgr == NULL) {
return 0;
}
BEGET_CHECK(hookMgr != NULL, return 0);
return ListGetCnt(&(hookMgr->stages));
}
......@@ -13,8 +13,8 @@
* limitations under the License.
*/
#ifndef STARTUP_SYSVERSION_API_H
#define STARTUP_SYSVERSION_API_H
#ifndef PARAM_WRAPPER_H
#define PARAM_WRAPPER_H
#include <string>
......@@ -25,4 +25,4 @@ int GetIntParameter(const std::string key, int def);
}
}
#endif // STARTUP_SYSVERSION_API_H
#endif // PARAM_WRAPPER_H
......@@ -14,24 +14,39 @@
import("//build/ohos.gni")
import("//build/ohos/native_stub/native_stub.gni")
config("libinit_module_engine_config") {
#
# exported include directories
#
config("init_module_engine_exported_config") {
visibility = [ ":*" ]
include_dirs = [
"//base/startup/init_lite/services/init/module_engine/include",
"include/",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/services/log",
]
}
#
# innerkits for module developement
#
ohos_native_stub_library("libinit_module_engine") {
output_extension = "so"
public_configs = [ ":libinit_module_engine_config" ]
public_configs = [ ":init_module_engine_exported_config" ]
stub_description_file = "./stub/libinit.stub.json"
}
#
# For init linking,
# export symbols defined in this json files only
#
ohos_native_stub_versionscript("libinit_stub_versionscript") {
stub_description_file = "./stub/libinit.stub.json"
}
#
# Generate empty library with symlink name to satisfy init loading required libraries
#
ohos_native_stub_library("libinit_stub_empty") {
output_extension = "so"
stub_description_file = "./stub/libinit.stub.empty.json"
......@@ -39,3 +54,27 @@ ohos_native_stub_library("libinit_stub_empty") {
install_enable = true
symlink_target_name = [ "libinit_module_engine.so" ]
}
config("init_module_engine_sources_config") {
include_dirs = [
"//base/startup/init_lite/interfaces/innerkits/init_module_engine/include",
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/log",
]
}
ohos_source_set("init_module_engine_sources") {
sources = [ "init_modulemgr.c" ]
public_configs = [ ":init_module_engine_sources_config" ]
}
#
# init module engine all modules
#
group("init_module_engine") {
deps = [
":libinit_module_engine",
":libinit_stub_empty",
]
}
......@@ -44,14 +44,10 @@ MODULE_MGR *ModuleMgrCreate(const char *name)
{
MODULE_MGR *moduleMgr;
if (name == NULL) {
return NULL;
}
BEGET_CHECK(name != NULL, return NULL);
moduleMgr = (MODULE_MGR *)malloc(sizeof(MODULE_MGR));
if (moduleMgr == NULL) {
return NULL;
}
BEGET_CHECK(moduleMgr != NULL, return NULL);
ListInit(&(moduleMgr->modules));
moduleMgr->name = strdup(name);
if (moduleMgr->name == NULL) {
......@@ -66,14 +62,10 @@ MODULE_MGR *ModuleMgrCreate(const char *name)
void ModuleMgrDestroy(MODULE_MGR *moduleMgr)
{
if (moduleMgr == NULL) {
return;
}
BEGET_CHECK(moduleMgr != NULL, return);
ModuleMgrUninstall(moduleMgr, NULL);
if (moduleMgr->name != NULL) {
free((void *)moduleMgr->name);
}
BEGET_CHECK(moduleMgr->name == NULL, free((void *)moduleMgr->name));
free((void *)moduleMgr);
}
......@@ -93,17 +85,11 @@ static void moduleDestroy(ListNode *node)
{
MODULE_ITEM *module;
if (node == NULL) {
return;
}
BEGET_CHECK(node != NULL, return);
module = (MODULE_ITEM *)node;
if (module->name != NULL) {
free((void *)module->name);
}
if (module->handle != NULL) {
dlclose(module->handle);
}
BEGET_CHECK(module->name == NULL, free((void *)module->name));
BEGET_CHECK(module->handle == NULL, dlclose(module->handle));
free((void *)module);
}
......@@ -132,9 +118,7 @@ static void *moduleInstall(MODULE_ITEM *module, int argc, const char *argv[])
currentInstallArgs = &(module->moduleMgr->installArgs);
handle = dlopen(path, RTLD_LAZY | RTLD_GLOBAL);
currentInstallArgs = NULL;
if (handle == NULL) {
BEGET_LOGE("moduleInstall path %s fail %d", path, errno);
}
BEGET_CHECK_ONLY_ELOG(handle != NULL, "moduleInstall path %s fail %d", path, errno);
return handle;
}
......@@ -147,15 +131,10 @@ int ModuleMgrInstall(MODULE_MGR *moduleMgr, const char *moduleName,
MODULE_ITEM *module;
// Get module manager
if ((moduleMgr == NULL) || (moduleName == NULL)) {
return -1;
}
BEGET_CHECK(!(moduleMgr == NULL || moduleName == NULL), return -1);
// Create module item
module = (MODULE_ITEM *)malloc(sizeof(MODULE_ITEM));
if (module == NULL) {
return -1;
}
BEGET_CHECK(module != NULL, return -1);
module->handle = NULL;
module->moduleMgr = moduleMgr;
......@@ -189,14 +168,10 @@ static int stringEndsWith(const char *srcStr, const char *endStr)
int srcStrLen = strlen(srcStr);
int endStrLen = strlen(endStr);
if (srcStrLen < endStrLen) {
return -1;
}
BEGET_CHECK(!(srcStrLen < endStrLen), return -1);
srcStr += (srcStrLen - endStrLen);
if (strcmp(srcStr, endStr) == 0) {
return (srcStrLen - endStrLen);
}
BEGET_CHECK(strcmp(srcStr, endStr) != 0, return (srcStrLen - endStrLen));
return -1;
}
......@@ -208,9 +183,7 @@ static void scanModules(MODULE_MGR *moduleMgr, const char *path)
struct dirent *file;
dir = opendir(path);
if (dir == NULL) {
return;
}
BEGET_CHECK(dir != NULL, return);
while (1) {
file = readdir(dir);
......@@ -243,18 +216,13 @@ MODULE_MGR *ModuleMgrScan(const char *modulePath)
char path[PATH_MAX];
moduleMgr = ModuleMgrCreate(modulePath);
if (moduleMgr == NULL) {
return NULL;
}
BEGET_CHECK(moduleMgr != NULL, return NULL);
if (modulePath[0] == '/') {
if (snprintf_s(path, sizeof(path), sizeof(path) - 1, "%s", modulePath) < 0) {
return NULL;
}
BEGET_CHECK(!(snprintf_s(path, sizeof(path), sizeof(path) - 1, "%s", modulePath) < 0), return NULL);
} else {
if (snprintf_s(path, sizeof(path), sizeof(path) - 1, "/system/" MODULE_LIB_NAME "/%s", modulePath) < 0) {
return NULL;
};
BEGET_CHECK(!(snprintf_s(path, sizeof(path), sizeof(path) - 1,
"/system/" MODULE_LIB_NAME "/%s", modulePath) < 0), return NULL);
}
scanModules(moduleMgr, path);
......@@ -275,11 +243,7 @@ static int moduleCompare(ListNode *node, void *data)
void ModuleMgrUninstall(MODULE_MGR *moduleMgr, const char *name)
{
MODULE_ITEM *module;
if (moduleMgr == NULL) {
return;
}
BEGET_CHECK(moduleMgr != NULL, return);
// Uninstall all modules if no name specified
if (name == NULL) {
ListRemoveAll(&(moduleMgr->modules), moduleDestroy);
......@@ -288,9 +252,7 @@ void ModuleMgrUninstall(MODULE_MGR *moduleMgr, const char *name)
// Find module by name
module = (MODULE_ITEM *)ListFind(&(moduleMgr->modules), (void *)name, moduleCompare);
if (module == NULL) {
return;
}
BEGET_CHECK(module != NULL, return);
// Remove from the list
ListRemove((ListNode *)module);
......@@ -300,9 +262,6 @@ void ModuleMgrUninstall(MODULE_MGR *moduleMgr, const char *name)
int ModuleMgrGetCnt(const MODULE_MGR *moduleMgr)
{
if (moduleMgr == NULL) {
return 0;
}
BEGET_CHECK(moduleMgr != NULL, return 0);
return ListGetCnt(&(moduleMgr->modules));
}
......@@ -63,5 +63,8 @@ ohos_static_library("libsandbox_static") {
"//base/startup/init_lite/services/utils:libinit_utils",
"//third_party/cJSON:cjson_static",
]
if (target_cpu == "arm64") {
defines = [ "SUPPORT_64BIT" ]
}
part_name = "init"
}
{
"sandbox-root" : "/mnt/sandbox/chipset",
"sandbox-root" : "/mnt/sandbox/system",
"mount-bind-paths" : [{
"src-path" : "/system/lib/vndk",
"sandbox-path" : "/system/lib/vndk",
"src-path" : "/system/bin",
"sandbox-path" : "/system/bin",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/system/lib/platform-vndk",
"sandbox-path" : "/system/lib/platform-vndk",
"src-path" : "/system/etc",
"sandbox-path" : "/system/etc",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/system/lib/ndk",
"sandbox-path" : "/system/lib/ndk",
"src-path" : "/system/lib",
"sandbox-path" : "/system/lib",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/vendor/lib",
"sandbox-path" : "/vendor/lib",
"src-path" : "/system/profile",
"sandbox-path" : "/system/profile",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/vendor/bin",
"sandbox-path" : "/vendor/bin",
"src-path" : "/system/app",
"sandbox-path" : "/system/app",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/vendor/etc",
"sandbox-path" : "/vendor/etc",
"src-path" : "/system/fonts",
"sandbox-path" : "/system/fonts",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/system/usr",
"sandbox-path" : "/system/usr",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/vendor",
"sandbox-path" : "/vendor",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/dev",
......@@ -48,18 +56,34 @@
"src-path" : "/sys",
"sandbox-path" : "/sys",
"sandbox-flags" : [ "bind", "private" ]
}, {
"src-path" : "/config",
"sandbox-path" : "/config",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/mnt",
"sandbox-path" : "/mnt",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/storage",
"sandbox-path" : "/storage",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/sys_prod",
"sandbox-path" : "/sys_prod",
"sandbox-flags" : [ "bind", "rec", "private" ]
}
],
"mount-bind-files" : [{
}],
"symbol-links" : [{
"target-name" : "/vendor/lib",
"target-name" : "/system/lib",
"link-name" : "/lib"
}, {
"target-name" : "/vendor/bin",
"target-name" : "/system/bin",
"link-name" : "/bin"
}, {
"target-name" : "/vendor/etc",
"target-name" : "/system/etc",
"link-name" : "/etc"
}
]
......
{
"sandbox-root" : "/mnt/sandbox/chipset",
"sandbox-root" : "/mnt/sandbox/system",
"mount-bind-paths" : [{
"src-path" : "/system/lib64/vndk",
"sandbox-path" : "/system/lib64/vndk",
"src-path" : "/system/bin",
"sandbox-path" : "/system/bin",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/system/lib64/platform-vndk",
"sandbox-path" : "/system/lib64/platform-vndk",
"src-path" : "/system/etc",
"sandbox-path" : "/system/etc",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/system/lib64/ndk",
"sandbox-path" : "/system/lib64/ndk",
"src-path" : "/system/lib64",
"sandbox-path" : "/system/lib64",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/vendor/lib64",
"sandbox-path" : "/vendor/lib64",
"src-path" : "/system/lib",
"sandbox-path" : "/system/lib",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/vendor/bin",
"sandbox-path" : "/vendor/bin",
"src-path" : "/system/profile",
"sandbox-path" : "/system/profile",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/vendor/etc",
"sandbox-path" : "/vendor/etc",
"src-path" : "/system/app",
"sandbox-path" : "/system/app",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/system/fonts",
"sandbox-path" : "/system/fonts",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/system/usr",
"sandbox-path" : "/system/usr",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/vendor",
"sandbox-path" : "/vendor",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/dev",
......@@ -44,22 +56,41 @@
"src-path" : "/sys/kernel/debug",
"sandbox-path" : "/sys/kernel/debug",
"sandbox-flags" : [ "bind", "private" ]
}, {
}, {
"src-path" : "/sys",
"sandbox-path" : "/sys",
"sandbox-flags" : [ "bind", "private" ]
}, {
"src-path" : "/config",
"sandbox-path" : "/config",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/mnt",
"sandbox-path" : "/mnt",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/storage",
"sandbox-path" : "/storage",
"sandbox-flags" : [ "bind", "rec", "private" ]
}, {
"src-path" : "/sys_prod",
"sandbox-path" : "/sys_prod",
"sandbox-flags" : [ "bind", "rec", "private" ]
}
],
"mount-bind-files" : [{
}],
"symbol-links" : [{
"target-name" : "/vendor/lib64",
"target-name" : "/system/lib64",
"link-name" : "/lib64"
}, {
"target-name" : "/vendor/bin",
"target-name" : "/system/lib",
"link-name" : "/lib"
}, {
"target-name" : "/system/bin",
"link-name" : "/bin"
}, {
"target-name" : "/vendor/etc",
"target-name" : "/system/etc",
"link-name" : "/etc"
}
]
......
......@@ -44,7 +44,8 @@ typedef struct LinkList {
} linklist_t;
typedef struct {
mountlist_t *mounts;
mountlist_t *pathMounts;
mountlist_t *fileMounts;
linklist_t *links;
char *rootPath; // /mnt/sandbox/system|vendor|xxx
char name[MAX_BUFFER_LEN]; // name of sandbox. i.e system, chipset etc.
......
......@@ -21,6 +21,7 @@
#include <sched.h>
#include <sys/mount.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <errno.h>
#include "beget_ext.h"
#include "init_utils.h"
......@@ -46,11 +47,21 @@
#define SANDBOX_CHIPSET_CONFIG_FILE "/system/etc/sandbox/chipset-sandbox64.json"
#endif
#ifdef STARTUP_INIT_TEST
#define SANDBOX_TEST_CONFIG_FILE "/system/etc/sandbox/test-sandbox.json"
#endif
#define SANDBOX_MOUNT_FLAGS_MS_BIND "bind"
#define SANDBOX_MOUNT_FLAGS_MS_PRIVATE "private"
#define SANDBOX_MOUNT_FLAGS_MS_REC "rec"
#define SANDBOX_MOUNT_FLAGS_MS_MOVE "move"
typedef enum SandboxTag {
SANDBOX_TAG_MOUNT_PATH = 0,
SANDBOX_TAG_MOUNT_FILE,
SANDBOX_TAG_SYMLINK
} SandboxTag;
struct SandboxMountFlags {
const char *flag;
unsigned long value;
......@@ -77,6 +88,9 @@ static const struct SandboxMountFlags g_flags[] = {
static sandbox_t g_systemSandbox;
static sandbox_t g_chipsetSandbox;
#ifdef STARTUP_INIT_TEST
static sandbox_t g_testSandbox;
#endif
struct SandboxMap {
const char *name;
......@@ -94,7 +108,14 @@ static const struct SandboxMap g_map[] = {
.name = "chipset",
.sandbox = &g_chipsetSandbox,
.configfile = SANDBOX_CHIPSET_CONFIG_FILE,
},
#ifdef STARTUP_INIT_TEST
{
.name = "test",
.sandbox = &g_testSandbox,
.configfile = SANDBOX_TEST_CONFIG_FILE,
}
#endif
};
static unsigned long GetSandboxMountFlags(cJSON *item)
......@@ -112,66 +133,72 @@ static unsigned long GetSandboxMountFlags(cJSON *item)
return 0;
}
typedef int (*AddInfoToSandboxCallback)(sandbox_t *sandbox, cJSON *item);
typedef int (*AddInfoToSandboxCallback)(sandbox_t *sandbox, cJSON *item, const char *type);
static int AddMountInfoToSandbox(sandbox_t *sandbox, cJSON *item)
static int AddMountInfoToSandbox(sandbox_t *sandbox, cJSON *item, const char *type)
{
if (sandbox == NULL || item == NULL) {
if (sandbox == NULL || item == NULL || type == NULL) {
return -1;
}
mountlist_t *tmpMount = (mountlist_t *)calloc(1, sizeof(mountlist_t));
BEGET_ERROR_CHECK(tmpMount != NULL, return -1, "Failed calloc err=%d", errno);
tmpMount->info = (mount_t *)calloc(1, sizeof(mount_t));
BEGET_ERROR_CHECK(tmpMount->info != NULL, return -1, "Failed calloc err=%d", errno);
char *srcPath = cJSON_GetStringValue(cJSON_GetObjectItem(item, SANDBOX_SOURCE));
if (srcPath != NULL) {
tmpMount->info->source = strdup(srcPath);
}
BEGET_ERROR_CHECK(srcPath != NULL, return 0, "Get src-path is null");
char *dstPath = cJSON_GetStringValue(cJSON_GetObjectItem(item, SANDBOX_TARGET));
if (dstPath != NULL) {
tmpMount->info->target = strdup(dstPath);
}
BEGET_ERROR_CHECK(dstPath != NULL, return 0, "Get sandbox-path is null");
cJSON *obj = cJSON_GetObjectItem(item, SANDBOX_FLAGS);
BEGET_ERROR_CHECK(obj != NULL, return -1, "Failed get sandbox-flags.");
BEGET_ERROR_CHECK(obj != NULL, return 0, "Get sandbox-flags is null");
int ret = cJSON_IsArray(obj);
BEGET_ERROR_CHECK(ret, return -1, "Failed get sandbox-flags array. ");
BEGET_ERROR_CHECK(ret, return 0, "Sandbox-flags is not array");
int count = cJSON_GetArraySize(obj);
BEGET_ERROR_CHECK(count > 0, return -1, "Failed get sandbox-flags array size.");
BEGET_ERROR_CHECK(count > 0, return 0, "Get sandbox-flags array size is zero");
mountlist_t *tmpMount = (mountlist_t *)calloc(1, sizeof(mountlist_t));
BEGET_ERROR_CHECK(tmpMount != NULL, return -1, "Failed calloc err=%d", errno);
tmpMount->info = (mount_t *)calloc(1, sizeof(mount_t));
BEGET_ERROR_CHECK(tmpMount->info != NULL, free(tmpMount); return -1, "Failed calloc err=%d", errno);
tmpMount->info->source = strdup(srcPath);
tmpMount->info->target = strdup(dstPath);
for (int i = 0; i < count; i++) {
cJSON *item = cJSON_GetArrayItem(obj, i);
tmpMount->info->flags |= GetSandboxMountFlags(item);
}
if (sandbox->mounts == NULL) {
sandbox->mounts = tmpMount;
tmpMount->next = NULL;
} else {
tmpMount->next = sandbox->mounts->next;
sandbox->mounts->next = tmpMount;
if (strcmp(type, SANDBOX_MOUNT_PATH_TAG) == 0) {
if (sandbox->pathMounts == NULL) {
sandbox->pathMounts = tmpMount;
tmpMount->next = NULL;
} else {
tmpMount->next = sandbox->pathMounts->next;
sandbox->pathMounts->next = tmpMount;
}
} else if (strcmp(type, SANDBOX_MOUNT_FILE_TAG) == 0) {
if (sandbox->fileMounts == NULL) {
sandbox->fileMounts = tmpMount;
tmpMount->next = NULL;
} else {
tmpMount->next = sandbox->fileMounts->next;
sandbox->fileMounts->next = tmpMount;
}
}
return 0;
}
static int AddSymbolLinksToSandbox(sandbox_t *sandbox, cJSON *item)
static int AddSymbolLinksToSandbox(sandbox_t *sandbox, cJSON *item, const char *type)
{
if (sandbox == NULL || item == NULL) {
if (sandbox == NULL || item == NULL || type == NULL) {
return -1;
}
if (strcmp(type, SANDBOX_SYMLINK_TAG) != 0) {
BEGET_LOGE("Type is not sandbox symbolLink.");
return -1;
}
char *target = cJSON_GetStringValue(cJSON_GetObjectItem(item, SANDBOX_SYMLINK_TARGET));
BEGET_ERROR_CHECK(target != NULL, return 0, "Get target-name is null");
char *name = cJSON_GetStringValue(cJSON_GetObjectItem(item, SANDBOX_SYMLINK_NAME));
BEGET_ERROR_CHECK(name != NULL, return 0, "Get link-name is null");
linklist_t *tmpLink = (linklist_t *)calloc(1, sizeof(linklist_t));
BEGET_ERROR_CHECK(tmpLink != NULL, return -1, "Failed calloc err=%d", errno);
tmpLink->info = (linker_t *)calloc(1, sizeof(linker_t));
BEGET_ERROR_CHECK(tmpLink->info != NULL, return -1, "Failed calloc err=%d", errno);
char *target = cJSON_GetStringValue(cJSON_GetObjectItem(item, SANDBOX_SYMLINK_TARGET));
if (target != NULL) {
tmpLink->info->target = strdup(target);
}
char *name = cJSON_GetStringValue(cJSON_GetObjectItem(item, SANDBOX_SYMLINK_NAME));
if (name != NULL) {
tmpLink->info->linkName = strdup(name);
}
BEGET_ERROR_CHECK(tmpLink->info != NULL, free(tmpLink); return -1, "Failed calloc err=%d", errno);
tmpLink->info->target = strdup(target);
tmpLink->info->linkName = strdup(name);
if (sandbox->links == NULL) {
sandbox->links = tmpLink;
tmpLink->next = NULL;
......@@ -188,25 +215,26 @@ static int GetSandboxInfo(sandbox_t *sandbox, cJSON *root, const char *itemName)
BEGET_LOGE("Get sandbox mount info with invalid argument");
return -1;
}
cJSON *obj = cJSON_GetObjectItem(root, itemName);
if (obj == NULL) {
BEGET_LOGE("Cannot find item \' %s \' in sandbox config", itemName);
return -1;
return 0;
}
if (!cJSON_IsArray(obj)) {
BEGET_LOGE("%s with invalid type, should be array", itemName);
return -1;
return 0;
}
int counts = cJSON_GetArraySize(obj);
if (counts <= 0) {
BEGET_LOGE("%s with invalid content", itemName);
return -1;
BEGET_LOGE("Item %s array size is zero.", itemName);
return 0;
}
AddInfoToSandboxCallback func;
AddInfoToSandboxCallback func = NULL;
if (strcmp(itemName, SANDBOX_MOUNT_PATH_TAG) == 0) {
func = AddMountInfoToSandbox;
} else if (strcmp(itemName, SANDBOX_MOUNT_FILE_TAG) == 0) {
func = AddMountInfoToSandbox;
} else if (strcmp(itemName, SANDBOX_SYMLINK_TAG) == 0) {
func = AddSymbolLinksToSandbox;
} else {
......@@ -216,7 +244,7 @@ static int GetSandboxInfo(sandbox_t *sandbox, cJSON *root, const char *itemName)
for (int i = 0; i < counts; i++) {
cJSON *item = cJSON_GetArrayItem(obj, i);
BEGET_ERROR_CHECK(item != NULL, return -1, "Failed get json array item %d", i);
if (func(sandbox, item) < 0) {
if (func(sandbox, item, itemName) < 0) {
BEGET_LOGE("Failed add info to sandbox.");
return -1;
}
......@@ -254,11 +282,19 @@ static int ParseSandboxConfig(sandbox_t *sandbox, const char *sandboxConfig)
return -1;
}
}
BEGET_LOGI("config file %s", sandboxConfig);
if (GetSandboxInfo(sandbox, root, SANDBOX_MOUNT_PATH_TAG) < 0) {
BEGET_LOGE("config file %s, SANDBOX_MOUNT_PATH_TAG error", sandboxConfig);
cJSON_Delete(root);
return -1;
}
if (GetSandboxInfo(sandbox, root, SANDBOX_MOUNT_FILE_TAG) < 0) {
BEGET_LOGE("config file %s, SANDBOX_MOUNT_FILE_TAG error", sandboxConfig);
cJSON_Delete(root);
return -1;
}
if (GetSandboxInfo(sandbox, root, SANDBOX_SYMLINK_TAG) < 0) {
BEGET_LOGE("config file %s, SANDBOX_SYMLINK_TAG error", sandboxConfig);
cJSON_Delete(root);
return -1;
}
......@@ -330,7 +366,7 @@ static int CheckAndMakeDir(const char *dir, mode_t mode)
return 0;
}
static int BindMount(const char *source, const char *target, unsigned long flags)
static int BindMount(const char *source, const char *target, unsigned long flags, SandboxTag tag)
{
if (source == NULL || target == NULL) {
BEGET_LOGE("Mount with invalid arguments");
......@@ -338,8 +374,18 @@ static int BindMount(const char *source, const char *target, unsigned long flags
return -1;
}
mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
if (CheckAndMakeDir(target, mode) != 0) {
BEGET_LOGE("Failed make %s dir.", target);
if (tag == SANDBOX_TAG_MOUNT_PATH) {
if (CheckAndMakeDir(target, mode) != 0) {
BEGET_LOGE("Failed make %s dir.", target);
return -1;
}
} else if (tag == SANDBOX_TAG_MOUNT_FILE) {
if (CheckAndCreatFile(target, mode) != 0) {
BEGET_LOGE("Failed make %s file.", target);
return -1;
}
} else {
BEGET_LOGE("Tag is error.");
return -1;
}
......@@ -356,7 +402,9 @@ static int BindMount(const char *source, const char *target, unsigned long flags
// do mount
if (mount(source, target, NULL, flags, NULL) != 0) {
BEGET_LOGE("Failed to bind mount \' %s \' to \' %s \', err = %d", source, target, errno);
return -1;
if (errno != ENOTDIR) { // mount errno is 'Not a directory' can ignore
return -1;
}
}
return 0;
......@@ -373,19 +421,16 @@ static bool IsValidSandbox(sandbox_t *sandbox)
return false;
}
if (sandbox->mounts == NULL) {
return false;
}
return true;
}
static int MountSandboxInfo(const mountlist_t *mounts, const char *rootPath)
static int MountSandboxInfo(const mountlist_t *mounts, const char *rootPath, SandboxTag tag)
{
if (mounts == NULL) {
return -1;
return 0;
}
if (mounts->info == NULL) {
return -1;
return 0;
}
while (mounts != NULL) {
mount_t *mount = mounts->info;
......@@ -395,7 +440,7 @@ static int MountSandboxInfo(const mountlist_t *mounts, const char *rootPath)
BEGET_LOGE("Failed snprintf_s err=%d", errno);
return -1;
}
int rc = BindMount(source, target, mount->flags);
int rc = BindMount(source, target, mount->flags, tag);
BEGET_ERROR_CHECK(rc == 0, return -1, "Failed bind mount %s to %s.", source, target);
mounts = mounts->next;
}
......@@ -405,10 +450,10 @@ static int MountSandboxInfo(const mountlist_t *mounts, const char *rootPath)
static int LinkSandboxInfo(const linklist_t *links, const char *rootPath)
{
if (links == NULL) {
return -1;
return 0;
}
if (links->info == NULL) {
return -1;
return 0;
}
while (links != NULL) {
linker_t *link = links->info;
......@@ -445,11 +490,16 @@ int PrepareSandbox(const char *name)
BEGET_ERROR_CHECK(CheckAndMakeDir(sandbox->rootPath, mode) == 0, return -1, "Failed root %s.", sandbox->rootPath);
int rc = mount(NULL, "/", NULL, MS_REC | MS_SLAVE, NULL);
BEGET_ERROR_CHECK(rc == 0, return -1, "Failed set mount slave err = %d", errno);
rc = BindMount(sandbox->rootPath, sandbox->rootPath, MS_BIND | MS_REC);
rc = BindMount(sandbox->rootPath, sandbox->rootPath, MS_BIND | MS_REC, SANDBOX_TAG_MOUNT_PATH);
BEGET_ERROR_CHECK(rc == 0, return -1, "Failed to mount rootpath bind err = %d", errno);
// 1) walk through all mounts and do bind mount
rc = MountSandboxInfo(sandbox->mounts, sandbox->rootPath);
rc = MountSandboxInfo(sandbox->pathMounts, sandbox->rootPath, SANDBOX_TAG_MOUNT_PATH);
if (rc < 0) {
return -1;
}
rc = MountSandboxInfo(sandbox->fileMounts, sandbox->rootPath, SANDBOX_TAG_MOUNT_FILE);
if (rc < 0) {
return -1;
}
......@@ -573,7 +623,8 @@ void DestroySandbox(const char *name)
sandbox->rootPath = NULL;
}
FreeLinks(sandbox->links);
FreeMounts(sandbox->mounts);
FreeMounts(sandbox->fileMounts);
FreeMounts(sandbox->pathMounts);
if (sandbox->ns > 0) {
(void)close(sandbox->ns);
}
......@@ -628,11 +679,18 @@ void DumpSandboxByName(const char *name)
BEGET_LOGI("Sandbox name: %s.", map->sandbox->name);
BEGET_LOGI("Sandbox rootPath: %s.", map->sandbox->rootPath);
BEGET_LOGI("Sandbox mounts info:");
mountlist_t *mounts = map->sandbox->mounts;
mountlist_t *mounts = map->sandbox->pathMounts;
while (mounts != NULL) {
mount_t *mount = mounts->info;
BEGET_LOGI("Sandbox path mounts list source: %s", mount->source);
BEGET_LOGI("Sandbox path mounts list target: %s", mount->target);
mounts = mounts->next;
}
mounts = map->sandbox->fileMounts;
while (mounts != NULL) {
mount_t *mount = mounts->info;
BEGET_LOGI("Sandbox mounts list source: %s", mount->source);
BEGET_LOGI("Sandbox mounts list target: %s", mount->target);
BEGET_LOGI("Sandbox file mounts list source: %s", mount->source);
BEGET_LOGI("Sandbox file mounts list target: %s", mount->target);
mounts = mounts->next;
}
BEGET_LOGI("Sandbox links info:");
......
......@@ -20,6 +20,9 @@
#include <string.h>
#include "init_param.h"
#ifdef LITEOS_SUPPORT
#include "hal_sys_param.h"
#endif
#include "parameter.h"
#include "sysparam_errno.h"
#ifdef USE_MBEDTLS
......@@ -28,6 +31,7 @@
#include "openssl/sha.h"
#endif
#include "securec.h"
#include "beget_ext.h"
static const char *g_emptyStr = "";
......@@ -46,6 +50,9 @@ 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 == PARAM_CODE_INVALID_NAME || ret == DAC_RESULT_FORBIDED || ret == PARAM_CODE_INVALID_PARAM) {
return EC_FAILURE;
}
if ((size > len) || (ret != 0)) {
return strcpy_s(value, len, def);
}
......@@ -55,9 +62,7 @@ INIT_LOCAL_API int GetParameter_(const char *key, const char *def, char *value,
INIT_LOCAL_API const char *GetProperty(const char *key, const char **paramHolder)
{
if (paramHolder == NULL) {
return NULL;
}
BEGET_CHECK(paramHolder != NULL, return NULL);
if (*paramHolder != NULL) {
return *paramHolder;
}
......@@ -65,9 +70,7 @@ INIT_LOCAL_API const char *GetProperty(const char *key, const char **paramHolder
int ret = SystemGetParameter(key, NULL, &len);
if (ret == 0 && len > 0) {
char *res = (char *)malloc(len + 1);
if (res == NULL) {
return g_emptyStr;
}
BEGET_CHECK(res != NULL, return g_emptyStr);
ret = SystemGetParameter(key, res, &len);
if (ret != 0) {
free(res);
......@@ -95,9 +98,7 @@ INIT_LOCAL_API int StringToLL(const char *str, long long int *out)
if (errno != 0) {
return -1;
}
if (s == end || *end != '\0') {
return -1;
}
BEGET_CHECK(!(s == end || *end != '\0'), return -1);
return 0;
}
......@@ -107,11 +108,7 @@ INIT_LOCAL_API int StringToULL(const char *str, unsigned long long int *out)
while (isspace(*s)) {
s++;
}
if (s[0] == '-') {
return -1;
}
BEGET_CHECK(s[0] != '-', return -1);
int base = (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) ? HEX : DECIMAL;
char* end = NULL;
errno = 0;
......@@ -119,12 +116,8 @@ INIT_LOCAL_API int StringToULL(const char *str, unsigned long long int *out)
if (errno != 0) {
return -1;
}
if (end == s) {
return -1;
}
if (*end != '\0') {
return -1;
}
BEGET_CHECK(end != s, return -1);
BEGET_CHECK(*end == '\0', return -1);
return 0;
}
......@@ -201,9 +194,7 @@ INIT_LOCAL_API const char *GetSerial_(void)
static char ohos_serial[PARAM_VALUE_LEN_MAX] = {0};
uint32_t len = PARAM_VALUE_LEN_MAX;
int ret = SystemGetParameter("ohos.boot.sn", ohos_serial, &len);
if (ret != 0) {
return NULL;
}
BEGET_CHECK(ret == 0, return NULL);
return ohos_serial;
#endif
}
......@@ -223,10 +214,8 @@ INIT_LOCAL_API int GetDevUdid_(char *udid, int size)
if (tmpSize <= 0 || tmpSize > DEV_BUF_MAX_LENGTH) {
return -1;
}
char *tmp = (char *)malloc(tmpSize);
if (tmp == NULL) {
return -1;
}
char *tmp = NULL;
BEGET_CHECK((tmp = (char *)malloc(tmpSize)) != NULL, return -1);
(void)memset_s(tmp, tmpSize, 0, tmpSize);
if ((strcat_s(tmp, tmpSize, manufacture) != 0) || (strcat_s(tmp, tmpSize, model) != 0) ||
......
......@@ -23,20 +23,17 @@
#include "sysparam_errno.h"
#include "securec.h"
#include "sysversion.h"
#include "beget_ext.h"
int WaitParameter(const char *key, const char *value, int timeout)
{
if ((key == NULL) || (value == NULL)) {
return EC_INVALID;
}
BEGET_CHECK(!(key == NULL || value == NULL), return EC_INVALID);
return SystemWaitParameter(key, value, timeout);
}
uint32_t FindParameter(const char *key)
{
if (key == NULL) {
return (uint32_t)(-1);
}
BEGET_CHECK(key != NULL, return (uint32_t)(-1));
uint32_t handle = 0;
int ret = SystemFindParameter(key, &handle);
if (ret != 0) {
......@@ -49,9 +46,7 @@ uint32_t GetParameterCommitId(uint32_t handle)
{
uint32_t commitId = 0;
int ret = SystemGetParameterCommitId(handle, &commitId);
if (ret != 0) {
return (uint32_t)(-1);
}
BEGET_CHECK(ret == 0, return (uint32_t)(-1));
return commitId;
}
......
......@@ -50,6 +50,9 @@ static void GetVersions(void)
return;
}
const char *fullName = GetFullName_();
if (fullName == NULL) {
return;
}
const char *tmp = strstr(fullName, "-");
if (tmp == NULL) {
return;
......
......@@ -50,29 +50,26 @@ if (ohos_kernel_type == "liteos_m") {
}
}
lite_component("inittoken") {
lite_component("token") {
features = []
if (enable_ohos_startup_init_feature_begetctl_liteos) {
if (ohos_kernel_type == "liteos_a" || ohos_kernel_type == "linux") {
features += [ ":token_shared" ]
}
if (ohos_kernel_type == "liteos_m") {
features += [ ":token_static" ]
}
if (ohos_kernel_type == "liteos_a" || ohos_kernel_type == "linux") {
features += [ ":token_shared" ]
}
if (ohos_kernel_type == "liteos_m") {
features += [ ":token_static" ]
}
}
ndk_lib("inittoken_notes") {
ndk_lib("token_notes") {
deps = []
head_files = []
if (enable_ohos_startup_init_feature_begetctl_liteos) {
if (ohos_kernel_type != "liteos_m") {
lib_extension = ".so"
}
if (ohos_kernel_type != "liteos_m") {
deps +=
[ "//base/startup/init_lite/interfaces/innerkits/token:token_shared" ]
}
head_files += [ "//base/startup/init_lite/interfaces/include/token" ]
if (ohos_kernel_type != "liteos_m") {
lib_extension = ".so"
}
if (ohos_kernel_type != "liteos_m") {
deps +=
[ "//base/startup/init_lite/interfaces/innerkits/token:token_shared" ]
}
head_files += [ "//base/startup/init_lite/interfaces/include/token" ]
}
# Copyright (c) 2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
group("kitsgroup") {
deps = [
"//base/startup/init_lite/interfaces/innerkits:libbeget_proxy",
"//base/startup/init_lite/interfaces/innerkits:libbegetutil",
]
deps += [ "syscap:deviceinfo_ndk" ]
if (support_jsapi) {
deps += [
"jskits:deviceinfo",
"jskits:systemparameter",
]
}
}
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Copyright (c) 2021-2022 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
......@@ -13,7 +13,7 @@
import("//build/ohos.gni")
ohos_shared_library("deviceinfo_init") {
ohos_shared_library("deviceinfo") {
include_dirs = [ "//base/startup/init_lite/interfaces/innerkits/include" ]
sources = [ "src/native_deviceinfo_js.cpp" ]
......@@ -28,11 +28,14 @@ ohos_shared_library("deviceinfo_init") {
]
relative_install_dir = "module"
subsystem_name = "startup"
part_name = "startup_l2"
part_name = "init"
}
ohos_shared_library("systemparameter_init") {
include_dirs = [ "src" ]
ohos_shared_library("systemparameter") {
include_dirs = [
"src",
"//third_party/libuv/include",
]
sources = [
"src/native_parameters_js.cpp",
......@@ -50,18 +53,5 @@ ohos_shared_library("systemparameter_init") {
]
relative_install_dir = "module"
subsystem_name = "startup"
part_name = "startup_l2"
}
group("syspara_js_init") {
deps = [
"//base/startup/init_lite/interfaces/innerkits:libbeget_proxy",
"//base/startup/init_lite/interfaces/innerkits:libbegetutil",
]
if (support_jsapi) {
deps += [
":deviceinfo_init",
":systemparameter_init",
]
}
part_name = "init"
}
......@@ -14,14 +14,12 @@
*/
#include "native_parameters_js.h"
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "StartupParametersJs" };
using namespace OHOS::HiviewDFX;
static constexpr int MAX_LENGTH = 128;
static constexpr int ARGC_NUMBER = 2;
static constexpr int ARGC_THREE_NUMBER = 3;
static constexpr int BUF_LENGTH = 256;
using StorageAsyncContext = struct {
using StorageAsyncContext = struct StorageAsyncContext {
napi_env env = nullptr;
napi_async_work work = nullptr;
......@@ -47,9 +45,7 @@ static void SetCallbackWork(napi_env env, StorageAsyncContextPtr asyncContext)
[](napi_env env, void *data) {
StorageAsyncContext *asyncContext = (StorageAsyncContext *)data;
asyncContext->status = SetParameter(asyncContext->key, asyncContext->value);
HiLog::Debug(LABEL,
"JSApp set::asyncContext-> status = %{public}d, asyncContext->key = %{public}s, asyncContext->value = "
"%{public}s.",
PARAM_JS_LOGV("JSApp set::asyncContext-> status = %d, asyncContext->key = %s, asyncContext->value = %s.",
asyncContext->status, asyncContext->key, asyncContext->value);
},
[](napi_env env, napi_status status, void *data) {
......@@ -154,7 +150,7 @@ static napi_value SetSync(napi_env env, napi_callback_info info)
std::string keyStr = keyBuf;
std::string valueStr = valueBuf;
int setResult = SetParameter(keyStr.c_str(), valueStr.c_str());
HiLog::Debug(LABEL, "JSApp SetSync::setResult = %{public}d, input keyBuf = %{public}s.", setResult, keyBuf);
PARAM_JS_LOGV("JSApp SetSync::setResult = %d, input keyBuf = %s.", setResult, keyBuf);
napi_value napiValue = nullptr;
if (setResult != 0) { // set failed
......@@ -202,7 +198,7 @@ static napi_value GetSync(napi_env env, napi_callback_info info)
valueStr = valueBuf;
}
int ret = OHOS::system::GetStringParameter(keyStr, getValue, valueStr);
HiLog::Debug(LABEL, "JSApp GetSync::getValue = %{public}s, input keyStr = %{public}s.", getValue.c_str(), keyBuf);
PARAM_JS_LOGV("JSApp GetSync::getValue = %s, input keyStr = %s.", getValue.c_str(), keyBuf);
napi_value napiValue = nullptr;
if (ret == 0) {
......@@ -222,9 +218,7 @@ static void GetCallbackWork(napi_env env, StorageAsyncContextPtr asyncContext)
StorageAsyncContext *asyncContext = (StorageAsyncContext *)data;
asyncContext->status =
OHOS::system::GetStringParameter(asyncContext->key, asyncContext->getValue, asyncContext->value);
HiLog::Debug(LABEL,
"JSApp get::asyncContext->status = %{public}d, asyncContext->getValue = %{public}s, asyncContext->key "
"= %{public}s, value = %{public}s.",
PARAM_JS_LOGV("JSApp get status = %d, asyncContext->getValue = %s, asyncContext->key = %s, value = %s.",
asyncContext->status, asyncContext->getValue.c_str(), asyncContext->key, asyncContext->value);
},
[](napi_env env, napi_status status, void *data) {
......
......@@ -26,15 +26,21 @@
#include <string>
#include <unistd.h>
#include "hilog/log.h"
#include "beget_ext.h"
#include "napi/native_api.h"
#include "napi/native_node_api.h"
#include "param_wrapper.h"
#include "parameter.h"
#define PARAM_JS_DOMAIN (BASE_DOMAIN + 0xc)
#define PARAM_JS_LOGI(fmt, ...) STARTUP_LOGI(PARAM_JS_DOMAIN, "PARAM_JS", fmt, ##__VA_ARGS__)
#define PARAM_JS_LOGE(fmt, ...) STARTUP_LOGE(PARAM_JS_DOMAIN, "PARAM_JS", fmt, ##__VA_ARGS__)
#define PARAM_JS_LOGV(fmt, ...) STARTUP_LOGV(PARAM_JS_DOMAIN, "PARAM_JS", fmt, ##__VA_ARGS__)
#define PARAM_JS_LOGW(fmt, ...) STARTUP_LOGW(PARAM_JS_DOMAIN, "PARAM_JS", fmt, ##__VA_ARGS__)
#define PARAM_JS_CHECK(retCode, exper, ...) \
if (!(retCode)) { \
HiLog::Error(LABEL, __VA_ARGS__); \
PARAM_JS_LOGE(__VA_ARGS__); \
exper; \
}
......
......@@ -16,15 +16,15 @@
#include <functional>
#include <vector>
#include "native_parameters_js.h"
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "StartupParametersJs" };
using namespace OHOS::HiviewDFX;
#include "uv.h"
using namespace OHOS::system;
static constexpr int ARGC_NUMBER = 2;
static constexpr int BUF_LENGTH = 128;
static napi_ref g_paramWatchRef;
using ParamAsyncContext = struct {
using ParamAsyncContext = struct ParamAsyncContext {
napi_env env = nullptr;
napi_async_work work = nullptr;
......@@ -40,7 +40,7 @@ using ParamAsyncContext = struct {
std::string getValue;
};
using ParamWatcher = struct {
using ParamWatcher = struct ParamWatcher {
napi_env env = nullptr;
napi_ref thisVarRef = nullptr;
char keyPrefix[BUF_LENGTH] = { 0 };
......@@ -52,12 +52,19 @@ using ParamWatcher = struct {
std::map<uint32_t, napi_ref> callbackReferences {};
};
using ParamWatcherWork = struct {
using ParamWatcherWork = struct ParamWatcherWork {
napi_async_work work = nullptr;
ParamWatcher *watcher = nullptr;
bool startWatch = false;
};
using ParamChangeValue = struct ParamChangeValue {
uv_work_t work;
ParamWatcher *watcher;
std::string key;
std::string value;
};
using ParamAsyncContextPtr = ParamAsyncContext *;
using ParamWatcherPtr = ParamWatcher *;
......@@ -98,8 +105,7 @@ static void WaitCallbackWork(napi_env env, ParamAsyncContextPtr asyncContext)
[](napi_env env, void *data) {
ParamAsyncContext *asyncContext = (ParamAsyncContext *)data;
asyncContext->status = WaitParameter(asyncContext->key, asyncContext->value, asyncContext->timeout);
HiLog::Debug(LABEL, "JSApp Wait status: %{public}d, key: %{public}s",
asyncContext->status, asyncContext->key);
PARAM_JS_LOGV("JSApp Wait status: %d, key: %s", asyncContext->status, asyncContext->key);
},
[](napi_env env, napi_status status, void *data) {
ParamAsyncContext *asyncContext = (ParamAsyncContext *)data;
......@@ -110,8 +116,7 @@ static void WaitCallbackWork(napi_env env, ParamAsyncContextPtr asyncContext)
napi_set_named_property(env, result[0], "code", message);
napi_get_undefined(env, &result[1]); // only one param
HiLog::Debug(LABEL, "JSApp Wait status: %{public}d, key: %{public}s ",
asyncContext->status, asyncContext->key);
PARAM_JS_LOGV("JSApp Wait status: %d, key: %s ", asyncContext->status, asyncContext->key);
if (asyncContext->deferred) {
if (asyncContext->status == 0) {
napi_resolve_deferred(env, asyncContext->deferred, result[1]);
......@@ -170,7 +175,7 @@ napi_value ParamWait(napi_env env, napi_callback_info info)
return GetNapiValue(env, ret), "Invalid param for wait callbackRef");
napi_create_reference(env, argv[ARGC_THREE_NUMBER], 1, &asyncContext->callbackRef);
}
HiLog::Debug(LABEL, "JSApp Wait key: %{public}s, value: %{public}s timeout %{public}d.",
PARAM_JS_LOGV("JSApp Wait key: %s, value: %s timeout %d.",
asyncContext->key, asyncContext->value, asyncContext->timeout);
napi_value result = nullptr;
......@@ -221,13 +226,13 @@ static void AddWatcherCallback(ParamWatcherPtr watcher, napi_ref callbackRef)
std::lock_guard<std::mutex> lock(watcher->mutex);
watcherId++;
watcher->callbackReferences[watcherId] = callbackRef;
HiLog::Debug(LABEL, "JSApp watcher add watcher callback %{public}s %{public}u.",
PARAM_JS_LOGV("JSApp watcher add watcher callback %s %u.",
watcher->keyPrefix, watcherId);
}
static void DelWatcherCallback(ParamWatcherPtr watcher, uint32_t next)
{
HiLog::Debug(LABEL, "JSApp watcher key %{public}s delete callack %{public}u", watcher->keyPrefix, next);
PARAM_JS_LOGV("JSApp watcher key %s delete callack %u", watcher->keyPrefix, next);
std::lock_guard<std::mutex> lock(watcher->mutex);
watcher->callbackReferences.erase(next);
}
......@@ -236,7 +241,7 @@ static void DelCallbackRef(napi_env env, ParamWatcherPtr watcher, napi_ref callb
{
std::lock_guard<std::mutex> lock(watcher->mutex);
if (callbackRef == watcher->currCallbackRef) {
HiLog::Debug(LABEL, "JSApp watcher key %{public}s has been callbacked %{public}u.",
PARAM_JS_LOGV("JSApp watcher key %s has been callbacked %u.",
watcher->keyPrefix, id);
watcher->currCallbackRef = nullptr;
} else {
......@@ -253,8 +258,7 @@ static void DelCallback(napi_env env, napi_value callback, ParamWatcherPtr watch
while (ret) {
napi_ref callbackRef = GetWatcherReference(watcher, next);
if (callbackRef == nullptr) {
HiLog::Debug(LABEL, "JSApp watcher key %{public}s callbackRef has been deleted %{public}d.",
watcher->keyPrefix, next);
PARAM_JS_LOGV("JSApp watcher key %s callbackRef has been deleted %d.", watcher->keyPrefix, next);
DelWatcherCallback(watcher, next);
} else if (callback != nullptr) {
napi_value handler = nullptr;
......@@ -341,9 +345,9 @@ napi_value GetWatcher(napi_env env, napi_callback_info info)
watcher->keyLen = BUF_LENGTH;
int ret = GetParamValue(env, argv[0], napi_string, watcher->keyPrefix, watcher->keyLen);
PARAM_JS_CHECK(ret == 0, return NapiGetNull(env), "Failed to get key prefix");
HiLog::Debug(LABEL, "JSApp watcher keyPrefix = %{public}s ", watcher->keyPrefix);
PARAM_JS_LOGV("JSApp watcher keyPrefix = %s ", watcher->keyPrefix);
ret = WatchParameter(watcher->keyPrefix, nullptr, watcher);
PARAM_JS_CHECK(ret == 0, return NapiGetNull(env), "Failed to get watcher ret %{public}d", ret);
PARAM_JS_CHECK(ret == 0, return NapiGetNull(env), "Failed to get watcher ret %d", ret);
}
return obj;
}
......@@ -380,11 +384,11 @@ static void NotifyValueChange(ParamWatcherPtr watcher, uint32_t id, napi_value t
{
napi_ref callbackRef = GetWatcherReference(watcher, id);
PARAM_JS_CHECK(callbackRef != nullptr, return,
"Failed to get callback for %{public}s %{public}d", watcher->keyPrefix, id);
"Failed to get callback for %s %d", watcher->keyPrefix, id);
napi_value callbackFunc = nullptr;
napi_status status = napi_get_reference_value(watcher->env, callbackRef, &callbackFunc);
PARAM_JS_CHECK(status == 0 && callbackFunc != nullptr, return,
"Failed to get callback for %{public}s %{public}d", watcher->keyPrefix, id);
"Failed to get callback for %s %d", watcher->keyPrefix, id);
{
std::lock_guard<std::mutex> lock(watcher->mutex);
watcher->currCallbackRef = callbackRef;
......@@ -396,7 +400,7 @@ static void NotifyValueChange(ParamWatcherPtr watcher, uint32_t id, napi_value t
{
std::lock_guard<std::mutex> lock(watcher->mutex);
if (watcher->currCallbackRef == nullptr) {
HiLog::Debug(LABEL, "JSApp watcher notify key %{public}s callback deleted watcherId %{public}u",
PARAM_JS_LOGV("JSApp watcher notify key %s callback deleted watcherId %u",
watcher->keyPrefix, id);
napi_delete_reference(watcher->env, callbackRef);
}
......@@ -404,12 +408,8 @@ static void NotifyValueChange(ParamWatcherPtr watcher, uint32_t id, napi_value t
}
}
static void ProcessParamChange(const char *key, const char *value, void *context)
static void HandleParameterChange(ParamWatcherPtr watcher, const char *key, const char *value)
{
ParamWatcherPtr watcher = static_cast<ParamWatcherPtr>(context);
PARAM_JS_CHECK(watcher != nullptr && watcher->env != nullptr, return, "Invalid param");
PARAM_JS_CHECK(watcher->callbackReferences.size() > 0, return, "No callback for watcher");
napi_handle_scope scope = nullptr;
napi_status status = napi_open_handle_scope(watcher->env, &scope);
PARAM_JS_CHECK(status == 0, return, "Failed to get reference ");
......@@ -427,12 +427,37 @@ static void ProcessParamChange(const char *key, const char *value, void *context
ret = GetNextRefence(watcher, next);
}
napi_close_handle_scope(watcher->env, scope);
HiLog::Debug(LABEL, "JSApp watcher ProcessParamChange %{public}s finish", key);
PARAM_JS_LOGV("JSApp watcher ProcessParamChange %s finish", key);
}
static void ProcessParamChange(const char *key, const char *value, void *context)
{
ParamWatcherPtr watcher = static_cast<ParamWatcherPtr>(context);
PARAM_JS_CHECK(watcher != nullptr && watcher->env != nullptr, return, "Invalid param");
PARAM_JS_CHECK(watcher->callbackReferences.size() > 0, return, "No callback for watcher");
uv_loop_s *loop = nullptr;
napi_get_uv_event_loop(watcher->env, &loop);
PARAM_JS_CHECK(loop != nullptr, return, "Failed to get loop for %s", watcher->keyPrefix);
ParamChangeValue *change = new (std::nothrow) ParamChangeValue;
PARAM_JS_CHECK(change != nullptr, return, "Failed to get change for %s", watcher->keyPrefix);
change->work.data = reinterpret_cast<void *>(change);
change->watcher = watcher;
change->key = std::string(key);
change->value = std::string(value);
int ret = uv_queue_work(loop, &change->work, [] (uv_work_t *work) {}, [] (uv_work_t *work, int result) {
ParamChangeValue *change = reinterpret_cast<ParamChangeValue *>(work->data);
HandleParameterChange(change->watcher, change->key.c_str(), change->value.c_str());
delete change;
change = nullptr;
});
PARAM_JS_CHECK(ret == 0, delete change;
return, "Failed to start work for %s", watcher->keyPrefix);
}
static void WatchCallbackWork(napi_env env, ParamWatcherPtr watcher)
{
HiLog::Debug(LABEL, "JSApp WatchCallbackWork key: %{public}s", watcher->keyPrefix);
PARAM_JS_LOGV("JSApp WatchCallbackWork key: %s", watcher->keyPrefix);
ParamWatcherWork *worker = new ParamWatcherWork();
PARAM_JS_CHECK(worker != nullptr, return, "Failed to create worker ");
worker->watcher = watcher;
......@@ -447,12 +472,12 @@ static void WatchCallbackWork(napi_env env, ParamWatcherPtr watcher)
PARAM_JS_CHECK(worker != nullptr && worker->watcher != nullptr, return, "Invalid worker ");
int status = WatchParameter(worker->watcher->keyPrefix,
worker->startWatch ? ProcessParamChange : nullptr, worker->watcher);
HiLog::Debug(LABEL, "JSApp WatchCallbackWork %{public}s status: %{public}d, key: %{public}s",
PARAM_JS_LOGV("JSApp WatchCallbackWork %s status: %d, key: %s",
worker->startWatch ? "on" : "off", status, worker->watcher->keyPrefix);
},
[](napi_env env, napi_status status, void *data) {
ParamWatcherWork *worker = (ParamWatcherWork *)data;
HiLog::Debug(LABEL, "JSApp WatchCallbackWork delete %{public}s key: %{public}s",
PARAM_JS_LOGV("JSApp WatchCallbackWork delete %s key: %s",
worker->startWatch ? "on" : "off", worker->watcher->keyPrefix);
napi_delete_async_work(env, worker->work);
delete worker;
......@@ -468,10 +493,10 @@ static napi_value SwithWatchOn(napi_env env, napi_callback_info info)
PARAM_JS_CHECK(watcher != nullptr, return GetNapiValue(env, -1), "Failed to get watcher swith param");
if (CheckCallbackEqual(env, callback, watcher)) {
HiLog::Warn(LABEL, "JSApp watcher repeater switch on %{public}s", watcher->keyPrefix);
PARAM_JS_LOGE("JSApp watcher repeater switch on %s", watcher->keyPrefix);
return 0;
}
HiLog::Debug(LABEL, "JSApp watcher on %{public}s", watcher->keyPrefix);
PARAM_JS_LOGV("JSApp watcher on %s", watcher->keyPrefix);
// save callback
napi_ref callbackRef;
napi_create_reference(env, callback, 1, &callbackRef);
......@@ -485,9 +510,9 @@ static napi_value SwithWatchOn(napi_env env, napi_callback_info info)
watcher->startWatch = true;
}
HiLog::Debug(LABEL, "JSApp watcher add %{public}s", watcher->keyPrefix);
PARAM_JS_LOGV("JSApp watcher add %s", watcher->keyPrefix);
WatchCallbackWork(env, watcher);
HiLog::Debug(LABEL, "JSApp watcher on %{public}s finish", watcher->keyPrefix);
PARAM_JS_LOGV("JSApp watcher on %s finish", watcher->keyPrefix);
return GetNapiValue(env, 0);
}
......@@ -496,7 +521,7 @@ static napi_value SwithWatchOff(napi_env env, napi_callback_info info)
napi_value callback = nullptr;
ParamWatcherPtr watcher = GetWatcherInfo(env, info, &callback);
PARAM_JS_CHECK(watcher != nullptr, return GetNapiValue(env, -1), "Failed to get watcher");
HiLog::Debug(LABEL, "JSApp watcher off %{public}s", watcher->keyPrefix);
PARAM_JS_LOGV("JSApp watcher off %s", watcher->keyPrefix);
DelCallback(env, callback, watcher);
{
std::lock_guard<std::mutex> lock(watcher->mutex);
......
......@@ -115,6 +115,32 @@ if (defined(ohos_lite)) {
import("//build/ohos.gni")
import("//build/ohos/native_stub/native_stub.gni")
ohos_executable("init_early") {
sources = [
"init/standard/device.c",
"init/standard/init_mount.c",
"init/standard/main_early.c",
"init/standard/switch_root.c",
]
include_dirs = [
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/init/include",
]
deps = [
"//base/startup/init_lite/interfaces/innerkits:libfsmanager_static",
"//base/startup/init_lite/services/log:init_log",
"//base/startup/init_lite/ueventd:libueventd_ramdisk_static",
"//third_party/bounds_checking_function:libsec_static",
"//third_party/cJSON:cjson_static",
]
install_images = [
"updater",
"ramdisk",
]
install_enable = true
part_name = "init"
}
ohos_executable("init") {
sources = [
"//base/startup/init_lite/interfaces/innerkits/fd_holder/fd_holder_internal.c",
......@@ -126,17 +152,14 @@ if (defined(ohos_lite)) {
"init/standard/init_cmds.c",
"init/standard/init_control_fd_service.c",
"init/standard/init_jobs.c",
"init/standard/init_mount.c",
"init/standard/init_reboot.c",
"init/standard/init_service.c",
"init/standard/init_signal_handler.c",
"init/standard/switch_root.c",
]
modulemgr_sources = [
"//base/startup/init_lite/interfaces/innerkits/hookmgr/hookmgr.c",
"//base/startup/init_lite/interfaces/innerkits/modulemgr/modulemgr.c",
"init/module_engine/init_modulemgr.c",
]
sources += modulemgr_sources
......@@ -150,13 +173,12 @@ if (defined(ohos_lite)) {
"//base/startup/init_lite/services/include/param",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/services/init/include",
"//base/startup/init_lite/services/init/module_engine/include",
"//base/startup/init_lite/interfaces/innerkits/init_module_engine/include",
"//base/startup/init_lite/services/log",
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/services/loopevent/include",
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/interfaces/innerkits/fd_holder",
"//base/startup/init_lite/ueventd/include",
"//third_party/cJSON",
"//third_party/bounds_checking_function/include",
"//base/startup/init_lite/interfaces/innerkits/control_fd",
......@@ -173,12 +195,12 @@ if (defined(ohos_lite)) {
"//base/startup/init_lite/services/param:param_init",
"//base/startup/init_lite/services/utils:libinit_tools",
"//base/startup/init_lite/services/utils:libinit_utils",
"//base/startup/init_lite/ueventd:libueventd_ramdisk_static",
"//third_party/bounds_checking_function:libsec_static",
"//third_party/cJSON:cjson_static",
]
deps += [ "//base/startup/init_lite/services/init/module_engine:libinit_stub_versionscript" ]
deps += [ "//base/startup/init_lite/interfaces/innerkits/init_module_engine:libinit_stub_versionscript" ]
deps += [ "//base/startup/init_lite/interfaces/innerkits/init_module_engine:init_module_engine_sources" ]
deps += [ "//base/startup/init_lite/services/modules:static_modules" ]
......@@ -227,15 +249,14 @@ if (defined(ohos_lite)) {
defines += [ "PRODUCT_RK" ]
}
version_script = get_label_info(
"//base/startup/init_lite/services/init/module_engine:libinit_stub_versionscript",
"//base/startup/init_lite/interfaces/innerkits/init_module_engine:libinit_stub_versionscript",
"target_gen_dir") + "/" + get_label_info(
"//base/startup/init_lite/services/init/module_engine:libinit_stub_versionscript",
"//base/startup/init_lite/interfaces/innerkits/init_module_engine:libinit_stub_versionscript",
"name") + stub_version_script_suffix
defines += [ "_GNU_SOURCE" ]
install_images = [
"system",
"updater",
"ramdisk",
]
install_enable = true
part_name = "init"
......@@ -244,6 +265,7 @@ if (defined(ohos_lite)) {
group("startup_init") {
deps = [
":init",
":init_early",
"etc:etc_files",
"//base/startup/init_lite/services/param:param_client",
"//base/startup/init_lite/services/param:param_init",
......
......@@ -61,6 +61,7 @@ if (defined(ohos_lite)) {
ohos_executable("begetctl") {
sources = [
"bootchart_cmd.c",
"dump_service.c",
"init_cmd_reboot.c",
"main.c",
"misc_daemon.cpp",
......@@ -129,6 +130,7 @@ if (defined(ohos_lite)) {
"stop_service",
"service",
"sandbox",
"dump_service",
]
install_images = [ "system" ]
......
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "begetctl.h"
#include "control_fd.h"
#include "init_utils.h"
#define DUMP_SERVICE_INFO_CMD_ARGS 2
static int main_cmd(BShellHandle shell, int argc, char **argv)
{
if (argc != DUMP_SERVICE_INFO_CMD_ARGS) {
BShellCmdHelp(shell, argc, argv);
return 0;
}
if (strcmp(argv[0], "dump_service") == 0) {
printf("dump service info \n");
CmdClientInit(INIT_CONTROL_FD_SOCKET_PATH, ACTION_DUMP, argv[1], "FIFO");
} else {
BShellCmdHelp(shell, argc, argv);
}
return 0;
}
MODULE_CONSTRUCTOR(void)
{
CmdInfo infos[] = {
{"dump_service", main_cmd, "dump one service info by serviceName", "dump_service serviceName", NULL},
{"dump_service", main_cmd, "dump all services info", "dump_service all", NULL},
};
for (size_t i = 0; i < sizeof(infos) / sizeof(infos[0]); i++) {
BShellEnvRegitsterCmd(GetShellHandle(), &infos[i]);
}
}
......@@ -74,7 +74,7 @@ int main(int argc, char *argv[])
printf("Failed to get shell handle \n");
return 0;
}
SetInitLogLevel(0);
BShellParamCmdRegister(handle, 0);
#ifdef INIT_TEST
BShellCmdRegister(handle, 0);
......
......@@ -28,6 +28,7 @@
#include "param_utils.h"
#include "shell_utils.h"
#include "init_param.h"
#include "beget_ext.h"
#ifdef PARAM_SUPPORT_SELINUX
#include <policycoreutils.h>
#include <selinux/selinux.h>
......@@ -47,9 +48,7 @@ void demoExit(void)
kill(g_shellPid, SIGKILL);
#endif
}
if (g_isSetTerminal != 0) {
tcsetattr(0, TCSAFLUSH, &g_terminalState);
}
BEGET_CHECK(g_isSetTerminal == 0, tcsetattr(0, TCSAFLUSH, &g_terminalState));
}
#define CMD_PATH "/system/bin/paramshell"
......@@ -60,9 +59,7 @@ void demoExit(void)
static char *GetLocalBuffer(uint32_t *buffSize)
{
static char buffer[PARAM_NAME_LEN_MAX + PARAM_CONST_VALUE_LEN_MAX] = {0};
if (buffSize != NULL) {
*buffSize = sizeof(buffer);
}
BEGET_CHECK(buffSize == NULL, *buffSize = sizeof(buffer));
return buffer;
}
......@@ -138,9 +135,7 @@ int SetParamShellPrompt(BShellHandle shell, const char *param)
static char *GetPermissionString(uint32_t mode, int shift, char *str, int size)
{
if (size < MASK_LENGTH_MAX) {
return str;
}
BEGET_CHECK(!(size < MASK_LENGTH_MAX), return str);
str[0] = '-';
str[1] = '-';
str[2] = '-'; // 2 watcher
......@@ -161,10 +156,7 @@ static void ShowParam(BShellHandle shell, const char *name, const char *value)
{
ParamAuditData auditData = {};
int ret = GetParamSecurityAuditData(name, 0, &auditData);
if (ret != 0) {
BSH_LOGE("Failed to get param security for %s", name);
return;
}
BSH_CHECK(ret == 0, return, "Failed to get param security for %s", name);
BShellEnvOutput(shell, "Parameter infomation:\r\n");
#ifdef PARAM_SUPPORT_SELINUX
BShellEnvOutput(shell, "selinux : %s \r\n", auditData.label);
......@@ -258,9 +250,7 @@ static int32_t BShellParamCmdCat(BShellHandle shell, int32_t argc, char *argv[])
char *realParameter = GetRealParameter(shell, argv[1], buffer, buffSize);
BSH_CHECK(realParameter != NULL, return BSH_INVALID_PARAM, "Invalid shell env");
int ret = SystemGetParameter(realParameter, buffer, &buffSize);
if (ret == 0) {
BShellEnvOutput(shell, " %s\r\n", buffer);
}
BSH_CHECK(ret != 0, BShellEnvOutput(shell, " %s\r\n", buffer));
return 0;
}
......@@ -276,9 +266,7 @@ static void ShowParamForCmdGet(ParamHandle handle, void *cookie)
{
uint32_t buffSize = 0;
char *buffer = GetLocalBuffer(&buffSize);
if (buffSize < (PARAM_NAME_LEN_MAX + PARAM_CONST_VALUE_LEN_MAX)) {
return;
}
BSH_CHECK(!(buffSize < (PARAM_NAME_LEN_MAX + PARAM_CONST_VALUE_LEN_MAX)), return);
char *value = buffer + PARAM_NAME_LEN_MAX;
(void)SystemGetParameterName(handle, buffer, PARAM_NAME_LEN_MAX);
uint32_t valueLen = buffSize - PARAM_NAME_LEN_MAX;
......
......@@ -73,7 +73,6 @@ int main(int argc, char *args[])
tio.c_cc[VMIN] = 1;
tcsetattr(0, TCSAFLUSH, &tio);
SetInitLogLevel(0);
BSH_LOGV("BShellEnvStart %d", argc);
do {
BShellHandle handle = GetShellHandle();
......
......@@ -119,6 +119,10 @@ if (defined(ohos_lite)) {
ohos_prebuilt_para("ohos.para") {
source = "//base/startup/init_lite/services/etc/param/ohos.para"
install_images = [
"system",
"updater",
]
part_name = "init"
if (target_cpu == "arm64") {
extra_paras = [ "const.product.cpu.abilist=arm64-v8a" ]
......@@ -128,6 +132,10 @@ if (defined(ohos_lite)) {
ohos_prebuilt_para("ohos.para.dac") {
source = "//base/startup/init_lite/services/etc/param/ohos.para.dac"
install_images = [
"system",
"updater",
]
part_name = "init"
module_install_dir = "etc/param"
}
......
......@@ -11,10 +11,9 @@
"services": [
"ueventd",
"console",
"watchdog_service",
"hdf_devmgr",
"samgr",
"param_watcher"
"hdcd",
"charger",
"misc"
],
"groups": [
]
......
{
"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",
"watchdog_service",
"hdf_devmgr",
"samgr",
"param_watcher"
],
"groups": [
]
}
\ No newline at end of file
......@@ -4,7 +4,6 @@ system:x:1000:
radio:x:1001:
bluetooth:x:1002:
graphics:x:1003:
samgr:x:1005:
file_manager:x:1006:
log:x:1007:
user_data_rw:x:1008:
......@@ -17,6 +16,7 @@ keystore:x:1017:
usb:x:1018:
drm:x:1019:
gps:x:1020:
location_host:x:1021:
media_rw:x:1023:
dsoftbus:x:1024:
nfc:x:1027:
......@@ -76,6 +76,7 @@ installs:x:3060:
deviceauth:x:3333:
huks_server:x:3510:
dms:x:5522:
samgr:x:5555:
update:x:6666:
charger:x:6667:
battery_stats:x:6668:
......@@ -101,4 +102,5 @@ watchdog:x:1100:
paramwatcher:x:1101:
deviceinfo:x:1102:
accessibility:x:1103:
memmgr:x:1111:
motion_dal_host:x:3065:
memmgr:x:1111:
\ No newline at end of file
......@@ -198,6 +198,9 @@
}, {
"name" : "boot",
"cmds" : [
"write /sys/block/zram0/disksize 1024M",
"mkswap /dev/block/zram0",
"swapon /dev/block/zram0",
"write /proc/sys/net/core/xfrm_acq_expires 3600",
"write /proc/sys/vm/overcommit_memory 1",
"write /proc/sys/vm/min_free_order_shift 4",
......
......@@ -46,7 +46,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.3.1
const.product.software.version=OpenHarmony 3.2.3.2
const.product.incremental.version=default
const.product.firstapiversion=1
const.product.build.type=default
......
......@@ -4,7 +4,6 @@ system:x:1000:1000:::/bin/false
radio:x:1001:1001:::/bin/false
bluetooth:x:1002:1002:::/bin/false
graphics:x:1003:1003:::/bin/false
samgr:x:1005:1005:::/bin/false
file_manager:x:1006:1006:::/bin/false
log:x:1007:1007:::/bin/false
user_data_rw:x:1008:1008:::/bin/false
......@@ -17,6 +16,7 @@ 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
media_rw:x:1023:1023:::/bin/false
dsoftbus:x:1024:1024:::/bin/false
nfc:x:1027:1027:::/bin/false
......@@ -75,6 +75,7 @@ installs:x:3060:3060:::/bin/false
deviceauth:x:3333:3333:::/bin/false
huks_server:x:3510:3510:::/bin/false
dms:x:5522:5522:::/bin/false
samgr:x:5555:5555:::/bin/false
dbms:x:6000:6000:::/bin/false
update:x:6666:6666:::/bin/false
charger:x:6667:6667:::/bin/false
......@@ -101,4 +102,5 @@ watchdog:x:1100:1100:::/bin/false
paramwatcher:x:1101:1101:::/bin/false
deviceinfo:x:1102:1102:::/bin/false
accessibility:x:1103:1103:::/bin/false
motion_dal_host:x:3065:3065:::/bin/false
memmgr:x:1111:1111:::/bin/false
......@@ -52,6 +52,7 @@ typedef struct {
typedef void *HashMapHandle;
int HashMapIsEmpty(HashMapHandle handle);
int32_t HashMapCreate(HashMapHandle *handle, const HashInfo *info);
void HashMapDestory(HashMapHandle handle);
int32_t HashMapAdd(HashMapHandle handle, HashNode *hashNode);
......
......@@ -60,13 +60,13 @@ char *GetRealPath(const char *source);
int StringToInt(const char *str, int defaultValue);
int MakeDirRecursive(const char *dir, mode_t mode);
void CheckAndCreateDir(const char *fileName);
int CheckAndCreatFile(const char *file, mode_t mode);
int MakeDir(const char *dir, mode_t mode);
int ReadFileInDir(const char *dirPath, const char *includeExt,
int (*processFile)(const char *fileName, void *context), void *context);
char **SplitStringExt(char *buffer, const char *del, int *returnCount, int maxItemCount);
void FreeStringVector(char **vector, int count);
int InUpdaterMode(void);
int InChargerMode(void);
int StringReplaceChr(char *strl, char oldChr, char newChr);
int GetMapValue(const char *name, const InitArgInfo *infos, int argNum, int defValue);
......
......@@ -50,6 +50,8 @@ typedef enum {
PARAM_CODE_READ_ONLY,
PARAM_CODE_FAIL_CONNECT,
PARAM_CODE_NODE_EXIST, // 9
DAC_RESULT_INVALID_PARAM = 1000,
DAC_RESULT_FORBIDED,
PARAM_CODE_MAX
} PARAM_CODE;
......
../module_engine/include/init_cmdexecutor.h
\ No newline at end of file
../../../interfaces/innerkits/init_module_engine/include/init_cmdexecutor.h
\ No newline at end of file
......@@ -63,11 +63,8 @@ void ReleaseService(Service *service);
void StartAllServices(int startMode);
void LoadAccessTokenId(void);
Service *AddService(const char *name);
#ifdef OHOS_SERVICE_DUMP
void DumpAllServices();
void DumpAllServices(void);
void DumpOneService(const Service *service);
#endif
#ifdef __cplusplus
#if __cplusplus
}
......
......@@ -105,18 +105,14 @@ static int SetPerms(const Service *service)
capData[CAP_TO_INDEX(service->servPerm.caps[i])].inheritable |= CAP_TO_MASK(service->servPerm.caps[i]);
}
if (capset(&capHeader, capData) != 0) {
INIT_LOGE("capset faild for service: %s, error: %d", service->name, errno);
return SERVICE_FAILURE;
}
INIT_ERROR_CHECK(capset(&capHeader, capData) == 0, return SERVICE_FAILURE,
"capset faild for service: %s, error: %d", service->name, errno);
for (unsigned int i = 0; i < service->servPerm.capsCnt; ++i) {
if (service->servPerm.caps[i] == FULL_CAP) {
return SetAllAmbientCapability();
}
if (SetAmbientCapability(service->servPerm.caps[i]) != 0) {
INIT_LOGE("SetAmbientCapability faild for service: %s", service->name);
return SERVICE_FAILURE;
}
INIT_ERROR_CHECK(SetAmbientCapability(service->servPerm.caps[i]) == 0, return SERVICE_FAILURE,
"SetAmbientCapability faild for service: %s", service->name);
}
return SERVICE_SUCCESS;
}
......@@ -183,10 +179,8 @@ void SetSecon(Service *service)
INIT_LOGI("service %s secon set to %s.", service->name, service->secon);
}
} else {
if (setexeccon("u:r:limit_domain:s0") < 0) {
INIT_LOGE("failed to set service %s's secon (%s).", service->name, "u:r:limit_domain:s0");
_exit(PROCESS_EXIT_CODE);
}
INIT_ERROR_CHECK(!(setexeccon("u:r:limit_domain:s0") < 0), _exit(PROCESS_EXIT_CODE),
"failed to set service %s's secon (%s).", service->name, "u:r:limit_domain:s0");
INIT_LOGE("Please set secon field in service %s's cfg file, limit_domain will be blocked", service->name);
}
#endif // WITH_SELINUX
......@@ -228,22 +222,16 @@ static void PublishHoldFds(Service *service)
INIT_LOGE("Duplicate file descriptors of Service \' %s \' failed. err = %d", service->name, errno);
continue;
}
if (snprintf_s((char *)fdBuffer + pos, sizeof(fdBuffer) - pos, sizeof(fdBuffer) - 1, "%d ", fd) < 0) {
INIT_LOGE("snprintf_s failed err=%d", errno);
return;
}
INIT_ERROR_CHECK(!(snprintf_s((char *)fdBuffer + pos, sizeof(fdBuffer) - pos, sizeof(fdBuffer) - 1,
"%d ", fd) < 0), return, "snprintf_s failed err=%d", errno);
pos = strlen(fdBuffer);
}
fdBuffer[pos - 1] = '\0'; // Remove last ' '
INIT_LOGI("fd buffer: [%s]", fdBuffer);
char envName[MAX_BUFFER_LEN] = {};
if (snprintf_s(envName, MAX_BUFFER_LEN, MAX_BUFFER_LEN - 1, ENV_FD_HOLD_PREFIX"%s", service->name) < 0) {
INIT_LOGE("snprintf_s failed err=%d", errno);
return;
}
if (setenv(envName, fdBuffer, 1) < 0) {
INIT_LOGE("Failed to set env %s", envName);
}
INIT_ERROR_CHECK(!(snprintf_s(envName, MAX_BUFFER_LEN, MAX_BUFFER_LEN - 1, ENV_FD_HOLD_PREFIX"%s",
service->name) < 0), return, "snprintf_s failed err=%d", errno);
INIT_CHECK_ONLY_ELOG(!(setenv(envName, fdBuffer, 1) < 0), "Failed to set env %s", envName);
INIT_LOGI("File descriptors of Service \' %s \' published", service->name);
}
}
......@@ -258,10 +246,8 @@ static int BindCpuCore(Service *service)
}
#ifndef __LITEOS_A__
int pid = getpid();
if (sched_setaffinity(pid, sizeof(service->cpuSet), &service->cpuSet) != 0) {
INIT_LOGE("%s set affinity between process(pid=%d) with CPU's core failed", service->name, pid);
return SERVICE_FAILURE;
}
INIT_ERROR_CHECK(sched_setaffinity(pid, sizeof(service->cpuSet), &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
return SERVICE_SUCCESS;
......@@ -629,9 +615,7 @@ void ServiceStartTimer(Service *service, uint64_t timeout)
return;
}
status = LE_StartTimer(LE_GetDefaultLoop(), service->timer, timeout, 1);
if (status != LE_SUCCESS) {
INIT_LOGE("Start service timer for service \' %s \' failed, status = %d", service->name, status);
return;
}
INIT_ERROR_CHECK(status == LE_SUCCESS, return,
"Start service timer for service \' %s \' failed, status = %d", service->name, status);
EnableServiceTimer(service);
}
......@@ -299,24 +299,18 @@ int CheckNodeValid(int type, const char *name)
if (type >= NODE_TYPE_GROUPS) {
return -1;
}
#ifndef INIT_TEST
if (g_initWorkspace.groupMode == GROUP_BOOT) {
return 0;
}
HashNode *node = HashMapGet(g_initWorkspace.hashMap[type], name);
if (node != NULL) {
return 0;
}
#else
HashNode *node = HashMapGet(g_initWorkspace.hashMap[type], name);
if (node != NULL) {
INIT_LOGI("Found %s in %s group", name, type == NODE_TYPE_JOBS ? "job" : "service");
return 0;
}
if (g_initWorkspace.groupMode == GROUP_BOOT) {
// for boot start, can not start charger service
if (strcmp(name, "charger") == 0) {
return -1;
}
return 0;
}
#endif
return -1;
}
......
......@@ -43,43 +43,42 @@ static const int CRITICAL_DEFAULT_CRASH_TIME = 20;
static const int CRITICAL_DEFAULT_CRASH_COUNT = 4;
static const int CRITICAL_CONFIG_ARRAY_LEN = 3;
#ifdef OHOS_SERVICE_DUMP
static void DumpServiceArgs(const char *info, const ServiceArgs *args)
{
printf("\tservice %s count %d", info, args->count);
printf("\tservice %s count %d \n", info, args->count);
for (int j = 0; j < args->count; j++) {
if (args->argv[j] != NULL) {
printf("\t\tinfo [%d] %s", j, args->argv[j]);
printf("\t\tinfo [%d] %s \n", j, args->argv[j]);
}
}
}
static void DumpServiceJobs(const Service *service)
{
printf("\tservice job info");
printf("\tservice job info \n");
if (service->serviceJobs.jobsName[JOB_ON_BOOT] != NULL) {
printf("\t\tservice boot job %s", service->serviceJobs.jobsName[JOB_ON_BOOT]);
printf("\t\tservice boot job %s \n", service->serviceJobs.jobsName[JOB_ON_BOOT]);
}
if (service->serviceJobs.jobsName[JOB_ON_START] != NULL) {
printf("\t\tservice start job %s", service->serviceJobs.jobsName[JOB_ON_START]);
printf("\t\tservice start job %s \n", service->serviceJobs.jobsName[JOB_ON_START]);
}
if (service->serviceJobs.jobsName[JOB_ON_STOP] != NULL) {
printf("\t\tservice stop job %s", service->serviceJobs.jobsName[JOB_ON_STOP]);
printf("\t\tservice stop job %s \n", service->serviceJobs.jobsName[JOB_ON_STOP]);
}
if (service->serviceJobs.jobsName[JOB_ON_RESTART] != NULL) {
printf("\t\tservice restart job %s", service->serviceJobs.jobsName[JOB_ON_RESTART]);
printf("\t\tservice restart job %s \n", service->serviceJobs.jobsName[JOB_ON_RESTART]);
}
}
static void DumpServiceSocket(const Service *service)
{
printf("\tservice socket info");
printf("\tservice socket info \n");
ServiceSocket *sockopt = service->socketCfg;
while (sockopt != NULL) {
printf("\t\tsocket name: %s", sockopt->name);
printf("\t\tsocket type: %d", sockopt->type);
printf("\t\tsocket uid: %d", sockopt->uid);
printf("\t\tsocket gid: %d", sockopt->gid);
printf("\t\tsocket name: %s \n", sockopt->name);
printf("\t\tsocket type: %d \n", sockopt->type);
printf("\t\tsocket uid: %d \n", sockopt->uid);
printf("\t\tsocket gid: %d \n", sockopt->gid);
sockopt = sockopt->next;
}
}
......@@ -93,33 +92,33 @@ void DumpOneService(const Service *service)
};
int size = 0;
const InitArgInfo *statusMap = GetServieStatusMap(&size);
printf("\tservice name: [%s]", service->name);
printf("\tservice pid: [%d]", service->pid);
printf("\tservice crashCnt: [%d]", service->crashCnt);
printf("\tservice attribute: [%d]", service->attribute);
printf("\tservice importance: [%d]", service->importance);
printf("\tservice startMode: [%s]", startModeMap[service->status].name);
printf("\tservice status: [%s]", statusMap[service->status].name);
printf("\tservice perms uID [%d]", service->servPerm.uID);
printf("\tservice name: [%s] \n", service->name);
printf("\tservice pid: [%d] \n", service->pid);
printf("\tservice crashCnt: [%d] \n", service->crashCnt);
printf("\tservice attribute: [%d] \n", service->attribute);
printf("\tservice importance: [%d] \n", service->importance);
printf("\tservice startMode: [%s] \n", startModeMap[service->status].name);
printf("\tservice status: [%s] \n", statusMap[service->status].name);
printf("\tservice perms uID [%d] \n", service->servPerm.uID);
DumpServiceArgs("path arg", &service->pathArgs);
DumpServiceArgs("writepid file", &service->writePidArgs);
DumpServiceJobs(service);
DumpServiceSocket(service);
printf("\tservice perms groupId %d", service->servPerm.gIDCnt);
printf("\tservice perms groupId %d \n", service->servPerm.gIDCnt);
for (int i = 0; i < service->servPerm.gIDCnt; i++) {
printf("\t\tservice perms groupId %d", service->servPerm.gIDArray[i]);
printf("\t\tservice perms groupId %d \n", service->servPerm.gIDArray[i]);
}
printf("\tservice perms capability %d", service->servPerm.capsCnt);
printf("\tservice perms capability %d \n", service->servPerm.capsCnt);
for (int i = 0; i < (int)service->servPerm.capsCnt; i++) {
printf("\t\tservice perms capability %d", service->servPerm.caps[i]);
printf("\t\tservice perms capability %d \n", service->servPerm.caps[i]);
}
}
void DumpAllServices()
void DumpAllServices(void)
{
printf("Ready to dump all services:");
printf("total service number: %d", g_serviceSpace.serviceCount);
printf("Ready to dump all services: \n");
printf("total service number: %d \n", g_serviceSpace.serviceCount);
InitGroupNode *node = GetNextGroupNode(NODE_TYPE_SERVICES, NULL);
while (node != NULL) {
if (node->data.service == NULL) {
......@@ -130,9 +129,8 @@ void DumpAllServices()
DumpOneService(service);
node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
}
printf("Dump all services finished");
printf("Dump all services finished \n");
}
#endif
static void FreeServiceArg(ServiceArgs *arg)
{
......
......@@ -65,11 +65,6 @@ void SystemConfig(void)
// read config
ReadConfig();
// dump config
#ifdef OHOS_SERVICE_DUMP
DumpAllServices();
#endif
// execute init
DoJob("pre-init");
#ifndef __LINUX__
......
文件模式从 100644 更改为 100755
......@@ -28,7 +28,6 @@
#include "config_policy_utils.h"
#include "device.h"
#include "fd_holder_service.h"
#include "fs_manager/fs_manager.h"
#include "init_control_fd_service.h"
#include "init_log.h"
#include "init_mount.h"
......@@ -38,9 +37,6 @@
#include "init_service_manager.h"
#include "init_utils.h"
#include "securec.h"
#include "switch_root.h"
#include "ueventd.h"
#include "ueventd_socket.h"
#include "fd_holder_internal.h"
#include "sandbox.h"
#include "sandbox_namespace.h"
......@@ -110,23 +106,8 @@ void SystemInit(void)
InitControlFd();
}
static void EnableDevKmsg(void)
{
/* printk_devkmsg default value is ratelimit, We need to set "on" and remove the restrictions */
int fd = open("/proc/sys/kernel/printk_devkmsg", O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
if (fd < 0) {
return;
}
char *kmsgStatus = "on";
write(fd, kmsgStatus, strlen(kmsgStatus) + 1);
close(fd);
fd = -1;
return;
}
void LogInit(void)
{
CloseStdio();
int ret = mknod("/dev/kmsg", S_IFCHR | S_IWUSR | S_IRUSR,
makedev(MEM_MAJOR, DEV_KMSG_MINOR));
if (ret == 0) {
......@@ -134,101 +115,9 @@ void LogInit(void)
}
}
static char **GetRequiredDevices(Fstab fstab, int *requiredNum)
{
int num = 0;
FstabItem *item = fstab.head;
while (item != NULL) {
if (FM_MANAGER_REQUIRED_ENABLED(item->fsManagerFlags)) {
num++;
}
item = item->next;
}
char **devices = (char **)calloc(num, sizeof(char *));
INIT_ERROR_CHECK(devices != NULL, return NULL, "Failed calloc err=%d", errno);
int i = 0;
item = fstab.head;
while (item != NULL) {
if (FM_MANAGER_REQUIRED_ENABLED(item->fsManagerFlags)) {
devices[i] = strdup(item->deviceName);
INIT_ERROR_CHECK(devices[i] != NULL, FreeStringVector(devices, num); return NULL,
"Failed strdup err=%d", errno);
i++;
}
item = item->next;
}
*requiredNum = num;
return devices;
}
static int StartUeventd(char **requiredDevices, int num)
{
INIT_ERROR_CHECK(requiredDevices != NULL && num > 0, return -1, "Failed parameters");
int ueventSockFd = UeventdSocketInit();
if (ueventSockFd < 0) {
INIT_LOGE("Failed to create uevent socket");
return -1;
}
RetriggerUevent(ueventSockFd, requiredDevices, num);
close(ueventSockFd);
return 0;
}
static void StartInitSecondStage(void)
{
int requiredNum = 0;
Fstab* fstab = LoadRequiredFstab();
INIT_ERROR_CHECK(fstab != NULL, abort(), "Failed to load required fstab");
char **devices = GetRequiredDevices(*fstab, &requiredNum);
if (devices != NULL && requiredNum > 0) {
int ret = StartUeventd(devices, requiredNum);
if (ret == 0) {
ret = MountRequriedPartitions(fstab);
}
FreeStringVector(devices, requiredNum);
devices = NULL;
ReleaseFstab(fstab);
fstab = NULL;
if (ret < 0) {
// If mount required partitions failure.
// There is no necessary to continue.
// Just abort
INIT_LOGE("Mount requried partitions failed; please check fstab file");
// Execute sh for debugging
execv("/bin/sh", NULL);
abort();
}
}
#ifndef DISABLE_INIT_TWO_STAGES
SwitchRoot("/usr");
// Execute init second stage
char * const args[] = {
"/bin/init",
"--second-stage",
NULL,
};
if (execv("/bin/init", args) != 0) {
INIT_LOGE("Failed to exec \"/bin/init\", err = %d", errno);
exit(-1);
}
#endif
}
void SystemPrepare(void)
{
MountBasicFs();
CreateDeviceNode();
LogInit();
// Make sure init log always output to /dev/kmsg.
EnableDevKmsg();
// Only ohos normal system support
// two stages of init.
// If we are in updater mode, only one stage of init,
INIT_LOGI("DISABLE_INIT_TWO_STAGES not defined");
if (InUpdaterMode() == 0) {
StartInitSecondStage();
}
// Second stage, nothing to prepare
}
void SystemLoadSelinux(void)
......@@ -266,7 +155,6 @@ static int SystemDump(int id, const char *name, int argc, const char **argv)
{
INIT_ERROR_CHECK(argv != NULL && argc >= 1, return 0, "Invalid install parameter");
INIT_LOGI("Dump system info %s", argv[0]);
DumpAllServices();
SystemDumpParameters(1);
SystemDumpTriggers(1);
return 0;
......@@ -293,6 +181,12 @@ static void IsEnableSandbox(void)
static void InitLoadParamFiles(void)
{
if (InUpdaterMode() != 0) {
LoadDefaultParams("/etc/param/ohos_const", LOAD_PARAM_NORMAL);
LoadDefaultParams("/etc/param", LOAD_PARAM_ONLY_ADD);
return;
}
// Load const params, these can't be override!
LoadDefaultParams("/system/etc/param/ohos_const", LOAD_PARAM_NORMAL);
CfgFiles *files = GetCfgFiles("etc/param");
......@@ -318,18 +212,19 @@ static void InitPreHook(const HOOK_INFO *hookInfo)
static void InitPostHook(const HOOK_INFO *hookInfo)
{
long long diff;
const long long baseTime = 1000;
HOOK_TIMING_STAT *stat = (HOOK_TIMING_STAT *)hookInfo->cookie;
clock_gettime(CLOCK_MONOTONIC, &(stat->endTime));
diff = (long long)((stat->endTime.tv_sec - stat->startTime.tv_sec) / 1000);
diff = (long long)((stat->endTime.tv_sec - stat->startTime.tv_sec) / baseTime);
if (stat->endTime.tv_nsec > stat->startTime.tv_nsec) {
diff += (stat->endTime.tv_nsec - stat->startTime.tv_nsec) * 1000;
diff += (stat->endTime.tv_nsec - stat->startTime.tv_nsec) * baseTime;
} else {
diff -= (stat->endTime.tv_nsec - stat->startTime.tv_nsec) * 1000;
diff -= (stat->endTime.tv_nsec - stat->startTime.tv_nsec) * baseTime;
}
INIT_LOGV("Executing hook [%d:%d:%p] cost [%lld]ms, return %d.",
hookInfo->stage, hookInfo->prio, hookInfo->hook, diff, hookInfo->retVal);
hookInfo->stage, hookInfo->prio, hookInfo->hook, diff, hookInfo->retVal);
}
void SystemConfig(void)
......@@ -399,7 +294,7 @@ void SetServiceEnterSandbox(const char *execPath, unsigned int attribute)
}
} else if (strncmp(execPath, "/vendor/bin/", strlen("/vendor/bin/")) == 0) {
// chipset sandbox will be implemented later.
INIT_INFO_CHECK(EnterSandbox("system") == 0, return,
INIT_INFO_CHECK(EnterSandbox("chipset") == 0, return,
"Service %s skip enter sandbox system.", execPath);
} else {
INIT_LOGI("Service %s does not enter sandbox", execPath);
......
......@@ -92,14 +92,9 @@ int GetParamValue(const char *symValue, unsigned int symLen, char *paramValue, u
static int SyncExecCommand(int argc, char * const *argv)
{
if (argc == 0 || argv == NULL || argv[0] == NULL) {
return -1;
}
INIT_CHECK(!(argc == 0 || argv == NULL || argv[0] == NULL), return -1);
pid_t pid = fork();
if (pid < 0) {
INIT_LOGE("Fork new process to format failed: %d", errno);
return -1;
}
INIT_ERROR_CHECK(!(pid < 0), return -1, "Fork new process to format failed: %d", errno);
if (pid == 0) {
INIT_CHECK_ONLY_ELOG(execv(argv[0], argv) == 0, "execv %s failed! err %d.", argv[0], errno);
exit(-1);
......@@ -110,9 +105,8 @@ static int SyncExecCommand(int argc, char * const *argv)
INIT_LOGE("Failed to wait pid %d, errno %d", pid, errno);
return ret;
}
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
INIT_LOGE("Command %s failed with status %d", argv[0], WEXITSTATUS(status));
}
INIT_CHECK_ONLY_ELOG(!(!WIFEXITED(status) || WEXITSTATUS(status) != 0),
"Command %s failed with status %d", argv[0], WEXITSTATUS(status));
return 0;
}
......@@ -221,9 +215,7 @@ static void DoExec(const struct CmdArgs *ctx)
if (pid == 0) {
OpenHidebug(ctx->argv[0]);
int ret = execv(ctx->argv[0], ctx->argv);
if (ret == -1) {
INIT_LOGE("DoExec: execute \"%s\" failed: %d.", ctx->argv[0], errno);
}
INIT_CHECK_ONLY_ELOG(ret != -1, "DoExec: execute \"%s\" failed: %d.", ctx->argv[0], errno);
_exit(0x7f);
}
return;
......
......@@ -47,11 +47,9 @@ static void ProcessDumpServiceControlFd(uint16_t type, const char *serviceCmd)
Service *service = GetServiceByName(serviceCmd);
if (service == NULL) {
#ifdef OHOS_SERVICE_DUMP
DumpAllServices();
} else {
DumpOneService(service);
#endif
}
return;
}
......
......@@ -33,31 +33,32 @@ int MountRequriedPartitions(const Fstab *fstab)
}
#define OHOS_REQUIRED_MOUNT_PREFIX "ohos.required_mount."
/*
* Fstab includes block device node, mount point, file system type, MNT_ Flags and options.
* We separate them by spaces in fstab.required file, but the separator is '@' in CmdLine.
* The prefix "ohos.required_mount." is the flag of required fstab information in CmdLine.
* Format as shown below:
* <block device>@<mount point>@<fstype>@<mount options>@<fstab options>
* e.g.
* ohos.required_mount.system=/dev/block/xxx/by-name/system@/usr@ext4@ro,barrier=1@wait,required
*/
static int ParseRequiredMountInfo(const char *item, Fstab *fstab)
{
char mountOptions[MAX_BUFFER_LEN] = {};
char partName[PARTITION_NAME_SIZE] = {};
// Sanity checks
if (item == NULL || *item == '\0' || fstab == NULL) {
return -1;
}
INIT_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
if (q == NULL || *q == '\0' || (p - q) <= 0) {
return -1;
}
if (strncpy_s(partName, PARTITION_NAME_SIZE -1, q, p - q) != EOK) {
INIT_LOGE("Failed to copy requried partition name");
return -1;
}
INIT_CHECK(!(q == NULL || *q == '\0' || (p - q) <= 0), return -1);
INIT_ERROR_CHECK(strncpy_s(partName, PARTITION_NAME_SIZE -1, q, p - q) == EOK,
return -1, "Failed to copy requried partition name");
p++; // skip '='
if (strncpy_s(mountOptions, MAX_BUFFER_LEN -1, p, strlen(p)) != EOK) {
INIT_LOGE("Failed to copy requried mount info: %s", item);
return -1;
}
INIT_ERROR_CHECK(strncpy_s(mountOptions, MAX_BUFFER_LEN -1, p, strlen(p)) == EOK,
return -1, "Failed to copy requried mount info: %s", item);
}
INIT_LOGV("Mount option of partition %s is [%s]", partName, mountOptions);
if (ParseFstabPerLine(mountOptions, fstab, false, "@") < 0) {
......@@ -70,18 +71,12 @@ static int ParseRequiredMountInfo(const char *item, Fstab *fstab)
static Fstab* LoadFstabFromCommandLine(void)
{
Fstab *fstab = NULL;
char *cmdline = ReadFileData("/proc/cmdline");
char *cmdline = ReadFileData(BOOT_CMD_LINE);
bool isDone = false;
if (cmdline == NULL) {
INIT_LOGE("Read from \'/proc/cmdline\' failed, err = %d", errno);
return NULL;
}
if ((fstab = (Fstab *)calloc(1, sizeof(Fstab))) == NULL) {
INIT_LOGE("Allocate memory for FS table failed, err = %d", errno);
return NULL;
}
INIT_ERROR_CHECK(cmdline != NULL, return NULL, "Read from \'/proc/cmdline\' failed, err = %d", errno);
INIT_ERROR_CHECK((fstab = (Fstab *)calloc(1, sizeof(Fstab))) != NULL, return NULL,
"Allocate memory for FS table failed, err = %d", errno);
char *start = cmdline;
char *end = start + strlen(cmdline);
while (start < end) {
......@@ -135,9 +130,7 @@ Fstab* LoadRequiredFstab(void)
if (fstab == NULL) {
INIT_LOGI("Cannot load fstab from command line, try read from fstab.required");
const char *fstabFile = "/etc/fstab.required";
if (access(fstabFile, F_OK) != 0) {
fstabFile = "/system/etc/fstab.required";
}
INIT_CHECK(access(fstabFile, F_OK) == 0, fstabFile = "/system/etc/fstab.required");
INIT_ERROR_CHECK(access(fstabFile, F_OK) == 0, abort(), "Failed get fstab.required");
fstab = ReadFstabFromFile(fstabFile, false);
}
......
......@@ -43,9 +43,7 @@ void NotifyServiceChange(Service *service, int status)
INIT_LOGI("NotifyServiceChange %s %s to %s", service->name,
statusMap[service->status].name, statusMap[status].name);
service->status = status;
if (status == SERVICE_IDLE) {
return;
}
INIT_CHECK(status != SERVICE_IDLE, return);
char paramName[PARAM_NAME_LEN_MAX] = { 0 };
int ret = snprintf_s(paramName, sizeof(paramName), sizeof(paramName) - 1,
"%s.%s", STARTUP_SERVICE_CTL, service->name);
......@@ -80,11 +78,8 @@ int ServiceExec(const Service *service)
INIT_ERROR_CHECK(service != NULL && service->pathArgs.count > 0,
return SERVICE_FAILURE, "Exec service failed! null ptr.");
if (service->importance != 0) {
if (setpriority(PRIO_PROCESS, 0, service->importance) != 0) {
INIT_LOGE("setpriority failed for %s, importance = %d, err=%d",
service->name, service->importance, errno);
_exit(0x7f); // 0x7f: user specified
}
INIT_ERROR_CHECK(setpriority(PRIO_PROCESS, 0, service->importance) == 0, _exit(0x7f),
"setpriority failed for %s, importance = %d, err=%d", service->name, service->importance, errno);
}
INIT_CHECK_ONLY_ELOG(unsetenv("UV_THREADPOOL_SIZE") == 0, "set UV_THREADPOOL_SIZE error : %d.", errno);
OpenHidebug(service->name);
......@@ -130,9 +125,8 @@ void GetAccessToken(void)
service->apl,
};
uint64_t tokenId = GetAccessTokenId(&nativeTokenInfoParams);
if (tokenId == 0) {
INIT_LOGE("Get totken id %lld of service \' %s \' failed", tokenId, service->name);
}
INIT_CHECK_ONLY_ELOG(tokenId != 0,
"Get totken id %lld of service \' %s \' failed", tokenId, service->name);
service->tokenId = tokenId;
}
node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
......
/*
* Copyright (c) 2020-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 <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <sys/sysmacros.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/major.h>
#include "device.h"
#include "init_log.h"
#include "init_utils.h"
#include "init_mount.h"
#include "fs_manager/fs_manager.h"
#include "switch_root.h"
#include "ueventd.h"
#include "ueventd_socket.h"
static void EnableDevKmsg(void)
{
/* printk_devkmsg default value is ratelimit, We need to set "on" and remove the restrictions */
int fd = open("/proc/sys/kernel/printk_devkmsg", O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
if (fd < 0) {
return;
}
char *kmsgStatus = "on";
write(fd, kmsgStatus, strlen(kmsgStatus) + 1);
close(fd);
fd = -1;
return;
}
static char **GetRequiredDevices(Fstab fstab, int *requiredNum)
{
int num = 0;
FstabItem *item = fstab.head;
while (item != NULL) {
if (FM_MANAGER_REQUIRED_ENABLED(item->fsManagerFlags)) {
num++;
}
item = item->next;
}
char **devices = (char **)calloc(num, sizeof(char *));
INIT_ERROR_CHECK(devices != NULL, return NULL, "Failed calloc err=%d", errno);
int i = 0;
item = fstab.head;
while (item != NULL) {
if (FM_MANAGER_REQUIRED_ENABLED(item->fsManagerFlags)) {
devices[i] = strdup(item->deviceName);
INIT_ERROR_CHECK(devices[i] != NULL, FreeStringVector(devices, num); return NULL,
"Failed strdup err=%d", errno);
i++;
}
item = item->next;
}
*requiredNum = num;
return devices;
}
static int StartUeventd(char **requiredDevices, int num)
{
INIT_ERROR_CHECK(requiredDevices != NULL && num > 0, return -1, "Failed parameters");
int ueventSockFd = UeventdSocketInit();
if (ueventSockFd < 0) {
INIT_LOGE("Failed to create uevent socket");
return -1;
}
RetriggerUevent(ueventSockFd, requiredDevices, num);
close(ueventSockFd);
return 0;
}
static void MountRequiredPartitions(void)
{
int requiredNum = 0;
Fstab* fstab = LoadRequiredFstab();
INIT_ERROR_CHECK(fstab != NULL, abort(), "Failed to load required fstab");
char **devices = GetRequiredDevices(*fstab, &requiredNum);
if (devices == NULL || requiredNum <= 0) {
return;
}
int ret = StartUeventd(devices, requiredNum);
if (ret == 0) {
ret = MountRequriedPartitions(fstab);
}
FreeStringVector(devices, requiredNum);
devices = NULL;
ReleaseFstab(fstab);
fstab = NULL;
if (ret < 0) {
// If mount required partitions failure.
// There is no necessary to continue.
// Just abort
INIT_LOGE("Mount requried partitions failed; please check fstab file");
// Execute sh for debugging
execv("/bin/sh", NULL);
abort();
}
SwitchRoot("/usr");
}
int main(int argc, char * const argv[])
{
MountBasicFs();
CreateDeviceNode();
OpenLogDevice();
// Make sure init log always output to /dev/kmsg.
EnableDevKmsg();
if (InUpdaterMode() == 0) {
MountRequiredPartitions();
}
// Execute init second stage
char * const args[] = {
"/bin/init",
"--second-stage",
NULL,
};
if (execv("/bin/init", args) != 0) {
INIT_LOGE("Failed to exec \"/bin/init\", err = %d", errno);
exit(-1);
}
return 0;
}
......@@ -31,6 +31,18 @@ if (defined(ohos_lite)) {
}
} else {
import("//build/ohos.gni")
#
# exported include directories
#
config("init_log_exported_config") {
visibility = [ ":*" ]
include_dirs = [
".",
"//base/startup/init_lite/interfaces/innerkits/include",
]
}
ohos_static_library("init_log") {
sources = [ "init_log.c" ]
defines = [ "INIT_DMESG" ]
......@@ -38,6 +50,7 @@ if (defined(ohos_lite)) {
"//base/startup/init_lite/interfaces/innerkits/include",
"//third_party/bounds_checking_function/include",
]
public_configs = [ ":init_log_exported_config" ]
part_name = "startup"
subsystem_name = "startup"
}
......@@ -58,6 +71,7 @@ if (defined(ohos_lite)) {
"system",
"updater",
]
public_configs = [ ":init_log_exported_config" ]
external_deps = [ "hilog_native:libhilog_base" ]
install_enable = true
part_name = "init"
......
......@@ -20,6 +20,7 @@
#include <stdarg.h>
#include <sys/stat.h>
#include <time.h>
#include <sys/time.h>
#include "securec.h"
#ifdef OHOS_LITE
......@@ -32,6 +33,7 @@
#include "hilog_base/log_base.h"
#endif
#define DEF_LOG_SIZE 128
#define MAX_LOG_SIZE 1024
#define BASE_YEAR 1900
......@@ -44,17 +46,16 @@ void SetInitLogLevel(InitLogLevel logLevel)
#ifdef INIT_FILE
static void LogToFile(const char *logFile, const char *tag, const char *info)
{
time_t second = time(0);
if (second <= 0) {
struct timespec curr;
if (clock_gettime(CLOCK_REALTIME, &curr) != 0) {
return;
}
struct tm *t = localtime(&second);
FILE *outfile = fopen(logFile, "a+");
if (t == NULL || outfile == NULL) {
return;
}
(void)fprintf(outfile, "[%d-%d-%d %d:%d:%d][pid=%d][%s]%s \n",
(t->tm_year + BASE_YEAR), (t->tm_mon + 1), t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, getpid(), tag, info);
FILE *outfile = NULL;
INIT_CHECK_ONLY_RETURN((outfile = fopen(logFile, "a+")) != NULL);
struct tm t;
char dateTime[80]; // 80 data time
strftime(dateTime, sizeof(dateTime), "%Y-%m-%d %H:%M:%S", localtime_r(&curr.tv_sec, &t));
(void)fprintf(outfile, "[%s.%ld][pid=%d %d][%s]%s \n", dateTime, curr.tv_nsec, getpid(), gettid(), tag, info);
(void)fflush(outfile);
fclose(outfile);
return;
......@@ -105,12 +106,17 @@ void InitLog(InitLogLevel logLevel, unsigned int domain, const char *tag, const
}
va_list vargs;
va_start(vargs, fmt);
char tmpFmt[MAX_LOG_SIZE] = {0};
if (vsnprintf_s(tmpFmt, MAX_LOG_SIZE, MAX_LOG_SIZE - 1, fmt, vargs) == -1) {
char tmpFmt[DEF_LOG_SIZE] = {0};
if (vsnprintf_s(tmpFmt, sizeof(tmpFmt), sizeof(tmpFmt) - 1, fmt, vargs) == -1) {
va_end(vargs);
#ifdef OHOS_LITE
static LogLevel LOG_LEVEL[] = { LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR, LOG_FATAL };
(void)HiLogPrint(INIT_LOG_INIT, LOG_LEVEL[logLevel], domain, tag, "%{public}s", fmt);
#endif
return;
}
va_end(vargs);
#ifdef OHOS_LITE
static LogLevel LOG_LEVEL[] = { LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR, LOG_FATAL };
(void)HiLogPrint(INIT_LOG_INIT, LOG_LEVEL[logLevel], domain, tag, "%{public}s", tmpFmt);
......
......@@ -92,7 +92,6 @@ LE_STATUS ProcessEvent(const EventLoop *loop, int fd, uint32_t oper)
}
task->handleEvent((LoopHandle)loop, (TaskHandle)task, oper);
} else {
LE_LOGE("ProcessEvent can not find task for %d", fd);
loop->delEvent(loop, fd, oper);
}
return LE_SUCCESS;
......
......@@ -108,9 +108,7 @@ static LE_STATUS HandleClientEvent_(const LoopHandle loopHandle, const TaskHandl
LE_STATUS status = LE_SUCCESS;
if (LE_TEST_FLAGS(oper, Event_Write)) {
if (client->connected == 0 && client->connectComplete) {
client->connectComplete(handle);
}
LE_ONLY_CHECK(!(client->connected == 0 && client->connectComplete), client->connectComplete(handle));
client->connected = 1;
status = HandleSendMsg_(loopHandle, handle, client->sendMessageComplete);
}
......@@ -143,9 +141,7 @@ static LE_STATUS HandleServerEvent_(const LoopHandle loopHandle, const TaskHandl
return LE_FAILURE;
}
StreamServerTask *server = (StreamServerTask *)serverTask;
if (server->incommingConntect == NULL) {
return LE_SUCCESS;
}
LE_ONLY_CHECK(server->incommingConntect != NULL, return LE_SUCCESS);
int ret = server->incommingConntect(loopHandle, serverTask);
if (ret != LE_SUCCESS) {
......
......@@ -77,11 +77,10 @@ void CloseTask(const LoopHandle loopHandle, BaseTask *task)
LE_Buffer *CreateBuffer(uint32_t bufferSize)
{
if (bufferSize >= LOOP_MAX_BUFFER) {
return NULL;
}
LE_Buffer *buffer = (LE_Buffer *)malloc(sizeof(LE_Buffer) + bufferSize);
LE_CHECK(buffer != NULL, return NULL, "Failed to alloc memory for buffer");
LE_ONLY_CHECK(bufferSize < LOOP_MAX_BUFFER, return NULL);
LE_Buffer *buffer = NULL;
LE_CHECK((buffer = (LE_Buffer *)malloc(sizeof(LE_Buffer) + bufferSize)) != NULL,
return NULL, "Failed to alloc memory for buffer");
ListInit(&buffer->node);
buffer->buffSize = bufferSize;
buffer->dataSize = 0;
......
......@@ -31,9 +31,7 @@ static LE_STATUS HandleWatcherEvent_(const LoopHandle loopHandle, const TaskHand
watcher->processEvent(taskHandle, fd, &events, (void *)userData);
}
watcher = (WatcherTask *)GetTaskByFd((EventLoop *)loopHandle, fd);
if (watcher == NULL) {
return 0;
}
LE_ONLY_CHECK(watcher != NULL, return 0);
if (watcher->base.flags & WATCHER_ONCE) {
loop->delEvent(loop, fd, watcher->events);
return 0;
......
......@@ -18,12 +18,8 @@ ohos_shared_library("bootchart") {
sources = [ "bootchart/bootchart.c" ]
include_dirs = [
"//base/startup/init_lite/services/include",
".",
"//base/startup/init_lite/services/include/param",
"//base/startup/init_lite/services/log",
"//base/startup/init_lite/services/modules",
"//base/startup/init_lite/interfaces/innerkits/include",
"//third_party/bounds_checking_function/include",
]
deps = [
......@@ -44,18 +40,13 @@ ohos_shared_library("bootchart") {
}
config("libbootchart_static_config") {
include_dirs = [
"//base/startup/init_lite/services/log",
"//base/startup/init_lite/services/modules",
"//base/startup/init_lite/services/init/module_engine/include",
"//base/startup/init_lite/services/include",
"//base/startup/init_lite/interfaces/innerkits/include",
]
include_dirs = [ "." ]
}
ohos_source_set("libbootchart_static") {
sources = [ "bootchart/bootchart_static.c" ]
public_configs = [ ":libbootchart_static_config" ]
public_configs += [ "//base/startup/init_lite/interfaces/innerkits/init_module_engine:init_module_engine_exported_config" ]
}
group("modules") {
......
......@@ -52,48 +52,6 @@ param_include_dirs = [
"//utils/native/lite/include",
]
if (enable_ohos_startup_init_feature_begetctl_liteos) {
action("lite_const_param_to") {
script = "//base/startup/init_lite/scripts/param_cfg_to_code.py"
args = [
"--source",
rebase_path(
"//base/startup/init_lite/services/etc_lite/param/ohos_const/ohos.para"),
"--dest_dir",
rebase_path("$root_out_dir/gen/init_lite/"),
"--priority",
"0",
]
outputs = [ "$target_gen_dir/${target_name}_param_cfg_to_code.log" ]
}
action("lite_ohos_param_to") {
script = "//base/startup/init_lite/scripts/param_cfg_to_code.py"
args = [
"--source",
rebase_path("//base/startup/init_lite/services/etc/param/ohos.para"),
"--dest_dir",
rebase_path("$root_out_dir/gen/init_lite/"),
"--priority",
"0",
]
outputs = [ "$target_gen_dir/${target_name}_param_cfg_to_code.log" ]
}
action("vendor_param_to") {
script = "//base/startup/init_lite/scripts/param_cfg_to_code.py"
args = [
"--source",
rebase_path("$ohos_product_adapter_dir/utils/sys_param/vendor.para"),
"--dest_dir",
rebase_path("$root_out_dir/gen/init_lite/"),
"--priority",
"1",
]
outputs = [ "$target_gen_dir/${target_name}_param_cfg_to_code.log" ]
}
}
if (defined(ohos_lite)) {
param_build_defines = [
"_GNU_SOURCE",
......@@ -105,6 +63,48 @@ if (defined(ohos_lite)) {
"BUILD_ROOTHASH=\"${ohos_build_roothash}\"",
]
if (enable_ohos_startup_init_feature_begetctl_liteos) {
action("lite_const_param_to") {
script = "//base/startup/init_lite/scripts/param_cfg_to_code.py"
args = [
"--source",
rebase_path(
"//base/startup/init_lite/services/etc_lite/param/ohos_const/ohos.para"),
"--dest_dir",
rebase_path("$root_out_dir/gen/init_lite/"),
"--priority",
"0",
]
outputs = [ "$target_gen_dir/${target_name}_param_cfg_to_code.log" ]
}
action("lite_ohos_param_to") {
script = "//base/startup/init_lite/scripts/param_cfg_to_code.py"
args = [
"--source",
rebase_path("//base/startup/init_lite/services/etc/param/ohos.para"),
"--dest_dir",
rebase_path("$root_out_dir/gen/init_lite/"),
"--priority",
"0",
]
outputs = [ "$target_gen_dir/${target_name}_param_cfg_to_code.log" ]
}
action("vendor_param_to") {
script = "//base/startup/init_lite/scripts/param_cfg_to_code.py"
args = [
"--source",
rebase_path("$ohos_product_adapter_dir/utils/sys_param/vendor.para"),
"--dest_dir",
rebase_path("$root_out_dir/gen/init_lite/"),
"--priority",
"1",
]
outputs = [ "$target_gen_dir/${target_name}_param_cfg_to_code.log" ]
}
}
static_library("param_init") {
defines = []
deps = []
......
......@@ -47,11 +47,7 @@ extern "C" {
#define SELINUX_CONTENT_LEN 64
#define SYS_UID_INDEX 1000
typedef enum {
DAC_RESULT_PERMISSION = 0,
DAC_RESULT_INVALID_PARAM = 1000,
DAC_RESULT_FORBIDED,
} DAC_RESULT;
#define DAC_RESULT_PERMISSION 0
typedef struct UserCred {
pid_t pid;
......
......@@ -44,13 +44,13 @@ static int InitParamClient(void)
if (PARAM_TEST_FLAG(g_clientSpace.flags, WORKSPACE_FLAGS_INIT)) {
return 0;
}
PARAM_LOGV("InitParamClient");
PARAM_LOGI("InitParamClient %p", &g_clientSpace);
pthread_mutex_init(&g_clientSpace.mutex, NULL);
g_clientSpace.clientFd = INVALID_SOCKET;
int ret = InitParamWorkSpace(1);
PARAM_CHECK(ret == 0, return -1, "Failed to init param workspace");
PARAM_SET_FLAG(g_clientSpace.flags, WORKSPACE_FLAGS_INIT);
PARAM_LOGI("InitParamClient finish");
PARAM_LOGI("InitParamClient %p finish", &g_clientSpace);
return 0;
}
......@@ -64,6 +64,7 @@ void ClientInit(void)
void ClientDeinit(void)
{
PARAM_LOGI("ClientDeinit %p", &g_clientSpace);
#ifndef STARTUP_INIT_TEST
if (PARAM_TEST_FLAG(g_clientSpace.flags, WORKSPACE_FLAGS_INIT)) {
CloseParamWorkSpace();
......@@ -74,6 +75,7 @@ void ClientDeinit(void)
}
PARAM_SET_FLAG(g_clientSpace.flags, 0);
pthread_mutex_destroy(&g_clientSpace.mutex);
PARAM_LOGI("ClientDeinit %p finish", &g_clientSpace);
}
static int ProcessRecvMsg(const ParamMessage *recvMsg)
......@@ -177,7 +179,6 @@ int SystemSetParameter(const char *name, const char *value)
request->msgSize = offset + sizeof(ParamMessage);
request->id.msgId = atomic_fetch_add(&g_requestId, 1);
PARAM_LOGV("SystemSetParameter name %s", name);
int fd = INVALID_SOCKET;
pthread_mutex_lock(&g_clientSpace.mutex);
if (g_clientSpace.clientFd == INVALID_SOCKET) {
......@@ -188,6 +189,7 @@ int SystemSetParameter(const char *name, const char *value)
PARAM_CHECK(fd > 0, return -1, "Failed to connect server for set %s", name);
ret = StartRequest(fd, request, DEFAULT_PARAM_SET_TIMEOUT);
free(request);
PARAM_LOGI("SystemSetParameter name %s %d", name, ret);
return ret;
}
......
......@@ -22,7 +22,7 @@
static ParamWorkSpace g_paramWorkSpace = {};
static int WorkSpaceNodeCompare(const HashNode *node1, const HashNode *node2)
PARAM_STATIC int WorkSpaceNodeCompare(const HashNode *node1, const HashNode *node2)
{
WorkSpace *workSpace1 = HASHMAP_ENTRY(node1, WorkSpace, hashNode);
WorkSpace *workSpace2 = HASHMAP_ENTRY(node2, WorkSpace, hashNode);
......@@ -117,6 +117,7 @@ PARAM_STATIC int RegisterSecurityOps(int onlyRead)
int InitParamWorkSpace(int onlyRead)
{
PARAM_LOGI("InitParamWorkSpace %p", &g_paramWorkSpace);
if (PARAM_TEST_FLAG(g_paramWorkSpace.flags, WORKSPACE_FLAGS_INIT)) {
return 0;
}
......@@ -695,7 +696,6 @@ WorkSpace *GetWorkSpace(const char *name)
space = HASHMAP_ENTRY(node, WorkSpace, hashNode);
}
WORKSPACE_RW_UNLOCK(g_paramWorkSpace);
PARAM_LOGV("GetWorkSpace %s space-name %s, space %p", name, tmpName, space);
return (space != NULL && space->area != NULL) ? space : NULL;
}
......
......@@ -112,12 +112,14 @@ int InitWorkSpace(WorkSpace *workSpace, int onlyRead, uint32_t spaceSize)
PARAM_CHECK(ret == 0, return ret, "Failed to init workspace %s", workSpace->fileName);
PARAMSPACE_AREA_INIT_LOCK(workSpace);
PARAM_SET_FLAG(workSpace->flags, WORKSPACE_FLAGS_INIT);
PARAM_LOGI("InitWorkSpace %s", workSpace->fileName);
return ret;
}
void CloseWorkSpace(WorkSpace *workSpace)
{
PARAM_CHECK(workSpace != NULL, return, "The workspace is null");
PARAM_LOGI("CloseWorkSpace %s", workSpace->fileName);
if (!PARAM_TEST_FLAG(workSpace->flags, WORKSPACE_FLAGS_INIT)) {
free(workSpace);
return;
......
......@@ -30,6 +30,11 @@ if (defined(ohos_lite)) {
} else {
import("//build/ohos.gni")
config("init_utils_exported_configs") {
visibility = [ ":*" ]
include_dirs = [ "//base/startup/init_lite/services/include" ]
}
ohos_static_library("libinit_tools") {
sources = [
"//base/startup/init_lite/services/utils/init_hashmap.c",
......@@ -42,6 +47,7 @@ if (defined(ohos_lite)) {
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/services/include",
]
public_configs = [ ":init_utils_exported_configs" ]
defines = [ "_GNU_SOURCE" ]
part_name = "init"
}
......@@ -55,6 +61,7 @@ if (defined(ohos_lite)) {
"//base/startup/init_lite/interfaces/innerkits/include",
"//base/startup/init_lite/services/include",
]
public_configs = [ ":init_utils_exported_configs" ]
defines = [ "_GNU_SOURCE" ]
part_name = "init"
}
......
......@@ -181,3 +181,16 @@ void HashMapTraverse(HashMapHandle handle, void (*hashNodeTraverse)(const HashNo
}
}
}
int HashMapIsEmpty(HashMapHandle handle)
{
INIT_ERROR_CHECK(handle != NULL, return 1, "Invalid param");
HashTab *tab = (HashTab *)handle;
for (int i = 0; i < tab->maxBucket; i++) {
HashNode *node = tab->buckets[i];
if (node != NULL) {
return 0;
}
}
return 1;
}
......@@ -368,6 +368,30 @@ void CheckAndCreateDir(const char *fileName)
#endif
}
int CheckAndCreatFile(const char *file, mode_t mode)
{
if (access(file, F_OK) == 0) {
BEGET_LOGW("File \' %s \' already exist", file);
return 0;
} else {
if (errno == ENOENT) {
CheckAndCreateDir(file);
int fd = open(file, O_CREAT, mode);
if (fd < 0) {
BEGET_LOGE("Failed create %s, err=%d", file, errno);
return -1;
} else {
BEGET_LOGI("Success create %s", file);
close(fd);
}
} else {
BEGET_LOGW("Failed to access \' %s \', err = %d", file, errno);
return -1;
}
}
return 0;
}
int StringToInt(const char *str, int defaultValue)
{
if (str == NULL || *str == '\0') {
......@@ -431,21 +455,6 @@ int InUpdaterMode(void)
}
}
int InChargerMode(void)
{
char *data = ReadFileData(BOOT_CMD_LINE);
char value[CMDLINE_VALUE_LEN_MAX];
int ret = 0;
if ((GetProcCmdlineValue("reboot_reason", data, value, CMDLINE_VALUE_LEN_MAX) == 0) &&
(strcmp(value, "poweroff_charge") == 0)) {
ret = 1;
}
INIT_LOGE("GetProcCmdlineValue():reboot_reason=%s ,ret=%d\n", value, ret);
free(data);
return ret;
}
int StringReplaceChr(char *strl, char oldChr, char newChr)
{
INIT_ERROR_CHECK(strl != NULL, return -1, "Invalid parament");
......
......@@ -127,6 +127,7 @@ ohos_unittest("init_ut") {
"init/group_unittest.cpp",
"init/init_reboot_unittest.cpp",
"init/mount_unittest.cpp",
"init/sandbox_unittest.cpp",
"init/service_file_unittest.cpp",
"init/service_socket_unittest.cpp",
"init/utils_unittest.cpp",
......@@ -192,6 +193,7 @@ ohos_unittest("init_ut") {
"//base/security/access_token/interfaces/innerkits/token_setproc/include",
"//base/security/access_token/interfaces/innerkits/nativetoken/include",
"//base/startup/init_lite/interfaces/innerkits/sandbox/include",
"//base/startup/init_lite/interfaces/innerkits/hals",
]
deps = [
......
......@@ -87,16 +87,6 @@ static TestHashNode *TestCreateHashNode(const char *value)
return node;
}
static void CreateTestFile(const char *fileName, const char *data)
{
FILE *tmpFile = fopen(fileName, "wr");
if (tmpFile != nullptr) {
fprintf(tmpFile, "%s", data);
(void)fflush(tmpFile);
fclose(tmpFile);
}
}
namespace init_ut {
class InitGroupManagerUnitTest : public testing::Test {
public:
......@@ -169,35 +159,6 @@ HWTEST_F(InitGroupManagerUnitTest, TestHashMap, TestSize.Level1)
HWTEST_F(InitGroupManagerUnitTest, TestInitGroupMgrInit, TestSize.Level1)
{
const char *data = "{"
"\"jobs\": [\"param:job1\", \"param:job2\", \"param:job4\"],"
"\"services\": [\"service:service1\", \"service:service3\", \"service:service2\"],"
"\"groups\": [\"subsystem.xxx1.group\", \"subsystem.xxx2.group\", \"subsystem.xxx4.group\"]"
"}";
const char *xxx1 = "{"
"\"groups\": [\"subsystem.xxx11.group\""
"}";
const char *xxx11 = "{"
"\"groups\": [\"subsystem.xxx12.group\""
"}";
const char *xxx12 = "{"
"\"groups\": [\"subsystem.xxx13.group\""
"}";
const char *xxx13 = "{"
"\"groups\": [\"subsystem.xxx14.group\""
"}";
const char *xxx14 = "{"
"\"groups\": [\"subsystem.xxx11.group\""
"}";
const char *cmdLine = "BOOT_IMAGE=/kernel init=/init bootgroup=device.charge.group";
CreateTestFile(GROUP_DEFAULT_PATH "/device.boot.group.cfg", data);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx1.group.cfg", xxx1);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx11.group.cfg", xxx11);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx12.group.cfg", xxx12);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx13.group.cfg", xxx13);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx14.group.cfg", xxx14);
CreateTestFile(BOOT_CMD_LINE, cmdLine);
InitServiceSpace();
InitWorkspace *workspace = GetInitWorkspace();
EXPECT_EQ(workspace->groupMode, GROUP_CHARGE);
......
......@@ -34,9 +34,24 @@
using namespace testing::ext;
using namespace std;
using HashTab = struct {
HashNodeCompare nodeCompare;
HashKeyCompare keyCompare;
HashNodeFunction nodeHash;
HashKeyFunction keyHash;
HashNodeOnFree nodeFree;
int maxBucket;
uint32_t tableId;
HashNode *buckets[0];
};
extern "C" {
void OnClose(ParamTaskPtr client);
}
static LE_STATUS TestHandleTaskEvent(const LoopHandle loop, const TaskHandle task, uint32_t oper)
{
return LE_SUCCESS;
}
static void OnReceiveRequest(const TaskHandle task, const uint8_t *buffer, uint32_t nread)
{
......@@ -187,6 +202,14 @@ public:
void ProcessEventTest()
{
ProcessEvent((EventLoop *)LE_GetDefaultLoop(), 1, Event_Read);
LE_BaseInfo info = {TASK_EVENT, NULL};
int testfd = 65535; // 65535 is not exist fd
BaseTask *task = CreateTask(LE_GetDefaultLoop(), testfd, &info, sizeof(StreamClientTask));
task->handleEvent = TestHandleTaskEvent;
if (task != nullptr) {
ProcessEvent((EventLoop *)LE_GetDefaultLoop(), testfd, Event_Read);
}
((HashTab *)(((EventLoop *)LE_GetDefaultLoop())->taskMap))->nodeFree(&task->hashNode);
}
void ProcessasynEvent()
{
......
......@@ -47,6 +47,7 @@ HWTEST_F(MountUnitTest, TestMountRequriedPartitions, TestSize.Level0)
int ret = MountRequriedPartitions(&fstab1);
EXPECT_EQ(ret, -1);
}
LoadRequiredFstab();
}
HWTEST_F(MountUnitTest, TestGetBlockDevicePath, TestSize.Level1)
{
......
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cerrno>
#include <unistd.h>
#include <sys/stat.h>
#include "init_unittest.h"
#include "cJSON.h"
#include "sandbox.h"
#include "sandbox_namespace.h"
#include "securec.h"
using namespace testing::ext;
namespace init_ut {
const int NULL_ROOT_PATH = 1;
const int NULL_MOUNT_FLAGS = 2;
const int NULL_MOUNT = 3;
const int NULL_MOUNT_ITEM = 13;
const int LINK_ARRARY_START = 5;
const int LINK_ARRARY_END = 8;
const int FLAGS_NUMBER = 3;
const char *TEST_SANDBOX_NAME = "test";
const char *SANDBOX_JSON_NAME = "test-sandbox.json";
const char *SANDBOX_CONFIG[] = {"sandbox-root", "mount-bind-paths", "mount-bind-files", "symbol-links"};
const char *SANDBOX_ROOT[] = { "/mnt/sandbox/test", "/mnt/sandbox/chipset", "/mnt/error"};
const char *SANDBOX_FLAGS[] = {"bind", "rec", "private"};
const char *MOUNT_BIND_PATHS[] = {"src-path", "sandbox-path", "sandbox-flags"};
const char *SYMBOL_LINKS[] = {"target-name", "link-name"};
const char *APP_PATHS[] = {"/mnt", "/sys", "/proc", "/dev", "/data",
"/system/bin", "/system/lib", "/system/etc", "/system"};
int RestartSandbox(const char *sandbox)
{
if (sandbox == nullptr) {
std::cout << "invalid parameters" << std::endl;
return 0;
}
InitDefaultNamespace();
std::cout << "init namespace" << std::endl;
if (!InitSandboxWithName(sandbox)) {
CloseDefaultNamespace();
std::cout << "Failed to init sandbox with name " << sandbox << std::endl;
return 0;
}
std::cout << "init sandbox with name" << std::endl;
DumpSandboxByName(sandbox);
std::cout << "dump sandbox" << std::endl;
if (PrepareSandbox(sandbox) != 0) {
std::cout << "Failed to prepare sandbox %s" << sandbox << std::endl;
DestroySandbox(sandbox);
CloseDefaultNamespace();
return 0;
}
std::cout << "prepare sandbox" << std::endl;
if (EnterDefaultNamespace() < 0) {
std::cout << "Failed to set default namespace" << std::endl;
DestroySandbox(sandbox);
CloseDefaultNamespace();
return 0;
}
std::cout << "enter default namespace" << std::endl;
CloseDefaultNamespace();
std::cout << "close namespace" << std::endl;
return 1;
}
cJSON *MakeSandboxJson(const char *sandboxFileName, const int MODE)
{
cJSON *mJsonSandbox = cJSON_CreateObject(); // json file object
cJSON *mJsonMtBdPth = cJSON_CreateArray(); // mount-bind-paths
cJSON *mJsonMtBdFl = cJSON_CreateArray(); // mount-bind-files
cJSON *mJsonSymLk = cJSON_CreateArray(); // symbol-links
cJSON *mJsonMtBdPthItmSdxFlg = cJSON_CreateArray(); // mount-bind-paths items sandbox-flags
cJSON *mJsonMtBdFlItm = cJSON_CreateObject(); // mount-bind-files items
if (mJsonSandbox == nullptr || mJsonMtBdPth == nullptr || mJsonMtBdFl == nullptr ||
mJsonSymLk == nullptr || mJsonMtBdPthItmSdxFlg == nullptr || mJsonMtBdFlItm == nullptr) {
std::cout << "create json object error" << std::endl;
return nullptr;
}
cJSON *mJsonMtBdPth_Itm; // point to mount-bind-paths items
cJSON *mJsonSymLk_Itm; // point to symbol-links items
// drop root path
if (MODE != NULL_ROOT_PATH) {
cJSON_AddItemToObject(mJsonSandbox, SANDBOX_CONFIG[0], cJSON_CreateString(SANDBOX_ROOT[0]));
}
// assemble SANDBOX_FLAGS
if (MODE != NULL_MOUNT_FLAGS) {
for (int i = 0; i < FLAGS_NUMBER; i++) {
cJSON_AddItemToArray(mJsonMtBdPthItmSdxFlg, cJSON_CreateString(SANDBOX_FLAGS[i]));
}
}
// assemble mount-bind-paths items
// Append items to mount-bind-paths
for (int i = 0; i < (sizeof(APP_PATHS) / sizeof(char *)); i++) {
cJSON_AddItemToArray(mJsonMtBdPth, mJsonMtBdPth_Itm = cJSON_CreateObject());
int MOUNT_FLAG_COUNT = 2;
if (MODE != NULL_MOUNT_ITEM) {
cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[0], cJSON_CreateString(APP_PATHS[i]));
cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[1], cJSON_CreateString(APP_PATHS[i]));
} else {
cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[0], nullptr);
cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[1], nullptr);
}
cJSON_AddItemToObject(mJsonMtBdPth_Itm, MOUNT_BIND_PATHS[MOUNT_FLAG_COUNT], mJsonMtBdPthItmSdxFlg);
}
if (MODE != NULL_MOUNT) {
// Append items to mount-bind-files
cJSON_AddItemToArray(mJsonMtBdFl, mJsonMtBdFlItm);
// assemble symbol-links items
for (int i = LINK_ARRARY_START; i < LINK_ARRARY_END; i++) {
// Append items to symbol-links
cJSON_AddItemToArray(mJsonSymLk, mJsonSymLk_Itm = cJSON_CreateObject());
cJSON_AddItemToObject(mJsonSymLk_Itm, SYMBOL_LINKS[0], cJSON_CreateString(APP_PATHS[i]));
cJSON_AddItemToObject(mJsonSymLk_Itm, SYMBOL_LINKS[1], cJSON_CreateString(APP_PATHS[i]));
}
}
// at last, assemble the json file
int count = 1;
cJSON_AddItemToObject(mJsonSandbox, SANDBOX_CONFIG[count++], mJsonMtBdPth);
cJSON_AddItemToObject(mJsonSandbox, SANDBOX_CONFIG[count++], mJsonMtBdFl);
cJSON_AddItemToObject(mJsonSandbox, SANDBOX_CONFIG[count], mJsonSymLk);
return mJsonSandbox;
}
bool MakeFileByJson(cJSON * mJson, const char *sandboxFileName)
{
const std::string sandboxJsonPth = std::string("/etc/sandbox/") + std::string(TEST_SANDBOX_NAME);
const char* cSandboxJsonPth = sandboxJsonPth.c_str();
int fd = open(cSandboxJsonPth, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd < 0) {
std::cout << "open sandbox json file failed" << std::endl;
return false;
}
char *cjValue1 = cJSON_Print(mJson);
int ret1 = write(fd, cjValue1, strlen(cjValue1));
if (-1 == ret1) {
std::cout << "Write file ERROR" << errno << " fd is :" << fd << std::endl;
return false;
}
free(cjValue1);
close(fd);
return true;
}
class SandboxUnitTest : public testing::Test {
public:
static void SetUpTestCase(void) {}
static void TearDownTestCase(void) {}
void SetUp() {};
void TearDown() {};
};
HWTEST_F(SandboxUnitTest, TestCreateNormalSandbox, TestSize.Level1) {
cJSON *mJson = MakeSandboxJson(SANDBOX_JSON_NAME, 0);
if (mJson == nullptr) {
std::cout << "created mJson error, mJson is null." << std::endl;
return;
}
MakeFileByJson(mJson, SANDBOX_JSON_NAME);
int ret = RestartSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, 1);
}
HWTEST_F(SandboxUnitTest, TestEnterErrorSandbox, TestSize.Level1) {
int ret1 = EnterSandbox("error_system");
ASSERT_EQ(ret1, -1);
const char *pname = nullptr;
int ret2 = EnterSandbox(pname);
ASSERT_EQ(ret2, -1);
DestroySandbox(TEST_SANDBOX_NAME);
int ret3 = EnterSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret3, -1);
}
HWTEST_F(SandboxUnitTest, TestCreateErrorSandbox1, TestSize.Level1) {
const char *pname = nullptr;
std::cout << "test destory nullptr" << std::endl;
DestroySandbox(pname);
std::cout << "test destory xapp" << std::endl;
DestroySandbox("xapp");
std::cout << "test enter xapp" << std::endl;
int ret1 = EnterSandbox("xapp");
ASSERT_EQ(ret1, -1);
bool result = InitSandboxWithName(pname);
ASSERT_FALSE(result);
DumpSandboxByName(pname);
DumpSandboxByName("xpp");
result = InitSandboxWithName("xapp");
ASSERT_FALSE(result);
}
HWTEST_F(SandboxUnitTest, TestCreateErrorSandbox2, TestSize.Level1) {
cJSON *mJson = MakeSandboxJson(SANDBOX_JSON_NAME, NULL_ROOT_PATH);
if (mJson == nullptr) {
std::cout << "created mJson error, mJson is null." << std::endl;
return;
}
bool ret1 = MakeFileByJson(mJson, SANDBOX_JSON_NAME);
ASSERT_TRUE(ret1);
InitSandboxWithName(TEST_SANDBOX_NAME);
int ret = PrepareSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, -1);
ret = PrepareSandbox("xapp");
ASSERT_EQ(ret, -1);
}
HWTEST_F(SandboxUnitTest, TestCreateSandboxNoneJsonError, TestSize.Level1) {
unlink("/etc/sandbox/test-sandbox.json");
int ret = PrepareSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, -1);
}
HWTEST_F(SandboxUnitTest, TestCreateSandboxMountFlagsError, TestSize.Level1) {
cJSON *mJson = MakeSandboxJson(SANDBOX_JSON_NAME, NULL_MOUNT_FLAGS);
if (mJson == nullptr) {
std::cout << "created mJson error, mJson is null." << std::endl;
return;
}
MakeFileByJson(mJson, SANDBOX_JSON_NAME);
int ret = PrepareSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, -1);
}
HWTEST_F(SandboxUnitTest, TestCreateSandboxMountNULLError, TestSize.Level1) {
cJSON *mJson = MakeSandboxJson(SANDBOX_JSON_NAME, NULL_MOUNT_ITEM);
if (mJson == nullptr) {
std::cout << "created mJson error, mJson is null." << std::endl;
return;
}
MakeFileByJson(mJson, SANDBOX_JSON_NAME);
int ret = PrepareSandbox(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, -1);
InitSandboxWithName(TEST_SANDBOX_NAME);
ASSERT_EQ(ret, -1);
}
HWTEST_F(SandboxUnitTest, TestUnshareNamespace, TestSize.Level1) {
int ret1 = UnshareNamespace(-1);
ASSERT_EQ(ret1, -1);
}
HWTEST_F(SandboxUnitTest, TestSetNamespace, TestSize.Level1) {
int ret1 = SetNamespace(-1, 1);
ASSERT_EQ(ret1, -1);
ret1 = SetNamespace(1, -1);
ASSERT_EQ(ret1, -1);
}
HWTEST_F(SandboxUnitTest, TestGetNamespaceFd, TestSize.Level1) {
int ret1 = GetNamespaceFd("");
ASSERT_EQ(ret1, -1);
const std::string sandboxJsonPth = std::string("/mnt/sandbox/") + std::string(TEST_SANDBOX_NAME);
const char* cSandboxJsonPth = sandboxJsonPth.c_str();
ret1 = GetNamespaceFd(cSandboxJsonPth);
EXPECT_GT(ret1, 1);
}
}
......@@ -25,6 +25,7 @@
#include "init_utils.h"
#include "securec.h"
#include "init_group_manager.h"
#include "trigger_manager.h"
using namespace testing::ext;
using namespace std;
......@@ -45,7 +46,10 @@ public:
void SetUp() {};
void TearDown() {};
};
HWTEST_F(ServiceUnitTest, TestDestoryHashMap, TestSize.Level1)
{
HashMapDestory(GetInitWorkspace()->hashMap[0]);
}
HWTEST_F(ServiceUnitTest, case01, TestSize.Level1)
{
const char *jsonStr = "{\"services\":{\"name\":\"test_service\",\"path\":[\"/data/init_ut/test_service\"],"
......
......@@ -70,7 +70,6 @@ HWTEST_F(UtilsUnitTest, TestUtilsApi, TestSize.Level0)
float sec = ConvertMicrosecondToSecond(1000000); // 1000000 microseconds
EXPECT_EQ(sec, 1);
EXPECT_EQ(WriteAll(2, "test", strlen("test")), 4);
EXPECT_EQ(InChargerMode(), 0);
GetRandom();
}
} // namespace init_ut
......@@ -80,6 +80,8 @@ if (defined(ohos_lite)) {
"//base/startup/init_lite/services/log",
"//base/startup/init_lite/services/loopevent/include",
"//base/startup/init_lite/services/loopevent/timer",
"//base/startup/init_lite/services/loopevent/task",
"//base/startup/init_lite/services/loopevent/utils",
"//base/startup/init_lite/services/param/adapter",
"//base/startup/init_lite/services/param/linux",
"//base/startup/init_lite/services/param/include",
......@@ -95,6 +97,7 @@ if (defined(ohos_lite)) {
"//third_party/bounds_checking_function/include",
"//base/hiviewdfx/hilog_lite/interfaces/native/kits",
"//base/startup/init_lite/interfaces/innerkits/fd_holder",
"//base/startup/init_lite/interfaces/hals",
]
sources = sysparam_source
......
......@@ -651,14 +651,6 @@ static void CheckService(const cJSON* curItem)
cJSON *capJ = cJSON_GetArrayItem(filedJ, i);
EXPECT_TRUE(cJSON_IsNumber(capJ));
EXPECT_TRUE(cJSON_GetNumberValue(capJ) >= 0.0);
// only shell can have all capabilities
if ((unsigned int)cJSON_GetNumberValue(capJ) == MAX_CAPABILITY_VALUE) {
if (nameStr != nullptr) {
EXPECT_EQ(0, strcmp(nameStr, "shell"));
}
EXPECT_EQ(1, capsCnt);
}
}
}
......
......@@ -20,6 +20,7 @@
#include "param_manager.h"
#include "param_security.h"
#include "param_utils.h"
#include "init_group_manager.h"
#ifdef PARAM_LOAD_CFG_FROM_CODE
#include "param_cfg.h"
#endif
......@@ -209,6 +210,35 @@ static void PrepareInnerKitsCfg()
CreateTestFile("/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable", innerKitsCfg);
CreateTestFile("/etc/fstab.required", "test");
}
static void PrepareGroupTestCfg()
{
const char *data = "{"
"\"jobs\": [\"param:job1\", \"param:job2\", \"param:job4\"],"
"\"services\": [\"service:service1\", \"service:service3\", \"service:service2\"],"
"\"groups\": [\"subsystem.xxx1.group\", \"subsystem.xxx2.group\", \"subsystem.xxx4.group\"]"
"}";
const char *xxx1 = "{"
"\"groups\": [\"subsystem.xxx11.group\""
"}";
const char *xxx11 = "{"
"\"groups\": [\"subsystem.xxx12.group\""
"}";
const char *xxx12 = "{"
"\"groups\": [\"subsystem.xxx13.group\""
"}";
const char *xxx13 = "{"
"\"groups\": [\"subsystem.xxx14.group\""
"}";
const char *xxx14 = "{"
"\"groups\": [\"subsystem.xxx11.group\""
"}";
CreateTestFile(GROUP_DEFAULT_PATH "/device.boot.group.cfg", data);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx1.group.cfg", xxx1);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx11.group.cfg", xxx11);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx12.group.cfg", xxx12);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx13.group.cfg", xxx13);
CreateTestFile(GROUP_DEFAULT_PATH "/subsystem.xxx14.group.cfg", xxx14);
}
static bool IsDir(const std::string &path)
{
struct stat st {};
......@@ -319,12 +349,14 @@ void PrepareInitUnitTestEnv(void)
PrepareUeventdcfg();
PrepareInnerKitsCfg();
PrepareModCfg();
PrepareGroupTestCfg();
SetInitLogLevel(INIT_FATAL);
#if !(defined __LITEOS_A__ || defined __LITEOS_M__)
// for cmdline
const char *cmdLine = "bootgroup=device.charge.group earlycon=uart8250,mmio32,0xfe660000 \
root=PARTUUID=614e0000-0000 rw rootwait rootfstype=ext4 console=ttyFIQ0 hardware=rk3568";
const char *cmdLine = "bootgroup=device.charge.group earlycon=uart8250,mmio32,0xfe660000 "
"root=PARTUUID=614e0000-0000 rw rootwait rootfstype=ext4 console=ttyFIQ0 hardware=rk3568"
" BOOT_IMAGE=/kernel init=/init ohos.required_mount.test=test";
CreateTestFile(BOOT_CMD_LINE, cmdLine);
// for dac
......
......@@ -18,10 +18,17 @@
#include "param_message.h"
#include "param_stub.h"
#include "trigger_manager.h"
#include "param_utils.h"
#include "param_osadp.h"
#include "param_manager.h"
using namespace testing::ext;
using namespace std;
extern "C" {
int WorkSpaceNodeCompare(const HashNode *node1, const HashNode *node2);
}
static void OnClose(ParamTaskPtr client)
{
UNUSED(client);
......@@ -389,4 +396,29 @@ HWTEST_F(ParamUnitTest, TestDumpParamMemory, TestSize.Level0)
ParamUnitTest test;
test.TestDumpParamMemory();
}
HWTEST_F(ParamUnitTest, TestLinuxRWLock, TestSize.Level0)
{
ParamRWMutexCreate(nullptr);
ParamRWMutexWRLock(nullptr);
ParamRWMutexRDLock(nullptr);
ParamRWMutexUnlock(nullptr);
ParamRWMutexDelete(nullptr);
ParamMutexDelete(nullptr);
WorkSpace *workspace1 = (WorkSpace *)malloc(sizeof(WorkSpace) + strlen("testfilename1"));
WorkSpace *workspace2 = (WorkSpace *)malloc(sizeof(WorkSpace) + strlen("testfilename1"));
if (strcpy_s(workspace1->fileName, strlen("testfilename1"), "testfilename") != EOK) {
EXPECT_EQ(0, 1);
}
if (strcpy_s(workspace2->fileName, strlen("testfilename1"), "testfilename") != EOK) {
EXPECT_EQ(0, 1);
}
EXPECT_EQ(WorkSpaceNodeCompare(&(workspace1->hashNode), &(workspace2->hashNode)), 0);
EXPECT_NE(GetPersistCommitId(), -1);
EXPECT_NE(GetPersistCommitId(), -1);
EXPECT_STREQ(GetServiceCtrlName("ohos.ctl.start", "test"), "ohos.servicectrl.test");
EXPECT_STREQ(GetServiceCtrlName("ohos.startup.powerctrl", "reboot"), "ohos.servicectrl.reboot");
EXPECT_STREQ(GetServiceCtrlName("ohos.servicectrl.", "test"), "ohos.servicectrl..test");
free(workspace1);
free(workspace2);
}
}
......@@ -18,6 +18,7 @@
#include "param_message.h"
#include "param_stub.h"
#include "trigger_manager.h"
#include "le_timer.h"
using namespace testing::ext;
using namespace std;
......@@ -427,6 +428,9 @@ public:
AddWatch(MSG_ADD_WATCHER, name, value);
char buffer[] = "testbuff";
CheckTrigger(GetTriggerWorkSpace(), TRIGGER_PARAM_WATCH, buffer, strlen(buffer), TestTriggerExecute);
#ifdef PARAM_SUPPORT_TRIGGER
SystemDumpTriggers(1);
#endif
AddWatch(MSG_DEL_WATCHER, name, value);
return 0;
}
......@@ -507,6 +511,11 @@ HWTEST_F(ParamServiceUnitTest, TestAddParamWatch3, TestSize.Level0)
{
ParamServiceUnitTest test;
test.TestAddParamWatch3();
if (GetParamService()->timer != nullptr) {
((TimerTask *)GetParamService()->timer)->processTimer(nullptr, nullptr);
}
int hashCode = CheckWatchTriggerTimeout();
EXPECT_EQ(hashCode, 0);
}
HWTEST_F(ParamServiceUnitTest, TestCloseTriggerWatch, TestSize.Level0)
......
......@@ -137,6 +137,16 @@ public:
EXPECT_EQ(ret, 0);
ret = clientParamSercurityOps.securityFreeLabel(&srclabel);
EXPECT_EQ(ret, 0);
int fd = open("/bin/updater", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, S_IRWXU);
if (fd < 0) {
return 0;
}
RegisterSecuritySelinuxOps(&clientParamSercurityOps, 0);
if (clientParamSercurityOps.securityCheckParamPermission != nullptr) {
clientParamSercurityOps.securityCheckParamPermission(nullptr, nullptr, 0);
}
close(fd);
unlink("/bin/updater");
return 0;
}
......
......@@ -17,6 +17,7 @@
#include "init_jobs_internal.h"
#include "init_param.h"
#include "init_utils.h"
#include "init_hashmap.h"
#include "loop_event.h"
#include "param_manager.h"
#include "param_stub.h"
......@@ -466,9 +467,9 @@ public:
int TestDumpTrigger()
{
SystemDumpTriggers(1);
RegisterBootStateChange(BootStateChange);
(void)AddCompleteJob("param:ohos.servicectrl.display", "ohos.servicectrl.display=*", "display system");
HashMapDestory(GetTriggerWorkSpace()->hashMap);
return 0;
}
};
......
......@@ -18,9 +18,14 @@
#include "init_param.h"
#include "parameter.h"
#include "sysparam_errno.h"
#include "param_comm.h"
#include "param_wrapper.h"
#include "sysversion.h"
using namespace testing::ext;
extern "C" {
int GetIntParameter(const char *key, int def);
}
namespace OHOS {
class SysparaUnitTest : public testing::Test {
public:
......@@ -30,7 +35,6 @@ public:
void TearDown() {}
};
HWTEST_F(SysparaUnitTest, parameterTest001, TestSize.Level0)
{
printf("Device type =%s\n", GetDeviceType());
......@@ -261,4 +265,29 @@ HWTEST_F(SysparaUnitTest, parameterTest0012, TestSize.Level0)
ret = GetParameterName(handle, nameGet1, 32);
EXPECT_EQ(ret, -1);
}
HWTEST_F(SysparaUnitTest, parameterTest0013, TestSize.Level0)
{
long long int out = 0;
unsigned long long int uout = 0;
char key1[] = "test.int";
char value1[] = "101";
int ret = SetParameter(key1, value1);
EXPECT_EQ(ret, 0);
GetParameter_(nullptr, nullptr, nullptr, 0);
EXPECT_EQ(GetIntParameter(key1, 0), 0);
EXPECT_EQ(IsValidParamValue(nullptr, 0), 0);
EXPECT_EQ(IsValidParamValue("testvalue", strlen("testvalue") + 1), 1);
EXPECT_EQ(StringToLL("0x11", &out), 0);
EXPECT_EQ(StringToULL("0x11", &uout), 0);
EXPECT_EQ(StringToLL("not vailed", &out), -1);
EXPECT_EQ(StringToULL("not vailed", &uout), -1);
SystemSetParameter("ohos.boot.sn", "1");
char udid[UDID_LEN] = {0};
ret = GetDevUdid(udid, UDID_LEN);
EXPECT_NE(ret, -1);
EXPECT_NE(GetMajorVersion(), 0);
GetSeniorVersion();
GetFeatureVersion();
GetBuildVersion();
}
} // namespace OHOS
......@@ -96,6 +96,13 @@ if (defined(ohos_lite)) {
]
}
#
# exported include directories
#
config("libueventd_exported_config") {
visibility = [ ":*" ]
include_dirs = [ "./include" ]
}
ohos_static_library("libueventd_ramdisk_static") {
sources = service_ueventd_sources
include_dirs = service_ueventd_include
......@@ -107,6 +114,8 @@ if (defined(ohos_lite)) {
external_deps = [ "selinux:librestorecon" ]
cflags += [ "-DWITH_SELINUX" ]
}
public_configs = [ ":libueventd_exported_config" ]
part_name = "init"
}
......
......@@ -20,7 +20,12 @@
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <fcntl.h>
#include <unistd.h>
#include "ueventd_device_handler.h"
#include "ueventd_firmware_handler.h"
#include "ueventd_read_cfg.h"
......@@ -119,6 +124,48 @@ static void HandleUevent(const struct Uevent *uevent)
}
}
#define DEFAULT_RW_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
typedef struct {
const char *dev;
mode_t mode;
} DYNAMIC_DEVICE_NODE;
#define DEV_NODE_PATH_PREFIX "/dev/"
#define DEV_NODE_PATH_PREFIX_LEN 5
static const DYNAMIC_DEVICE_NODE dynamicDevices[] = {
{ DEV_NODE_PATH_PREFIX"tty", S_IFCHR | DEFAULT_RW_MODE },
{ DEV_NODE_PATH_PREFIX"binder", S_IFCHR | DEFAULT_RW_MODE }
};
static void HandleRequiredDynamicDeviceNodes(const struct Uevent *uevent)
{
mode_t mask;
int idx = 0;
if (uevent->deviceName == NULL) {
return;
}
while (idx < sizeof(dynamicDevices)/sizeof(dynamicDevices[0])) {
if (strcmp(uevent->deviceName, dynamicDevices[idx].dev + DEV_NODE_PATH_PREFIX_LEN) != 0) {
idx++;
continue;
}
// Matched
mask = umask(0);
if (mknod(dynamicDevices[idx].dev, dynamicDevices[idx].mode,
makedev(uevent->major, uevent->minor)) != 0) {
INIT_LOGE("Create device node %s failed. %s", dynamicDevices[idx].dev, strerror(errno));
}
// Restore umask
umask(mask);
break;
}
}
static void HandleUeventRequired(const struct Uevent *uevent, char **devices, int num)
{
const char *deviceName;
......@@ -146,6 +193,10 @@ static void HandleUeventRequired(const struct Uevent *uevent, char **devices, in
break;
}
}
return;
}
if ((type == SUBSYSTEM_OTHERS) && (num > 0)) {
HandleRequiredDynamicDeviceNodes(uevent);
}
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册