提交 5f8198d2 编写于 作者: C cheng_jinsong 提交者: Gitee

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

Signed-off-by: Ncheng_jinsong <chengjinsong2@huawei.com>
......@@ -18,6 +18,7 @@
#endif
#include "param_comm.h"
#include "securec.h"
#include "sysparam_errno.h"
#ifdef __cplusplus
#if __cplusplus
......@@ -28,7 +29,7 @@ extern "C" {
int AclGetDevUdid(char *udid, int size)
{
if (udid == nullptr || size < UDID_LEN) {
return -1;
return SYSPARAM_INVALID_INPUT;
}
(void)memset_s(udid, size, 0, size);
#ifdef PARAM_FEATURE_DEVICEINFO
......
......@@ -23,6 +23,7 @@
#include "string_ex.h"
#include "system_ability_definition.h"
#include "param_comm.h"
#include "sysparam_errno.h"
using std::u16string;
namespace OHOS {
......@@ -35,15 +36,15 @@ REGISTER_SYSTEM_ABILITY_BY_ID(DeviceInfoService, SYSPARAM_DEVICE_SERVICE_ID, tru
int32_t DeviceInfoStub::OnRemoteRequest(uint32_t code,
MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
std::u16string myDescripter = IDeviceInfo::GetDescriptor();
std::u16string remoteDescripter = data.ReadInterfaceToken();
DINFO_CHECK(myDescripter == remoteDescripter, return ERR_INVALD_DESC, "Invalid remoteDescripter");
std::u16string myDescriptor = IDeviceInfo::GetDescriptor();
std::u16string remoteDescriptor = data.ReadInterfaceToken();
DINFO_CHECK(myDescriptor == remoteDescriptor, return ERR_FAIL, "Invalid remoteDescriptor");
int ret = ERR_FAIL;
switch (code) {
case COMMAND_GET_UDID: {
if (!CheckPermission(data, PERMISSION_UDID)) {
return ERR_FAIL;
return SYSPARAM_PERMISSION_DENIED;
}
char localDeviceInfo[UDID_LEN] = {0};
ret = GetDevUdid_(localDeviceInfo, UDID_LEN);
......@@ -53,7 +54,7 @@ int32_t DeviceInfoStub::OnRemoteRequest(uint32_t code,
}
case COMMAND_GET_SERIAL_ID: {
if (!CheckPermission(data, PERMISSION_UDID)) {
return ERR_FAIL;
return SYSPARAM_PERMISSION_DENIED;
}
const char *serialNumber = GetSerial_();
DINFO_CHECK(serialNumber != nullptr, break, "Failed to get serialNumber");
......
......@@ -33,7 +33,6 @@ public:
static constexpr int COMMAND_GET_UDID = MIN_TRANSACTION_ID + 0;
static constexpr int COMMAND_GET_SERIAL_ID = MIN_TRANSACTION_ID + 1;
static constexpr int ERR_FAIL = -1;
static constexpr int ERR_INVALD_DESC = -1;
const std::string PERMISSION_UDID = "ohos.permission.sec.ACCESS_UDID";
};
} // namespace device_info
......
......@@ -50,6 +50,7 @@ static unsigned int ConvertFlags(char *flagBuffer)
{"check", FS_MANAGER_CHECK},
{"wait", FS_MANAGER_WAIT},
{"required", FS_MANAGER_REQUIRED},
{"nofail", FS_MANAGER_NOFAIL},
};
BEGET_CHECK_RETURN_VALUE(flagBuffer != NULL && *flagBuffer != '\0', 0); // No valid flags.
......
......@@ -37,7 +37,7 @@ extern "C" {
#define FS_MANAGER_BUFFER_SIZE 512
#define BLOCK_SIZE_BUFFER (64)
#define RESIZE_BUFFER_SIZE 1024
const off_t MISC_PARTITION_ACTIVE_SLOT_OFFSET = 1400;
const off_t MISC_PARTITION_ACTIVE_SLOT_OFFSET = 4096;
const off_t MISC_PARTITION_ACTIVE_SLOT_SIZE = 4;
bool IsSupportedFilesystem(const char *fsType)
......@@ -61,6 +61,7 @@ static int ExecCommand(int argc, char **argv)
if (argc == 0 || argv == NULL || argv[0] == NULL) {
return -1;
}
BEGET_LOGI("Execute %s begin", argv[0]);
pid_t pid = fork();
if (pid < 0) {
BEGET_LOGE("Fork new process to format failed: %d", errno);
......@@ -75,6 +76,7 @@ static int ExecCommand(int argc, char **argv)
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
BEGET_LOGE("Command %s failed with status %d", argv[0], WEXITSTATUS(status));
}
BEGET_LOGI("Execute %s end", argv[0]);
return WEXITSTATUS(status);
}
......@@ -192,7 +194,6 @@ static int DoResizeF2fs(const char* device, const unsigned long long size)
char **argv = (char **)cmd;
ret = ExecCommand(argc, argv);
}
BEGET_LOGI("resize.f2fs is ending.");
return ret;
}
......@@ -209,7 +210,6 @@ static int DoFsckF2fs(const char* device)
};
int argc = ARRAY_LENGTH(cmd);
char **argv = (char **)cmd;
BEGET_LOGI("fsck.f2fs is ending.");
return ExecCommand(argc, argv);
}
......@@ -242,7 +242,6 @@ static int DoResizeExt(const char* device, const unsigned long long size)
char **argv = (char **)cmd;
ret = ExecCommand(argc, argv);
}
BEGET_LOGI("resize2fs is ending.");
return ret;
}
......@@ -259,7 +258,6 @@ static int DoFsckExt(const char* device)
};
int argc = ARRAY_LENGTH(cmd);
char **argv = (char **)cmd;
BEGET_LOGI("e2fsck is ending.");
return ExecCommand(argc, argv);
}
......@@ -287,15 +285,8 @@ static int Mount(const char *source, const char *target, const char *fsType,
}
}
errno = 0;
while ((rc = mount(source, target, fsType, flags, data)) != 0) {
if (errno == EAGAIN) {
BEGET_LOGE("Mount %s to %s failed. try again", source, target);
continue;
}
if (errno == EBUSY) {
rc = 0;
}
break;
if ((rc = mount(source, target, fsType, flags, data)) != 0) {
BEGET_WARNING_CHECK(errno != EBUSY, rc = 0, "Mount %s to %s busy, ignore", source, target);
}
return rc;
}
......@@ -406,7 +397,12 @@ int MountOneItem(FstabItem *item)
int rc = Mount(item->deviceName, item->mountPoint, item->fsType, mountFlags, fsSpecificData);
if (rc != 0) {
BEGET_LOGE("Mount %s to %s failed %d", item->deviceName, item->mountPoint, errno);
if (FM_MANAGER_NOFAIL_ENABLED(item->fsManagerFlags)) {
BEGET_LOGE("Mount no fail device %s to %s failed, err = %d", item->deviceName, item->mountPoint, errno);
} else {
BEGET_LOGW("Mount %s to %s failed, err = %d. Ignore failure", item->deviceName, item->mountPoint, errno);
rc = 0;
}
} else {
BEGET_LOGI("Mount %s to %s successful", item->deviceName, item->mountPoint);
}
......
......@@ -51,9 +51,11 @@ typedef void (*InitCommLog)(int logLevel, uint32_t domain, const char *tag, cons
#define FILE_NAME (strrchr((__FILE__), '/') ? strrchr((__FILE__), '/') + 1 : (__FILE__))
INIT_PUBLIC_API void StartupLog(InitLogLevel logLevel, uint32_t domain, const char *tag, const char *fmt, ...);
INIT_PUBLIC_API void EnableInitLog(void);
INIT_PUBLIC_API void EnableInitLog(InitLogLevel level);
INIT_PUBLIC_API void SetInitLogLevel(InitLogLevel level);
INIT_PUBLIC_API int GetInitLogLevel(void);
INIT_PUBLIC_API void SetInitCommLog(InitCommLog logFunc);
INIT_PUBLIC_API void EnableInitLogFromCmdline(void);
#define STARTUP_LOGV(domain, tag, fmt, ...) \
StartupLog(INIT_DEBUG, domain, tag, "[%s:%d]" fmt, (FILE_NAME), (__LINE__), ##__VA_ARGS__)
......
......@@ -29,6 +29,7 @@ extern "C" {
#define FS_MANAGER_CHECK 0x00000001
#define FS_MANAGER_WAIT 0x00000002
#define FS_MANAGER_REQUIRED 0x00000004
#define FS_MANAGER_NOFAIL 0x00000008
#define NAME_SIZE 32
#define MAX_SLOT 2
......@@ -38,6 +39,7 @@ extern "C" {
#define FM_MANAGER_CHECK_ENABLED(fsMgrFlags) FS_MANAGER_FLAGS_ENABLED((fsMgrFlags), CHECK)
#define FM_MANAGER_WAIT_ENABLED(fsMgrFlags) FS_MANAGER_FLAGS_ENABLED((fsMgrFlags), WAIT)
#define FM_MANAGER_REQUIRED_ENABLED(fsMgrFlags) FS_MANAGER_FLAGS_ENABLED((fsMgrFlags), REQUIRED)
#define FM_MANAGER_NOFAIL_ENABLED(fsMgrFlags) FS_MANAGER_FLAGS_ENABLED((fsMgrFlags), NOFAIL)
typedef enum MountStatus {
MOUNT_ERROR = -1,
......
......@@ -28,6 +28,13 @@ enum OHOSStartUpSysParamErrorCode {
EC_FAILURE = -1, /* Execution failed */
EC_INVALID = -9, /* Invalid argument */
EC_SYSTEM_ERR = -10, /* system error */
SYSPARAM_INVALID_INPUT = -401, /*Input parameter is missing or invalid*/
SYSPARAM_NOT_FOUND = -14700101, /*System parameter can not be found.*/
SYSPARAM_INVALID_VALUE = -14700102, /*System parameter value is invalid*/
SYSPARAM_PERMISSION_DENIED = -14700103, /*System permission operation permission denied*/
SYSPARAM_SYSTEM_ERROR = -14700104, /* System internal error including out of memory, deadlock etc.*/
SYSPARAM_WAIT_TIMEOUT = -14700105, /* System wait parameter value change time out.*/
};
#ifdef __cplusplus
......
......@@ -57,7 +57,11 @@ static int DoReboot_(const char *option)
int DoReboot(const char *option)
{
// check if param set ok
#ifndef STARTUP_INIT_TEST
const int maxCount = 10;
#else
const int maxCount = 1;
#endif
int count = 0;
DoReboot_(option);
while (count < maxCount) {
......
......@@ -16,7 +16,10 @@ import("//build/ohos.gni")
config("exported_header_files") {
visibility = [ ":*" ]
include_dirs = [ "//base/startup/init/interfaces/innerkits/sandbox/include" ]
include_dirs = [
"//base/startup/init/interfaces/innerkits/sandbox/include",
"//base/customization/config_policy/interfaces/inner_api/include",
]
}
ohos_static_library("sandbox") {
......
......@@ -21,33 +21,33 @@ extern "C" {
#endif
#include <stdbool.h>
#include "init_utils.h"
#include "list.h"
typedef struct {
typedef enum SandboxTag {
SANDBOX_TAG_MOUNT_PATH = 0,
SANDBOX_TAG_MOUNT_FILE,
SANDBOX_TAG_SYMLINK
} SandboxTag;
typedef struct MountList {
char *source; // source 目录,一般是全局的fs 目录
char *target; // 沙盒化后的目录
unsigned long flags;
bool ignoreErrors;
} mount_t;
typedef struct MountList {
mount_t *info;
struct MountList *next;
SandboxTag tag;
struct ListNode node;
} mountlist_t;
typedef struct {
typedef struct LinkList {
char *target;
char *linkName;
} linker_t;
typedef struct LinkList {
linker_t *info;
struct LinkList *next;
struct ListNode node;
} linklist_t;
typedef struct {
mountlist_t *pathMounts;
mountlist_t *fileMounts;
linklist_t *links;
ListNode pathMountsHead;
ListNode fileMountsHead;
ListNode linksHead;
char *rootPath; // /mnt/sandbox/system|vendor|xxx
char name[MAX_BUFFER_LEN]; // name of sandbox. i.e system, chipset etc.
bool isCreated; // sandbox already created or not
......
......@@ -26,12 +26,40 @@
#include "sysparam_errno.h"
#ifdef USE_MBEDTLS
#include "mbedtls/sha256.h"
#elif !(defined OHOS_LITE)
#include "openssl/sha.h"
#endif
#include "securec.h"
#include "beget_ext.h"
INIT_LOCAL_API int GetSystemError(int err)
{
switch(err) {
case 0:
return 0;
case PARAM_CODE_INVALID_PARAM:
case PARAM_CODE_INVALID_NAME:
case PARAM_CODE_READ_ONLY:
return EC_INVALID;
case PARAM_CODE_INVALID_VALUE:
return SYSPARAM_INVALID_VALUE;
case PARAM_CODE_NOT_FOUND:
case PARAM_CODE_NODE_EXIST:
return SYSPARAM_NOT_FOUND;
case DAC_RESULT_FORBIDED:
return SYSPARAM_PERMISSION_DENIED;
case PARAM_CODE_REACHED_MAX:
case PARAM_CODE_FAIL_CONNECT:
case PARAM_CODE_INVALID_SOCKET:
case PARAM_CODE_NOT_SUPPORT:
return SYSPARAM_SYSTEM_ERROR;
case PARAM_CODE_TIMEOUT:
return SYSPARAM_WAIT_TIMEOUT;
default:
return SYSPARAM_SYSTEM_ERROR;
}
return 0;
}
INIT_LOCAL_API int IsValidParamValue(const char *value, uint32_t len)
{
if ((value == NULL) || (strlen(value) + 1 > len)) {
......@@ -48,7 +76,10 @@ INIT_LOCAL_API int GetParameter_(const char *key, const char *def, char *value,
uint32_t size = len;
int ret = SystemGetParameter(key, NULL, &size);
if (ret != 0) {
if (def == NULL || strlen(def) > len) {
if (def == NULL) {
return GetSystemError(ret);
}
if (strlen(def) > len) {
return EC_INVALID;
}
ret = strcpy_s(value, len, def);
......@@ -56,8 +87,10 @@ INIT_LOCAL_API int GetParameter_(const char *key, const char *def, char *value,
} else if (size > len) {
return EC_INVALID;
}
size = len;
return (SystemGetParameter(key, value, &size) == 0) ? EC_SUCCESS : EC_FAILURE;
ret = SystemGetParameter(key, value, &size);
return GetSystemError(ret);
}
INIT_LOCAL_API const char *GetProperty(const char *key, const char **paramHolder)
......@@ -118,27 +151,6 @@ static int GetSha256Value(const char *input, char *udid, int udidSize)
}
return EC_SUCCESS;
}
#elif !(defined OHOS_LITE)
static int GetSha256Value(const char *input, char *udid, int udidSize)
{
char buf[DEV_BUF_LENGTH] = { 0 };
unsigned char hash[SHA256_DIGEST_LENGTH] = { 0 };
SHA256_CTX sha256;
if ((SHA256_Init(&sha256) == 0) || (SHA256_Update(&sha256, input, strlen(input)) == 0) ||
(SHA256_Final(hash, &sha256) == 0)) {
return -1;
}
for (size_t i = 0; i < SHA256_DIGEST_LENGTH; i++) {
unsigned char value = hash[i];
(void)memset_s(buf, DEV_BUF_LENGTH, 0, DEV_BUF_LENGTH);
int len = sprintf_s(buf, sizeof(buf), "%02X", value);
if (len > 0 && strcat_s(udid, udidSize, buf) != 0) {
return -1;
}
}
return 0;
}
#else
static int GetSha256Value(const char *input, char *udid, int udidSize)
{
......@@ -170,6 +182,11 @@ INIT_LOCAL_API int GetDevUdid_(char *udid, int size)
if (size < UDID_LEN || udid == NULL) {
return EC_FAILURE;
}
uint32_t len = size;
int ret = SystemGetParameter("const.product.udid", udid, &len);
BEGET_CHECK(ret != 0, return ret);
const char *manufacture = GetManufacture_();
const char *model = GetProductModel_();
const char *sn = GetSerial_();
......@@ -190,7 +207,7 @@ INIT_LOCAL_API int GetDevUdid_(char *udid, int size)
return -1;
}
int ret = GetSha256Value(tmp, udid, size);
ret = GetSha256Value(tmp, udid, size);
free(tmp);
return ret;
}
......
......@@ -40,6 +40,7 @@ INIT_LOCAL_API int GetDevUdid_(char *udid, int size);
INIT_LOCAL_API int IsValidParamValue(const char *value, uint32_t len);
INIT_LOCAL_API const char *GetFullName_(void);
INIT_LOCAL_API int GetSystemError(int err);
#ifdef __cplusplus
#if __cplusplus
}
......
......@@ -163,7 +163,7 @@ std::string GetDeviceType(void)
{"fitnessWatch", "liteWearable"},
};
static const char *productType = nullptr;
const char *type = GetProperty("const.build.devicetype", &productType);
const char *type = GetProperty("const.product.devicetype", &productType);
if (type == nullptr) {
type = GetProperty("const.build.characteristics", &productType);
}
......
......@@ -28,7 +28,8 @@
int WaitParameter(const char *key, const char *value, int timeout)
{
BEGET_CHECK(!(key == NULL || value == NULL), return EC_INVALID);
return SystemWaitParameter(key, value, timeout);
int ret = SystemWaitParameter(key, value, timeout);
return GetSystemError(ret);
}
uint32_t FindParameter(const char *key)
......@@ -56,7 +57,10 @@ int GetParameterName(uint32_t handle, char *name, uint32_t len)
return EC_INVALID;
}
int ret = SystemGetParameterName(handle, name, len);
return (ret != 0) ? EC_FAILURE : strlen(name);
if (ret == 0) {
return strlen(name);
}
return GetSystemError(ret);
}
int GetParameterValue(uint32_t handle, char *value, uint32_t len)
......@@ -66,7 +70,10 @@ int GetParameterValue(uint32_t handle, char *value, uint32_t len)
}
uint32_t size = len;
int ret = SystemGetParameterValue(handle, value, &size);
return (ret != 0) ? EC_FAILURE : strlen(value);
if (ret == 0) {
return strlen(value);
}
return GetSystemError(ret);
}
int GetParameter(const char *key, const char *def, char *value, uint32_t len)
......@@ -84,17 +91,13 @@ int SetParameter(const char *key, const char *value)
return EC_INVALID;
}
int ret = SystemSetParameter(key, value);
if (ret == PARAM_CODE_INVALID_NAME || ret == DAC_RESULT_FORBIDED ||
ret == PARAM_CODE_INVALID_PARAM || ret == PARAM_CODE_INVALID_VALUE) {
return EC_INVALID;
}
return (ret == 0) ? EC_SUCCESS : EC_FAILURE;
return GetSystemError(ret);
}
const char *GetDeviceType(void)
{
static const char *productType = NULL;
const char *deviceType = GetProperty("const.build.devicetype", &productType);
const char *deviceType = GetProperty("const.product.devicetype", &productType);
if (deviceType != NULL) {
return deviceType;
}
......@@ -320,14 +323,14 @@ int32_t GetIntParameter(const char *key, int32_t def)
{
char value[MAX_INT_LEN] = {0};
int ret = GetParameter(key, "0", value, sizeof(value));
if (ret != 0) {
if (ret < 0) {
return def;
}
long long int result = 0;
if (StringToLL(value, &result) != 0) {
return def;
}
if (result <= INT32_MIN && result >= INT32_MAX) {
if (result <= INT32_MIN || result >= INT32_MAX) {
return def;
}
return (int32_t)result;
......@@ -337,7 +340,7 @@ uint32_t GetUintParameter(const char *key, uint32_t def)
{
char value[MAX_INT_LEN] = {0};
int ret = GetParameter(key, "0", value, sizeof(value));
if (ret != 0) {
if (ret < 0) {
return def;
}
unsigned long long int result = 0;
......
......@@ -24,6 +24,7 @@ group("kitsgroup") {
deps += [
"jskits:deviceinfo",
"jskits:systemparameter",
"jskits:systemparameterv9",
]
}
}
......
......@@ -49,3 +49,22 @@ ohos_shared_library("systemparameter") {
subsystem_name = "startup"
part_name = "init"
}
ohos_shared_library("systemparameterv9") {
include_dirs = [
"src",
"//third_party/libuv/include",
]
sources = [ "src_v9/native_parameters_js.cpp" ]
deps = [
"//base/startup/init/interfaces/innerkits:libbeget_proxy",
"//base/startup/init/interfaces/innerkits:libbegetutil",
]
external_deps = [ "napi:ace_napi" ]
relative_install_dir = "module"
subsystem_name = "startup"
part_name = "init"
}
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "native_parameters_js.h"
#include "sysparam_errno.h"
static constexpr int ARGC_NUMBER = 2;
static constexpr int ARGC_THREE_NUMBER = 3;
static constexpr int MAX_NAME_LENGTH = 128;
static constexpr int MAX_VALUE_LENGTH = PARAM_CONST_VALUE_LEN_MAX;
using StorageAsyncContext = struct StorageAsyncContext {
napi_env env = nullptr;
napi_async_work work = nullptr;
char key[MAX_NAME_LENGTH] = { 0 };
size_t keyLen = 0;
char value[MAX_VALUE_LENGTH] = { 0 };
size_t valueLen = 0;
napi_deferred deferred = nullptr;
napi_ref callbackRef = nullptr;
int status = -1;
std::string getValue;
};
using StorageAsyncContextPtr = StorageAsyncContext *;
static int GetErrorInfo(int status, std::string &errMsg)
{
switch(status) {
case EC_FAILURE:
case EC_SYSTEM_ERR:
case SYSPARAM_SYSTEM_ERROR:
errMsg = "System internal error including out of memory, deadlock etc";
return -SYSPARAM_SYSTEM_ERROR;
case EC_INVALID:
case SYSPARAM_INVALID_INPUT:
errMsg = "Input parameter is missing or invalid";
return -SYSPARAM_INVALID_INPUT;
case SYSPARAM_PERMISSION_DENIED:
errMsg = "System permission operation permission denied";
return -SYSPARAM_PERMISSION_DENIED;
case SYSPARAM_NOT_FOUND:
errMsg = "System parameter can not be found";
return -SYSPARAM_NOT_FOUND;
case SYSPARAM_INVALID_VALUE:
errMsg = "System parameter value is invalid";
return -SYSPARAM_INVALID_VALUE;
default:
errMsg = "System internal error including out of memory, deadlock etc";
return -SYSPARAM_SYSTEM_ERROR;
}
return 0;
}
static napi_value BusinessErrorCreate(napi_env env, int status)
{
std::string errMsg = "";
int ret = GetErrorInfo(status, errMsg);
PARAM_JS_LOGV("BusinessErrorCreate status %d err %d msg: %s", status, ret, errMsg.c_str());
napi_value code = nullptr;
napi_create_int32(env, ret, &code);
napi_value msg = nullptr;
napi_create_string_utf8(env, errMsg.c_str(), NAPI_AUTO_LENGTH, &msg);
napi_value businessError = nullptr;
napi_create_error(env, nullptr, msg, &businessError);
napi_set_named_property(env, businessError, "code", code);
return businessError;
}
#define PARAM_NAPI_ASSERT(env, assertion, result, info) \
do { \
if (!(assertion)) { \
napi_value d_err = BusinessErrorCreate(env, result); \
napi_throw(env, d_err); \
return nullptr; \
} \
} while (0)
static int GetParamString(napi_env env, napi_value arg, char *buffer, size_t maxBuff, size_t *keySize)
{
(void)napi_get_value_string_utf8(env, arg, nullptr, maxBuff - 1, keySize);
if (*keySize >= maxBuff || *keySize == 0) {
return SYSPARAM_INVALID_INPUT;
}
(void)napi_get_value_string_utf8(env, arg, buffer, maxBuff - 1, keySize);
return 0;
}
static void SetCallbackWork(napi_env env, StorageAsyncContextPtr asyncContext)
{
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSStartupSet", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(
env, nullptr, resource,
[](napi_env env, void *data) {
StorageAsyncContext *asyncContext = (StorageAsyncContext *)data;
asyncContext->status = SetParameter(asyncContext->key, asyncContext->value);
PARAM_JS_LOGV("JSApp set status: %d, key: '%s', value: '%s'.",
asyncContext->status, asyncContext->key, asyncContext->value);
},
[](napi_env env, napi_status status, void *data) {
StorageAsyncContext *asyncContext = (StorageAsyncContext *)data;
napi_value result[ARGC_NUMBER] = { 0 };
if (asyncContext->status == 0) {
napi_get_undefined(env, &result[0]);
napi_get_undefined(env, &result[1]);
} else {
result[0] = BusinessErrorCreate(env, asyncContext->status);
napi_get_undefined(env, &result[1]);
}
if (asyncContext->deferred) {
if (asyncContext->status == 0) {
napi_resolve_deferred(env, asyncContext->deferred, result[1]);
} else {
napi_reject_deferred(env, asyncContext->deferred, result[0]);
}
} else {
napi_value callback = nullptr;
napi_value callResult = nullptr;
napi_get_reference_value(env, asyncContext->callbackRef, &callback);
napi_call_function(env, nullptr, callback, ARGC_NUMBER, result, &callResult);
napi_delete_reference(env, asyncContext->callbackRef);
}
napi_delete_async_work(env, asyncContext->work);
delete asyncContext;
},
(void *)asyncContext, &asyncContext->work);
napi_queue_async_work(env, asyncContext->work);
}
static napi_value Set(napi_env env, napi_callback_info info)
{
size_t argc = ARGC_THREE_NUMBER;
napi_value argv[ARGC_THREE_NUMBER] = { nullptr };
napi_value thisVar = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, &argc, argv, &thisVar, &data);
PARAM_NAPI_ASSERT(env, argc >= ARGC_NUMBER, SYSPARAM_INVALID_INPUT, "requires 2 parameter");
StorageAsyncContextPtr asyncContext = new StorageAsyncContext();
asyncContext->env = env;
for (size_t i = 0; i < argc; i++) {
napi_valuetype valueType = napi_null;
napi_typeof(env, argv[i], &valueType);
int ret = 0;
if (i == 0 && valueType == napi_string) {
ret = GetParamString(env, argv[i], asyncContext->key, MAX_NAME_LENGTH, &asyncContext->keyLen);
} else if (i == 1 && valueType == napi_string) {
ret = GetParamString(env, argv[i], asyncContext->value, MAX_VALUE_LENGTH, &asyncContext->valueLen);
} else if (i == ARGC_NUMBER && valueType == napi_function) {
napi_create_reference(env, argv[i], 1, &asyncContext->callbackRef);
} else {
delete asyncContext;
ret = SYSPARAM_INVALID_INPUT;
}
if (ret != 0) {
ret = (i == 1) ? SYSPARAM_INVALID_VALUE : ret;
napi_value err = BusinessErrorCreate(env, ret);
napi_throw(env, err);
return nullptr;
}
}
PARAM_JS_LOGV("JSApp set key: %s(%d), value: %s(%d).",
asyncContext->key, asyncContext->keyLen, asyncContext->value, asyncContext->valueLen);
napi_value result = nullptr;
if (asyncContext->callbackRef == nullptr) {
napi_create_promise(env, &asyncContext->deferred, &result);
} else {
napi_get_undefined(env, &result);
}
SetCallbackWork(env, asyncContext);
return result;
}
static napi_value SetSync(napi_env env, napi_callback_info info)
{
size_t argc = ARGC_NUMBER;
napi_value args[ARGC_NUMBER] = { nullptr };
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
PARAM_NAPI_ASSERT(env, argc == ARGC_NUMBER, SYSPARAM_INVALID_INPUT, "Wrong number of arguments");
napi_valuetype valuetype0 = napi_null;
NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0));
napi_valuetype valuetype1 = napi_null;
NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1));
PARAM_NAPI_ASSERT(env, valuetype0 == napi_string && valuetype1 == napi_string,
SYSPARAM_INVALID_INPUT, "Wrong argument type. string expected.");
size_t keySize = 0;
std::vector<char> keyBuf(MAX_NAME_LENGTH, 0);
int ret = GetParamString(env, args[0], keyBuf.data(), MAX_NAME_LENGTH, &keySize);
if (ret != 0) {
napi_value err = BusinessErrorCreate(env, SYSPARAM_INVALID_INPUT);
napi_throw(env, err);
return nullptr;
}
std::vector<char> value(MAX_VALUE_LENGTH, 0);
size_t valueSize = 0;
ret = GetParamString(env, args[1], value.data(), MAX_VALUE_LENGTH, &valueSize);
if (ret != 0) {
napi_value err = BusinessErrorCreate(env, SYSPARAM_INVALID_VALUE);
napi_throw(env, err);
return nullptr;
}
ret = SetParameter(keyBuf.data(), value.data());
PARAM_JS_LOGV("JSApp SetSync result:%d, key: '%s'.", ret, keyBuf.data());
napi_value napiValue = nullptr;
if (ret != 0) { // set failed
napi_value err = BusinessErrorCreate(env, ret);
napi_throw(env, err);
} else {
napi_get_undefined(env, &napiValue);
}
return napiValue;
}
static napi_value GetSync(napi_env env, napi_callback_info info)
{
size_t argc = ARGC_NUMBER;
napi_value args[ARGC_NUMBER] = { nullptr };
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
PARAM_NAPI_ASSERT(env, argc == 1 || argc == ARGC_NUMBER, SYSPARAM_INVALID_INPUT, "Wrong number of arguments");
napi_valuetype valuetype0 = napi_null;
NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0));
PARAM_NAPI_ASSERT(env, valuetype0 == napi_string,
SYSPARAM_INVALID_INPUT, "Wrong argument type. Numbers expected.");
if (argc == ARGC_NUMBER) {
napi_valuetype valuetype1 = napi_null;
NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1));
PARAM_NAPI_ASSERT(env, valuetype1 == napi_string,
SYSPARAM_INVALID_INPUT, "Wrong argument type. string expected.");
}
size_t keySize = 0;
std::vector<char> keyBuf(MAX_NAME_LENGTH, 0);
int ret = GetParamString(env, args[0], keyBuf.data(), MAX_NAME_LENGTH, &keySize);
if (ret != 0) {
napi_value err = BusinessErrorCreate(env, SYSPARAM_INVALID_INPUT);
napi_throw(env, err);
return nullptr;
}
std::vector<char> defValue(MAX_VALUE_LENGTH, 0);
size_t valueSize = 0;
if (argc == ARGC_NUMBER) {
ret = GetParamString(env, args[1], defValue.data(), MAX_VALUE_LENGTH, &valueSize);
if (ret != 0) {
napi_value err = BusinessErrorCreate(env, SYSPARAM_INVALID_INPUT);
napi_throw(env, err);
return nullptr;
}
}
std::vector<char> value(MAX_VALUE_LENGTH, 0);
ret = GetParameter(keyBuf.data(), (valueSize == 0) ? nullptr : defValue.data(), value.data(), MAX_VALUE_LENGTH);
PARAM_JS_LOGV("JSApp get status: %d, key: '%s', value: '%s', defValue: '%s'.",
ret, keyBuf.data(), value.data(), defValue.data());
if (ret < 0) {
napi_value err = BusinessErrorCreate(env, ret);
napi_throw(env, err);
return nullptr;
}
napi_value napiValue = nullptr;
NAPI_CALL(env, napi_create_string_utf8(env, value.data(), strlen(value.data()), &napiValue));
return napiValue;
}
static void GetCallbackWork(napi_env env, StorageAsyncContextPtr asyncContext)
{
napi_value resource = nullptr;
napi_create_string_utf8(env, "JSStartupGet", NAPI_AUTO_LENGTH, &resource);
napi_create_async_work(
env, nullptr, resource,
[](napi_env env, void *data) {
StorageAsyncContext *asyncContext = (StorageAsyncContext *)data;
std::vector<char> value(MAX_VALUE_LENGTH, 0);
asyncContext->status = GetParameter(asyncContext->key,
(asyncContext->valueLen == 0) ? nullptr : asyncContext->value, value.data(), MAX_VALUE_LENGTH);
asyncContext->getValue = std::string(value.begin(), value.end());
PARAM_JS_LOGV("JSApp get asyncContext status: %d, key: '%s', value: '%s', defValue: '%s'.",
asyncContext->status, asyncContext->key, asyncContext->getValue.c_str(), asyncContext->value);
},
[](napi_env env, napi_status status, void *data) {
StorageAsyncContext *asyncContext = (StorageAsyncContext *)data;
napi_value result[ARGC_NUMBER] = { 0 };
if (asyncContext->status > 0) {
napi_get_undefined(env, &result[0]);
napi_create_string_utf8(env,
asyncContext->getValue.c_str(), strlen(asyncContext->getValue.c_str()), &result[1]);
} else {
result[0] = BusinessErrorCreate(env, asyncContext->status);
napi_get_undefined(env, &result[1]);
}
if (asyncContext->deferred) {
if (asyncContext->status > 0) {
napi_resolve_deferred(env, asyncContext->deferred, result[1]);
} else {
napi_reject_deferred(env, asyncContext->deferred, result[0]);
}
} else {
napi_value callback = nullptr;
napi_value callResult = nullptr;
napi_get_reference_value(env, asyncContext->callbackRef, &callback);
napi_call_function(env, nullptr, callback, ARGC_NUMBER, result, &callResult);
napi_delete_reference(env, asyncContext->callbackRef);
}
napi_delete_async_work(env, asyncContext->work);
delete asyncContext;
},
(void *)asyncContext, &asyncContext->work);
napi_queue_async_work(env, asyncContext->work);
}
static napi_value Get(napi_env env, napi_callback_info info)
{
size_t argc = ARGC_THREE_NUMBER;
napi_value argv[ARGC_THREE_NUMBER] = { nullptr };
napi_value thisVar = nullptr;
void *data = nullptr;
napi_get_cb_info(env, info, &argc, argv, &thisVar, &data);
PARAM_NAPI_ASSERT(env, argc >= 1, SYSPARAM_INVALID_INPUT, "requires 1 parameter");
StorageAsyncContextPtr asyncContext = new StorageAsyncContext();
asyncContext->env = env;
for (size_t i = 0; i < argc; i++) {
napi_valuetype valueType = napi_null;
napi_typeof(env, argv[i], &valueType);
int ret = 0;
if (i == 0 && valueType == napi_string) {
ret = GetParamString(env, argv[i], asyncContext->key, MAX_NAME_LENGTH, &asyncContext->keyLen);
} else if (i == 1 && valueType == napi_string) {
ret = GetParamString(env, argv[i], asyncContext->value, MAX_VALUE_LENGTH, &asyncContext->valueLen);
} else if (i == 1 && valueType == napi_function) {
napi_create_reference(env, argv[i], 1, &asyncContext->callbackRef);
break;
} else if (i == ARGC_NUMBER && valueType == napi_function) {
napi_create_reference(env, argv[i], 1, &asyncContext->callbackRef);
} else {
delete asyncContext;
ret = SYSPARAM_INVALID_INPUT;
}
if (ret != 0) {
ret = (i == 1) ? SYSPARAM_INVALID_VALUE : ret;
napi_value err = BusinessErrorCreate(env, ret);
napi_throw(env, err);
return nullptr;
}
}
PARAM_JS_LOGV("JSApp Get key: '%s'(%d), def value: '%s'(%d).",
asyncContext->key, asyncContext->keyLen, asyncContext->value, asyncContext->valueLen);
napi_value result = nullptr;
if (asyncContext->callbackRef == nullptr) {
napi_create_promise(env, &asyncContext->deferred, &result);
} else {
napi_get_undefined(env, &result);
}
GetCallbackWork(env, asyncContext);
return result;
}
EXTERN_C_START
/*
* Module init
*/
static napi_value Init(napi_env env, napi_value exports)
{
/*
* Attribute definition
*/
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("set", Set),
DECLARE_NAPI_FUNCTION("setSync", SetSync),
DECLARE_NAPI_FUNCTION("get", Get),
DECLARE_NAPI_FUNCTION("getSync", GetSync),
#ifdef PARAM_SUPPORT_WAIT
DECLARE_NAPI_FUNCTION("wait", ParamWait),
DECLARE_NAPI_FUNCTION("getWatcher", GetWatcher)
#endif
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc));
#ifdef PARAM_SUPPORT_WAIT
return RegisterWatcher(env, exports);
#else
return exports;
#endif
}
EXTERN_C_END
/*
* Module definition
*/
static napi_module _module = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = NULL,
.nm_register_func = Init,
.nm_modname = "systemParameterV9",
.nm_priv = ((void *)0),
.reserved = { 0 }
};
/*
* Module registration function
*/
extern "C" __attribute__((constructor)) void RegisterModule(void)
{
napi_module_register(&_module);
}
......@@ -71,6 +71,7 @@ if (defined(ohos_lite)) {
"param_cmd.c",
"sandbox.cpp",
"service_control.c",
"setloglevel.c",
"shell/shell_bas.c",
]
......@@ -119,6 +120,8 @@ if (defined(ohos_lite)) {
"service",
"sandbox",
"dump_service",
"setloglevel",
"getloglevel",
]
if (enable_ohos_startup_init_feature_ab_partition) {
......
......@@ -37,6 +37,7 @@ static int main_cmd(BShellHandle shell, int argc, char **argv)
}
size_t serviceNameLen = strlen(argv[1]) + strlen(argv[2]) + 2; // 2 is \0 and #
char *cmd = (char *)calloc(1, serviceNameLen);
BEGET_ERROR_CHECK(cmd != NULL, return 0, "failed to allocate cmd memory");
BEGET_ERROR_CHECK(sprintf_s(cmd, serviceNameLen, "%s#%s", argv[1], argv[2]) >= 0, free(cmd);
return 0, "dump service arg create failed");
CmdClientInit(INIT_CONTROL_FD_SOCKET_PATH, ACTION_DUMP, cmd);
......
/*
* 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 <stdlib.h>
#include "begetctl.h"
#include "init_utils.h"
#include "init_param.h"
#include "securec.h"
#include "shell_utils.h"
static int32_t SetInitLogLevelFromParam(BShellHandle shell, int argc, char **argv)
{
if (argc != 2) { // 2 is set log level parameter number
BShellCmdHelp(shell, argc, argv);
return 0;
}
errno = 0;
unsigned int level = strtoul(argv[1], 0, 10); // 10 is decimal
if (errno != 0) {
printf("Failed to transform %s to unsigned int. \n", argv[1]);
return -1;
}
if ((level >= INIT_DEBUG) && (level <= INIT_FATAL)) {
int ret = SystemSetParameter("persist.init.debug.loglevel", argv[1]);
if (ret != 0) {
printf("Failed to set log level by param \"persist.init.debug.loglevel\" %s. \n", argv[1]);
} else {
printf("Success to set log level by param \"persist.init.debug.loglevel\" %s. \n", argv[1]);
}
} else {
printf("Set init log level in invailed parameter %s. \n", argv[1]);
}
return 0;
}
static int32_t GetInitLogLevelFromParam(BShellHandle shell, int argc, char **argv)
{
char logLevel[2] = {0}; // 2 is set param "persist.init.debug.loglevel" value length.
uint32_t len = sizeof(logLevel);
int ret = SystemReadParam("persist.init.debug.loglevel", logLevel, &len);
if (ret == 0) {
printf("Success to get init log level: %s from param \"persist.init.debug.loglevel\" \n", logLevel);
} else {
printf("Failed to get init log level from param, keep the system origin log level: %d.\n", GetInitLogLevel());
}
return 0;
}
MODULE_CONSTRUCTOR(void)
{
const CmdInfo infos[] = {
{"setloglevel", SetInitLogLevelFromParam, "set init log level 0:debug, 1:info, 2:warning, 3:err, 4:fatal",
"setloglevel level", NULL},
{"getloglevel", GetInitLogLevelFromParam, "get init log level 0:debug, 1:info, 2:warning, 3:err, 4:fatal",
"getloglevel", NULL},
};
for (size_t i = 0; i < sizeof(infos) / sizeof(infos[0]); i++) {
BShellEnvRegisterCmd(GetShellHandle(), &infos[i]);
}
}
\ No newline at end of file
......@@ -160,12 +160,6 @@ if (defined(ohos_lite)) {
subsystem_name = "startup"
}
ohos_prebuilt_etc("charge.group") {
source = "//base/startup/init/services/etc/device.charge.group.cfg"
part_name = "init"
subsystem_name = "startup"
}
ohos_prebuilt_etc("syscap.para") {
source = "${preloader_output_dir}/system/etc/param/syscap.para"
module_install_dir = "etc/param/"
......@@ -224,7 +218,6 @@ if (defined(ohos_lite)) {
group("etc_files") {
deps = [
":boot.group",
":charge.group",
":chipset-sandbox.json",
":console.cfg",
":features.json",
......
{
"jobs": [
"param:sys.usb.config=hdc && param:sys.usb.configfs=1",
"param:sys.usb.ffs.ready=1 && param:sys.usb.config=hdc && param:sys.usb.configfs=1",
"boot && param:persist.sys.usb.config=*",
"param:sys.usb.config=none && param:sys.usb.configfs=0",
"boot && param:const.debuggable=1",
"param:sys.usb.config=none && param:sys.usb.configfs=1",
"load_persist_props_action"
],
"services": [
"ueventd",
"console",
"hdcd",
"charger",
"misc"
],
"groups": [
]
}
\ No newline at end of file
......@@ -17,8 +17,8 @@ vpn:x:1016:
keystore:x:1017:
usb:x:1018:
drm:x:1019:
gps:x:1020:
location_host:x:1021:
gps:x:1021:
location_host:x:1022:
media_rw:x:1023:
dsoftbus:x:1024:
nfc:x:1027:
......@@ -84,11 +84,10 @@ huks_server:x:3510:
cert_manager_server:x:3515:
dms:x:5522:
foundation:x:5523:
quickfixserver:x:5524;
quickfixserver:x:5524:
samgr:x:5555:
update:x:6666:
charger:x:6667:
battery_stats:x:6668:
sensor:x:6688:
input:x:6696:
msdp:x:6699:
......@@ -117,3 +116,4 @@ memmgr:x:1111:
ispserver:x:3821:
dfs_share:x:3822:
appspawn:x:4000:
security_guard:x:3520:
......@@ -139,11 +139,7 @@
"mkdir /data/service/el2/0/hmdfs 0711 system system",
"mkdir /data/chipset/el2/0 0711 root root",
"mkdir /storage/media 0711 root root",
"copy /data/system/entropy.dat /dev/urandom",
"mkdir /data/misc 01771 system misc",
"mkdir /data/misc/wifi 0770 wifi wifi",
"mkdir /data/misc/wifi/sockets 0770 wifi wifi",
"mkdir /data/misc/wifi/wpa_supplicant 0770 wifi wifi",
"mkdir /data/local 0751 root root",
"mkdir /data/vendor 0771 root root",
"mkdir /data/local/tmp 0771 shell shell",
......@@ -152,9 +148,6 @@
"mkdir /data/app 0771 system system",
"mkdir /data/nfc 0770 nfc nfc",
"mkdir /data/nfc/param 0770 nfc nfc",
"mkdir /data/system 0775 system system",
"mkdir /data/misc_de 01771 system misc",
"mkdir /data/misc_ce 01771 system misc",
"setparam sys.use_memfd false",
"chown root system /dev/fscklogs/log",
"chmod 0770 /dev/fscklogs/log",
......
......@@ -28,6 +28,7 @@
"uid" : "system",
"gid" : "system"
}],
"apl" : "normal",
"permission" : [
"ohos.permission.CHANGE_ABILITY_ENABLED_STATE",
"ohos.permission.DUMP",
......@@ -40,7 +41,16 @@
"ohos.permission.START_ABILITIES_FROM_BACKGROUND",
"ohos.permission.PERMISSION_USED_STATS"
],
"permission_acls" : ["ohos.permission.DUMP"],
"permission_acls" : [
"ohos.permission.CHANGE_ABILITY_ENABLED_STATE",
"ohos.permission.DUMP",
"ohos.permission.GET_BUNDLE_INFO_PRIVILEGED",
"ohos.permission.INSTALL_BUNDLE",
"ohos.permission.LISTEN_BUNDLE_CHANGE",
"ohos.permission.REMOVE_CACHE_FILES",
"ohos.permission.START_ABILITIES_FROM_BACKGROUND",
"ohos.permission.PERMISSION_USED_STATS"
],
"sandbox" : 0,
"start-mode" : "condition",
"secon" : "u:r:hdcd:s0",
......
......@@ -129,9 +129,6 @@
"mkdir /data/app-staging 0750 system system",
"copy /data/system/entropy.dat /dev/urandom",
"mkdir /data/misc 01771 system misc",
"mkdir /data/misc/wifi 0770 wifi wifi",
"mkdir /data/misc/wifi/sockets 0770 wifi wifi",
"mkdir /data/misc/wifi/wpa_supplicant 0770 wifi wifi",
"mkdir /data/local 0751 root root",
"mkdir /data/preloads 0775 system system",
"mkdir /data/vendor 0771 root root",
......
......@@ -30,7 +30,7 @@ const.build.product=default
const.product.hardwareversion=default
const.product.bootloader.version=bootloader
const.product.cpu.abilist=default
const.product.software.version=OpenHarmony 3.2.8.1
const.product.software.version=OpenHarmony 3.2.8.2
const.product.incremental.version=default
const.product.firstapiversion=1
const.product.build.type=default
......
......@@ -32,6 +32,7 @@ persist.appspawn. = root:root:0775
#udid and sn, only read
ohos.boot.sn = root:deviceprivate:0750
const.product.udid = root:deviceprivate:0750
const.actionable_compatible_property.enabled = root:root:0777
const.postinstall.fstab.prefix = root:root:0777
......
......@@ -16,8 +16,8 @@ vpn:x:1016:1016:::/bin/false
keystore:x:1017:1017:::/bin/false
usb:x:1018:1018:::/bin/false
drm:x:1019:1019:::/bin/false
gps:x:1020:1020:::/bin/false
location_host:x:1021:1021:::/bin/false
gps:x:1021:1021:::/bin/false
location_host:x:1022:1022:::/bin/false
media_rw:x:1023:1023:::/bin/false
dsoftbus:x:1024:1024:::/bin/false
nfc:x:1027:1027:::/bin/false
......@@ -85,7 +85,6 @@ samgr:x:5555:5555:::/bin/false
dbms:x:6000:6000:::/bin/false
update:x:6666:6666:::/bin/false
charger:x:6667:6667:::/bin/false
battery_stats:x:6668:6668:::/bin/false
sensor:x:6688:6688:::/bin/false
input:x:6696:6696:::/bin/false
msdp:x:6699:6699:::/bin/false
......@@ -112,3 +111,4 @@ motion_host:x:3065:3065:::/bin/false
memmgr:x:1111:1111:::/bin/false
ispserver:x:3821:3821:::/bin/false
dfs_share:x:3822:3822:::/bin/false
security_guard:x:3520:3520:::/bin/false
......@@ -2,4 +2,7 @@ root:x:0:
bin:x:2:
system:x:1000:
servicectrl:x:1050:root,shell,system,samgr,hdf_devmgr
shell:x:2000:
\ No newline at end of file
shell:x:2000:
faultloggerd:x:1202:root,system
watchdog:x:2001:root
ueventd:x:2002:root
......@@ -14,4 +14,4 @@
const.ohos.releasetype=Beta3
const.ohos.apiversion=9
const.ohos.version.security_patch=2022-09-01
const.ohos.fullname=OpenHarmony-3.2.8.1
\ No newline at end of file
const.ohos.fullname=OpenHarmony-3.2.8.2
\ No newline at end of file
......@@ -2,3 +2,6 @@ root:x:0:0:::/bin/false
bin:x:2:2:::/bin/false
system:x:1000:1000:::/bin/false
shell:x:2000:2000:::/bin/false
faultloggerd:x:1202:1202:::/bin/false
watchdog:x:2001:2001:::/bin/false
ueventd:x:2002:2002:::/bin/false
......@@ -44,7 +44,7 @@ int DoJobNow(const char *jobName);
#define INIT_CONFIGURATION_FILE "/etc/init.without_two_stages.cfg"
#endif
#define OTHER_CFG_PATH "/system/etc/init"
#define OTHER_CHARGE_PATH "/system/etc/charge"
#define OTHER_CHARGE_PATH "/vendor/etc/charger"
#define MAX_PATH_ARGS_CNT 20
void ReadConfig(void);
......
......@@ -30,7 +30,7 @@ int main(int argc, char * const argv[])
INIT_LOGE("Process id error %d!", getpid());
return 0;
}
EnableInitLog();
EnableInitLog(INIT_INFO);
if (isSecondStage == 0) {
SystemPrepare();
} else {
......
......@@ -123,7 +123,7 @@ int PluginExecCmd(const char *name, int argc, const char **argv)
return -1;
}
PluginCmd *cmd = groupNode->data.cmd;
INIT_LOGI("PluginExecCmd index %s", cmd->name);
INIT_LOGV("PluginExecCmd index %s", cmd->name);
int ret = 0;
ListNode *node = cmd->cmdExecutor.next;
while (node != &cmd->cmdExecutor) {
......
......@@ -38,13 +38,17 @@ static void ProcessSignal(const struct signalfd_siginfo *siginfo)
Service* service = GetServiceByPid(sigPID);
// check child process exit status
if (WIFSIGNALED(procStat)) {
INIT_LOGE("Child process %d exit with signal: %d", sigPID, WTERMSIG(procStat));
INIT_LOGE("Child process %s(pid %d) exit with code : %d",
service == NULL ? "Unknown" : service->name, sigPID, sigPID, WTERMSIG(procStat));
}
if (WIFEXITED(procStat)) {
INIT_LOGE("Child process %s(pid %d) exit with code : %d",
service == NULL ? "Unknown" : service->name, sigPID, WEXITSTATUS(procStat));
}
CmdServiceProcessDelClient(sigPID);
INIT_LOGI("SigHandler, SIGCHLD received, Service:%s pid:%d uid:%d status:%d.",
service == NULL ? "Unknown" : service->name,
sigPID, siginfo->ssi_uid, procStat);
CheckWaitPid(sigPID);
ServiceReap(service);
}
......@@ -75,4 +79,4 @@ void SignalInit(void)
if (LE_AddSignal(LE_GetDefaultLoop(), g_sigHandle, SIGTERM) != 0) {
INIT_LOGW("start SIGTERM handler failed");
}
}
\ No newline at end of file
}
......@@ -25,6 +25,7 @@
#include "init_log.h"
#include "fs_manager/fs_manager.h"
#include "securec.h"
#include "init_utils.h"
static void FreeOldRoot(DIR *dir, dev_t dev)
{
......@@ -77,21 +78,14 @@ static void FreeOldRoot(DIR *dir, dev_t dev)
// all sub mount tree in the future.
static bool UnderBasicMountPoint(const char *path)
{
unsigned int i;
if (path == NULL || *path == '\0') {
return false;
}
size_t pathSize = strlen(path);
if (strncmp(path, "/dev/", strlen("/dev/")) == 0 && pathSize > strlen("/dev/")) {
return true;
}
if (strncmp(path, "/sys/", strlen("/sys/")) == 0 && pathSize > strlen("/sys/")) {
return true;
}
if (strncmp(path, "/proc/", strlen("/proc/")) == 0 && pathSize > strlen("/proc/")) {
return true;
const char *basicMountPoint[] = {"/dev/", "/sys/", "/proc/"};
for (i = 0; i < ARRAY_LENGTH(basicMountPoint); i++) {
if (strncmp(path, basicMountPoint[i], strlen(basicMountPoint[i])) == 0)
return true;
}
return false;
}
......
......@@ -28,7 +28,6 @@ if (defined(ohos_lite)) {
"_GNU_SOURCE",
"OHOS_LITE",
]
cflags = [ "-fPIC" ]
public_configs = [ ":exported_header_files" ]
if (ohos_kernel_type == "linux") {
......
......@@ -22,7 +22,7 @@
#include <time.h>
#include <sys/time.h>
#include "param/init_param.h"
#include "init_utils.h"
#include "securec.h"
#ifdef OHOS_LITE
#ifndef INIT_LOG_INIT
......@@ -121,7 +121,7 @@ static void PrintLog(InitLogLevel logLevel, unsigned int domain, const char *tag
INIT_LOCAL_API void InitLog(int logLevel, unsigned int domain, const char *tag, const char *fmt, va_list vargs)
{
if (g_logLevel > logLevel) {
if ((int)g_logLevel > logLevel) {
return;
}
char tmpFmt[DEF_LOG_SIZE] = {0};
......@@ -129,7 +129,7 @@ INIT_LOCAL_API void InitLog(int logLevel, unsigned int domain, const char *tag,
tmpFmt[sizeof(tmpFmt) - 2] = '\n'; // 2 add \n to tail
tmpFmt[sizeof(tmpFmt) - 1] = '\0';
}
PrintLog(logLevel, domain, tag, tmpFmt);
PrintLog((InitLogLevel)logLevel, domain, tag, tmpFmt);
}
INIT_PUBLIC_API void SetInitLogLevel(InitLogLevel level)
......@@ -140,18 +140,35 @@ INIT_PUBLIC_API void SetInitLogLevel(InitLogLevel level)
return;
}
INIT_PUBLIC_API void EnableInitLog(void)
INIT_PUBLIC_API int GetInitLogLevel(void)
{
return g_logLevel;
}
INIT_PUBLIC_API void EnableInitLog(InitLogLevel level)
{
g_logLevel = level;
SetInitCommLog(InitLog);
char logLevel[2] = {0}; // 2 is set param "persist.init.debug.loglevel" value length.
uint32_t len = sizeof(logLevel);
int ret = SystemReadParam("persist.init.debug.loglevel", logLevel, &len);
INIT_INFO_CHECK(ret == 0, return, "Can not get log level from param, keep the original loglevel.");
errno = 0;
unsigned int level = (unsigned int)strtoul(logLevel, 0, 10); // 10 is decimal
INIT_INFO_CHECK(errno == 0, return, "Failed strtoul %s, err=%d", logLevel, errno);
if ((level >= INIT_DEBUG) && (level <= INIT_FATAL)) {
g_logLevel = level;
}
INIT_PUBLIC_API void EnableInitLogFromCmdline(void)
{
SetInitCommLog(InitLog);
char level[MAX_BUFFER_LEN] = {0};
char *buffer = ReadFileData("/proc/cmdline");
if (buffer == NULL) {
INIT_LOGE("Failed to read \"/proc/cmdline\"");
return;
}
int ret = GetProcCmdlineValue("initloglevel", buffer, level, MAX_BUFFER_LEN);
free(buffer);
if (ret != 0) {
INIT_LOGE("Failed get log level from cmdline");
return;
}
errno = 0;
unsigned int logLevel = (unsigned int)strtoul(level, 0, 10); // 10 is decimal
INIT_INFO_CHECK(errno == 0, return, "Failed strtoul %s, err=%d", level, errno);
SetInitLogLevel(logLevel);
return;
}
......@@ -28,7 +28,7 @@ static LE_STATUS SetTimer_(int tfd, uint64_t timeout)
struct itimerspec timeValue;
time_t sec = timeout / TIMEOUT_BASE;
timeValue.it_interval.tv_sec = sec;
long nsec = (timeout % TIMEOUT_BASE) * TIMEOUT_BASE;
long nsec = (timeout % TIMEOUT_BASE) * TIMEOUT_BASE * TIMEOUT_BASE;
timeValue.it_interval.tv_nsec = nsec;
timeValue.it_value.tv_sec = sec;
timeValue.it_value.tv_nsec = nsec;
......
......@@ -342,7 +342,6 @@ static void SetServiceBootEventFork(SERVICE_INFO_CTX *serviceCtx)
MODULE_CONSTRUCTOR(void)
{
EnableInitLog();
InitAddServiceHook(SetServiceBootEventFork, INIT_SERVICE_FORK_BEFORE);
InitAddServiceHook(ClearServiceBootEvent, INIT_SERVICE_CLEAR);
InitAddServiceHook(DumpServiceBootEvent, INIT_SERVICE_DUMP);
......
......@@ -142,7 +142,7 @@ static int CmdSetLogLevel(int id, const char *name, int argc, const char **argv)
static int ParamSetInitCmdHook(const HOOK_INFO *hookInfo, void *cookie)
{
AddCmdExecutor("clear", CmdClear);
AddCmdExecutor("setinitloglevel", CmdSetLogLevel);
AddCmdExecutor("setloglevel", CmdSetLogLevel);
return 0;
}
......@@ -168,11 +168,24 @@ static void DumpServiceHook(void)
return;
}
static void InitLogLevelFromPersist(void)
{
char logLevel[2] = {0}; // 2 is set param "persist.init.debug.loglevel" value length.
uint32_t len = sizeof(logLevel);
int ret = SystemReadParam("persist.init.debug.loglevel", logLevel, &len);
INIT_INFO_CHECK(ret == 0, return, "Can not get log level from param, keep the original loglevel.");
errno = 0;
unsigned int level = (unsigned int)strtoul(logLevel, 0, 10); // 10 is decimal
INIT_INFO_CHECK(errno == 0, return, "Failed strtoul %s, err=%d", logLevel, errno);
SetInitLogLevel(level);
return;
}
static int InitDebugHook(const HOOK_INFO *info, void *cookie)
{
UNUSED(info);
UNUSED(cookie);
EnableInitLog();
InitLogLevelFromPersist();
DumpServiceHook();
return 0;
}
......
......@@ -62,7 +62,7 @@ const ParamCmdInfo *GetOtherSpecial(size_t *size)
{
static const ParamCmdInfo other[] = {
{"bootevent.", "bootevent.", "bootevent"},
{"persist.init.debug.", "persist.init.debug.", "setinitloglevel"}
{"persist.init.debug.", "persist.init.debug.", "setloglevel"},
};
*size = ARRAY_LENGTH(other);
return other;
......
......@@ -161,6 +161,7 @@ prlimit64
cacheflush
set_tls
sched_setscheduler
mkdir
@allowListWithArgs
getrusage:if arg0 == RUSAGE_SELF || arg0 == RUSAGE_THREAD; return ALLOW; else return KILL_PROCESS;
......
......@@ -28,8 +28,11 @@
#define USER_BUFFER_LEN 64
#define MAX_BUF_SIZE 1024
#define GROUP_FORMAT "const.group"
#define INVALID_MODE 0550
#define GROUP_FILE_PATH "/etc/group"
#define OCT_BASE 8
#define INVALID_UID(uid) ((uid) == (uid_t)-1)
static void GetUserIdByName(uid_t *uid, const char *name, uint32_t nameLen)
{
*uid = -1;
......@@ -210,7 +213,6 @@ static int CheckFilePermission(const ParamSecurityLabel *localLabel, const char
static int CheckUserInGroup(WorkSpace *space, gid_t groupId, uid_t uid)
{
#ifdef __MUSL__
char buffer[USER_BUFFER_LEN] = {0};
uint32_t labelIndex = 0;
int ret = ParamSprintf(buffer, sizeof(buffer), "%s.%d.%d", GROUP_FORMAT, groupId, uid);
......@@ -218,14 +220,11 @@ static int CheckUserInGroup(WorkSpace *space, gid_t groupId, uid_t uid)
(void)FindTrieNode(space, buffer, strlen(buffer), &labelIndex);
ParamSecurityNode *node = (ParamSecurityNode *)GetTrieNode(space, labelIndex);
PARAM_CHECK(node != NULL, return DAC_RESULT_FORBIDED, "Can not get security label %d", labelIndex);
PARAM_LOGV("CheckUserInGroup %s groupid %d uid %d", buffer, groupId, uid);
PARAM_LOGV("CheckUserInGroup %s groupid %d uid %d", buffer, node->gid, node->uid);
if (node->gid == groupId && node->uid == uid) {
return 0;
}
return -1;
#else
return 0;
#endif
}
static int DacCheckParamPermission(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode)
......@@ -265,9 +264,6 @@ static int DacCheckParamPermission(const ParamSecurityLabel *srcLabel, const cha
PARAM_LOGW("Cfg label %d gid:%d uid:%d mode 0%o ", labelIndex, node->gid, node->uid, node->mode);
#ifndef STARTUP_INIT_TEST
ret = DAC_RESULT_PERMISSION;
#endif
#ifndef __MUSL__ // for wgr, return permission
ret = DAC_RESULT_PERMISSION;
#endif
}
return ret;
......@@ -288,45 +284,136 @@ INIT_LOCAL_API int RegisterSecurityDacOps(ParamSecurityOps *ops, int isInit)
return ret;
}
static void AddGroupUser(unsigned int uid, unsigned int gid, int mode, const char *format)
static void AddGroupUser(const char *userName, gid_t gid)
{
if (userName == NULL || strlen(userName) == 0) {
return;
}
uid_t uid = 0;
GetUserIdByName(&uid, userName, strlen(userName));
PARAM_LOGV("Add group user '%s' gid %d uid %d", userName, gid, uid);
if (INVALID_UID(gid) || INVALID_UID(uid)) {
PARAM_LOGW("Invalid user for '%s' gid %d uid %d", userName, gid, uid);
return;
}
ParamAuditData auditData = {0};
char buffer[USER_BUFFER_LEN] = {0};
int ret = ParamSprintf(buffer, sizeof(buffer), "%s.%u.%u", format, gid, uid);
PARAM_CHECK(ret >= 0, return, "Failed to format name for %s.%d.%d", format, gid, uid);
int ret = ParamSprintf(buffer, sizeof(buffer), "%s.%u.%u", GROUP_FORMAT, gid, uid);
PARAM_CHECK(ret >= 0, return, "Failed to format name for %d.%d", gid, uid);
auditData.name = buffer;
auditData.dacData.uid = uid;
auditData.dacData.gid = gid;
auditData.dacData.mode = mode;
auditData.dacData.mode = INVALID_MODE;
AddSecurityLabel(&auditData);
}
INIT_LOCAL_API void LoadGroupUser(void)
#ifdef PARAM_DECODE_GROUPID_FROM_FILE
static char *UserNameTrim(char *str)
{
#ifndef __MUSL__
if (str == NULL) {
return NULL;
}
size_t len = strlen(str);
if (str == NULL || len == 0) {
return NULL;
}
char *end = str + len - 1;
while (end >= str && (*end == ' ' || *end == '\t' || *end == '\n' || *end == '\r')) {
*end = '\0';
end--;
}
len = strlen(str);
char *head = str;
end = str + strlen(str);
while (head < end && (*head == ' ' || *head == '\t' || *head == '\n' || *head == '\r')) {
*head = '\0';
head++;
}
if (strlen(str) == 0) {
return NULL;
}
return head;
}
static void LoadGroupUser_(void)
{
// decode group file
FILE *fp = fopen(GROUP_FILE_PATH, "r");
const uint32_t buffSize = 1024; // 1024 max buffer for decode
char *buff = (char *)calloc(1, buffSize);
while (fp != NULL && buff != NULL && fgets(buff, buffSize, fp) != NULL) {
buff[buffSize - 1] = '\0';
// deviceprivate:x:1053:root,shell,system,samgr,hdf_devmgr,deviceinfo,dsoftbus,dms,account
char *buffer = UserNameTrim(buff);
PARAM_CHECK(buffer != NULL, continue, "Invalid buffer %s", buff);
PARAM_LOGV("LoadGroupUser_ '%s'", buffer);
// group name
char *groupName = strtok(buffer, ":");
groupName = UserNameTrim(groupName);
PARAM_CHECK(groupName != NULL, continue, "Invalid group name %s", buff);
// skip x
(void)strtok(NULL, ":");
char *strGid = strtok(NULL, ":");
strGid = UserNameTrim(strGid);
PARAM_CHECK(strGid != NULL, continue, "Invalid gid %s", buff);
errno = 0;
gid_t gid = (gid_t)strtoul(strGid, 0, 10); // 10 base
PARAM_CHECK(errno == 0, continue, "Invalid gid %s", strGid);
char *userName = strGid + strlen(strGid) + 1;
userName = UserNameTrim(userName);
PARAM_LOGV("LoadGroupUser_ %s userName '%s'", groupName, userName);
if (userName == NULL) {
AddGroupUser(groupName, gid);
continue;
}
char *tmp = strtok(userName, ",");
while (tmp != NULL) {
PARAM_LOGV("LoadGroupUser_ %s userName '%s'", groupName, tmp);
AddGroupUser(UserNameTrim(tmp), gid);
userName = tmp + strlen(tmp) + 1;
tmp = strtok(NULL, ",");
}
// last username
if (userName != NULL) {
AddGroupUser(UserNameTrim(userName), gid);
}
}
if (fp != NULL) {
(void)fclose(fp);
}
if (buff != NULL) {
free(buff);
}
return;
#endif
PARAM_LOGV("LoadGroupUser ");
uid_t uid = 0;
}
#else
static void LoadGroupUser_(void)
{
struct group *data = NULL;
while ((data = getgrent()) != NULL) {
if (data->gr_name == NULL || data->gr_mem == NULL) {
continue;
}
if (data->gr_mem[0] == NULL) { // default user in group
GetUserIdByName(&uid, data->gr_name, strlen(data->gr_name));
PARAM_LOGV("LoadGroupUser %s gid %d uid %d", data->gr_name, data->gr_gid, uid);
AddGroupUser(uid, data->gr_gid, 0550, GROUP_FORMAT); // 0550 read and watch
AddGroupUser(data->gr_name, data->gr_gid);
continue;
}
int index = 0;
while (data->gr_mem[index]) { // user in this group
GetUserIdByName(&uid, data->gr_mem[index], strlen(data->gr_mem[index]));
PARAM_LOGV("LoadGroupUser %s gid %d uid %d user %s", data->gr_name, data->gr_gid, uid, data->gr_mem[index]);
AddGroupUser(uid, data->gr_gid, 0550, GROUP_FORMAT); // 0550 read and watch
AddGroupUser(data->gr_mem[index], data->gr_gid);
index++;
}
}
PARAM_LOGV("LoadGroupUser getgrent fail errnor %d ", errno);
endgrent();
}
#endif
INIT_LOCAL_API void LoadGroupUser(void)
{
PARAM_LOGV("LoadGroupUser ");
LoadGroupUser_();
}
......@@ -32,6 +32,7 @@
#define CHECKER_LIB_NAME "/system/lib/libparaperm_checker.z.so"
#define CHECKER_UPDATER_LIB_NAME "/lib/libparaperm_checker.z.so"
#endif
typedef int (*SelinuxSetParamCheck)(const char *paraName, const char *destContext, const SrcInfo *info);
static int InitSelinuxOpsForInit(SelinuxSpace *selinuxSpace)
{
......
......@@ -102,7 +102,10 @@ if (defined(ohos_lite)) {
cflags = [ "-fPIC" ]
include_dirs = base_include_dirs
public_configs = [ ":exported_header_files" ]
defines = [ "_GNU_SOURCE" ]
defines = [
"_GNU_SOURCE",
"PARAM_DECODE_GROUPID_FROM_FILE",
]
deps = []
if (use_musl) {
......
......@@ -20,7 +20,7 @@
#include "param_manager.h"
#include "param_trie.h"
static ParamWorkSpace g_paramWorkSpace = {};
static ParamWorkSpace g_paramWorkSpace = {0};
PARAM_STATIC int WorkSpaceNodeCompare(const HashNode *node1, const HashNode *node2)
{
WorkSpace *workSpace1 = HASHMAP_ENTRY(node1, WorkSpace, hashNode);
......@@ -168,7 +168,7 @@ INIT_INNER_API int InitParamWorkSpace(int onlyRead, const PARAM_WORKSPACE_OPS *o
// load user info for dac
LoadGroupUser();
// add default dac policy
ParamAuditData auditData = {};
ParamAuditData auditData = {0};
auditData.name = "#";
auditData.dacData.gid = DAC_DEFAULT_GROUP; // 2000 for shell
auditData.dacData.uid = DAC_DEFAULT_USER; // for root
......
......@@ -491,7 +491,7 @@ INIT_LOCAL_API int ReadParamValue(ParamHandle handle, char *value, uint32_t *len
PARAM_CHECK(length != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param");
ParamNode *entry = (ParamNode *)GetTrieNodeByHandle(handle);
if (entry == NULL) {
return -1;
return PARAM_CODE_NOT_FOUND;
}
if (value == NULL) {
*length = entry->valueLength + 1;
......@@ -516,7 +516,7 @@ INIT_LOCAL_API int ReadParamName(ParamHandle handle, char *name, uint32_t length
PARAM_CHECK(name != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param");
ParamNode *entry = (ParamNode *)GetTrieNodeByHandle(handle);
if (entry == NULL) {
return -1;
return PARAM_CODE_NOT_FOUND;
}
PARAM_CHECK(length > entry->keyLength, return -1, "Invalid param size %u %u", entry->keyLength, length);
int ret = ParamMemcpy(name, length, entry->data, entry->keyLength);
......@@ -531,8 +531,8 @@ INIT_LOCAL_API int CheckParamPermission(const ParamSecurityLabel *srcLabel, cons
ParamWorkSpace *paramSpace = GetParamWorkSpace();
PARAM_CHECK(paramSpace != NULL, return DAC_RESULT_FORBIDED, "Invalid workspace");
int ret = DAC_RESULT_PERMISSION;
PARAM_LOGV("CheckParamPermission mode 0x%x name: %s uid:%d pid:%d",
mode, name, (int)srcLabel->cred.uid, (int)srcLabel->cred.pid);
PARAM_LOGV("CheckParamPermission mode 0x%x name: %s uid:%d gid:%d pid:%d",
mode, name, (int)srcLabel->cred.uid, (int)srcLabel->cred.gid, (int)srcLabel->cred.pid);
// for root, all permission, but for appspawn must to check
if (srcLabel->cred.uid == 0 && srcLabel->cred.pid == 1) {
return DAC_RESULT_PERMISSION;
......
......@@ -67,7 +67,7 @@ extern "C" {
#define DAC_DEFAULT_MODE 0774
#define PARAM_WORKSPACE_DEF (1024 * 30)
#endif
#define DAC_DEFAULT_GROUP 2000
#define DAC_DEFAULT_GROUP 0
#define DAC_DEFAULT_USER 0
#endif
......
......@@ -22,12 +22,6 @@
#include <sys/types.h>
#ifdef PARAM_SUPPORT_SELINUX
#include "selinux_parameter.h"
#else
typedef struct ParamContextsList_ {
} ParamContextsList;
typedef struct SrcInfo {
} SrcInfo;
#endif
#include "beget_ext.h"
......@@ -100,9 +94,9 @@ typedef struct {
} ParamSecurityOps;
typedef int (*RegisterSecurityOpsPtr)(ParamSecurityOps *ops, int isInit);
typedef int (*SelinuxSetParamCheck)(const char *paraName, const char *destContext, const SrcInfo *info);
typedef struct SelinuxSpace_ {
void *selinuxHandle;
#ifdef PARAM_SUPPORT_SELINUX
void (*setSelinuxLogCallback)(void);
int (*setParamCheck)(const char *paraName, const char *destContext, const SrcInfo *info);
const char *(*getParamLabel)(const char *paraName);
......@@ -110,6 +104,7 @@ typedef struct SelinuxSpace_ {
int (*readParamCheck)(const char *paraName);
ParamContextsList *(*getParamList)(void);
void (*destroyParamList)(ParamContextsList **list);
#endif
} SelinuxSpace;
#ifdef PARAM_SUPPORT_SELINUX
INIT_LOCAL_API int RegisterSecuritySelinuxOps(ParamSecurityOps *ops, int isInit);
......
......@@ -61,7 +61,7 @@ typedef struct {
uint32_t watcherId;
uint32_t waitId;
} id;
char key[PARAM_NAME_LEN_MAX];
char key[PARAM_NAME_LEN_MAX + 4];
char data[0];
} ParamMessage;
......
......@@ -41,6 +41,7 @@ __attribute__((constructor)) static void ParameterInit(void)
if (getpid() == 1) {
return;
}
EnableInitLog(INIT_ERROR);
PARAM_WORKSPACE_OPS ops = {0};
ops.updaterMode = 0;
#ifdef PARAM_BASE_LOG
......@@ -50,7 +51,6 @@ __attribute__((constructor)) static void ParameterInit(void)
ops.setfilecon = NULL;
#endif
InitParamWorkSpace(1, &ops);
EnableInitLog();
}
__attribute__((destructor)) static void ParameterDeinit(void)
......@@ -132,6 +132,7 @@ static int GetClientSocket(int timeout)
static int StartRequest(int clientFd, ParamMessage *request, int timeout)
{
errno = 0;
ssize_t sendLen = send(clientFd, (char *)request, request->msgSize, 0);
if (errno == EINVAL || errno == EACCES) {
return PARAM_CODE_INVALID_SOCKET;
......@@ -173,7 +174,7 @@ int SystemSetParameter(const char *name, const char *value)
g_clientFd = GetClientSocket(DEFAULT_PARAM_SET_TIMEOUT);
}
if (g_clientFd < 0) {
ret = PARAM_CODE_INVALID_PARAM;
ret = DAC_RESULT_FORBIDED;
break;
}
ret = StartRequest(g_clientFd, request, DEFAULT_PARAM_SET_TIMEOUT);
......@@ -181,7 +182,7 @@ int SystemSetParameter(const char *name, const char *value)
close(g_clientFd);
g_clientFd = INVALID_SOCKET;
retryCount++;
ret = 0;
ret = DAC_RESULT_FORBIDED;
} else {
break;
}
......
......@@ -108,10 +108,13 @@ static_library("param_init_lite") {
static_library("param_client_lite") {
sources = base_sources
include_dirs = param_include_dirs
cflags = [ "-fPIC" ]
defines = param_build_defines
public_configs = [ ":exported_header_files" ]
if (use_musl) {
defines += [ "PARAM_BASE" ]
}
if (ohos_kernel_type == "liteos_a") {
sources +=
[ "//base/startup/init/services/param/adapter/param_persistadp.c" ]
......
......@@ -19,20 +19,20 @@
static int g_flags = 0;
__attribute__((constructor)) static void ClientInit(void);
__attribute__((destructor)) static void ClientDeinit(void);
static void ClientDeinit(void);
static int InitParamClient(void)
{
if (PARAM_TEST_FLAG(g_flags, WORKSPACE_FLAGS_INIT)) {
return 0;
}
EnableInitLog(INIT_INFO);
PARAM_LOGV("InitParamClient");
int ret = InitParamWorkSpace(1, NULL);
PARAM_CHECK(ret == 0, return -1, "Failed to init param workspace");
PARAM_SET_FLAG(g_flags, WORKSPACE_FLAGS_INIT);
// init persist to save
InitPersistParamWorkSpace();
EnableInitLog();
return 0;
}
......
......@@ -27,7 +27,7 @@
#include "utils_file.h"
// for linux, no mutex
static ParamMutex g_saveMutex = {};
static ParamMutex g_saveMutex = {0};
#ifdef PARAM_SUPPORT_POSIX
#define MODE_READ O_RDONLY
#define MODE_APPEND (O_RDWR | O_CREAT | O_APPEND)
......@@ -138,7 +138,7 @@ static int LoadPersistParam(void)
buffer = malloc(fileSize);
PARAM_CHECK(buffer != NULL, break, "Failed to get file");
ret = ParamFileRead(fd, buffer, fileSize);
PARAM_CHECK(ret == 0, break, "Failed to get read file %s", path);
PARAM_CHECK(ret >= 0, break, "Failed to read file %s", path);
uint32_t currLen = 0;
while (currLen < fileSize) {
......
......@@ -14,6 +14,7 @@
*/
#include "param_osadp.h"
#include "param_security.h"
#include "securec.h"
static int InitLocalSecurityLabel(ParamSecurityLabel *security, int isInit)
{
......@@ -81,4 +82,4 @@ INIT_LOCAL_API int RegisterSecurityDacOps(ParamSecurityOps *ops, int isInit)
INIT_LOCAL_API void LoadGroupUser(void)
{
}
\ No newline at end of file
}
......@@ -24,6 +24,7 @@
#include <sys/shm.h>
#else
#include "los_task.h"
#include "los_mux.h"
#endif
#include <sys/stat.h>
#include <sys/time.h>
......@@ -318,4 +319,4 @@ INIT_LOCAL_API uint32_t Difftime(time_t curr, time_t base)
(void)base;
return 0;
#endif
}
\ No newline at end of file
}
......@@ -132,11 +132,11 @@ static void ParamServiceTask(int *arg)
void LiteParamService(void)
{
EnableInitLog(INIT_INFO);
PARAM_LOGI("LiteParamService");
InitParamService();
// get persist param
LoadPersistParams();
EnableInitLog();
osThreadAttr_t attr;
attr.name = "ParamServiceTask";
attr.attr_bits = 0U;
......
......@@ -365,7 +365,7 @@ int SystemGetParameterCommitId(ParamHandle handle, uint32_t *commitId)
ParamNode *entry = (ParamNode *)GetTrieNodeByHandle(handle);
if (entry == NULL) {
return -1;
return PARAM_CODE_NOT_FOUND;
}
*commitId = ReadCommitId(entry);
return 0;
......
......@@ -23,7 +23,7 @@
#include "param_osadp.h"
#include "securec.h"
static ParamPersistWorkSpace g_persistWorkSpace = {0, 0, NULL, 0, {}};
static ParamPersistWorkSpace g_persistWorkSpace = {0, 0, NULL, 0, {0}};
static int IsNeedToSave(const char *name)
{
#if defined(__LITEOS_M__) || defined(__LITEOS_A__)
......@@ -241,4 +241,4 @@ int LoadPersistParams(void)
}
#endif
return 0;
}
\ No newline at end of file
}
......@@ -183,7 +183,7 @@ char *ReadFileData(const char *fileName)
int fd = -1;
fd = open(fileName, O_RDONLY);
INIT_ERROR_CHECK(fd >= 0, return NULL, "Failed to read file %s", fileName);
buffer = (char *)malloc(MAX_SMALL_BUFFER); // fsmanager not create, can not get fileStat st_size
buffer = (char *)calloc(1, MAX_SMALL_BUFFER); // fsmanager not create, can not get fileStat st_size
INIT_ERROR_CHECK(buffer != NULL, close(fd);
return NULL, "Failed to allocate memory for %s", fileName);
ssize_t readLen = read(fd, buffer, MAX_SMALL_BUFFER - 1);
......@@ -322,10 +322,13 @@ char **SplitStringExt(char *buffer, const char *del, int *returnCount, int maxIt
void WaitForFile(const char *source, unsigned int maxSecond)
{
INIT_ERROR_CHECK(maxSecond <= WAIT_MAX_SECOND, maxSecond = WAIT_MAX_SECOND, "WaitForFile max time is 5s");
struct stat sourceInfo = {};
struct stat sourceInfo = {0};
unsigned int waitTime = 500000;
/* 500ms interval, check maxSecond*2 times total */
unsigned int maxCount = maxSecond * 2;
#ifdef STARTUP_INIT_TEST
maxCount = 0;
#endif
unsigned int count = 0;
while ((stat(source, &sourceInfo) < 0) && (errno == ENOENT) && (count < maxCount)) {
usleep(waitTime);
......@@ -382,7 +385,7 @@ int MakeDir(const char *dir, mode_t mode)
int MakeDirRecursive(const char *dir, mode_t mode)
{
int rc = -1;
char buffer[PATH_MAX] = {};
char buffer[PATH_MAX] = {0};
const char *p = NULL;
if (dir == NULL || *dir == '\0') {
errno = EINVAL;
......@@ -469,7 +472,7 @@ int ReadFileInDir(const char *dirPath, const char *includeExt,
INIT_CHECK_RETURN_VALUE(dirPath != NULL && processFile != NULL, -1);
DIR *pDir = opendir(dirPath);
INIT_ERROR_CHECK(pDir != NULL, return -1, "Read dir :%s failed.%d", dirPath, errno);
char *fileName = malloc(MAX_BUF_SIZE);
char *fileName = calloc(1, MAX_BUF_SIZE);
INIT_ERROR_CHECK(fileName != NULL, closedir(pDir);
return -1, "Failed to malloc for %s", dirPath);
......
......@@ -49,19 +49,30 @@ ohos_moduletest("InitModuleTest") {
sources = [
"hookmgr_moduletest.cpp",
"modulemgr_moduletest.cpp",
"service_control_test.cpp",
"service_watcher_moduleTest.cpp",
"syspara_moduleTest.cpp",
"test_utils.cpp",
]
include_dirs = [ "//base/startup/init/interfaces/innerkits/include" ]
include_dirs = [
"//base/startup/init/interfaces/innerkits/include",
"//base/startup/init/interfaces/innerkits/include/syspara",
"//base/startup/init/interfaces/innerkits/syspara",
"//base/startup/init/services/include/param",
".",
]
deps = [
"//base/startup/init/interfaces/innerkits:libbeget_proxy",
"//base/startup/init/interfaces/innerkits:libbegetutil",
"//third_party/bounds_checking_function:libsec_shared",
"//third_party/googletest:gtest_main",
]
}
group("moduletest") {
testonly = true
deps = [ ":InitModuleTest" ]
}
......
/*
* 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 <chrono>
#include <thread>
#include <gtest/gtest.h>
#include "service_control.h"
#include "test_utils.h"
using namespace testing::ext;
namespace initModuleTest {
namespace {
// Default wait for service status change time is 10 seconds
constexpr int WAIT_SERVICE_STATUS_TIMEOUT = 10;
}
class ServiceControlTest : public testing::Test {
public:
static void SetUpTestCase() {};
static void TearDownTestCase() {};
void SetUp() {};
void TearDown() {};
};
// Test service start
HWTEST_F(ServiceControlTest, ServiceStartTest, TestSize.Level1)
{
// Pick an unusual service for testing
// Try to start media_service.
// 1) Check if media_service exist
std::string serviceName = "media_service";
auto status = GetServiceStatus(serviceName);
if (status == "running") {
int ret = ServiceControl(serviceName.c_str(), STOP);
ASSERT_EQ(ret, 0);
ret = ServiceWaitForStatus(serviceName.c_str(), SERVICE_STOPPED, WAIT_SERVICE_STATUS_TIMEOUT);
ASSERT_EQ(ret, 0);
} else if (status != "created" && status != "stopped") {
std::cout << serviceName << " in invalid status " << status << std::endl;
std::cout << "Debug " << serviceName << " in unexpected status " << status << std::endl;
ASSERT_TRUE(0);
}
// 2) Now try to start service
int ret = ServiceControl(serviceName.c_str(), START);
EXPECT_EQ(ret, 0);
ret = ServiceWaitForStatus(serviceName.c_str(), SERVICE_STARTED, WAIT_SERVICE_STATUS_TIMEOUT);
EXPECT_EQ(ret, 0);
status = GetServiceStatus(serviceName);
std::cout << "Debug " << serviceName << " in status " << status << std::endl;
EXPECT_TRUE(status == "running");
}
HWTEST_F(ServiceControlTest, NonExistServiceStartTest, TestSize.Level1)
{
std::string serviceName = "non_exist_service";
int ret = ServiceControl(serviceName.c_str(), START);
EXPECT_EQ(ret, 0); // No matter if service exist or not, ServiceControl always success.
auto status = GetServiceStatus(serviceName);
EXPECT_TRUE(status == "idle");
}
HWTEST_F(ServiceControlTest, ServiceStopTest, TestSize.Level1)
{
std::string serviceName = "media_service";
auto status = GetServiceStatus(serviceName);
if (status == "stopped" || status == "created") {
int ret = ServiceControl(serviceName.c_str(), START);
ASSERT_EQ(ret, 0); // start must be success
} else if (status != "running") {
std::cout << serviceName << " in invalid status " << status << std::endl;
ASSERT_TRUE(0);
}
int ret = ServiceControl(serviceName.c_str(), STOP);
EXPECT_EQ(ret, 0);
// Sleep for a while, let init handle service starting.
const int64_t ms = 500;
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
status = GetServiceStatus(serviceName);
bool isStopped = status == "stopped";
EXPECT_TRUE(isStopped);
}
HWTEST_F(ServiceControlTest, NonExistServiceStopTest, TestSize.Level1)
{
std::string serviceName = "non_exist_service";
int ret = ServiceControl(serviceName.c_str(), STOP);
EXPECT_EQ(ret, 0); // No matter if service exist or not, ServiceControl always success.
auto status = GetServiceStatus(serviceName);
EXPECT_TRUE(status == "idle");
}
HWTEST_F(ServiceControlTest, ServiceTimerStartTest, TestSize.Level1)
{
uint64_t timeout = 1000; // Start service in 1 second
std::string serviceName = "media_service";
// stop this service first
int ret = ServiceControl(serviceName.c_str(), STOP);
auto oldStatus = GetServiceStatus(serviceName);
bool isRunning = oldStatus == "running";
EXPECT_FALSE(isRunning);
ret = StartServiceByTimer(serviceName.c_str(), timeout);
EXPECT_EQ(ret, 0);
// Service will be started in @timeout seconds
// Now we try to sleep about @timeout / 2 seconds, then check service status.
int64_t ms = 600;
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
// Get service status.
auto newStatus = GetServiceStatus(serviceName);
bool notChange = oldStatus == newStatus;
EXPECT_TRUE(notChange);
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
newStatus = GetServiceStatus(serviceName);
isRunning = newStatus == "running";
EXPECT_TRUE(isRunning);
}
HWTEST_F(ServiceControlTest, ServiceTimerStartContinuouslyTest, TestSize.Level1)
{
uint64_t oldTimeout = 500;
uint64_t newTimeout = 1000;
std::string serviceName = "media_service";
int ret = ServiceControl(serviceName.c_str(), STOP);
EXPECT_EQ(ret, 0);
ret = ServiceWaitForStatus(serviceName.c_str(), SERVICE_STOPPED, WAIT_SERVICE_STATUS_TIMEOUT);
EXPECT_EQ(ret, 0);
auto oldStatus = GetServiceStatus(serviceName);
bool isRunning = oldStatus == "running";
EXPECT_FALSE(isRunning);
ret = StartServiceByTimer(serviceName.c_str(), oldTimeout); // Set timer as 500 ms
EXPECT_EQ(ret, 0);
ret = StartServiceByTimer(serviceName.c_str(), newTimeout); // Set timer as 1 second
EXPECT_EQ(ret, 0);
std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<int64_t>(oldTimeout)));
auto newStatus = GetServiceStatus(serviceName);
bool notChange = oldStatus == newStatus;
EXPECT_TRUE(notChange);
uint64_t margin = 20; // 20 ms margin in case of timer not that precisely
std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<int64_t>(oldTimeout + margin)));
newStatus = GetServiceStatus(serviceName);
isRunning = newStatus == "running";
EXPECT_TRUE(isRunning);
}
HWTEST_F(ServiceControlTest, ServiceTimerStopTest, TestSize.Level1)
{
uint64_t timeout = 1000; // set timer as 1 second
std::string serviceName = "media_service";
int ret = ServiceControl(serviceName.c_str(), STOP);
EXPECT_EQ(ret, 0);
ret = ServiceWaitForStatus(serviceName.c_str(), SERVICE_STOPPED, WAIT_SERVICE_STATUS_TIMEOUT);
EXPECT_EQ(ret, 0);
auto oldStatus = GetServiceStatus(serviceName);
bool isRunning = oldStatus == "running";
EXPECT_FALSE(isRunning);
ret = StartServiceByTimer(serviceName.c_str(), timeout);
EXPECT_EQ(ret, 0);
// Now sleep for a while
int64_t ms = 300;
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
auto newStatus = GetServiceStatus(serviceName);
bool notChange = oldStatus == newStatus;
EXPECT_TRUE(notChange);
ret = StopServiceTimer(serviceName.c_str());
EXPECT_EQ(ret, 0);
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
newStatus = GetServiceStatus(serviceName);
notChange = oldStatus == newStatus;
EXPECT_TRUE(notChange);
}
HWTEST_F(ServiceControlTest, ServiceTimerStopLateTest, TestSize.Level1)
{
uint64_t timeout = 500; // set timer as 5 micro seconds
std::string serviceName = "media_service";
int ret = ServiceControl(serviceName.c_str(), STOP);
auto oldStatus = GetServiceStatus(serviceName);
bool isRunning = oldStatus == "running";
EXPECT_FALSE(isRunning);
ret = StartServiceByTimer(serviceName.c_str(), timeout);
EXPECT_EQ(ret, 0);
int64_t ms = 550;
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
ret = StopServiceTimer(serviceName.c_str());
EXPECT_EQ(ret, 0);
auto newStatus = GetServiceStatus(serviceName);
isRunning = newStatus == "running";
EXPECT_TRUE(isRunning);
}
HWTEST_F(ServiceControlTest, RestartServiceTest, TestSize.Level1)
{
std::string serviceName = "media_service";
auto status = GetServiceStatus(serviceName);
EXPECT_FALSE(status.empty());
int ret = ServiceControl(serviceName.c_str(), RESTART);
EXPECT_EQ(ret, 0);
ret = ServiceControl(serviceName.c_str(), STOP);
EXPECT_EQ(ret, 0);
ret = ServiceWaitForStatus(serviceName.c_str(), SERVICE_STOPPED, WAIT_SERVICE_STATUS_TIMEOUT);
EXPECT_EQ(ret, 0);
ret = ServiceControl(serviceName.c_str(), RESTART);
EXPECT_EQ(ret, 0);
status = GetServiceStatus(serviceName);
bool isRunning = status == "running";
EXPECT_TRUE(isRunning);
}
HWTEST_F(ServiceControlTest, WaitForServiceStatusTest, TestSize.Level1)
{
std::string serviceName = "media_service";
int ret = ServiceControl(serviceName.c_str(), STOP);
EXPECT_EQ(ret, 0);
ret = ServiceWaitForStatus(serviceName.c_str(), SERVICE_STOPPED, WAIT_SERVICE_STATUS_TIMEOUT);
EXPECT_EQ(ret, 0);
auto status = GetServiceStatus(serviceName);
bool isStopped = status == "stopped";
EXPECT_TRUE(isStopped);
// service is stopped now. try to wait a status which will not be set
std::cout << "Wait for service " << serviceName << " status change to start\n";
ret = ServiceWaitForStatus(serviceName.c_str(), SERVICE_STARTED, WAIT_SERVICE_STATUS_TIMEOUT);
EXPECT_EQ(ret, -1);
serviceName = "non-exist-service";
std::cout << "Wait for service " << serviceName << " status change to stop\n";
ret = ServiceWaitForStatus(serviceName.c_str(), SERVICE_STOPPED, WAIT_SERVICE_STATUS_TIMEOUT);
EXPECT_EQ(ret, -1);
}
} // initModuleTest
/*
* 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 <thread>
#include <string>
#include <gtest/gtest.h>
#include "service_control.h"
#include "service_watcher.h"
#include "test_utils.h"
using namespace testing::ext;
namespace initModuleTest {
class serviceWatcherModuleTest : public testing::Test {
public:
static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {};
void SetUp(void) {};
void TearDown(void) {};
};
static void ServiceStatusChange(const char *key, ServiceStatus status)
{
std::cout<<"service Name is: "<<key<<", ServiceStatus is: "<<status<<std::endl;
}
HWTEST_F(serviceWatcherModuleTest,serviceWatcher_test_001, TestSize.Level0)
{
GTEST_LOG_(INFO) << "serviceWatcher_test_001 start";
string serviceName = "test.Service";
int ret = ServiceWatchForStatus(serviceName.c_str(), ServiceStatusChange);
EXPECT_EQ(ret, 0); // No matter if service exist or not, ServiceWatchForStatus always success.
auto status = GetServiceStatus(serviceName);
EXPECT_TRUE(status == "idle");
GTEST_LOG_(INFO) << "serviceWatcher_test_001 end";
}
HWTEST_F(serviceWatcherModuleTest,serviceWatcher_test_002, TestSize.Level0)
{
GTEST_LOG_(INFO) << "serviceWatcher_test_002 start";
string serviceName = "media_service";
auto status = GetServiceStatus(serviceName);
if (status == "running") {
int ret = ServiceControl(serviceName.c_str(), STOP);
ASSERT_EQ(ret , 0);
} else if (status != "created" && status != "stopped") {
std::cout << serviceName << " in invalid status " << status << std::endl;
ASSERT_TRUE(0);
}
int ret = ServiceWatchForStatus(serviceName.c_str(), ServiceStatusChange);
EXPECT_EQ(ret, 0);
status = GetServiceStatus(serviceName);
EXPECT_TRUE(status == "stopped");
GTEST_LOG_(INFO) << "serviceWatcher_test_002 end";
}
}
/*
* 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 <thread>
#include <gtest/gtest.h>
#include <stdint.h>
#include "param_wrapper.h"
#include "parameter.h"
#include "parameters.h"
#include "sysversion.h"
#include "param_comm.h"
#include "init_param.h"
#include "sysparam_errno.h"
using namespace std;
using namespace testing::ext;
using namespace OHOS;
const int THREAD_NUM = 5;
namespace initModuleTest {
static void GetAllParameterTestFunc(void)
{
EXPECT_STRNE(GetSecurityPatchTag(), nullptr);
EXPECT_STRNE(GetOSFullName(), nullptr);
EXPECT_STRNE(GetVersionId(), nullptr);
EXPECT_STRNE(GetBuildRootHash(), nullptr);
EXPECT_STRNE(GetOsReleaseType(), nullptr);
GetSdkApiVersion();
EXPECT_STRNE(GetDeviceType(), nullptr);
EXPECT_STRNE(GetProductModel(), nullptr);
EXPECT_STRNE(GetManufacture(), nullptr);
EXPECT_STRNE(GetBrand(), nullptr);
EXPECT_STRNE(GetMarketName(), nullptr);
EXPECT_STRNE(GetProductSeries(), nullptr);
EXPECT_STRNE(GetSoftwareModel(), nullptr);
EXPECT_STRNE(GetHardwareModel(), nullptr);
EXPECT_STRNE(GetHardwareProfile(), nullptr);
EXPECT_STRNE(GetSerial(), nullptr);
EXPECT_STRNE(GetAbiList(), nullptr);
EXPECT_STRNE(GetDisplayVersion(), nullptr);
EXPECT_STRNE(GetIncrementalVersion(), nullptr);
EXPECT_STRNE(GetBootloaderVersion(), nullptr);
EXPECT_STRNE(GetBuildType(), nullptr);
EXPECT_STRNE(GetBuildUser(), nullptr);
EXPECT_STRNE(GetBuildHost(), nullptr);
EXPECT_STRNE(GetBuildTime(), nullptr);
GetFirstApiVersion();
EXPECT_STRNE(system::GetDeviceType().c_str(), nullptr);
}
static void GetUdidTestFunc(char* udid, int size)
{
int ret = GetDevUdid(udid, size);
EXPECT_EQ(ret, 0);
EXPECT_STRNE(udid, nullptr);
}
static void SetParameterTestFunc(const char *key, const char *value)
{
EXPECT_EQ(SetParameter(key, value), 0);
uint32_t handle = FindParameter(key);
EXPECT_NE(handle, static_cast<unsigned int>(-1));
uint32_t result = GetParameterCommitId(handle);
EXPECT_NE(result, static_cast<unsigned int>(-1));
char nameGet[64] = {0};
int ret = GetParameterName(handle, nameGet, 64);
EXPECT_EQ(ret, strlen(nameGet));
EXPECT_STREQ(key, nameGet);
char valueGet[64] = {0};
ret = GetParameterValue(handle, valueGet, 64);
EXPECT_EQ(ret, strlen(valueGet));
EXPECT_STREQ(value, valueGet);
EXPECT_NE(GetSystemCommitId(), 0);
}
static void GetParameterTestReInt(const char *key, const char *def, char *value, uint32_t len)
{
int ret = GetParameter(key, def, value, len);
EXPECT_EQ(ret, strlen(value));
EXPECT_STREQ(value, "v10.1.1");
}
static void GetParameterTestFuncReStr(string key, string def)
{
string ret = system::GetParameter(key, def);
EXPECT_STREQ(ret.c_str(), "v10.1.1");
}
static void ParamSetFun(string key, string value)
{
bool ret = system::SetParameter(key, value);
EXPECT_TRUE(ret);
string testValue = system::GetParameter(key, "");
EXPECT_STREQ(testValue.c_str(), value.c_str());
}
static void TestParameterChange(const char *key, const char *value, void *context)
{
std::cout<<"TestParameterChange key: "<<key<<"value: "<<value<<endl;
}
static void TestParameterWatchChange(void)
{
size_t index = 1;
int ret = WatchParameter("test.param.watcher.test1", TestParameterChange, (void *)index);
EXPECT_EQ(ret, 0);
ret = RemoveParameterWatcher("test.param.watcher.test1", TestParameterChange, (void *)index);
EXPECT_EQ(ret, 0);
}
class SysparaModuleTest : public testing::Test {
public:
static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {};
void SetUp(void) {};
void TearDown(void) {};
};
HWTEST_F(SysparaModuleTest, Syspara_SysVersion_test_001, TestSize.Level0)
{
GTEST_LOG_(INFO) << "Syspara_SysVersion_test_001 start";
GetMajorVersion();
GetSeniorVersion();
GetFeatureVersion();
GetBuildVersion();
GTEST_LOG_(INFO) << "Syspara_SysVersion_test_001 end";
}
HWTEST_F(SysparaModuleTest, Syspara_GetParam_test_002, TestSize.Level0)
{
GTEST_LOG_(INFO) << "Syspara_GetParam_test_002 start";
for(int i = 0; i < THREAD_NUM; ++i) {
std::thread(GetAllParameterTestFunc).join();
}
GTEST_LOG_(INFO) << "Syspara_GetParam_test_002 end";
}
HWTEST_F(SysparaModuleTest, Syspara_GetUdid_test_003, TestSize.Level0)
{
GTEST_LOG_(INFO) << "Syspara_GetUdid_test_003 start";
for(int i = 0; i < THREAD_NUM; ++i) {
char udid[UDID_LEN] = {0};
std::thread(GetUdidTestFunc, udid, UDID_LEN).join();
}
GTEST_LOG_(INFO) << "Syspara_GetUdid_test_003 end";
}
HWTEST_F(SysparaModuleTest, Syspara_SetParameter_test_004, TestSize.Level0)
{
GTEST_LOG_(INFO) << "Syspara_SetParameter_test_004 start";
char key1[] = "test1.param.version";
char value1[] = "v10.1.1";
char key2[] = "test2.param.version";
char value2[] = "v10.2.2";
char key3[] = "test3.param.version";
char value3[] = "v10.3.3";
std::thread(SetParameterTestFunc, key1, value1).join();
std::thread(SetParameterTestFunc, key2, value2).join();
std::thread(SetParameterTestFunc, key3, value3).join();
GTEST_LOG_(INFO) << "Syspara_SetParameter_test_004 end";
}
HWTEST_F(SysparaModuleTest, Syspara_SetParameter_test_005, TestSize.Level0)
{
GTEST_LOG_(INFO) << "Syspara_SetParameter_test_005 start";
//check param name length
char key1[] = "test.param.name.xxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxx";
char value[] = "test.value.xxxx";
int ret = SetParameter(key1, value);
EXPECT_EQ(ret, EC_INVALID);
//check param name, Illegal param name
char key2[] = ".test.param.name.xxxxx";
ret = SetParameter(key2, value);
EXPECT_EQ(ret, EC_INVALID);
char key3[] = "test..param.name.xxxxx";
ret = SetParameter(key3, value);
EXPECT_EQ(ret, EC_INVALID);
char key4[] = "test..param. .name";
ret = SetParameter(key4, value);
EXPECT_EQ(ret, EC_INVALID);
//check param name, legal param name
char key5[] = "test.param.name.--__.:::";
ret = SetParameter(key5, value);
EXPECT_EQ(ret, 0);
EXPECT_STREQ(value, "test.value.xxxx");
char key6[] = "test.param.name.@@@.---";
ret = SetParameter(key6, value);
EXPECT_EQ(ret, 0);
EXPECT_STREQ(value, "test.value.xxxx");
//not const param, check param value, bool 8, int 32, other 96
char key7[] = "test.param.name.xxxx";
char value1[] = "test.value.xxxxxxxxx.xxxxxxxxxxxxx.xxxxxxxxxxxx.xxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxx";
ret = SetParameter(key7, value1);
EXPECT_EQ(ret, SYSPARAM_INVALID_VALUE);
char key8[] = "startup.service.ctl.test.int";
char value2[] = "111111111111111111111111111111111";
ret = SetParameter(key8, value2);
EXPECT_EQ(ret, SYSPARAM_INVALID_VALUE);
GTEST_LOG_(INFO) << "Syspara_SetParameter_test_005 end";
}
HWTEST_F(SysparaModuleTest, Syspara_Getparameter_test_006, TestSize.Level0)
{
GTEST_LOG_(INFO) << "Syspara_Getparameter_test_006 start";
string key = "test.param.set.001";
string value = "xxx.xxx.xxx";
bool ret = system::SetParameter(key, value);
EXPECT_TRUE(ret);
string testValue = system::GetParameter(key, "");
EXPECT_STREQ(testValue.c_str(), value.c_str());
//not read param value,the result is default
testValue = system::GetParameter("test.param.set.002", "aaa.aaa.aaa");
EXPECT_STREQ(testValue.c_str(), "aaa.aaa.aaa");
testValue = system::GetParameter("test.param.set.003", "");
EXPECT_STREQ(testValue.c_str(), "");
//correct set value
string key1 = "test.param.set.bool";
ret = system::SetParameter(key1, "1");
EXPECT_TRUE(ret);
EXPECT_TRUE(system::GetBoolParameter(key1, false));
ret = system::SetParameter(key1, "y");
EXPECT_TRUE(ret);
EXPECT_TRUE(system::GetBoolParameter(key1, false));
ret = system::SetParameter(key1, "yes");
EXPECT_TRUE(ret);
EXPECT_TRUE(system::GetBoolParameter(key1, false));
ret = system::SetParameter(key1, "on");
EXPECT_TRUE(ret);
EXPECT_TRUE(system::GetBoolParameter(key1, false));
ret = system::SetParameter(key1, "true");
EXPECT_TRUE(ret);
EXPECT_TRUE(system::GetBoolParameter(key1, false));
ret = system::SetParameter(key1, "0");
EXPECT_TRUE(ret);
EXPECT_FALSE(system::GetBoolParameter(key1, true));
ret = system::SetParameter(key1, "off");
EXPECT_TRUE(ret);
EXPECT_FALSE(system::GetBoolParameter(key1, true));
ret = system::SetParameter(key1, "n");
EXPECT_TRUE(ret);
EXPECT_FALSE(system::GetBoolParameter(key1, true));
ret = system::SetParameter(key1, "no");
EXPECT_TRUE(ret);
EXPECT_FALSE(system::GetBoolParameter(key1, true));
ret = system::SetParameter(key1, "false");
EXPECT_TRUE(ret);
EXPECT_FALSE(system::GetBoolParameter(key1, true));
//set value type not bool,the result get form def
ret = system::SetParameter(key1, "test");
EXPECT_TRUE(ret);
EXPECT_TRUE(system::GetBoolParameter(key1, true));
EXPECT_FALSE(system::GetBoolParameter(key1, false));
GTEST_LOG_(INFO) << "Syspara_Getparameter_test_006 end";
}
HWTEST_F(SysparaModuleTest, Syspara_SetParameter_test_007, TestSize.Level0)
{
GTEST_LOG_(INFO) << "Syspara_SetParameter_test_007 start";
string key1 = "const.param.test";
string value1 = "test.param.value.001";
int ret = 0;
string vRet = "";
uint32_t handle1 = FindParameter(key1.c_str());
cout<<"handle1 is: "<<handle1<<std::endl;
if (handle1 == (uint32_t)-1) {
ret = SetParameter(key1.c_str(), value1.c_str());
EXPECT_EQ(ret, 0);
vRet = system::GetParameter(key1, "");
EXPECT_STREQ(vRet.c_str(), value1.c_str());
}
string value2 = "test.param.value.002";
ret = SetParameter(key1.c_str(), value2.c_str());
EXPECT_EQ(ret, EC_INVALID);
string key2 = "ro.param.test";
string value3 = "test.param.value.003";
uint32_t handle2 = FindParameter(key2.c_str());
cout<<"handle2 is: "<<handle2<<std::endl;
if (handle2 == (uint32_t)-1) {
ret = SetParameter(key2.c_str(), value3.c_str());
EXPECT_EQ(ret, 0);
vRet = system::GetParameter(key2, "");
EXPECT_STREQ(vRet.c_str(), value3.c_str());
}
string value4 = "test.param.value.004";
ret = SetParameter(key2.c_str(), value4.c_str());
EXPECT_EQ(ret, EC_INVALID);
GTEST_LOG_(INFO) << "Syspara_SetParameter_test_007 end";
}
HWTEST_F(SysparaModuleTest, Syspara_GetParameterReIntOrStr_test_008, TestSize.Level0)
{
GTEST_LOG_(INFO) << "Syspara_GetParameterReIntOrStr_test_008 start";
string key = "test1.param.version";
string value = "v10.1.1";
int ret = SetParameter(key.c_str(), value.c_str());
EXPECT_EQ(ret, 0);
char retValue[PARAM_VALUE_LEN_MAX] = {0};
for(int i = 0; i < THREAD_NUM; ++i) {
std::thread(GetParameterTestReInt, key.c_str(), "", retValue, PARAM_VALUE_LEN_MAX).join();
}
for(int j = 0; j < THREAD_NUM; ++j) {
std::thread(GetParameterTestFuncReStr, key, "").join();
}
GTEST_LOG_(INFO) << "Syspara_GetParameterReIntOrStr_test_008 end";
}
HWTEST_F(SysparaModuleTest, Syspara_WaitParameter_test_009, TestSize.Level0)
{
GTEST_LOG_(INFO) << "Syspara_WaitParameter_test_009 start";
//param already set succeed,waitParamter succeed.
char key[] = "test1.param.wait";
char value[] = "aaa.bbb.ccc";
int ret = SetParameter(key, value);
EXPECT_EQ(ret, 0);
ret = WaitParameter(key, value, 5);
EXPECT_EQ(ret, 0);
// param not set,waitParamter will wait param set,return succeed.
char key1[] = "test2.param.wait";
char value1[] = "aaa.aaa.aaa";
std::thread(ParamSetFun, key1, value1).join();
ret = WaitParameter(key1, value1, 5);
EXPECT_EQ(ret, 0);
char key2[] = "test3.param.wait";
std::thread(ParamSetFun, key2, "*****").join();
ret = WaitParameter(key2, "*****", 5);
EXPECT_EQ(ret, 0);
// param not set,waitParamter will timeout,return failed.
char key3[] = "test4.param.wait";
ret = WaitParameter(key3, "*****", 5);
EXPECT_EQ(ret, SYSPARAM_WAIT_TIMEOUT);
GTEST_LOG_(INFO) << "Syspara_WaitParameter_test_009 end";
}
HWTEST_F(SysparaModuleTest, Syspara_watcherParameter_test_010, TestSize.Level0)
{
GTEST_LOG_(INFO) << "Syspara_watcherParameter_test_010 start";
for(int i = 0; i < THREAD_NUM; ++i) {
std::thread(TestParameterWatchChange).join();
}
std::thread(ParamSetFun, "test.param.watcher.test1", "test.param.value.xxx").join();
GTEST_LOG_(INFO) << "Syspara_watcherParameter_test_010 end";
}
HWTEST_F(SysparaModuleTest, Syspara_GetParameter_test_011, TestSize.Level0)
{
GTEST_LOG_(INFO) << "Syspara_GetParameter_test_011 start";
char key1[] = "test.param.int1";
char value1[] = "0x111111";
int setRet = SetParameter(key1, value1);
EXPECT_EQ(setRet, 0);
int32_t getRet = GetIntParameter(key1, 0);
EXPECT_EQ(getRet, 1118481); //0x111111 decimalism result
uint32_t uRet = GetUintParameter(key1, 0);
EXPECT_EQ(uRet, 1118481);
char key2[] = "test.param.int2";
char value2[] = "-0x111111";
setRet = SetParameter(key2, value2);
EXPECT_EQ(setRet, 0);
getRet = GetIntParameter(key2, 0);
EXPECT_EQ(getRet, -1118481); //0x111111 decimalism result
uRet = GetUintParameter(key2, 0);
char key3[] = "test.param.int3";
char value3[] = "9999999";
setRet = SetParameter(key3, value3);
EXPECT_EQ(setRet, 0);
getRet = GetIntParameter(key3, 0);
EXPECT_EQ(getRet, 9999999); //value3 int result
uRet = GetUintParameter(key3, 0);
EXPECT_EQ(uRet, 9999999); //value3 uint result
char key4[] = "test.param.int4";
char value4[] = "-9999999";
setRet = SetParameter(key4, value4);
EXPECT_EQ(setRet, 0);
getRet = GetIntParameter(key4, 0);
EXPECT_EQ(getRet, -9999999); //value4 int result
uRet = GetUintParameter(key4, 0);
EXPECT_EQ(uRet, 0);
char key5[] = "test.param.int5";
char value5[] = "-2147483648"; //INT32_MIN
setRet = SetParameter(key5, value5);
EXPECT_EQ(setRet, 0);
getRet = GetIntParameter(key5, 0);
EXPECT_EQ(getRet, 0);
char key6[] = "test.param.int6";
char value6[] = "2147483647"; //INT32_MAX
setRet = SetParameter(key6, value6);
EXPECT_EQ(setRet, 0);
getRet = GetIntParameter(key6, 0);
EXPECT_EQ(getRet, 0);
char key7[] = "test.param.uint7";
char value7[] = "4294967295"; //UINT32_MAX
setRet = SetParameter(key7, value7);
EXPECT_EQ(setRet, 0);
uRet = GetUintParameter(key7, 0);
EXPECT_EQ(uRet, 0);
GTEST_LOG_(INFO) << "Syspara_GetParameter_test_011 end";
}
}
\ No newline at end of file
/*
* 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 "test_utils.h"
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <list>
#include <thread>
#include <memory>
#include <fcntl.h>
#include <cerrno>
#include <sys/stat.h>
#include "parameters.h"
#include "service_control.h"
namespace initModuleTest {
namespace {
constexpr size_t MAX_BUFFER_SIZE = 4096;
}
// File operator
int ReadFileContent(const std::string &fileName, std::string &content)
{
content.clear();
auto fp = std::unique_ptr<FILE, decltype(&fclose)>(fopen(fileName.c_str(), "r"), fclose);
if (fp == nullptr) {
std::cout << "Cannot open file " << fileName << std::endl;
return -1;
}
struct stat st {};
if (stat(fileName.c_str(), &st) < 0) {
std::cout << "Cannot get " << fileName << " stat\n";
return -1;
}
ssize_t n = 0;
char buffer[MAX_BUFFER_SIZE] = {};
while ((n = fread(buffer, 1, MAX_BUFFER_SIZE, fp.get())) > 0) {
content.append(buffer, n);
}
return feof(fp.get()) ? 0 : -1;
}
bool StartsWith(const std::string &str, const std::string &prefix)
{
return ((str.size() > prefix.size()) && (str.substr(0, prefix.size()) == prefix));
}
bool EndsWith(const std::string &str, const std::string &suffix)
{
return ((str.size() > suffix.size()) && (str.substr(str.size() - suffix.size(), suffix.size()) == suffix));
}
std::string Trim(const std::string &str)
{
size_t start = 0;
size_t end = str.size() - 1;
while (start < str.size()) {
if (!isspace(str[start])) {
break;
}
start++;
}
while (start < end) {
if (!isspace(str[end])) {
break;
}
end--;
}
if (end < start) {
return "";
}
return str.substr(start, end - start + 1);
}
std::vector<std::string> Split(const std::string &str, const std::string &pattern)
{
std::vector<std::string> result {};
size_t pos = std::string::npos;
size_t start = 0;
while (true) {
pos = str.find_first_of(pattern, start);
result.push_back(str.substr(start, pos - start));
if (pos == std::string::npos) {
break;
}
start = pos + 1;
}
return result;
}
static std::map<ServiceStatus, std::string> g_serviceStatusMap = {
{ SERVICE_IDLE, "idle"},
{ SERVICE_STARTING, "starting"},
{ SERVICE_STARTED, "running"},
{ SERVICE_READY, "ready"},
{ SERVICE_STOPPING, "stopping"},
{ SERVICE_STOPPED, "stopped"},
{ SERVICE_ERROR, "error" },
{ SERVICE_SUSPENDED, "suspended" },
{ SERVICE_FREEZED, "freezed" },
{ SERVICE_DISABLED, "disabled" },
{ SERVICE_CRITICAL, "critical" },
};
static inline bool ValidStatus(ServiceStatus status)
{
return status >= SERVICE_IDLE && status <= SERVICE_CRITICAL;
}
std::string GetServiceStatus(const std::string &serviceName)
{
if (serviceName.empty()) {
return "";
}
const std::string serviceCtlPrefix = "startup.service.ctl.";
const std::string serviceCtlName = serviceCtlPrefix + serviceName;
uint32_t ret = OHOS::system::GetUintParameter<uint32_t>(serviceCtlName, 0);
ServiceStatus status = static_cast<ServiceStatus>(ret);
if (!ValidStatus(status)) {
return "";
}
return g_serviceStatusMap[status];
}
} // initModuleTest
/*
* 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.
*/
#ifndef INIT_MODULE_TEST_UTILS_H
#define INIT_MODULE_TEST_UTILS_H
#include <string>
#include <vector>
namespace initModuleTest {
// File operator
int ReadFileContent(const std::string &fileName, std::string &content);
std::string Trim(const std::string &str);
std::vector<std::string> Split(const std::string &str, const std::string &pattern);
std::string GetServiceStatus(const std::string &serviceName);
} // initModuleTest
#endif // INIT_MODULE_TEST_UTILS_H
......@@ -241,6 +241,7 @@ ohos_unittest("init_unittest") {
"_GNU_SOURCE",
"PARAM_SUPPORT_TRIGGER",
"USE_MBEDTLS",
"PARAM_DECODE_GROUPID_FROM_FILE",
]
defines += [ "_GNU_SOURCE" ]
......
......@@ -271,10 +271,6 @@ HWTEST_F(CmdsUnitTest, TestGetCmdLinesFromJson, TestSize.Level1)
HWTEST_F(CmdsUnitTest, TestInitCmdFunc, TestSize.Level1)
{
int ret = GetBootModeFromMisc();
#ifdef __MUSL__
EXPECT_EQ(ret, 0);
#else
EXPECT_NE(ret, 0);
#endif
}
} // namespace init_ut
......@@ -34,7 +34,7 @@ public:
HWTEST_F(MountUnitTest, TestMountRequriedPartitions, TestSize.Level0)
{
const char *fstabFiles = "/etc/fstab.required";
const char *fstabFiles = "/data/init_ut/etc/fstab.required";
Fstab *fstab = NULL;
fstab = ReadFstabFromFile(fstabFiles, false);
if (fstab != NULL) {
......
......@@ -82,15 +82,18 @@ HWTEST_F(ServiceUnitTest, case02, TestSize.Level1)
cJSON *serviceItem = cJSON_GetObjectItem(jobItem, "services");
ASSERT_NE(nullptr, serviceItem);
Service *service = AddService("test_service8");
ASSERT_NE(nullptr, service);
int ret = ParseOneService(serviceItem, service);
EXPECT_EQ(ret, 0);
int *fds = (int *)malloc(sizeof(int) * 1); // ServiceStop will release fds
ASSERT_NE(nullptr, fds);
UpdaterServiceFds(service, fds, 1);
service->attribute = SERVICE_ATTR_ONDEMAND;
ret = ServiceStart(service);
EXPECT_EQ(ret, 0);
CmdLines *cmdline = (CmdLines *)malloc(sizeof(CmdLines) + sizeof(CmdLine));
ASSERT_NE(nullptr, cmdline);
cmdline->cmdNum = 1;
cmdline->cmds[0].cmdIndex = 0;
service->restartArg = cmdline;
......@@ -213,20 +216,26 @@ HWTEST_F(ServiceUnitTest, TestServiceManagerRelease, TestSize.Level1)
service = AddService("test_service5");
ASSERT_NE(nullptr, service);
service->pathArgs.argv = (char **)malloc(sizeof(char *));
ASSERT_NE(nullptr, service->pathArgs.argv);
service->pathArgs.count = 1;
const char *path = "/data/init_ut/test_service_release";
service->pathArgs.argv[0] = strdup(path);
service->writePidArgs.argv = (char **)malloc(sizeof(char *));
ASSERT_NE(nullptr, service->writePidArgs.argv);
service->writePidArgs.count = 1;
service->writePidArgs.argv[0] = strdup(path);
service->servPerm.caps = (unsigned int *)malloc(sizeof(unsigned int));
ASSERT_NE(nullptr, service->servPerm.caps);
service->servPerm.gIDArray = (gid_t *)malloc(sizeof(gid_t));
ASSERT_NE(nullptr, service->servPerm.gIDArray);
service->socketCfg = (ServiceSocket *)malloc(sizeof(ServiceSocket));
ASSERT_NE(nullptr, service->socketCfg);
service->socketCfg->sockFd = 0;
service->socketCfg->next = nullptr;
service->fileCfg = (ServiceFile *)malloc(sizeof(ServiceFile));
ASSERT_NE(nullptr, service->fileCfg);
service->fileCfg->fd = 0;
service->fileCfg->next = nullptr;
ReleaseService(service);
......@@ -330,6 +339,7 @@ HWTEST_F(ServiceUnitTest, TestServiceExec, TestSize.Level1)
service->servPerm.gIDCnt = -1;
service->servPerm.uID = 0;
unsigned int *caps = (unsigned int *)calloc(1, sizeof(unsigned int) * 1);
ASSERT_NE(nullptr, caps);
caps[0] = FULL_CAP;
service->servPerm.caps = caps;
service->servPerm.capsCnt = 1;
......
......@@ -218,7 +218,7 @@ HWTEST_F(InnerkitsUnitTest, DoFormat_unittest, TestSize.Level1)
*/
HWTEST_F(InnerkitsUnitTest, MountAllWithFstabFile_unittest, TestSize.Level1)
{
EXPECT_NE(MountAllWithFstabFile("/etc/fstab.required", 0), 1);
EXPECT_NE(MountAllWithFstabFile("/data/init_ut/etc/fstab.required", 0), 1);
}
HWTEST_F(InnerkitsUnitTest, others_unittest, TestSize.Level1)
......
......@@ -123,10 +123,10 @@ HWTEST_F(ModuleMgrUnitTest, ModuleInstallTest, TestSize.Level1)
ModuleMgrDestroy(moduleMgr);
// Scan all modules
moduleMgr = ModuleMgrScan("init");
moduleMgr = ModuleMgrScan("init/autorun");
ASSERT_NE(moduleMgr, nullptr);
cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_NE(cnt, 0);
ASSERT_EQ(cnt, 0);
ModuleMgrUninstall(moduleMgr, NULL);
cnt = ModuleMgrGetCnt(moduleMgr);
......
......@@ -124,7 +124,7 @@ public:
}
void SetUp()
{
EnableInitLog();
EnableInitLog(INIT_FATAL);
}
void TearDown() {}
};
......@@ -180,7 +180,7 @@ HWTEST_F(StartupInitUTest, cmdFuncParseCmdTest_001, TestSize.Level0)
HWTEST_F(StartupInitUTest, cmdFuncParseCmdTest_002, TestSize.Level0)
{
TestCmdLine curCmdLine;
memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
(void)memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
ParseCmdLine(nullptr, &curCmdLine);
EXPECT_EQ(0, strlen(curCmdLine.name));
......@@ -207,7 +207,7 @@ HWTEST_F(StartupInitUTest, cmdFuncParseCmdTest_002, TestSize.Level0)
HWTEST_F(StartupInitUTest, cmdFuncParseCmdTest_003, TestSize.Level0)
{
TestCmdLine curCmdLine;
memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
(void)memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
for (size_t i = 0; i < g_supportedCmds.size(); ++i) {
ParseCmdLine(g_supportedCmds[i].c_str(), &curCmdLine);
......@@ -224,10 +224,12 @@ HWTEST_F(StartupInitUTest, cmdFuncParseCmdTest_003, TestSize.Level0)
HWTEST_F(StartupInitUTest, cmdFuncParseCmdTest_004, TestSize.Level0)
{
TestCmdLine curCmdLine;
memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
(void)memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
char toLongContent[MAX_CMD_CONTENT_LEN + 10];
memset_s(toLongContent, MAX_CMD_CONTENT_LEN + 10, 'x', MAX_CMD_CONTENT_LEN + 9);
int ret = memset_s(toLongContent, MAX_CMD_CONTENT_LEN + 10, 'x', MAX_CMD_CONTENT_LEN + 9);
EXPECT_EQ(0, ret);
toLongContent[MAX_CMD_CONTENT_LEN + 9] = '\0';
for (size_t i = 0; i < g_supportedCmds.size(); ++i) {
size_t curCmdLen = g_supportedCmds[i].length();
......@@ -262,7 +264,7 @@ HWTEST_F(StartupInitUTest, cmdFuncParseCmdTest_004, TestSize.Level0)
HWTEST_F(StartupInitUTest, cmdFuncParseCmdTest_005, TestSize.Level0)
{
TestCmdLine curCmdLine;
memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
(void)memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
ParseCmdLine("start InitTestService", &curCmdLine);
EXPECT_EQ(0, strcmp("start ", curCmdLine.name));
......@@ -304,7 +306,7 @@ HWTEST_F(StartupInitUTest, cmdFuncDoCmdTest_001, TestSize.Level0)
HWTEST_F(StartupInitUTest, cmdFuncDoCmdTest_002, TestSize.Level0)
{
TestCmdLine curCmdLine;
memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
(void)memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
std::string cmdStr = "start ";
std::string cmdContentStr = "NameNotExist";
......@@ -323,7 +325,7 @@ HWTEST_F(StartupInitUTest, cmdFuncDoCmdTest_002, TestSize.Level0)
HWTEST_F(StartupInitUTest, cmdFuncDoCmdTest_003, TestSize.Level0)
{
TestCmdLine curCmdLine;
memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
(void)memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
std::string cmdStr = "mkdir ";
std::string cmdContentStr = "/DirNotExist/DirNotExist/DirNotExist";
......@@ -368,7 +370,7 @@ HWTEST_F(StartupInitUTest, cmdFuncDoCmdTest_003, TestSize.Level0)
HWTEST_F(StartupInitUTest, cmdFuncDoCmdTest_004, TestSize.Level0)
{
TestCmdLine curCmdLine;
memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
(void)memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
std::string cmdStr = "chmod ";
std::string cmdContentStr = "755 " + TEST_FILE; // should be 0755, wrong format here
......@@ -424,7 +426,7 @@ HWTEST_F(StartupInitUTest, cmdFuncDoCmdTest_004, TestSize.Level0)
HWTEST_F(StartupInitUTest, cmdFuncDoCmdTest_005, TestSize.Level0)
{
TestCmdLine curCmdLine;
memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
(void)memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
std::string cmdStr = "chown ";
std::string cmdContentStr = "888 " + TEST_FILE; // uid or gid missing, wrong format here
......@@ -629,12 +631,12 @@ static void CheckService(const cJSON* curItem)
}
cJSON *filedJ = cJSON_GetObjectItem(curItem, "uid");
EXPECT_TRUE(cJSON_IsNumber(filedJ));
EXPECT_TRUE(cJSON_GetNumberValue(filedJ) >= 0.0);
EXPECT_TRUE(cJSON_IsNumber(filedJ) || cJSON_IsString(filedJ));
EXPECT_TRUE(cJSON_GetNumberValue(filedJ) >= 0.0 || cJSON_GetStringValue(filedJ));
filedJ = cJSON_GetObjectItem(curItem, "gid");
EXPECT_TRUE(cJSON_IsNumber(filedJ));
EXPECT_TRUE(cJSON_GetNumberValue(filedJ) >= 0.0);
EXPECT_TRUE(cJSON_IsNumber(filedJ) || cJSON_IsArray(filedJ));
EXPECT_TRUE(cJSON_GetNumberValue(filedJ) >= 0.0 || cJSON_GetArraySize(filedJ) >= 0);
filedJ = cJSON_GetObjectItem(curItem, "once");
EXPECT_TRUE(cJSON_IsNumber(filedJ));
......@@ -648,8 +650,8 @@ static void CheckService(const cJSON* curItem)
EXPECT_TRUE(capsCnt <= MAX_CAPS_CNT_FOR_ONE_SERVICE);
for (int i = 0; i < capsCnt; ++i) {
cJSON *capJ = cJSON_GetArrayItem(filedJ, i);
EXPECT_TRUE(cJSON_IsNumber(capJ));
EXPECT_TRUE(cJSON_GetNumberValue(capJ) >= 0.0);
EXPECT_TRUE(cJSON_IsNumber(capJ) || cJSON_GetStringValue(capJ));
EXPECT_TRUE(cJSON_GetNumberValue(capJ) >= 0.0 || cJSON_GetStringValue(capJ));
}
}
......@@ -829,7 +831,7 @@ static void CreateIllegalCfg()
HWTEST_F(StartupInitUTest, cmdFuncDoLoadCfgTest_001, TestSize.Level0)
{
TestCmdLine curCmdLine;
memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
(void)memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
ParseCmdLine("loadcfg /patch/fstab.cfg", &curCmdLine);
EXPECT_EQ(0, strcmp("loadcfg ", curCmdLine.name));
......@@ -848,7 +850,7 @@ HWTEST_F(StartupInitUTest, cmdFuncDoLoadCfgTest_002, TestSize.Level0)
std::string cmdContentStr = "/patch/file_not_exist.cfg";
struct stat testCfgStat = {0};
memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
(void)memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
std::string command = cmdStr + cmdContentStr;
ParseCmdLine(command.c_str(), &curCmdLine);
EXPECT_EQ(0, strcmp(cmdStr.c_str(), curCmdLine.name));
......@@ -859,7 +861,7 @@ HWTEST_F(StartupInitUTest, cmdFuncDoLoadCfgTest_002, TestSize.Level0)
cmdContentStr = TEST_CFG_ILLEGAL;
CreateIllegalCfg();
memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
(void)memset_s(&curCmdLine, sizeof(curCmdLine), 0, sizeof(curCmdLine));
command = cmdStr + cmdContentStr;
ParseCmdLine(command.c_str(), &curCmdLine);
EXPECT_EQ(0, strcmp(cmdStr.c_str(), curCmdLine.name));
......
......@@ -124,7 +124,7 @@ HWTEST_F(DacUnitTest, TestDacCheckFilePermission, TestSize.Level0)
DacUnitTest test;
test.TestDacCheckFilePermission(STARTUP_INIT_UT_PATH "/trigger_test.cfg");
}
#ifdef __MUSL__
HWTEST_F(DacUnitTest, TestDacCheckUserParaPermission, TestSize.Level0)
{
// 相同用户
......@@ -247,7 +247,7 @@ HWTEST_F(DacUnitTest, TestDacCheckOtherParaPermission, TestSize.Level0)
ret = test.TestDacCheckParaPermission("test.permission.watch.aaa", &dacData, DAC_WATCH);
EXPECT_EQ(ret, 0);
}
#endif
HWTEST_F(DacUnitTest, TestClientDacCheckFilePermission, TestSize.Level0)
{
DacUnitTest test;
......
......@@ -55,7 +55,7 @@ static int TestGenHashCode(const char *buff)
static void TestSetSelinuxLogCallback(void) {}
static const char *forbitWriteParamName[] = {
static const char *forbidWriteParamName[] = {
"ohos.servicectrl.",
"test.permission.read",
"test.persmission.watch"
......@@ -64,9 +64,9 @@ static const char *forbitWriteParamName[] = {
static int TestSetParamCheck(const char *paraName, const char *context, const SrcInfo *info)
{
// forbid to read ohos.servicectrl.
for (size_t i = 0; i < ARRAY_LENGTH(forbitWriteParamName); i++) {
if (strncmp(paraName, forbitWriteParamName[i], strlen(forbitWriteParamName[i])) == 0) {
return 1;
for (size_t i = 0; i < ARRAY_LENGTH(forbidWriteParamName); i++) {
if (strncmp(paraName, forbidWriteParamName[i], strlen(forbidWriteParamName[i])) == 0) {
return g_testPermissionResult;
}
}
return g_testPermissionResult;
......@@ -147,6 +147,18 @@ void TestSetSelinuxOps(void)
selinuxSpace->destroyParamList = TestDestroyParamList;
#endif
}
void TestSetParamCheckResult(const char *prefix, uint16_t mode, int result)
{
ParamAuditData auditData = {};
auditData.name = prefix;
auditData.dacData.gid = 202; // 202 test dac gid
auditData.dacData.uid = 202; // 202 test dac uid
auditData.dacData.mode = mode;
AddSecurityLabel(&auditData);
SetTestPermissionResult(result);
}
static void CreateTestFile(const char *fileName, const char *data)
{
CheckAndCreateDir(fileName);
......@@ -207,14 +219,14 @@ static void PrepareInnerKitsCfg()
"aa aa aa aa\n";
const char *fstabRequired = "# fstab file.\n"
"#<src> <mnt_point> <type> <mnt_flags and options> <fs_mgr_flags>\n"
"/dev/block/platform/fe310000.sdhci/by-name/testsystem /usr ext4 ro,barrier=1 wait,required\n"
"/dev/block/platform/fe310000.sdhci/by-name/testsystem /usr ext4 ro,barrier=1 wait,required,nofail\n"
"/dev/block/platform/fe310000.sdhci/by-name/testvendor /vendor ext4 ro,barrier=1 wait,required\n"
"/dev/block/platform/fe310000.sdhci/by-name/testuserdata1 /data f2fs noatime,nosuid,nodev wait,check,quota\n"
"/dev/block/platform/fe310000.sdhci/by-name/testuserdata2 /data ext4 noatime,fscrypt=xxx wait,check,quota\n"
"/dev/block/platform/fe310000.sdhci/by-name/testmisc /misc none none wait,required";
mkdir("/data/init_ut/mount_unitest/", S_IRWXU | S_IRWXG | S_IRWXO);
CreateTestFile("/data/init_ut/mount_unitest/ReadFstabFromFile1.fstable", innerKitsCfg);
CreateTestFile("/etc/fstab.required", fstabRequired);
CreateTestFile("/data/init_ut/etc/fstab.required", fstabRequired);
}
static void PrepareGroupTestCfg()
{
......@@ -434,7 +446,7 @@ int TestFreeLocalSecurityLabel(ParamSecurityLabel *srcLabel)
static __attribute__((constructor(101))) void ParamTestStubInit(void)
{
EnableInitLog();
EnableInitLog(INIT_DEBUG);
PARAM_LOGI("ParamTestStubInit");
PrepareInitUnitTestEnv();
}
......
......@@ -18,6 +18,8 @@
#include <cstdlib>
#include <cstring>
#include <gtest/gtest.h>
#include <sys/socket.h>
#include <sys/types.h>
#include "param_manager.h"
#include "param_security.h"
......@@ -30,10 +32,27 @@ extern "C" {
#endif
#endif
#ifndef PARAM_SUPPORT_SELINUX
typedef struct ParameterNode {
const char *paraName;
const char *paraContext;
} ParameterNode;
typedef struct ParamContextsList {
struct ParameterNode info;
struct ParamContextsList *next;
} ParamContextsList;
typedef struct SrcInfo {
int sockFd;
struct ucred uc;
} SrcInfo;
#endif
void PrepareInitUnitTestEnv(void);
void TestSetSelinuxOps(void);
void SetTestPermissionResult(int result);
void TestSetParamCheckResult(const char *prefix, uint16_t mode, int result);
int TestCheckParamPermission(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode);
int TestFreeLocalSecurityLabel(ParamSecurityLabel *srcLabel);
......
......@@ -405,7 +405,9 @@ HWTEST_F(ParamUnitTest, TestLinuxRWLock, TestSize.Level0)
ParamRWMutexDelete(nullptr);
ParamMutexDelete(nullptr);
WorkSpace *workspace1 = (WorkSpace *)malloc(sizeof(WorkSpace) + strlen("testfilename1"));
ASSERT_NE(nullptr, workspace1);
WorkSpace *workspace2 = (WorkSpace *)malloc(sizeof(WorkSpace) + strlen("testfilename1"));
ASSERT_NE(nullptr, workspace2);
if (strcpy_s(workspace1->fileName, strlen("testfilename1"), "testfilename") != EOK) {
EXPECT_EQ(0, 1);
}
......
......@@ -445,27 +445,17 @@ public:
return 0;
}
int TestServiceCtrl(const char *serviceName, int mode)
int TestServiceCtrl(const char *serviceName, uint16_t mode)
{
// service forbid
ParamAuditData auditData = {};
auditData.name = "ohos.servicectrl.";
auditData.dacData.gid = 202; // 202 test dac gid
auditData.dacData.uid = 202; // 202 test dac uid
auditData.dacData.mode = mode;
AddSecurityLabel(&auditData);
TestSetParamCheckResult("ohos.servicectrl.", mode, 1);
return SystemWriteParam("ohos.ctl.start", serviceName);
}
int TestPowerCtrl(const char *reboot, int mode)
int TestPowerCtrl(const char *reboot, uint16_t mode)
{
// service forbid
ParamAuditData auditData = {};
auditData.name = "ohos.servicectrl.reboot";
auditData.dacData.gid = 202; // 202 test dac gid
auditData.dacData.uid = 202; // 202 test dac uid
auditData.dacData.mode = mode;
AddSecurityLabel(&auditData);
TestSetParamCheckResult("ohos.servicectrl.reboot", mode, 1);
return SystemWriteParam("ohos.startup.powerctrl", reboot);
}
};
......@@ -528,9 +518,7 @@ HWTEST_F(ParamServiceUnitTest, TestServiceCtrl, TestSize.Level0)
{
ParamServiceUnitTest test;
int ret = test.TestServiceCtrl("server1", 0770);
#ifdef __MUSL__
EXPECT_NE(ret, 0);
#endif
#ifdef PARAM_SUPPORT_SELINUX
// selinux forbid
ret = test.TestServiceCtrl("server2", 0772);
......@@ -543,36 +531,29 @@ HWTEST_F(ParamServiceUnitTest, TestPowerCtrl, TestSize.Level0)
{
ParamServiceUnitTest test;
int ret = test.TestPowerCtrl("reboot,shutdown", 0770);
#ifdef __MUSL__
EXPECT_NE(ret, 0);
#endif
#ifdef PARAM_SUPPORT_SELINUX
ret = test.TestPowerCtrl("reboot,shutdown", 0772);
// selinux forbid
EXPECT_NE(ret, 0);
#endif
ret = test.TestPowerCtrl("reboot,updater", 0770);
#ifdef __MUSL__
EXPECT_NE(ret, 0);
#endif
#ifdef PARAM_SUPPORT_SELINUX
ret = test.TestPowerCtrl("reboot,updater", 0772);
// selinux forbid
EXPECT_NE(ret, 0);
#endif
ret = test.TestPowerCtrl("reboot,flash", 0770);
#ifdef __MUSL__
ret = test.TestPowerCtrl("reboot,flashd", 0770);
EXPECT_NE(ret, 0);
#endif
#ifdef PARAM_SUPPORT_SELINUX
ret = test.TestPowerCtrl("reboot,flash", 0772);
ret = test.TestPowerCtrl("reboot,flashd", 0772);
// selinux forbid
EXPECT_NE(ret, 0);
#endif
ret = test.TestPowerCtrl("reboot", 0770);
#ifdef __MUSL__
EXPECT_NE(ret, 0);
#endif
#ifdef PARAM_SUPPORT_SELINUX
ret = test.TestPowerCtrl("reboot", 0772);
// selinux forbid
......
......@@ -29,7 +29,10 @@ public:
SelinuxUnitTest() {}
virtual ~SelinuxUnitTest() {}
void SetUp() {}
void SetUp()
{
SetTestPermissionResult(0);
}
void TearDown() {}
void TestBody() {}
......
......@@ -68,7 +68,10 @@ public:
TriggerUnitTest() {}
virtual ~TriggerUnitTest() {}
void SetUp() {}
void SetUp()
{
SetTestPermissionResult(0);
}
void TearDown() {}
void TestBody() {}
......
......@@ -22,6 +22,7 @@
#include "message_parcel.h"
#include "parameter.h"
#include "param_manager.h"
#include "param_stub.h"
#include "param_utils.h"
#include "system_ability_definition.h"
#include "watcher.h"
......@@ -33,11 +34,12 @@ using namespace std;
using namespace OHOS;
using namespace OHOS::init_param;
void TestParameterChange(const char *key, const char *value, void *context)
static void TestParameterChange(const char *key, const char *value, void *context)
{
printf("TestParameterChange key:%s %s", key, value);
}
void TestWatcherCallBack(const char *key, ServiceStatus status)
static void TestWatcherCallBack(const char *key, ServiceStatus status)
{
printf("TestWatcherCallBack key:%s %d", key, status);
}
......@@ -53,6 +55,7 @@ public:
GetParamSecurityLabel()->cred.uid = 1000; // 1000 test uid
GetParamSecurityLabel()->cred.gid = 1000; // 1000 test gid
}
SetTestPermissionResult(0);
}
void TearDown() {}
void TestBody() {}
......
......@@ -20,6 +20,7 @@
#include "parameter.h"
#include "sysparam_errno.h"
#include "param_comm.h"
#include "param_stub.h"
#include "param_wrapper.h"
#include "sysversion.h"
......@@ -32,7 +33,10 @@ class SysparaUnitTest : public testing::Test {
public:
static void SetUpTestCase() {}
static void TearDownTestCase() {}
void SetUp() {}
void SetUp()
{
SetTestPermissionResult(0);
}
void TearDown() {}
};
......@@ -135,7 +139,7 @@ HWTEST_F(SysparaUnitTest, parameterTest005, TestSize.Level0)
char value4[] = "rw.sys.version.version.version.version flash_offset = *(hi_u32 *)DT_SetGetU32(&g_Element[0], 0)a\
size = *(hi_u32 *)DT_SetGetU32(&g_Element[1], 0)a";
int ret = SetParameter(key4, value4);
EXPECT_EQ(ret, EC_INVALID);
EXPECT_EQ(ret, SYSPARAM_INVALID_VALUE);
}
HWTEST_F(SysparaUnitTest, parameterTest006, TestSize.Level0)
......@@ -171,7 +175,7 @@ HWTEST_F(SysparaUnitTest, parameterTest009, TestSize.Level0)
char value5[] = "rw.sys.version.version.version.version \
flash_offset = *(hi_u32 *)DT_SetGetU32(&g_Element[0], 0)";
int ret = SetParameter(key5, value5);
EXPECT_EQ(ret, EC_INVALID);
EXPECT_EQ(ret, SYSPARAM_INVALID_VALUE);
char valueGet[2] = {0};
char defValue3[] = "value of key > 32 ...";
ret = GetParameter(key5, defValue3, valueGet, 2);
......@@ -235,7 +239,7 @@ HWTEST_F(SysparaUnitTest, parameterTest0011, TestSize.Level0)
EXPECT_EQ(ret, 0);
char key2[] = "test.rw.sys.version.wait2";
ret = WaitParameter(key2, "*", 1);
EXPECT_EQ(ret, 105);
EXPECT_EQ(ret, SYSPARAM_WAIT_TIMEOUT);
}
HWTEST_F(SysparaUnitTest, parameterTest0012, TestSize.Level0)
......@@ -262,10 +266,11 @@ HWTEST_F(SysparaUnitTest, parameterTest0012, TestSize.Level0)
handle = FindParameter(key2);
EXPECT_EQ(handle, static_cast<unsigned int>(-1));
ret = GetParameterValue(handle, valueGet1, 32);
EXPECT_EQ(ret, -1);
EXPECT_EQ(ret, SYSPARAM_NOT_FOUND);
ret = GetParameterName(handle, nameGet1, 32);
EXPECT_EQ(ret, -1);
EXPECT_EQ(ret, SYSPARAM_NOT_FOUND);
}
HWTEST_F(SysparaUnitTest, parameterTest0013, TestSize.Level0)
{
long long int out = 0;
......@@ -275,8 +280,13 @@ HWTEST_F(SysparaUnitTest, parameterTest0013, TestSize.Level0)
int ret = SetParameter(key1, value1);
EXPECT_EQ(ret, 0);
GetParameter_(nullptr, nullptr, nullptr, 0);
#if defined(__LITEOS_A__) || defined(__LITEOS_M__)
EXPECT_EQ(GetIntParameter(key1, 0), 101);
EXPECT_EQ(GetUintParameter(key1, 0), 101);
#else
EXPECT_EQ(GetIntParameter(key1, 0), 0);
EXPECT_EQ(GetUintParameter(key1, 0), 0);
#endif
EXPECT_EQ(IsValidParamValue(nullptr, 0), 0);
EXPECT_EQ(IsValidParamValue("testvalue", strlen("testvalue") + 1), 1);
EXPECT_EQ(StringToLL("0x11", &out), 0);
......
# 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
......@@ -14,4 +14,7 @@
[device]
# <device name> <mode> <uid> <gid>
/dev/binder 0666 0 0
/dev/random 0666 0 0
/dev/urandom 0666 0 0
/dev/mmz_userdev 0666 0 0
/dev/watchdog 0660 watchdog watchdog
......@@ -50,7 +50,7 @@ static void PollUeventdSocketTimeout(int ueventSockFd, bool ondemand)
int main(int argc, char **argv)
{
// start log
EnableInitLog();
EnableInitLog(INIT_INFO);
char *ueventdConfigs[] = {"/etc/ueventd.config", "/vendor/etc/ueventd.config", NULL};
int i = 0;
while (ueventdConfigs[i] != NULL) {
......
......@@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
......@@ -40,34 +40,28 @@
#define PRETIMEOUT_GAP 5
#define PRETIMEOUT_DIV 2
#define WATCHDOG_DEV "/dev/watchdog"
static int WaitForWatchDogDevice(void)
static void WaitAtStartup(const char *source)
{
unsigned int count = 0;
struct stat sourceInfo;
const unsigned int waitTime = 500000;
while ((stat(WATCHDOG_DEV, &sourceInfo) < 0) && (errno == ENOENT) && (count < WAIT_MAX_COUNT)) {
do {
usleep(waitTime);
count++;
}
} while ((stat(source, &sourceInfo) < 0) && (errno == ENOENT) && (count < WAIT_MAX_COUNT));
if (count == WAIT_MAX_COUNT) {
INIT_LOGE("Wait for watchdog device failed after %u seconds", (WAIT_MAX_COUNT * waitTime) / CONVERSION_BASE);
return 0;
INIT_LOGE("wait for file:%s failed after %u seconds.", source, (WAIT_MAX_COUNT * waitTime) / CONVERSION_BASE);
}
return 1;
return;
}
int main(int argc, const char *argv[])
{
if (WaitForWatchDogDevice() == 0) {
return -1;
}
int fd = open(WATCHDOG_DEV, O_RDWR | O_CLOEXEC);
if (fd < 0) {
INIT_LOGE("Open watchdog device failed, err = %d", errno);
return -1;
WaitAtStartup("/dev/watchdog");
int fd = open("/dev/watchdog", O_RDWR);
if (fd == -1) {
INIT_LOGE("Can't open /dev/watchdog.");
return 1;
}
int interval = 0;
......@@ -82,10 +76,11 @@ int main(int argc, const char *argv[])
}
gap = (gap > 0) ? gap : DEFAULT_GAP;
INIT_LOGI("Watchdog started (interval %d, margin %d), fd = %d\n", interval, gap, fd);
#ifdef OHOS_LITE_WATCHDOG
#ifndef LINUX_WATCHDOG
if (setpriority(PRIO_PROCESS, 0, 14) != 0) { // 14 is process priority
INIT_LOGE("setpriority failed, err=%d", errno);
INIT_LOGE("setpriority failed err=%d\n", errno);
}
#endif
#endif
......@@ -98,16 +93,12 @@ int main(int argc, const char *argv[])
#endif
int ret = ioctl(fd, WDIOC_SETTIMEOUT, &timeoutSet);
if (ret < 0) {
INIT_LOGE("ioctl failed with command WDIOC_SETTIMEOUT, err = %d", errno);
close(fd);
return -1;
if (ret) {
INIT_LOGE("Failed to set timeout to %d\n", timeoutSet);
}
ret = ioctl(fd, WDIOC_GETTIMEOUT, &timeoutGet);
if (ret < 0) {
INIT_LOGE("ioctl failed with command WDIOC_GETTIMEOUT, err = %d", errno);
close(fd);
return -1;
if (ret) {
INIT_LOGE("Failed to get timeout\n");
}
if (timeoutGet > 0) {
......@@ -115,19 +106,15 @@ int main(int argc, const char *argv[])
}
#ifdef WDIOC_SETPRETIMEOUT
preTimeout = timeoutGet - PRETIMEOUT_GAP; // ensure pre timeout smaller then timeout
preTimeout = timeoutGet - PRETIMEOUT_GAP; // ensure pretimeout smaller then timeout
if (preTimeout > 0) {
ret = ioctl(fd, WDIOC_SETPRETIMEOUT, &preTimeout);
if (ret < 0) {
INIT_LOGE("ioctl failed with command WDIOC_SETPRETIMEOUT, err = %d", errno);
close(fd);
return -1;
if (ret) {
INIT_LOGE("Failed to set pretimeout to %d\n", preTimeout);
}
ret = ioctl(fd, WDIOC_GETPRETIMEOUT, &preTimeoutGet);
if (ret < 0) {
INIT_LOGE("ioctl failed with command WDIOC_GETPRETIMEOUT, err = %d", errno);
close(fd);
return -1;
if (ret) {
INIT_LOGE("Failed to get pretimeout\n");
}
}
......@@ -136,14 +123,8 @@ int main(int argc, const char *argv[])
}
#endif
INIT_LOGI("watchdog started (interval %d, margin %d)", interval, gap);
while (1) {
ret = ioctl(fd, WDIOC_KEEPALIVE);
if (ret < 0) {
// Fed watchdog failed, we don't need to quit the process.
// Wait for kernel to trigger panic.
INIT_LOGE("ioctl failed with command WDIOC_KEEPALIVE, err = %d", errno);
}
ioctl(fd, WDIOC_KEEPALIVE);
sleep(interval);
}
close(fd);
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册