提交 7f8376bf 编写于 作者: M Mupceet 提交者: Gitee

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

Signed-off-by: NMupceet <laiguizhong@huawei.com>
...@@ -63,7 +63,7 @@ ...@@ -63,7 +63,7 @@
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/--> <!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/-->
<filteritem type="filname" name="*.jpg|*.png|*.gif|*.pdf" desc="already checked"/> <filteritem type="filename" name="*.jpg|*.png|*.gif|*.pdf" desc="already checked"/>
<filteritem type="filepath" name="services/test/unittest/test_data/proc/*" desc="启动功能UT测试的资源文件"/> <filteritem type="filepath" name="services/test/unittest/test_data/proc/*" desc="启动功能UT测试的资源文件"/>
</filefilter> </filefilter>
......
...@@ -39,11 +39,15 @@ ohos_shared_library("deviceinfoservice") { ...@@ -39,11 +39,15 @@ ohos_shared_library("deviceinfoservice") {
"//base/startup/init_lite/interfaces/innerkits/syspara", "//base/startup/init_lite/interfaces/innerkits/syspara",
"//base/startup/init_lite/interfaces/hals", "//base/startup/init_lite/interfaces/hals",
] ]
defines = [
"INIT_AGENT",
"_GNU_SOURCE",
"USE_MBEDTLS",
]
deps = [ deps = [
"//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//base/startup/init_lite/interfaces/innerkits:libbegetutil",
"//third_party/bounds_checking_function:libsec_shared", "//third_party/bounds_checking_function:libsec_shared",
"//third_party/openssl:libcrypto_shared", "//third_party/mbedtls:mbedtls_shared",
] ]
external_deps = [ external_deps = [
......
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "beget_ext.h" #include "beget_ext.h"
#ifdef PARAM_FEATURE_DEVICEINFO #ifdef PARAM_FEATURE_DEVICEINFO
#include "device_info_kits.h" #include "device_info_kits.h"
#endif #endif
#include "param_comm.h" #include "param_comm.h"
#include "securec.h" #include "securec.h"
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
extern "C" { extern "C" {
#endif #endif
#endif /* __cplusplus */ #endif /* __cplusplus */
int AclGetDevUdid(char *udid, int size) int AclGetDevUdid(char *udid, int size)
{ {
if (udid == nullptr || size < UDID_LEN) { if (udid == nullptr || size < UDID_LEN) {
return -1; return -1;
} }
#ifdef PARAM_FEATURE_DEVICEINFO #ifdef PARAM_FEATURE_DEVICEINFO
std::string result = {}; std::string result = {};
OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance(); OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance();
int ret = instance.GetUdid(result); int ret = instance.GetUdid(result);
if (ret == 0) { if (ret == 0) {
ret = strcpy_s(udid, size, result.c_str()); ret = strcpy_s(udid, size, result.c_str());
} }
#else #else
int ret = GetDevUdid_(udid, size); int ret = GetDevUdid_(udid, size);
#endif #endif
BEGET_LOGI("AclGetDevUdid %s", udid); BEGET_LOGI("AclGetDevUdid %s", udid);
return ret; return ret;
} }
const char *AclGetSerial(void) const char *AclGetSerial(void)
{ {
static char serialNumber[MAX_SERIAL_LEN] = {"1234567890"}; static char serialNumber[MAX_SERIAL_LEN] = {"1234567890"};
#ifdef PARAM_FEATURE_DEVICEINFO #ifdef PARAM_FEATURE_DEVICEINFO
std::string result = {}; std::string result = {};
OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance(); OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance();
int ret = instance.GetSerialID(result); int ret = instance.GetSerialID(result);
if (ret == 0) { if (ret == 0) {
ret = strcpy_s(serialNumber, sizeof(serialNumber), result.c_str()); ret = strcpy_s(serialNumber, sizeof(serialNumber), result.c_str());
BEGET_ERROR_CHECK(ret == 0, return nullptr, "Failed to copy"); BEGET_ERROR_CHECK(ret == 0, return nullptr, "Failed to copy");
} }
#else #else
const char *tmpSerial = GetSerial_(); const char *tmpSerial = GetSerial_();
if (tmpSerial != nullptr) { if (tmpSerial != nullptr) {
int ret = strcpy_s(serialNumber, sizeof(serialNumber), tmpSerial); int ret = strcpy_s(serialNumber, sizeof(serialNumber), tmpSerial);
BEGET_ERROR_CHECK(ret == 0, return nullptr, "Failed to copy"); BEGET_ERROR_CHECK(ret == 0, return nullptr, "Failed to copy");
} }
#endif #endif
BEGET_LOGI("AclGetSerial %s", serialNumber); BEGET_LOGI("AclGetSerial %s", serialNumber);
return serialNumber; return serialNumber;
} }
#ifdef __cplusplus #ifdef __cplusplus
#if __cplusplus #if __cplusplus
} }
#endif #endif
#endif /* __cplusplus */ #endif /* __cplusplus */
\ No newline at end of file
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "device_info_kits.h" #include "device_info_kits.h"
#include "beget_ext.h" #include "beget_ext.h"
#include "device_info_proxy.h" #include "device_info_proxy.h"
#include "idevice_info.h" #include "device_info_load.h"
#include "if_system_ability_manager.h" #include "idevice_info.h"
#include "iservice_registry.h" #include "if_system_ability_manager.h"
#include "system_ability_definition.h" #include "iservice_registry.h"
#include "securec.h" #include "system_ability_definition.h"
#include "securec.h"
namespace OHOS {
namespace device_info { namespace OHOS {
DeviceInfoKits::DeviceInfoKits() {} namespace device_info {
DeviceInfoKits::DeviceInfoKits() {}
DeviceInfoKits::~DeviceInfoKits() {}
DeviceInfoKits::~DeviceInfoKits() {}
DeviceInfoKits &DeviceInfoKits::GetInstance()
{ DeviceInfoKits &DeviceInfoKits::GetInstance()
return DelayedRefSingleton<DeviceInfoKits>::GetInstance(); {
} return DelayedRefSingleton<DeviceInfoKits>::GetInstance();
}
void DeviceInfoKits::ResetService(const wptr<IRemoteObject> &remote)
{ void DeviceInfoKits::LoadDeviceInfoSa()
std::lock_guard<std::mutex> lock(lock_); {
if (deviceInfoService_ != nullptr) { DINFO_LOGV("deviceInfoService_ is %d", deviceInfoService_ == nullptr);
sptr<IRemoteObject> object = deviceInfoService_->AsObject();
if ((object != nullptr) && (remote == object)) { auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
object->RemoveDeathRecipient(deathRecipient_); DINFO_CHECK(sam != nullptr, return, "GetSystemAbilityManager return null");
deviceInfoService_ = nullptr;
} sptr<DeviceInfoLoad> deviceInfoLoad = new (std::nothrow) DeviceInfoLoad();
} DINFO_CHECK(deviceInfoLoad != nullptr, return, "new deviceInfoLoad fail.");
}
int32_t ret = sam->LoadSystemAbility(SYSPARAM_DEVICE_SERVICE_ID, deviceInfoLoad);
sptr<IDeviceInfo> DeviceInfoKits::GetService() DINFO_CHECK(ret == ERR_OK, return, "LoadSystemAbility deviceinfo sa failed");
{
std::lock_guard<std::mutex> lock(lock_); std::unique_lock<std::mutex> lock(lock_);
if (deviceInfoService_ != nullptr) { // wait_for release lock and block until time out(60s) or match the condition with notice
return deviceInfoService_; auto waitStatus = deviceInfoLoadCon_.wait_for(lock, std::chrono::milliseconds(DEVICEINFO_LOAD_SA_TIMEOUT_MS),
} [this]() { return deviceInfoService_ != nullptr; });
if (!waitStatus) {
sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); // time out or loadcallback fail
DINFO_CHECK(samgr != nullptr, return nullptr, "Get samgr failed"); DINFO_LOGE("tokensync load sa timeout");
sptr<IRemoteObject> object = samgr->GetSystemAbility(SYSPARAM_DEVICE_SERVICE_ID); return;
DINFO_CHECK(object != nullptr, return nullptr, "Get device service object from samgr failed"); }
if (deathRecipient_ == nullptr) { }
deathRecipient_ = new DeathRecipient();
} sptr<IDeviceInfo> DeviceInfoKits::GetService()
{
if ((object->IsProxyObject()) && (!object->AddDeathRecipient(deathRecipient_))) { LoadDeviceInfoSa();
DINFO_LOGE("Failed to add death recipient"); return deviceInfoService_;
} }
deviceInfoService_ = iface_cast<IDeviceInfo>(object);
if (deviceInfoService_ == nullptr) { void DeviceInfoKits::FinishStartSASuccess(const sptr<IRemoteObject> &remoteObject)
DINFO_LOGE("device service iface_cast failed"); {
} DINFO_LOGI("get deviceinfo sa success.");
return deviceInfoService_; deviceInfoService_ = iface_cast<IDeviceInfo>(remoteObject);
}
// get lock which wait_for release and send a notice so that wait_for can out of block
void DeviceInfoKits::DeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote) std::unique_lock<std::mutex> lock(lock_);
{ deviceInfoLoadCon_.notify_one();
DelayedRefSingleton<DeviceInfoKits>::GetInstance().ResetService(remote); }
}
void DeviceInfoKits::FinishStartSAFailed()
int32_t DeviceInfoKits::GetUdid(std::string& result) {
{ DINFO_LOGI("get deviceinfo sa failed.");
auto deviceService = GetService();
DINFO_CHECK(deviceService != nullptr, return -1, "Failed to get watcher manager"); // get lock which wait_for release and send a notice
return deviceService->GetUdid(result); std::unique_lock<std::mutex> lock(lock_);
} deviceInfoLoadCon_.notify_one();
}
int32_t DeviceInfoKits::GetSerialID(std::string& result)
{ int32_t DeviceInfoKits::GetUdid(std::string& result)
auto deviceService = GetService(); {
DINFO_CHECK(deviceService != nullptr, return -1, "Failed to get watcher manager"); auto deviceService = GetService();
return deviceService->GetSerialID(result); DINFO_CHECK(deviceService != nullptr, return -1, "Failed to get deviceinfo manager");
} return deviceService->GetUdid(result);
} // namespace device_info }
} // namespace OHOS
int32_t DeviceInfoKits::GetSerialID(std::string& result)
{
auto deviceService = GetService();
DINFO_CHECK(deviceService != nullptr, return -1, "Failed to get deviceinfo manager");
return deviceService->GetSerialID(result);
}
} // namespace device_info
} // namespace OHOS
...@@ -29,26 +29,16 @@ public: ...@@ -29,26 +29,16 @@ public:
static DeviceInfoKits &GetInstance(); static DeviceInfoKits &GetInstance();
int32_t GetUdid(std::string& result); int32_t GetUdid(std::string& result);
int32_t GetSerialID(std::string& result); int32_t GetSerialID(std::string& result);
void ResetService(const wptr<IRemoteObject> &remote);
// For death event procession
class DeathRecipient final : public IRemoteObject::DeathRecipient {
public:
DeathRecipient() = default;
~DeathRecipient() final = default;
DISALLOW_COPY_AND_MOVE(DeathRecipient);
void OnRemoteDied(const wptr<IRemoteObject> &remote) final;
};
sptr<IRemoteObject::DeathRecipient> GetDeathRecipient()
{
return deathRecipient_;
}
void FinishStartSASuccess(const sptr<IRemoteObject> &remoteObject);
void FinishStartSAFailed();
private: private:
static const int DEVICEINFO_LOAD_SA_TIMEOUT_MS = 60000;
void LoadDeviceInfoSa();
sptr<IDeviceInfo> GetService(); sptr<IDeviceInfo> GetService();
std::mutex lock_; std::mutex lock_;
std::condition_variable deviceInfoLoadCon_;
sptr<IDeviceInfo> deviceInfoService_ {}; sptr<IDeviceInfo> deviceInfoService_ {};
sptr<IRemoteObject::DeathRecipient> deathRecipient_ {};
}; };
} // namespace device_info } // namespace device_info
} // namespace OHOS } // namespace OHOS
......
/*
* 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 "device_info_load.h"
#include "device_info_kits.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace device_info {
DeviceInfoLoad::DeviceInfoLoad()
{
}
void DeviceInfoLoad::OnLoadSystemAbilitySuccess(int32_t systemAbilityId,
const sptr<IRemoteObject>& remoteObject)
{
DINFO_CHECK(systemAbilityId == SYSPARAM_DEVICE_SERVICE_ID, return,
"start aystemabilityId is not deviceinfo! %d", systemAbilityId);
DINFO_CHECK(remoteObject != nullptr, return, "remoteObject is null.");
DINFO_LOGI("OnLoadSystemAbilitySuccess start systemAbilityId: %d success!", systemAbilityId);
DeviceInfoKits::GetInstance().FinishStartSASuccess(remoteObject);
}
void DeviceInfoLoad::OnLoadSystemAbilityFail(int32_t systemAbilityId)
{
DINFO_CHECK(systemAbilityId == SYSPARAM_DEVICE_SERVICE_ID, return,
"start aystemabilityId is not deviceinfo! %d", systemAbilityId);
DINFO_LOGI("OnLoadSystemAbilityFail systemAbilityId: %d failed.", systemAbilityId);
DeviceInfoKits::GetInstance().FinishStartSAFailed();
}
} // namespace device_info
} // namespace OHOS
/*
* 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 DEVICE_INFO_LOAD_H
#define DEVICE_INFO_LOAD_H
#include "system_ability_load_callback_stub.h"
#include "idevice_info.h"
namespace OHOS {
namespace device_info {
class DeviceInfoLoad : public SystemAbilityLoadCallbackStub {
public:
explicit DeviceInfoLoad();
void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject);
void OnLoadSystemAbilityFail(int32_t systemAbilityId);
private:
};
} // namespace device_info
} // namespace OHOS
#endif // DEVICE_INFO_LOAD_H
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "device_info_proxy.h" #include "device_info_proxy.h"
#include "beget_ext.h" #include "beget_ext.h"
#include "idevice_info.h" #include "idevice_info.h"
#include "parcel.h" #include "parcel.h"
#include "string_ex.h" #include "string_ex.h"
namespace OHOS { namespace OHOS {
namespace device_info { namespace device_info {
int32_t DeviceInfoProxy::GetUdid(std::string& result) int32_t DeviceInfoProxy::GetUdid(std::string& result)
{ {
MessageParcel data; MessageParcel data;
MessageParcel reply; MessageParcel reply;
MessageOption option { MessageOption::TF_SYNC }; MessageOption option { MessageOption::TF_SYNC };
data.WriteInterfaceToken(DeviceInfoProxy::GetDescriptor()); data.WriteInterfaceToken(DeviceInfoProxy::GetDescriptor());
int32_t ret = Remote()->SendRequest(COMMAND_GET_UDID, data, reply, option); int32_t ret = Remote()->SendRequest(COMMAND_GET_UDID, data, reply, option);
DINFO_CHECK(ret == ERR_NONE, return ret, "getUdid failed, error code is %d", ret); DINFO_CHECK(ret == ERR_NONE, return ret, "getUdid failed, error code is %d", ret);
result = Str16ToStr8(reply.ReadString16()); result = Str16ToStr8(reply.ReadString16());
return ERR_OK; return ERR_OK;
} }
int32_t DeviceInfoProxy::GetSerialID(std::string& result) int32_t DeviceInfoProxy::GetSerialID(std::string& result)
{ {
MessageParcel data; MessageParcel data;
MessageParcel reply; MessageParcel reply;
MessageOption option { MessageOption::TF_SYNC }; MessageOption option { MessageOption::TF_SYNC };
data.WriteInterfaceToken(DeviceInfoProxy::GetDescriptor()); data.WriteInterfaceToken(DeviceInfoProxy::GetDescriptor());
int32_t ret = Remote()->SendRequest(COMMAND_GET_SERIAL_ID, data, reply, option); int32_t ret = Remote()->SendRequest(COMMAND_GET_SERIAL_ID, data, reply, option);
DINFO_CHECK(ret == ERR_NONE, return ret, "GetSerial failed, error code is %d", ret); DINFO_CHECK(ret == ERR_NONE, return ret, "GetSerial failed, error code is %d", ret);
result = Str16ToStr8(reply.ReadString16()); result = Str16ToStr8(reply.ReadString16());
return ERR_OK; return ERR_OK;
} }
} // namespace device_info } // namespace device_info
} // namespace OHOS } // namespace OHOS
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "device_info_stub.h" #include "device_info_stub.h"
#include "beget_ext.h" #include "beget_ext.h"
#include "idevice_info.h" #include "idevice_info.h"
#include "ipc_skeleton.h" #include "ipc_skeleton.h"
#include "accesstoken_kit.h" #include "accesstoken_kit.h"
#include "parcel.h" #include "parcel.h"
#include "string_ex.h" #include "string_ex.h"
#include "system_ability_definition.h" #include "system_ability_definition.h"
#include "param_comm.h" #include "param_comm.h"
using std::u16string; using std::u16string;
namespace OHOS { namespace OHOS {
using namespace Security; using namespace Security;
using namespace Security::AccessToken; using namespace Security::AccessToken;
namespace device_info { namespace device_info {
REGISTER_SYSTEM_ABILITY_BY_ID(DeviceInfoService, SYSPARAM_DEVICE_SERVICE_ID, true) REGISTER_SYSTEM_ABILITY_BY_ID(DeviceInfoService, SYSPARAM_DEVICE_SERVICE_ID, true)
int32_t DeviceInfoStub::OnRemoteRequest(uint32_t code, int32_t DeviceInfoStub::OnRemoteRequest(uint32_t code,
MessageParcel &data, MessageParcel &reply, MessageOption &option) MessageParcel &data, MessageParcel &reply, MessageOption &option)
{ {
std::u16string myDescripter = IDeviceInfo::GetDescriptor(); std::u16string myDescripter = IDeviceInfo::GetDescriptor();
std::u16string remoteDescripter = data.ReadInterfaceToken(); std::u16string remoteDescripter = data.ReadInterfaceToken();
DINFO_CHECK(myDescripter == remoteDescripter, return ERR_INVALD_DESC, "Invalid remoteDescripter"); DINFO_CHECK(myDescripter == remoteDescripter, return ERR_INVALD_DESC, "Invalid remoteDescripter");
int ret = ERR_FAIL; int ret = ERR_FAIL;
switch (code) { switch (code) {
case COMMAND_GET_UDID: { case COMMAND_GET_UDID: {
if (!CheckPermission(data, PERMISSION_UDID)) { if (!CheckPermission(data, PERMISSION_UDID)) {
return ERR_FAIL; return ERR_FAIL;
} }
char localDeviceInfo[UDID_LEN] = {0}; char localDeviceInfo[UDID_LEN] = {0};
ret = GetDevUdid_(localDeviceInfo, UDID_LEN); ret = GetDevUdid_(localDeviceInfo, UDID_LEN);
DINFO_CHECK(ret == 0, break, "Failed to get dev udid"); DINFO_CHECK(ret == 0, break, "Failed to get dev udid");
reply.WriteString16(Str8ToStr16(localDeviceInfo)); reply.WriteString16(Str8ToStr16(localDeviceInfo));
break; break;
} }
case COMMAND_GET_SERIAL_ID: { case COMMAND_GET_SERIAL_ID: {
if (!CheckPermission(data, PERMISSION_UDID)) { if (!CheckPermission(data, PERMISSION_UDID)) {
return ERR_FAIL; return ERR_FAIL;
} }
const char *serialNumber = GetSerial_(); const char *serialNumber = GetSerial_();
DINFO_CHECK(serialNumber != nullptr, break, "Failed to get serialNumber"); DINFO_CHECK(serialNumber != nullptr, break, "Failed to get serialNumber");
reply.WriteString16(Str8ToStr16(serialNumber)); reply.WriteString16(Str8ToStr16(serialNumber));
break; break;
} }
default: { default: {
return IPCObjectStub::OnRemoteRequest(code, data, reply, option); return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
} }
} }
return ret; return ret;
} }
bool DeviceInfoStub::CheckPermission(MessageParcel &data, const std::string &permission) bool DeviceInfoStub::CheckPermission(MessageParcel &data, const std::string &permission)
{ {
AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID(); AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
int32_t result = TypePermissionState::PERMISSION_GRANTED; int32_t result = TypePermissionState::PERMISSION_GRANTED;
int32_t tokenType = AccessTokenKit::GetTokenTypeFlag(callerToken); int32_t tokenType = AccessTokenKit::GetTokenTypeFlag(callerToken);
if (tokenType == TOKEN_NATIVE) { if (tokenType == TOKEN_NATIVE) {
result = AccessTokenKit::VerifyNativeToken(callerToken, permission); result = AccessTokenKit::VerifyNativeToken(callerToken, permission);
} else if (tokenType == TOKEN_HAP) { } else if (tokenType == TOKEN_HAP) {
result = AccessTokenKit::VerifyAccessToken(callerToken, permission); result = AccessTokenKit::VerifyAccessToken(callerToken, permission);
} else { } else {
DINFO_LOGE("AccessToken type:%d, permission:%d denied!", tokenType, callerToken); DINFO_LOGE("AccessToken type:%d, permission:%d denied!", tokenType, callerToken);
return false; return false;
} }
if (result == TypePermissionState::PERMISSION_DENIED) { if (result == TypePermissionState::PERMISSION_DENIED) {
DINFO_LOGE("AccessTokenID:%d, permission:%s denied!", callerToken, permission.c_str()); DINFO_LOGE("AccessTokenID:%d, permission:%s denied!", callerToken, permission.c_str());
return false; return false;
} }
DINFO_LOGI("tokenType %d dAccessTokenID:%d, permission:%s matched!", tokenType, callerToken, permission.c_str()); DINFO_LOGI("tokenType %d dAccessTokenID:%d, permission:%s matched!", tokenType, callerToken, permission.c_str());
return true; return true;
} }
int32_t DeviceInfoService::GetUdid(std::string& result) int32_t DeviceInfoService::GetUdid(std::string& result)
{ {
return 0; return 0;
} }
int32_t DeviceInfoService::GetSerialID(std::string& result) int32_t DeviceInfoService::GetSerialID(std::string& result)
{ {
return 0; return 0;
} }
void DeviceInfoService::OnStart(void) void DeviceInfoService::OnStart(void)
{ {
DINFO_LOGI("WatcherManager OnStart"); DINFO_LOGI("WatcherManager OnStart");
bool res = Publish(this); bool res = Publish(this);
if (!res) { if (!res) {
DINFO_LOGE("WatcherManager Publish failed"); DINFO_LOGE("WatcherManager Publish failed");
} }
return; return;
} }
void DeviceInfoService::OnStop() void DeviceInfoService::OnStop()
{ {
} }
} // namespace device_info } // namespace device_info
} // namespace OHOS } // namespace OHOS
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
"path" : ["/system/bin/sa_main", "/system/profile/deviceinfoservice.xml"], "path" : ["/system/bin/sa_main", "/system/profile/deviceinfoservice.xml"],
"uid" : "deviceinfo", "uid" : "deviceinfo",
"gid" : ["deviceinfo", "shell"], "gid" : ["deviceinfo", "shell"],
"ondemand" : true,
"secon" : "u:r:deviceinfoservice:s0" "secon" : "u:r:deviceinfoservice:s0"
} }
] ]
......
...@@ -51,7 +51,7 @@ typedef struct { ...@@ -51,7 +51,7 @@ typedef struct {
#define QUICKSTART_NODE "/dev/quickstart" #define QUICKSTART_NODE "/dev/quickstart"
/* Simple sample Useage: /* Simple sample Usage:
* INIT PROCESS * INIT PROCESS
* SystemInitStage(QS_STAGE1)----(1)fork----> key APP * SystemInitStage(QS_STAGE1)----(1)fork----> key APP
* |(2) |(3) * |(2) |(3)
......
...@@ -67,7 +67,6 @@ if (defined(ohos_lite)) { ...@@ -67,7 +67,6 @@ if (defined(ohos_lite)) {
] ]
deps += [ deps += [
"//base/startup/init_lite/services/log:init_log", "//base/startup/init_lite/services/log:init_log",
"//base/startup/init_lite/services/param/base:parameterbase",
"//base/startup/init_lite/services/utils:libinit_utils", "//base/startup/init_lite/services/utils:libinit_utils",
] ]
if (enable_ohos_startup_init_feature_begetctl_liteos) { if (enable_ohos_startup_init_feature_begetctl_liteos) {
...@@ -87,6 +86,7 @@ if (defined(ohos_lite)) { ...@@ -87,6 +86,7 @@ if (defined(ohos_lite)) {
defines += [ "__LINUX__" ] defines += [ "__LINUX__" ]
deps += [ deps += [
"//base/startup/init_lite/services/loopevent:loopevent", "//base/startup/init_lite/services/loopevent:loopevent",
"//base/startup/init_lite/services/param/base:parameterbase",
"//base/startup/init_lite/services/param/linux:param_client", "//base/startup/init_lite/services/param/linux:param_client",
] ]
} }
...@@ -121,7 +121,6 @@ if (defined(ohos_lite)) { ...@@ -121,7 +121,6 @@ if (defined(ohos_lite)) {
defines += [ "USE_MBEDTLS" ] defines += [ "USE_MBEDTLS" ]
} }
deps += [ deps += [
"//base/startup/init_lite/services/param/base:parameterbase",
"//base/startup/init_lite/services/param/liteos:param_client_lite", "//base/startup/init_lite/services/param/liteos:param_client_lite",
"//base/startup/init_lite/services/utils:libinit_utils", "//base/startup/init_lite/services/utils:libinit_utils",
] ]
...@@ -149,6 +148,7 @@ if (defined(ohos_lite)) { ...@@ -149,6 +148,7 @@ if (defined(ohos_lite)) {
ohos_shared_library("libbegetutil") { ohos_shared_library("libbegetutil") {
sources = [ sources = [
"fd_holder/fd_holder.c",
"reboot/init_reboot_innerkits.c", "reboot/init_reboot_innerkits.c",
"service_control/service_control.c", "service_control/service_control.c",
] ]
...@@ -230,6 +230,7 @@ if (defined(ohos_lite)) { ...@@ -230,6 +230,7 @@ if (defined(ohos_lite)) {
if (enable_ohos_startup_init_feature_deviceinfo) { if (enable_ohos_startup_init_feature_deviceinfo) {
sources += [ sources += [
"//base/startup/init_lite/device_info/device_info_kits.cpp", "//base/startup/init_lite/device_info/device_info_kits.cpp",
"//base/startup/init_lite/device_info/device_info_load.cpp",
"//base/startup/init_lite/device_info/device_info_proxy.cpp", "//base/startup/init_lite/device_info/device_info_proxy.cpp",
] ]
defines += [ "PARAM_FEATURE_DEVICEINFO" ] defines += [ "PARAM_FEATURE_DEVICEINFO" ]
...@@ -242,7 +243,6 @@ if (defined(ohos_lite)) { ...@@ -242,7 +243,6 @@ if (defined(ohos_lite)) {
external_deps = [ external_deps = [
"hilog_native:libhilog_base", "hilog_native:libhilog_base",
"ipc:ipc_core", "ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_standard:samgr_proxy", "samgr_standard:samgr_proxy",
"utils_base:utils", "utils_base:utils",
] ]
......
...@@ -38,12 +38,12 @@ static int g_FifoWriteFd = -1; ...@@ -38,12 +38,12 @@ static int g_FifoWriteFd = -1;
static void ProcessFifoWrite(const WatcherHandle taskHandle, int fd, uint32_t *events, const void *context) static void ProcessFifoWrite(const WatcherHandle taskHandle, int fd, uint32_t *events, const void *context)
{ {
if ((fd < 0) || (events == NULL) || (context == NULL)) { if ((fd < 0) || (events == NULL) || (context == NULL)) {
BEGET_LOGE("[control_fd] Invaild fifo write parameter"); BEGET_LOGE("[control_fd] Invalid fifo write parameter");
return; return;
} }
int fifow = *((int *)context); int fifow = *((int *)context);
if (fifow < 0) { if (fifow < 0) {
BEGET_LOGE("[control_fd] invaild fifo write fd"); BEGET_LOGE("[control_fd] invalid fifo write fd");
return; return;
} }
char rbuf[FIFO_BUF_SIZE] = {0}; char rbuf[FIFO_BUF_SIZE] = {0};
...@@ -63,7 +63,7 @@ static void ProcessFifoWrite(const WatcherHandle taskHandle, int fd, uint32_t *e ...@@ -63,7 +63,7 @@ static void ProcessFifoWrite(const WatcherHandle taskHandle, int fd, uint32_t *e
static void ProcessFifoRead(const WatcherHandle taskHandle, int fd, uint32_t *events, const void *context) static void ProcessFifoRead(const WatcherHandle taskHandle, int fd, uint32_t *events, const void *context)
{ {
if ((fd < 0) || (events == NULL)) { if ((fd < 0) || (events == NULL)) {
BEGET_LOGE("[control_fd] Invaild fifo read parameter"); BEGET_LOGE("[control_fd] Invalid fifo read parameter");
return; return;
} }
char buf[FIFO_BUF_SIZE] = {0}; char buf[FIFO_BUF_SIZE] = {0};
...@@ -123,7 +123,7 @@ static void CmdDisConnectComplete(const TaskHandle client) ...@@ -123,7 +123,7 @@ static void CmdDisConnectComplete(const TaskHandle client)
static void CmdAgentInit(WatcherHandle handle, const char *path, bool read, ProcessWatchEvent func) static void CmdAgentInit(WatcherHandle handle, const char *path, bool read, ProcessWatchEvent func)
{ {
if (path == NULL) { if (path == NULL) {
BEGET_LOGE("[control_fd] Invaild parameter"); BEGET_LOGE("[control_fd] Invalid parameter");
return; return;
} }
BEGET_LOGI("[control_fd] client open %s", (read ? "read" : "write")); BEGET_LOGI("[control_fd] client open %s", (read ? "read" : "write"));
...@@ -173,7 +173,7 @@ static void CmdOnSendMessageComplete(const TaskHandle task, const BufferHandle h ...@@ -173,7 +173,7 @@ static void CmdOnSendMessageComplete(const TaskHandle task, const BufferHandle h
static CmdAgent *CmdAgentCreate(const char *server) static CmdAgent *CmdAgentCreate(const char *server)
{ {
if (server == NULL) { if (server == NULL) {
BEGET_LOGE("[control_fd] Invaild parameter"); BEGET_LOGE("[control_fd] Invalid parameter");
return NULL; return NULL;
} }
TaskHandle task = NULL; TaskHandle task = NULL;
...@@ -197,7 +197,7 @@ static CmdAgent *CmdAgentCreate(const char *server) ...@@ -197,7 +197,7 @@ static CmdAgent *CmdAgentCreate(const char *server)
static int CreateFifo(const char *pipeName) static int CreateFifo(const char *pipeName)
{ {
if (pipeName == NULL) { if (pipeName == NULL) {
BEGET_LOGE("[control_fd] Invaild parameter"); BEGET_LOGE("[control_fd] Invalid parameter");
return -1; return -1;
} }
// create fifo for cmd // create fifo for cmd
...@@ -214,7 +214,7 @@ static int CreateFifo(const char *pipeName) ...@@ -214,7 +214,7 @@ static int CreateFifo(const char *pipeName)
static int SendCmdMessage(const CmdAgent *agent, uint16_t type, const char *cmd, const char *fifoName) static int SendCmdMessage(const CmdAgent *agent, uint16_t type, const char *cmd, const char *fifoName)
{ {
if ((agent == NULL) || (cmd == NULL) || (fifoName == NULL)) { if ((agent == NULL) || (cmd == NULL) || (fifoName == NULL)) {
BEGET_LOGE("[control_fd] Invaild parameter"); BEGET_LOGE("[control_fd] Invalid parameter");
return -1; return -1;
} }
int ret = 0; int ret = 0;
...@@ -242,7 +242,7 @@ static int SendCmdMessage(const CmdAgent *agent, uint16_t type, const char *cmd, ...@@ -242,7 +242,7 @@ static int SendCmdMessage(const CmdAgent *agent, uint16_t type, const char *cmd,
static int CmdMakeFifoInit(const char *fifoPath) static int CmdMakeFifoInit(const char *fifoPath)
{ {
if (fifoPath == NULL) { if (fifoPath == NULL) {
BEGET_LOGE("[control_fd] Invaild parameter"); BEGET_LOGE("[control_fd] Invalid parameter");
return -1; return -1;
} }
int ret = sprintf_s(g_FifoReadPath, sizeof(g_FifoReadPath) - 1, "/dev/fifo/%s0.%d", fifoPath, getpid()); int ret = sprintf_s(g_FifoReadPath, sizeof(g_FifoReadPath) - 1, "/dev/fifo/%s0.%d", fifoPath, getpid());
...@@ -260,7 +260,7 @@ static int CmdMakeFifoInit(const char *fifoPath) ...@@ -260,7 +260,7 @@ static int CmdMakeFifoInit(const char *fifoPath)
void CmdClientInit(const char *socketPath, uint16_t type, const char *cmd, const char *fifoName) void CmdClientInit(const char *socketPath, uint16_t type, const char *cmd, const char *fifoName)
{ {
if ((socketPath == NULL) || (cmd == NULL)) { if ((socketPath == NULL) || (cmd == NULL)) {
BEGET_LOGE("[control_fd] Invaild parameter"); BEGET_LOGE("[control_fd] Invalid parameter");
} }
BEGET_LOGI("[control_fd] CmdAgentInit"); BEGET_LOGI("[control_fd] CmdAgentInit");
int ret = CmdMakeFifoInit(fifoName); int ret = CmdMakeFifoInit(fifoName);
......
...@@ -95,7 +95,7 @@ static void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint3 ...@@ -95,7 +95,7 @@ static void CmdOnRecvMessage(const TaskHandle task, const uint8_t *buffer, uint3
static int SendMessage(LoopHandle loop, TaskHandle task, const char *message) static int SendMessage(LoopHandle loop, TaskHandle task, const char *message)
{ {
if (message == NULL) { if (message == NULL) {
BEGET_LOGE("[control_fd] Invaild parameter"); BEGET_LOGE("[control_fd] Invalid parameter");
return -1; return -1;
} }
BufferHandle handle = NULL; BufferHandle handle = NULL;
...@@ -135,7 +135,7 @@ static int CmdOnIncommingConntect(const LoopHandle loop, const TaskHandle server ...@@ -135,7 +135,7 @@ static int CmdOnIncommingConntect(const LoopHandle loop, const TaskHandle server
void CmdServiceInit(const char *socketPath, CallbackControlFdProcess func) void CmdServiceInit(const char *socketPath, CallbackControlFdProcess func)
{ {
if ((socketPath == NULL) || (func == NULL)) { if ((socketPath == NULL) || (func == NULL)) {
BEGET_LOGE("[control_fd] Invaild parameter"); BEGET_LOGE("[control_fd] Invalid parameter");
return; return;
} }
LE_StreamServerInfo info = {}; LE_StreamServerInfo info = {};
......
...@@ -55,7 +55,7 @@ int BuildControlMessage(struct msghdr *msghdr, int *fds, int fdCount, bool send ...@@ -55,7 +55,7 @@ int BuildControlMessage(struct msghdr *msghdr, int *fds, int fdCount, bool send
cmsg->cmsg_len = CMSG_LEN(sizeof(int) * fdCount); cmsg->cmsg_len = CMSG_LEN(sizeof(int) * fdCount);
int ret = memcpy_s(CMSG_DATA(cmsg), cmsg->cmsg_len, fds, sizeof(int) * fdCount); int ret = memcpy_s(CMSG_DATA(cmsg), cmsg->cmsg_len, fds, sizeof(int) * fdCount);
if (ret != 0) { if (ret != 0) {
BEGET_LOGE("Controll message is not valid"); BEGET_LOGE("Control message is not valid");
free(msghdr->msg_control); free(msghdr->msg_control);
return -1; return -1;
} }
...@@ -65,7 +65,7 @@ int BuildControlMessage(struct msghdr *msghdr, int *fds, int fdCount, bool send ...@@ -65,7 +65,7 @@ int BuildControlMessage(struct msghdr *msghdr, int *fds, int fdCount, bool send
if (sendUcred) { if (sendUcred) {
if (cmsg == NULL) { if (cmsg == NULL) {
BEGET_LOGE("Controll message is not valid"); BEGET_LOGE("Control message is not valid");
free(msghdr->msg_control); free(msghdr->msg_control);
return -1; return -1;
} }
...@@ -106,7 +106,7 @@ int *ReceiveFds(int sock, struct iovec iovec, size_t *outFdCount, bool nonblock, ...@@ -106,7 +106,7 @@ int *ReceiveFds(int sock, struct iovec iovec, size_t *outFdCount, bool nonblock,
BEGET_ERROR_CHECK(rc >= 0, return NULL, "Failed to get fds from remote, err = %d", errno); BEGET_ERROR_CHECK(rc >= 0, return NULL, "Failed to get fds from remote, err = %d", errno);
if ((msghdr.msg_flags) & MSG_TRUNC) { if ((msghdr.msg_flags) & MSG_TRUNC) {
BEGET_LOGE("Message was trucated when receiving fds"); BEGET_LOGE("Message was truncated when receiving fds");
return NULL; return NULL;
} }
......
...@@ -256,7 +256,7 @@ static int Mount(const char *source, const char *target, const char *fsType, ...@@ -256,7 +256,7 @@ static int Mount(const char *source, const char *target, const char *fsType,
int rc = -1; int rc = -1;
if (source == NULL || target == NULL || fsType == NULL) { if (source == NULL || target == NULL || fsType == NULL) {
BEGET_LOGE("Invalid argment for mount."); BEGET_LOGE("Invalid argument for mount.");
return -1; return -1;
} }
if (stat(target, &st) != 0 && errno != ENOENT) { if (stat(target, &st) != 0 && errno != ENOENT) {
......
...@@ -28,7 +28,7 @@ config("init_module_engine_exported_config") { ...@@ -28,7 +28,7 @@ config("init_module_engine_exported_config") {
} }
# #
# innerkits for module developement # innerkits for module development
# #
ohos_native_stub_library("libinit_module_engine") { ohos_native_stub_library("libinit_module_engine") {
output_extension = "so" output_extension = "so"
......
...@@ -231,7 +231,7 @@ static int GetSandboxInfo(sandbox_t *sandbox, cJSON *root, const char *itemName) ...@@ -231,7 +231,7 @@ static int GetSandboxInfo(sandbox_t *sandbox, cJSON *root, const char *itemName)
static int ParseSandboxConfig(cJSON *root, sandbox_t *sandbox) static int ParseSandboxConfig(cJSON *root, sandbox_t *sandbox)
{ {
BEGET_ERROR_CHECK(!(root == NULL || sandbox == NULL), return -1, "Invaild parameter."); BEGET_ERROR_CHECK(!(root == NULL || sandbox == NULL), return -1, "Invalid parameter.");
cJSON *sandboxRoot = cJSON_GetObjectItem(root, SANDBOX_ROOT_TAG); cJSON *sandboxRoot = cJSON_GetObjectItem(root, SANDBOX_ROOT_TAG);
BEGET_ERROR_CHECK(sandboxRoot != NULL, return -1, BEGET_ERROR_CHECK(sandboxRoot != NULL, return -1,
......
...@@ -52,7 +52,7 @@ int UnshareNamespace(int nsType) ...@@ -52,7 +52,7 @@ int UnshareNamespace(int nsType)
int SetNamespace(int nsFd, int nsType) int SetNamespace(int nsFd, int nsType)
{ {
if (nsFd < 0) { if (nsFd < 0) {
BEGET_LOGE("Namespace fd is invaild"); BEGET_LOGE("Namespace fd is invalid");
return -1; return -1;
} }
if (nsType != CLONE_NEWNS) { if (nsType != CLONE_NEWNS) {
......
...@@ -228,7 +228,7 @@ int ServiceSetReady(const char *serviceName) ...@@ -228,7 +228,7 @@ int ServiceSetReady(const char *serviceName)
int StartServiceByTimer(const char *serviceName, uint64_t timeout) int StartServiceByTimer(const char *serviceName, uint64_t timeout)
{ {
if (serviceName == NULL) { if (serviceName == NULL) {
BEGET_LOGE("Request start serivce by timer with invalid service name"); BEGET_LOGE("Request start service by timer with invalid service name");
return -1; return -1;
} }
...@@ -253,7 +253,7 @@ int StartServiceByTimer(const char *serviceName, uint64_t timeout) ...@@ -253,7 +253,7 @@ int StartServiceByTimer(const char *serviceName, uint64_t timeout)
int StopServiceTimer(const char *serviceName) int StopServiceTimer(const char *serviceName)
{ {
if (serviceName == NULL) { if (serviceName == NULL) {
BEGET_LOGE("Request stop serivce timer with invalid service name"); BEGET_LOGE("Request stop service timer with invalid service name");
return -1; return -1;
} }
......
...@@ -191,7 +191,10 @@ INIT_LOCAL_API const char *GetSerial_(void) ...@@ -191,7 +191,10 @@ INIT_LOCAL_API const char *GetSerial_(void)
#ifdef LITEOS_SUPPORT #ifdef LITEOS_SUPPORT
return HalGetSerial(); return HalGetSerial();
#else #else
static char ohos_serial[PARAM_VALUE_LEN_MAX] = {0}; static char *ohos_serial = NULL;
if (ohos_serial == NULL) {
BEGET_CHECK((ohos_serial = (char *)calloc(1, PARAM_VALUE_LEN_MAX)) != NULL, return NULL);
}
uint32_t len = PARAM_VALUE_LEN_MAX; uint32_t len = PARAM_VALUE_LEN_MAX;
int ret = SystemGetParameter("ohos.boot.sn", ohos_serial, &len); int ret = SystemGetParameter("ohos.boot.sn", ohos_serial, &len);
BEGET_CHECK(ret == 0, return NULL); BEGET_CHECK(ret == 0, return NULL);
......
/* /*
* Copyright (c) 2021-2022 Huawei Device Co., Ltd. * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "param_wrapper.h" #include "param_wrapper.h"
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include <climits> #include <climits>
#include "beget_ext.h" #include "beget_ext.h"
#include "param_comm.h" #include "param_comm.h"
#include "init_param.h" #include "init_param.h"
#include "sysparam_errno.h" #include "sysparam_errno.h"
#include "securec.h" #include "securec.h"
#include "parameter.h" #include "parameter.h"
#include "parameters.h" #include "parameters.h"
namespace OHOS { namespace OHOS {
namespace system { namespace system {
bool SetParameter(const std::string& key, const std::string& value) bool SetParameter(const std::string& key, const std::string& value)
{ {
int ret = SystemSetParameter(key.c_str(), value.c_str()); int ret = SystemSetParameter(key.c_str(), value.c_str());
return (ret == 0) ? true : false; return (ret == 0) ? true : false;
} }
template<typename T> template<typename T>
bool StringToInt(const std::string& str, T min, T max, T& out) bool StringToInt(const std::string& str, T min, T max, T& out)
{ {
long long int result = 0; long long int result = 0;
if (StringToLL(str.c_str(), &result) != 0) { if (StringToLL(str.c_str(), &result) != 0) {
return false; return false;
} }
if (result < min || max < result) { if (result < min || max < result) {
return false; return false;
} }
out = static_cast<T>(result); out = static_cast<T>(result);
return true; return true;
} }
template<typename T> template<typename T>
bool StringToUint(const std::string& str, T max, T& out) bool StringToUint(const std::string& str, T max, T& out)
{ {
unsigned long long int result = 0; unsigned long long int result = 0;
if (StringToULL(str.c_str(), &result) != 0) { if (StringToULL(str.c_str(), &result) != 0) {
return false; return false;
} }
if (max < result) { if (max < result) {
return false; return false;
} }
out = static_cast<T>(result); out = static_cast<T>(result);
return true; return true;
} }
std::string GetParameter(const std::string& key, const std::string& def) std::string GetParameter(const std::string& key, const std::string& def)
{ {
uint32_t size = 0; uint32_t size = 0;
int ret = SystemReadParam(key.c_str(), NULL, &size); int ret = SystemReadParam(key.c_str(), NULL, &size);
if (ret == 0) { if (ret == 0) {
std::vector<char> value(size + 1); std::vector<char> value(size + 1);
ret = SystemReadParam(key.c_str(), value.data(), &size); ret = SystemReadParam(key.c_str(), value.data(), &size);
if (ret == 0) { if (ret == 0) {
return std::string(value.data()); return std::string(value.data());
} }
} }
if (IsValidParamValue(def.c_str(), MAX_VALUE_LEN) == 1) { if (IsValidParamValue(def.c_str(), MAX_VALUE_LEN) == 1) {
return std::string(def); return std::string(def);
} }
return ""; return "";
} }
bool GetBoolParameter(const std::string& key, bool def) bool GetBoolParameter(const std::string& key, bool def)
{ {
static const std::string trueMap[] = { "1", "y", "yes", "on", "true" }; static const std::string trueMap[] = { "1", "y", "yes", "on", "true" };
static const std::string falseMap[] = { "0", "off", "n", "no", "false" }; static const std::string falseMap[] = { "0", "off", "n", "no", "false" };
std::string value = GetParameter(key, ""); std::string value = GetParameter(key, "");
for (size_t i = 0; i < sizeof(trueMap) / sizeof(trueMap[0]); i++) { for (size_t i = 0; i < sizeof(trueMap) / sizeof(trueMap[0]); i++) {
if (trueMap[i] == value) { if (trueMap[i] == value) {
return true; return true;
} }
} }
for (size_t i = 0; i < sizeof(falseMap) / sizeof(falseMap[0]); i++) { for (size_t i = 0; i < sizeof(falseMap) / sizeof(falseMap[0]); i++) {
if (falseMap[i] == value) { if (falseMap[i] == value) {
return false; return false;
} }
} }
return def; return def;
} }
int GetStringParameter(const std::string key, std::string &value, const std::string def) int GetStringParameter(const std::string key, std::string &value, const std::string def)
{ {
uint32_t size = 0; uint32_t size = 0;
int ret = SystemReadParam(key.c_str(), NULL, &size); int ret = SystemReadParam(key.c_str(), NULL, &size);
if (ret == 0) { if (ret == 0) {
std::vector<char> data(size + 1); std::vector<char> data(size + 1);
ret = SystemReadParam(key.c_str(), data.data(), &size); ret = SystemReadParam(key.c_str(), data.data(), &size);
if (ret == 0) { if (ret == 0) {
value = std::string(data.data()); value = std::string(data.data());
return EC_SUCCESS; return EC_SUCCESS;
} }
} }
if (IsValidParamValue(def.c_str(), MAX_VALUE_LEN) == 1) { if (IsValidParamValue(def.c_str(), MAX_VALUE_LEN) == 1) {
value = std::string(def); value = std::string(def);
return EC_SUCCESS; return EC_SUCCESS;
} }
return EC_FAILURE; return EC_FAILURE;
} }
template<typename T> template<typename T>
T GetIntParameter(const std::string& key, T def, T min, T max) T GetIntParameter(const std::string& key, T def, T min, T max)
{ {
if (!std::is_signed<T>::value) { if (!std::is_signed<T>::value) {
return def; return def;
} }
T result; T result;
std::string value = GetParameter(key, ""); std::string value = GetParameter(key, "");
if (!value.empty() && StringToInt(value, min, max, result)) { if (!value.empty() && StringToInt(value, min, max, result)) {
return result; return result;
} }
return def; return def;
} }
template int8_t GetIntParameter(const std::string&, int8_t, int8_t, int8_t); template int8_t GetIntParameter(const std::string&, int8_t, int8_t, int8_t);
template int16_t GetIntParameter(const std::string&, int16_t, int16_t, int16_t); template int16_t GetIntParameter(const std::string&, int16_t, int16_t, int16_t);
template int32_t GetIntParameter(const std::string&, int32_t, int32_t, int32_t); template int32_t GetIntParameter(const std::string&, int32_t, int32_t, int32_t);
template int64_t GetIntParameter(const std::string&, int64_t, int64_t, int64_t); template int64_t GetIntParameter(const std::string&, int64_t, int64_t, int64_t);
template<typename T> template<typename T>
T GetUintParameter(const std::string& key, T def, T max) T GetUintParameter(const std::string& key, T def, T max)
{ {
if (!std::is_unsigned<T>::value) { if (!std::is_unsigned<T>::value) {
return def; return def;
} }
T result; T result;
std::string value = GetParameter(key, ""); std::string value = GetParameter(key, "");
if (!value.empty() && StringToUint(value, max, result)) { if (!value.empty() && StringToUint(value, max, result)) {
return result; return result;
} }
return def; return def;
} }
template uint8_t GetUintParameter(const std::string&, uint8_t, uint8_t); template uint8_t GetUintParameter(const std::string&, uint8_t, uint8_t);
template uint16_t GetUintParameter(const std::string&, uint16_t, uint16_t); template uint16_t GetUintParameter(const std::string&, uint16_t, uint16_t);
template uint32_t GetUintParameter(const std::string&, uint32_t, uint32_t); template uint32_t GetUintParameter(const std::string&, uint32_t, uint32_t);
template uint64_t GetUintParameter(const std::string&, uint64_t, uint64_t); template uint64_t GetUintParameter(const std::string&, uint64_t, uint64_t);
std::string GetDeviceType(void) std::string GetDeviceType(void)
{ {
std::unordered_map<std::string, std::string> deviceTypeMap = { std::unordered_map<std::string, std::string> deviceTypeMap = {
{"watch", "wearable"}, {"watch", "wearable"},
{"fitnessWatch", "liteWearable"}, {"fitnessWatch", "liteWearable"},
}; };
static const char *productType = nullptr; static const char *productType = nullptr;
const char *type = GetProperty("const.build.characteristics", &productType); const char *type = GetProperty("const.build.characteristics", &productType);
if (deviceTypeMap.count(type) != 0) { if (deviceTypeMap.count(type) != 0) {
return deviceTypeMap[type]; return deviceTypeMap[type];
} }
return std::string(type); return std::string(type);
} }
int GetIntParameter(const std::string key, int def) int GetIntParameter(const std::string key, int def)
{ {
return GetIntParameter(key, def, INT_MIN, INT_MAX); return GetIntParameter(key, def, INT_MIN, INT_MAX);
} }
} // namespace system } // namespace system
} // namespace OHOS } // namespace OHOS
\ No newline at end of file
文件模式从 100755 更改为 100644
...@@ -328,7 +328,7 @@ static napi_module _module = { ...@@ -328,7 +328,7 @@ static napi_module _module = {
.nm_flags = 0, .nm_flags = 0,
.nm_filename = NULL, .nm_filename = NULL,
.nm_register_func = Init, .nm_register_func = Init,
.nm_modname = "systemParameter", .nm_modname = "systemparameter",
.nm_priv = ((void *)0), .nm_priv = ((void *)0),
.reserved = { 0 } .reserved = { 0 }
}; };
......
...@@ -232,7 +232,7 @@ static void AddWatcherCallback(ParamWatcherPtr watcher, napi_ref callbackRef) ...@@ -232,7 +232,7 @@ static void AddWatcherCallback(ParamWatcherPtr watcher, napi_ref callbackRef)
static void DelWatcherCallback(ParamWatcherPtr watcher, uint32_t next) static void DelWatcherCallback(ParamWatcherPtr watcher, uint32_t next)
{ {
PARAM_JS_LOGV("JSApp watcher key %s delete callack %u", watcher->keyPrefix, next); PARAM_JS_LOGV("JSApp watcher key %s delete callback %u", watcher->keyPrefix, next);
std::lock_guard<std::mutex> lock(watcher->mutex); std::lock_guard<std::mutex> lock(watcher->mutex);
watcher->callbackReferences.erase(next); watcher->callbackReferences.erase(next);
} }
...@@ -490,7 +490,7 @@ static napi_value SwithWatchOn(napi_env env, napi_callback_info info) ...@@ -490,7 +490,7 @@ static napi_value SwithWatchOn(napi_env env, napi_callback_info info)
{ {
napi_value callback = nullptr; napi_value callback = nullptr;
ParamWatcherPtr watcher = GetWatcherInfo(env, info, &callback); ParamWatcherPtr watcher = GetWatcherInfo(env, info, &callback);
PARAM_JS_CHECK(watcher != nullptr, return GetNapiValue(env, -1), "Failed to get watcher swith param"); PARAM_JS_CHECK(watcher != nullptr, return GetNapiValue(env, -1), "Failed to get watcher switch param");
if (CheckCallbackEqual(env, callback, watcher)) { if (CheckCallbackEqual(env, callback, watcher)) {
PARAM_JS_LOGE("JSApp watcher repeater switch on %s", watcher->keyPrefix); PARAM_JS_LOGE("JSApp watcher repeater switch on %s", watcher->keyPrefix);
...@@ -553,4 +553,4 @@ napi_value RegisterWatcher(napi_env env, napi_value exports) ...@@ -553,4 +553,4 @@ napi_value RegisterWatcher(napi_env env, napi_value exports)
napi_set_named_property(env, exports, "paramWatcher", result); napi_set_named_property(env, exports, "paramWatcher", result);
napi_create_reference(env, result, 1, &g_paramWatchRef); napi_create_reference(env, result, 1, &g_paramWatchRef);
return exports; return exports;
} }
\ No newline at end of file
...@@ -188,7 +188,8 @@ if (defined(ohos_lite)) { ...@@ -188,7 +188,8 @@ if (defined(ohos_lite)) {
deps = [ deps = [
"//base/startup/init_lite/services/log:agent_log", "//base/startup/init_lite/services/log:agent_log",
"//base/startup/init_lite/services/loopevent:loopevent", "//base/startup/init_lite/services/loopevent:loopevent",
"//base/startup/init_lite/services/param:parameter", "//base/startup/init_lite/services/param/base:parameterbase",
"//base/startup/init_lite/services/param/linux:param_client",
"//base/startup/init_lite/services/utils:libinit_utils", "//base/startup/init_lite/services/utils:libinit_utils",
"//third_party/bounds_checking_function:libsec_static", "//third_party/bounds_checking_function:libsec_static",
] ]
......
...@@ -158,7 +158,7 @@ static void ShowParam(BShellHandle shell, const char *name, const char *value) ...@@ -158,7 +158,7 @@ static void ShowParam(BShellHandle shell, const char *name, const char *value)
ParamAuditData auditData = {}; ParamAuditData auditData = {};
int ret = GetParamSecurityAuditData(name, 0, &auditData); int ret = GetParamSecurityAuditData(name, 0, &auditData);
BSH_CHECK(ret == 0, return, "Failed to get param security for %s", name); BSH_CHECK(ret == 0, return, "Failed to get param security for %s", name);
BShellEnvOutput(shell, "Parameter infomation:\r\n"); BShellEnvOutput(shell, "Parameter information:\r\n");
#ifdef PARAM_SUPPORT_SELINUX #ifdef PARAM_SUPPORT_SELINUX
BShellEnvOutput(shell, "selinux : %s \r\n", auditData.label); BShellEnvOutput(shell, "selinux : %s \r\n", auditData.label);
#endif #endif
......
...@@ -170,10 +170,10 @@ static int main_cmd(BShellHandle shell, int argc, char **argv) ...@@ -170,10 +170,10 @@ static int main_cmd(BShellHandle shell, int argc, char **argv)
processName = optarg; processName = optarg;
break; break;
case '?': case '?':
std::cout << "Invalid arugment\n"; std::cout << "Invalid argument\n";
break; break;
default: default:
std::cout << "Invalid arugment\n"; std::cout << "Invalid argument\n";
break; break;
} }
} }
......
...@@ -720,7 +720,7 @@ const ParamInfo *BShellEnvGetReservedParam(BShellHandle handle, const char *name ...@@ -720,7 +720,7 @@ const ParamInfo *BShellEnvGetReservedParam(BShellHandle handle, const char *name
{ {
BSH_CHECK(handle != NULL, return NULL, "Invalid shell env"); BSH_CHECK(handle != NULL, return NULL, "Invalid shell env");
static ParamInfo reservedParams[] = { static ParamInfo reservedParams[] = {
{PARAM_REVERESD_NAME_CURR_PARAMETER, "current paramater", PARAM_STRING} {PARAM_REVERESD_NAME_CURR_PARAMETER, "current parameter", PARAM_STRING}
}; };
for (size_t i = 0; i < sizeof(reservedParams) / sizeof(reservedParams[0]); i++) { for (size_t i = 0; i < sizeof(reservedParams) / sizeof(reservedParams[0]); i++) {
if (strcmp(name, reservedParams[i].name) == 0) { if (strcmp(name, reservedParams[i].name) == 0) {
...@@ -744,4 +744,4 @@ int32_t BShellEnvDirectExecute(BShellHandle handle, int argc, char *args[]) ...@@ -744,4 +744,4 @@ int32_t BShellEnvDirectExecute(BShellHandle handle, int argc, char *args[])
BShellCmdHelp(handle, argc, args); BShellCmdHelp(handle, argc, args);
} }
return 0; return 0;
} }
\ No newline at end of file
...@@ -72,7 +72,7 @@ int main(int argc, char *args[]) ...@@ -72,7 +72,7 @@ int main(int argc, char *args[])
return 0; return 0;
} }
const ParamInfo *param = BShellEnvGetReservedParam(handle, PARAM_REVERESD_NAME_CURR_PARAMETER); const ParamInfo *param = BShellEnvGetReservedParam(handle, PARAM_REVERESD_NAME_CURR_PARAMETER);
BSH_CHECK(param != NULL && param->type == PARAM_STRING, break, "Failed to get revered param"); BSH_CHECK(param != NULL && param->type == PARAM_STRING, break, "Failed to get reversed param");
BShellEnvSetParam(handle, param->name, param->desc, param->type, (void *)""); BShellEnvSetParam(handle, param->name, param->desc, param->type, (void *)"");
if (argc > 1) { if (argc > 1) {
int ret = SetParamShellPrompt(handle, args[1]); int ret = SetParamShellPrompt(handle, args[1]);
......
...@@ -30,7 +30,7 @@ const.build.product=default ...@@ -30,7 +30,7 @@ const.build.product=default
const.product.hardwareversion=default const.product.hardwareversion=default
const.product.bootloader.version=bootloader const.product.bootloader.version=bootloader
const.product.cpu.abilist=default const.product.cpu.abilist=default
const.product.software.version=OpenHarmony 3.2.3.5 const.product.software.version=OpenHarmony 3.2.5.1
const.product.incremental.version=default const.product.incremental.version=default
const.product.firstapiversion=1 const.product.firstapiversion=1
const.product.build.type=default const.product.build.type=default
......
...@@ -19,7 +19,7 @@ const.allow.mock.location = root:root:0777 ...@@ -19,7 +19,7 @@ const.allow.mock.location = root:root:0777
const.debuggable = root:root:0777 const.debuggable = root:root:0777
persist.sys.usb.config = root:root:0777 persist.sys.usb.config = root:root:0777
# default forbit other user to start service # default forbid other user to start service
ohos.servicectrl. = system:servicectrl:0775 ohos.servicectrl. = system:servicectrl:0775
ohos.startup.powerctrl. = system:powerctrl:0775 ohos.startup.powerctrl. = system:powerctrl:0775
ohos.boot. = system:bootctrl:0775 ohos.boot. = system:bootctrl:0775
...@@ -30,4 +30,4 @@ persist.window.boot. = root:system:0775 ...@@ -30,4 +30,4 @@ persist.window.boot. = root:system:0775
#permission for log #permission for log
debug.bytrace. = root:system:0775 debug.bytrace. = root:system:0775
persist.distributed_hardware.device_manager. = system:system:0775 persist.distributed_hardware.device_manager. = system:system:0775
\ No newline at end of file
...@@ -12,5 +12,5 @@ ...@@ -12,5 +12,5 @@
# limitations under the License. # limitations under the License.
const.ohos.version.security_patch=2022-03-30 const.ohos.version.security_patch=2022-03-30
const.ohos.releasetype=Canary1 const.ohos.releasetype=Canary1
const.ohos.apiversion=8 const.ohos.apiversion=9
const.ohos.fullname=OpenHarmony-2.2.0.0 const.ohos.fullname=OpenHarmony-2.2.0.0
\ No newline at end of file
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
#include <fcntl.h> #include <fcntl.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <stdint.h> #include <stdint.h>
#include <stdbool.h>
#include <unistd.h> #include <unistd.h>
#ifdef __cplusplus #ifdef __cplusplus
...@@ -49,6 +50,7 @@ typedef struct { ...@@ -49,6 +50,7 @@ typedef struct {
#define BOOT_CMD_LINE STARTUP_INIT_UT_PATH"/proc/cmdline" #define BOOT_CMD_LINE STARTUP_INIT_UT_PATH"/proc/cmdline"
uid_t DecodeUid(const char *name); uid_t DecodeUid(const char *name);
gid_t DecodeGid(const char *name);
char *ReadFileToBuf(const char *configFile); char *ReadFileToBuf(const char *configFile);
int GetProcCmdlineValue(const char *name, const char *buffer, char *value, int length); int GetProcCmdlineValue(const char *name, const char *buffer, char *value, int length);
char *ReadFileData(const char *fileName); char *ReadFileData(const char *fileName);
...@@ -58,6 +60,7 @@ void WaitForFile(const char *source, unsigned int maxSecond); ...@@ -58,6 +60,7 @@ void WaitForFile(const char *source, unsigned int maxSecond);
size_t WriteAll(int fd, const char *buffer, size_t size); size_t WriteAll(int fd, const char *buffer, size_t size);
char *GetRealPath(const char *source); char *GetRealPath(const char *source);
int StringToInt(const char *str, int defaultValue); int StringToInt(const char *str, int defaultValue);
int StringToUint(const char *name, unsigned int *value);
int MakeDirRecursive(const char *dir, mode_t mode); int MakeDirRecursive(const char *dir, mode_t mode);
void CheckAndCreateDir(const char *fileName); void CheckAndCreateDir(const char *fileName);
int CheckAndCreatFile(const char *file, mode_t mode); int CheckAndCreatFile(const char *file, mode_t mode);
......
...@@ -79,7 +79,7 @@ void ListAddTail(struct ListNode *list, struct ListNode *item); ...@@ -79,7 +79,7 @@ void ListAddTail(struct ListNode *list, struct ListNode *item);
void ListRemove(struct ListNode *item); void ListRemove(struct ListNode *item);
/** /**
* @brief ListNode comparision function prototype * @brief ListNode comparison function prototype
* *
* @param node ListNode to be compared. * @param node ListNode to be compared.
* @param newNode new ListNode to be compared. * @param newNode new ListNode to be compared.
...@@ -132,9 +132,9 @@ ListNode *ListFind(const ListNode *head, void *data, ListTraversalProc comparePr ...@@ -132,9 +132,9 @@ ListNode *ListFind(const ListNode *head, void *data, ListTraversalProc comparePr
* @brief Traversal the list with specified function * @brief Traversal the list with specified function
* *
* @param head list head, make sure head is valid pointer. * @param head list head, make sure head is valid pointer.
* @param cookie optinal traversing data. * @param cookie optional traversing data.
* @param traversalProc comparing function, return 0 if matched. * @param traversalProc comparing function, return 0 if matched.
* @param flags optinal traversing flags: * @param flags optional traversing flags:
* TRAVERSE_REVERSE_ORDER: traversing from last node to first node; * TRAVERSE_REVERSE_ORDER: traversing from last node to first node;
* default behaviour is from first node to last node * default behaviour is from first node to last node
* TRAVERSE_STOP_WHEN_ERROR: stop traversing if traversalProc return non-zero * TRAVERSE_STOP_WHEN_ERROR: stop traversing if traversalProc return non-zero
......
...@@ -126,7 +126,7 @@ typedef struct { ...@@ -126,7 +126,7 @@ typedef struct {
typedef struct Service_ { typedef struct Service_ {
char *name; char *name;
#ifdef WITH_SELINUX #ifdef WITH_SELINUX
char secon[MAX_SECON_LEN]; char *secon;
#endif // WITH_SELINUX #endif // WITH_SELINUX
int pid; int pid;
int crashCnt; int crashCnt;
......
...@@ -173,7 +173,7 @@ static void DoSleep(const struct CmdArgs *ctx) ...@@ -173,7 +173,7 @@ static void DoSleep(const struct CmdArgs *ctx)
{ {
errno = 0; errno = 0;
unsigned long sleepTime = strtoul(ctx->argv[0], NULL, DECIMAL_BASE); unsigned long sleepTime = strtoul(ctx->argv[0], NULL, DECIMAL_BASE);
INIT_ERROR_CHECK(errno == 0, return, "cannot covert sleep time in command \" sleep \""); INIT_ERROR_CHECK(errno == 0, return, "cannot convert sleep time in command \" sleep \"");
// Limit sleep time in 5 seconds // Limit sleep time in 5 seconds
const unsigned long sleepTimeLimit = 5; const unsigned long sleepTimeLimit = 5;
...@@ -192,7 +192,7 @@ static void DoWait(const struct CmdArgs *ctx) ...@@ -192,7 +192,7 @@ static void DoWait(const struct CmdArgs *ctx)
errno = 0; errno = 0;
waitSecond = strtoul(ctx->argv[timePos], NULL, DECIMAL_BASE); waitSecond = strtoul(ctx->argv[timePos], NULL, DECIMAL_BASE);
INIT_ERROR_CHECK(errno == 0, INIT_ERROR_CHECK(errno == 0,
return, "cannot covert sleep time in command \" wait \""); return, "cannot convert sleep time in command \" wait \"");
} }
INIT_LOGI("Waiting %s %lu second(s)", ctx->argv[filePos], waitSecond); INIT_LOGI("Waiting %s %lu second(s)", ctx->argv[filePos], waitSecond);
...@@ -291,7 +291,7 @@ static int SetOwner(const char *file, const char *ownerStr, const char *groupStr ...@@ -291,7 +291,7 @@ static int SetOwner(const char *file, const char *ownerStr, const char *groupStr
uid_t owner = DecodeUid(ownerStr); uid_t owner = DecodeUid(ownerStr);
INIT_ERROR_CHECK(owner != (uid_t)-1, return -1, "SetOwner invalid uid :%s.", ownerStr); INIT_ERROR_CHECK(owner != (uid_t)-1, return -1, "SetOwner invalid uid :%s.", ownerStr);
gid_t group = DecodeUid(groupStr); gid_t group = DecodeGid(groupStr);
INIT_ERROR_CHECK(group != (gid_t)-1, return -1, "SetOwner invalid gid :%s.", groupStr); INIT_ERROR_CHECK(group != (gid_t)-1, return -1, "SetOwner invalid gid :%s.", groupStr);
return (chown(file, owner, group) != 0) ? -1 : 0; return (chown(file, owner, group) != 0) ? -1 : 0;
} }
...@@ -548,7 +548,7 @@ static void DoSetrlimit(const struct CmdArgs *ctx) ...@@ -548,7 +548,7 @@ static void DoSetrlimit(const struct CmdArgs *ctx)
} }
} }
if (rcs == -1) { if (rcs == -1) {
INIT_LOGE("DoSetrlimit failed, resouces :%s not support.", ctx->argv[0]); INIT_LOGE("DoSetrlimit failed, resources :%s not support.", ctx->argv[0]);
return; return;
} }
INIT_CHECK_ONLY_ELOG(setrlimit(rcs, &limit) == 0, "DoSetrlimit failed : %d", errno); INIT_CHECK_ONLY_ELOG(setrlimit(rcs, &limit) == 0, "DoSetrlimit failed : %d", errno);
......
...@@ -106,13 +106,13 @@ static int SetPerms(const Service *service) ...@@ -106,13 +106,13 @@ static int SetPerms(const Service *service)
} }
INIT_ERROR_CHECK(capset(&capHeader, capData) == 0, return SERVICE_FAILURE, INIT_ERROR_CHECK(capset(&capHeader, capData) == 0, return SERVICE_FAILURE,
"capset faild for service: %s, error: %d", service->name, errno); "capset failed for service: %s, error: %d", service->name, errno);
for (unsigned int i = 0; i < service->servPerm.capsCnt; ++i) { for (unsigned int i = 0; i < service->servPerm.capsCnt; ++i) {
if (service->servPerm.caps[i] == FULL_CAP) { if (service->servPerm.caps[i] == FULL_CAP) {
return SetAllAmbientCapability(); return SetAllAmbientCapability();
} }
INIT_ERROR_CHECK(SetAmbientCapability(service->servPerm.caps[i]) == 0, return SERVICE_FAILURE, INIT_ERROR_CHECK(SetAmbientCapability(service->servPerm.caps[i]) == 0, return SERVICE_FAILURE,
"SetAmbientCapability faild for service: %s", service->name); "SetAmbientCapability failed for service: %s", service->name);
} }
return SERVICE_SUCCESS; return SERVICE_SUCCESS;
} }
...@@ -171,7 +171,7 @@ static int WritePid(const Service *service) ...@@ -171,7 +171,7 @@ static int WritePid(const Service *service)
void SetSecon(Service *service) void SetSecon(Service *service)
{ {
#ifdef WITH_SELINUX #ifdef WITH_SELINUX
if (*(service->secon)) { if (service->secon != NULL) {
if (setexeccon(service->secon) < 0) { if (setexeccon(service->secon) < 0) {
INIT_LOGE("failed to set service %s's secon (%s).", service->name, service->secon); INIT_LOGE("failed to set service %s's secon (%s).", service->name, service->secon);
_exit(PROCESS_EXIT_CODE); _exit(PROCESS_EXIT_CODE);
...@@ -267,7 +267,7 @@ static void ClearEnvironment(Service *service) ...@@ -267,7 +267,7 @@ static void ClearEnvironment(Service *service)
static int InitServicePropertys(Service *service) static int InitServicePropertys(Service *service)
{ {
INIT_ERROR_CHECK(service != NULL, return -1, "Invaild parameter."); INIT_ERROR_CHECK(service != NULL, return -1, "Invalid parameter.");
SetServiceEnterSandbox(service->pathArgs.argv[0], service->attribute); SetServiceEnterSandbox(service->pathArgs.argv[0], service->attribute);
INIT_CHECK_ONLY_ELOG(SetAccessToken(service) == SERVICE_SUCCESS, "access token failed %s", service->name); INIT_CHECK_ONLY_ELOG(SetAccessToken(service) == SERVICE_SUCCESS, "access token failed %s", service->name);
// deal start job // deal start job
...@@ -427,7 +427,7 @@ static void CheckServiceSocket(Service *service) ...@@ -427,7 +427,7 @@ static void CheckServiceSocket(Service *service)
ServiceSocket *tmpSock = service->socketCfg; ServiceSocket *tmpSock = service->socketCfg;
while (tmpSock != NULL) { while (tmpSock != NULL) {
if (tmpSock->sockFd <= 0) { if (tmpSock->sockFd <= 0) {
INIT_LOGE("Invaid socket %s for service", service->name); INIT_LOGE("Invalid socket %s for service", service->name);
tmpSock = tmpSock->next; tmpSock = tmpSock->next;
} }
SocketAddWatcher(&tmpSock->watcher, service, tmpSock->sockFd); SocketAddWatcher(&tmpSock->watcher, service, tmpSock->sockFd);
......
...@@ -36,7 +36,7 @@ ...@@ -36,7 +36,7 @@
# include "init_selinux_param.h" # include "init_selinux_param.h"
#endif // WITH_SELINUX #endif // WITH_SELINUX
// All serivce processes that init will fork+exec. // All service processes that init will fork+exec.
static ServiceSpace g_serviceSpace = { 0 }; static ServiceSpace g_serviceSpace = { 0 };
static const int CRITICAL_DEFAULT_CRASH_TIME = 20; static const int CRITICAL_DEFAULT_CRASH_TIME = 20;
// maximum number of crashes within time CRITICAL_DEFAULT_CRASH_TIME for one service // maximum number of crashes within time CRITICAL_DEFAULT_CRASH_TIME for one service
...@@ -93,6 +93,11 @@ void DumpOneService(const Service *service) ...@@ -93,6 +93,11 @@ void DumpOneService(const Service *service)
int size = 0; int size = 0;
const InitArgInfo *statusMap = GetServieStatusMap(&size); const InitArgInfo *statusMap = GetServieStatusMap(&size);
printf("\tservice name: [%s] \n", service->name); printf("\tservice name: [%s] \n", service->name);
#ifdef WITH_SELINUX
if (service->secon != NULL) {
printf("\tservice secon: [%s] \n", service->secon);
}
#endif
printf("\tservice pid: [%d] \n", service->pid); printf("\tservice pid: [%d] \n", service->pid);
printf("\tservice crashCnt: [%d] \n", service->crashCnt); printf("\tservice crashCnt: [%d] \n", service->crashCnt);
printf("\tservice attribute: [%d] \n", service->attribute); printf("\tservice attribute: [%d] \n", service->attribute);
...@@ -204,6 +209,12 @@ void ReleaseService(Service *service) ...@@ -204,6 +209,12 @@ void ReleaseService(Service *service)
if (service == NULL) { if (service == NULL) {
return; return;
} }
#ifdef WITH_SELINUX
if (service->secon != NULL) {
free(service->secon);
service->secon = NULL;
}
#endif
FreeServiceArg(&service->pathArgs); FreeServiceArg(&service->pathArgs);
FreeServiceArg(&service->writePidArgs); FreeServiceArg(&service->writePidArgs);
FreeServiceArg(&service->capsArgs); FreeServiceArg(&service->capsArgs);
...@@ -483,7 +494,7 @@ static int AddServiceSocket(cJSON *json, Service *service) ...@@ -483,7 +494,7 @@ static int AddServiceSocket(cJSON *json, Service *service)
stringValue = GetStringValue(json, "gid", &strLen); stringValue = GetStringValue(json, "gid", &strLen);
INIT_ERROR_CHECK((stringValue != NULL) && (strLen > 0), free(sockopt); sockopt = NULL; return SERVICE_FAILURE, INIT_ERROR_CHECK((stringValue != NULL) && (strLen > 0), free(sockopt); sockopt = NULL; return SERVICE_FAILURE,
"Failed to get string for gid"); "Failed to get string for gid");
sockopt->gid = DecodeUid(stringValue); sockopt->gid = DecodeGid(stringValue);
INIT_ERROR_CHECK((sockopt->uid != (uid_t)-1) && (sockopt->gid != (uid_t)-1), INIT_ERROR_CHECK((sockopt->uid != (uid_t)-1) && (sockopt->gid != (uid_t)-1),
free(sockopt); sockopt = NULL; return SERVICE_FAILURE, "Invalid uid or gid"); free(sockopt); sockopt = NULL; return SERVICE_FAILURE, "Invalid uid or gid");
ret = ParseSocketOption(json, sockopt); ret = ParseSocketOption(json, sockopt);
...@@ -555,7 +566,7 @@ static int AddServiceFile(cJSON *json, Service *service) ...@@ -555,7 +566,7 @@ static int AddServiceFile(cJSON *json, Service *service)
} }
fileOpt->perm = strtoul(opt[SERVICE_FILE_PERM], 0, OCTAL_BASE); fileOpt->perm = strtoul(opt[SERVICE_FILE_PERM], 0, OCTAL_BASE);
fileOpt->uid = DecodeUid(opt[SERVICE_FILE_UID]); fileOpt->uid = DecodeUid(opt[SERVICE_FILE_UID]);
fileOpt->gid = DecodeUid(opt[SERVICE_FILE_GID]); fileOpt->gid = DecodeGid(opt[SERVICE_FILE_GID]);
if (fileOpt->uid == (uid_t)-1 || fileOpt->gid == (gid_t)-1) { if (fileOpt->uid == (uid_t)-1 || fileOpt->gid == (gid_t)-1) {
free(fileOpt); free(fileOpt);
fileOpt = NULL; fileOpt = NULL;
...@@ -788,7 +799,12 @@ int ParseOneService(const cJSON *curItem, Service *service) ...@@ -788,7 +799,12 @@ int ParseOneService(const cJSON *curItem, Service *service)
INIT_CHECK_RETURN_VALUE(curItem != NULL && service != NULL, SERVICE_FAILURE); INIT_CHECK_RETURN_VALUE(curItem != NULL && service != NULL, SERVICE_FAILURE);
int ret = 0; int ret = 0;
#ifdef WITH_SELINUX #ifdef WITH_SELINUX
(void)GetStringItem(curItem, SECON_STR_IN_CFG, service->secon, MAX_SECON_LEN); size_t strLen = 0;
char *fieldStr = GetStringValue(curItem, SECON_STR_IN_CFG, &strLen);
if (fieldStr != NULL) {
service->secon = strdup(fieldStr);
INIT_ERROR_CHECK(service->secon != NULL, return -1, "Failed to get secon for service %s", service->name);
}
#endif // WITH_SELINUX #endif // WITH_SELINUX
ret = GetServiceArgs(curItem, "path", MAX_PATH_ARGS_CNT, &service->pathArgs); ret = GetServiceArgs(curItem, "path", MAX_PATH_ARGS_CNT, &service->pathArgs);
INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get path for service %s", service->name); INIT_ERROR_CHECK(ret == 0, return SERVICE_FAILURE, "Failed to get path for service %s", service->name);
...@@ -1026,7 +1042,7 @@ void StartAllServices(int startMode) ...@@ -1026,7 +1042,7 @@ void StartAllServices(int startMode)
} }
node = GetNextGroupNode(NODE_TYPE_SERVICES, node); node = GetNextGroupNode(NODE_TYPE_SERVICES, node);
} }
INIT_LOGI("StartAllServices %d finsh", startMode); INIT_LOGI("StartAllServices %d finish", startMode);
} }
void LoadAccessTokenId(void) void LoadAccessTokenId(void)
......
...@@ -52,7 +52,7 @@ static int SetSocketAddr(ServiceSocket *sockopt, sockaddr_union *addr) ...@@ -52,7 +52,7 @@ static int SetSocketAddr(ServiceSocket *sockopt, sockaddr_union *addr)
if (sockopt->family == AF_NETLINK) { if (sockopt->family == AF_NETLINK) {
#ifndef __LITEOS_A__ #ifndef __LITEOS_A__
if (memset_s(&(addr->addrnl), sizeof(addr->addrnl), 0, sizeof(addr->addrnl)) != EOK) { if (memset_s(&(addr->addrnl), sizeof(addr->addrnl), 0, sizeof(addr->addrnl)) != EOK) {
INIT_LOGE("Faild to clear socket address"); INIT_LOGE("Failed to clear socket address");
return -1; return -1;
} }
addr->addrnl.nl_family = AF_NETLINK; addr->addrnl.nl_family = AF_NETLINK;
......
...@@ -70,12 +70,12 @@ static void ParseJob(const cJSON *jobItem, Job *resJob) ...@@ -70,12 +70,12 @@ static void ParseJob(const cJSON *jobItem, Job *resJob)
cJSON *cmdsItem = cJSON_GetObjectItem(jobItem, CMDS_ARR_NAME_IN_JSON); cJSON *cmdsItem = cJSON_GetObjectItem(jobItem, CMDS_ARR_NAME_IN_JSON);
if (!cJSON_IsArray(cmdsItem)) { if (!cJSON_IsArray(cmdsItem)) {
INIT_LOGE("job %s is not an arrary", resJob->name); INIT_LOGE("job %s is not an array", resJob->name);
return; return;
} }
int ret = GetCmdLinesFromJson(cmdsItem, &resJob->cmdLines); int ret = GetCmdLinesFromJson(cmdsItem, &resJob->cmdLines);
if (ret != 0) { if (ret != 0) {
INIT_LOGE("ParseJob, faild to get cmds for job!"); INIT_LOGE("ParseJob, failed to get cmds for job!");
return; return;
} }
return; return;
......
...@@ -116,7 +116,7 @@ static void SendFdsInfo(int sock, Service *service) ...@@ -116,7 +116,7 @@ static void SendFdsInfo(int sock, Service *service)
}; };
if (BuildControlMessage(&msghdr, service->fds, service->fdCount, false) < 0) { if (BuildControlMessage(&msghdr, service->fds, service->fdCount, false) < 0) {
SendErrorInfo(sock, "Faild to build send message", service->name); SendErrorInfo(sock, "Failed to build send message", service->name);
} else { } else {
if (TEMP_FAILURE_RETRY(sendmsg(sock, &msghdr, MSG_NOSIGNAL)) < 0) { if (TEMP_FAILURE_RETRY(sendmsg(sock, &msghdr, MSG_NOSIGNAL)) < 0) {
INIT_LOGE("Failed to send fd info to service \' %s \', err = %d", service->name, errno); INIT_LOGE("Failed to send fd info to service \' %s \', err = %d", service->name, errno);
...@@ -220,7 +220,7 @@ static void HandlerFdHolder(int sock) ...@@ -220,7 +220,7 @@ static void HandlerFdHolder(int sock)
// In this case, ignore fds, just close them if fd passed to init // In this case, ignore fds, just close them if fd passed to init
HandlerGetFds(sock, service); HandlerGetFds(sock, service);
} else { } else {
INIT_LOGE("Unexpect action: %s", action); INIT_LOGE("Unexpected action: %s", action);
} }
FreeFds(fds); FreeFds(fds);
CloseFds(fds, fdCount); CloseFds(fds, fdCount);
......
...@@ -74,7 +74,7 @@ static int FdHolderSockInit(void) ...@@ -74,7 +74,7 @@ static int FdHolderSockInit(void)
addr.sun_family = AF_UNIX; addr.sun_family = AF_UNIX;
if (strncpy_s(addr.sun_path, sizeof(addr.sun_path), if (strncpy_s(addr.sun_path, sizeof(addr.sun_path),
INIT_HOLDER_SOCKET_PATH, strlen(INIT_HOLDER_SOCKET_PATH)) != 0) { INIT_HOLDER_SOCKET_PATH, strlen(INIT_HOLDER_SOCKET_PATH)) != 0) {
INIT_LOGE("Faild to copy fd hoder socket path"); INIT_LOGE("Failed to copy fd hoder socket path");
close(sock); close(sock);
return -1; return -1;
} }
...@@ -193,7 +193,7 @@ static void StartInitSecondStage(void) ...@@ -193,7 +193,7 @@ static void StartInitSecondStage(void)
// If mount required partitions failure. // If mount required partitions failure.
// There is no necessary to continue. // There is no necessary to continue.
// Just abort // Just abort
INIT_LOGE("Mount requried partitions failed; please check fstab file"); INIT_LOGE("Mount required partitions failed; please check fstab file");
// Execute sh for debugging // Execute sh for debugging
execv("/bin/sh", NULL); execv("/bin/sh", NULL);
abort(); abort();
......
...@@ -376,7 +376,7 @@ static void DoTimerStart(const struct CmdArgs *ctx) ...@@ -376,7 +376,7 @@ static void DoTimerStart(const struct CmdArgs *ctx)
} }
if (count != expectedCount) { if (count != expectedCount) {
INIT_LOGE("Call timer_start with unexpect arguments %s", arg); INIT_LOGE("Call timer_start with unexpected arguments %s", arg);
FreeStringVector(splitArgs, count); FreeStringVector(splitArgs, count);
return; return;
} }
...@@ -514,7 +514,7 @@ static void DoMkSandbox(const struct CmdArgs *ctx) ...@@ -514,7 +514,7 @@ static void DoMkSandbox(const struct CmdArgs *ctx)
const char *sandbox = ctx->argv[0]; const char *sandbox = ctx->argv[0];
if (sandbox == NULL) { if (sandbox == NULL) {
INIT_LOGE("Invaild sandbox name."); INIT_LOGE("Invalid sandbox name.");
return; return;
} }
InitDefaultNamespace(); InitDefaultNamespace();
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
static void ProcessSandboxControlFd(uint16_t type, const char *serviceCmd) static void ProcessSandboxControlFd(uint16_t type, const char *serviceCmd)
{ {
if ((type != ACTION_SANDBOX) || (serviceCmd == NULL)) { if ((type != ACTION_SANDBOX) || (serviceCmd == NULL)) {
INIT_LOGE("Invaild parameter"); INIT_LOGE("Invalid parameter");
return; return;
} }
Service *service = GetServiceByName(serviceCmd); Service *service = GetServiceByName(serviceCmd);
......
...@@ -55,10 +55,10 @@ static int ParseRequiredMountInfo(const char *item, Fstab *fstab) ...@@ -55,10 +55,10 @@ static int ParseRequiredMountInfo(const char *item, Fstab *fstab)
q = item + strlen(OHOS_REQUIRED_MOUNT_PREFIX); // Get partition name q = item + strlen(OHOS_REQUIRED_MOUNT_PREFIX); // Get partition name
INIT_CHECK(!(q == NULL || *q == '\0' || (p - q) <= 0), return -1); INIT_CHECK(!(q == NULL || *q == '\0' || (p - q) <= 0), return -1);
INIT_ERROR_CHECK(strncpy_s(partName, PARTITION_NAME_SIZE -1, q, p - q) == EOK, INIT_ERROR_CHECK(strncpy_s(partName, PARTITION_NAME_SIZE -1, q, p - q) == EOK,
return -1, "Failed to copy requried partition name"); return -1, "Failed to copy required partition name");
p++; // skip '=' p++; // skip '='
INIT_ERROR_CHECK(strncpy_s(mountOptions, MAX_BUFFER_LEN -1, p, strlen(p)) == EOK, INIT_ERROR_CHECK(strncpy_s(mountOptions, MAX_BUFFER_LEN -1, p, strlen(p)) == EOK,
return -1, "Failed to copy requried mount info: %s", item); return -1, "Failed to copy required mount info: %s", item);
} }
INIT_LOGV("Mount option of partition %s is [%s]", partName, mountOptions); INIT_LOGV("Mount option of partition %s is [%s]", partName, mountOptions);
if (ParseFstabPerLine(mountOptions, fstab, false, "@") < 0) { if (ParseFstabPerLine(mountOptions, fstab, false, "@") < 0) {
......
...@@ -78,7 +78,7 @@ static void BootchartLogHeader(void) ...@@ -78,7 +78,7 @@ static void BootchartLogHeader(void)
char release[PARAM_VALUE_LEN_MAX] = {}; char release[PARAM_VALUE_LEN_MAX] = {};
uint32_t len = sizeof(release); uint32_t len = sizeof(release);
(void)SystemReadParam("hw_sc.build.os.releasetype", release, &len); (void)SystemReadParam("const.ohos.releasetype", release, &len);
char *cmdLine = ReadFileToBuffer("/proc/cmdline", g_bootchartCtrl->buffer, g_bootchartCtrl->bufferSize); char *cmdLine = ReadFileToBuffer("/proc/cmdline", g_bootchartCtrl->buffer, g_bootchartCtrl->bufferSize);
PLUGIN_CHECK(cmdLine != NULL, return, "Failed to open file /data/bootchart/header"); PLUGIN_CHECK(cmdLine != NULL, return, "Failed to open file /data/bootchart/header");
...@@ -260,7 +260,7 @@ static int DoBootchartStop(void) ...@@ -260,7 +260,7 @@ static int DoBootchartStop(void)
pthread_mutex_unlock(&(g_bootchartCtrl->mutex)); pthread_mutex_unlock(&(g_bootchartCtrl->mutex));
pthread_join(g_bootchartCtrl->threadId, NULL); pthread_join(g_bootchartCtrl->threadId, NULL);
BootchartDestory(); BootchartDestory();
PLUGIN_LOGI("bootcharting stoped"); PLUGIN_LOGI("bootcharting stopped");
return 0; return 0;
} }
......
...@@ -118,7 +118,7 @@ static int LoadParamLabels(const char *fileName) ...@@ -118,7 +118,7 @@ static int LoadParamLabels(const char *fileName)
buff[buffSize - 1] = '\0'; buff[buffSize - 1] = '\0';
int ret = SpliteString(buff, NULL, 0, LoadOneParam_, NULL); int ret = SpliteString(buff, NULL, 0, LoadOneParam_, NULL);
if (ret != 0) { if (ret != 0) {
PARAM_LOGE("Failed to splite string %s fileName %s", buff, fileName); PARAM_LOGE("Failed to split string %s fileName %s", buff, fileName);
continue; continue;
} }
infoCount++; infoCount++;
...@@ -298,4 +298,4 @@ INIT_LOCAL_API void LoadGroupUser(void) ...@@ -298,4 +298,4 @@ INIT_LOCAL_API void LoadGroupUser(void)
} }
PARAM_LOGV("LoadGroupUser getgrent fail errnor %d ", errno); PARAM_LOGV("LoadGroupUser getgrent fail errnor %d ", errno);
endgrent(); endgrent();
} }
\ No newline at end of file
...@@ -180,7 +180,7 @@ INIT_LOCAL_API int RegisterSecuritySelinuxOps(ParamSecurityOps *ops, int isInit) ...@@ -180,7 +180,7 @@ INIT_LOCAL_API int RegisterSecuritySelinuxOps(ParamSecurityOps *ops, int isInit)
ops->securityCheckParamPermission = SelinuxCheckParamPermission; ops->securityCheckParamPermission = SelinuxCheckParamPermission;
} }
ops->securityFreeLabel = FreeLocalSecurityLabel; ops->securityFreeLabel = FreeLocalSecurityLabel;
if (isInit) { if (isInit != 0) {
ops->securityGetLabel = SelinuxGetParamSecurityLabel; ops->securityGetLabel = SelinuxGetParamSecurityLabel;
} }
return ret; return ret;
......
...@@ -142,7 +142,7 @@ static int SystemSetParam(const char *name, const char *value, const ParamSecuri ...@@ -142,7 +142,7 @@ static int SystemSetParam(const char *name, const char *value, const ParamSecuri
PARAM_LOGV("SystemWriteParam name %s value: %s", name, value); PARAM_LOGV("SystemWriteParam name %s value: %s", name, value);
int ctrlService = 0; int ctrlService = 0;
int ret = CheckParameterSet(name, value, srcLabel, &ctrlService); int ret = CheckParameterSet(name, value, srcLabel, &ctrlService);
PARAM_CHECK(ret == 0, return ret, "Forbit to set parameter %s", name); PARAM_CHECK(ret == 0, return ret, "Forbid to set parameter %s", name);
if (ctrlService & PARAM_CTRL_SERVICE) { // ctrl param if (ctrlService & PARAM_CTRL_SERVICE) { // ctrl param
PostParamTrigger(EVENT_TRIGGER_PARAM, name, value); PostParamTrigger(EVENT_TRIGGER_PARAM, name, value);
...@@ -431,4 +431,4 @@ ParamService *GetParamService() ...@@ -431,4 +431,4 @@ ParamService *GetParamService()
{ {
return &g_paramService; return &g_paramService;
} }
#endif #endif
\ No newline at end of file
...@@ -12,11 +12,6 @@ ...@@ -12,11 +12,6 @@
# limitations under the License. # limitations under the License.
import("//base/startup/init_lite/begetd.gni") import("//base/startup/init_lite/begetd.gni")
param_comm_sources = [
"//base/startup/init_lite/services/param/manager/param_manager.c",
"//base/startup/init_lite/services/param/manager/param_server.c",
]
param_include_dirs = [ param_include_dirs = [
"//base/startup/init_lite/services/param/include", "//base/startup/init_lite/services/param/include",
"//base/startup/init_lite/services/param/adapter", "//base/startup/init_lite/services/param/adapter",
...@@ -91,10 +86,27 @@ config("exported_header_files") { ...@@ -91,10 +86,27 @@ config("exported_header_files") {
] ]
} }
base_sources = [
"//base/startup/init_lite/services/log/init_commlog.c",
"//base/startup/init_lite/services/param/base/param_base.c",
"//base/startup/init_lite/services/param/base/param_comm.c",
"//base/startup/init_lite/services/param/base/param_trie.c",
"//base/startup/init_lite/services/param/liteos/param_client.c",
"//base/startup/init_lite/services/param/liteos/param_litedac.c",
"//base/startup/init_lite/services/param/liteos/param_osadp.c",
"//base/startup/init_lite/services/param/manager/param_manager.c",
"//base/startup/init_lite/services/param/manager/param_persist.c",
"//base/startup/init_lite/services/utils/init_hashmap.c",
"//base/startup/init_lite/services/utils/list.c",
]
static_library("param_init_lite") { static_library("param_init_lite") {
defines = [] defines = []
deps = [] deps = []
sources = param_comm_sources sources = [
"//base/startup/init_lite/services/param/manager/param_manager.c",
"//base/startup/init_lite/services/param/manager/param_server.c",
]
include_dirs = param_include_dirs include_dirs = param_include_dirs
defines += param_build_defines defines += param_build_defines
public_configs = [ ":exported_header_files" ] public_configs = [ ":exported_header_files" ]
...@@ -116,18 +128,15 @@ static_library("param_init_lite") { ...@@ -116,18 +128,15 @@ static_library("param_init_lite") {
} }
static_library("param_client_lite") { static_library("param_client_lite") {
sources = param_comm_sources sources = base_sources
include_dirs = param_include_dirs include_dirs = param_include_dirs
cflags = [ "-fPIC" ] cflags = [ "-fPIC" ]
defines = param_build_defines defines = param_build_defines
public_configs = [ ":exported_header_files" ] public_configs = [ ":exported_header_files" ]
if (ohos_kernel_type == "liteos_a") { if (ohos_kernel_type == "liteos_a") {
sources += [ sources +=
"//base/startup/init_lite/services/param/adapter/param_persistadp.c", [ "//base/startup/init_lite/services/param/adapter/param_persistadp.c" ]
"//base/startup/init_lite/services/param/liteos/param_client.c",
"//base/startup/init_lite/services/param/manager/param_persist.c",
]
defines += [ defines += [
"__LITEOS_A__", "__LITEOS_A__",
"WORKSPACE_AREA_NEED_MUTEX", "WORKSPACE_AREA_NEED_MUTEX",
...@@ -135,16 +144,8 @@ static_library("param_client_lite") { ...@@ -135,16 +144,8 @@ static_library("param_client_lite") {
"PARAMWORKSPACE_NEED_MUTEX", "PARAMWORKSPACE_NEED_MUTEX",
] ]
} else if (ohos_kernel_type == "liteos_m") { } else if (ohos_kernel_type == "liteos_m") {
sources += [ sources +=
"//base/startup/init_lite/services/log/init_commlog.c", [ "//base/startup/init_lite/services/param/manager/param_server.c" ]
"//base/startup/init_lite/services/param/base/param_base.c",
"//base/startup/init_lite/services/param/base/param_comm.c",
"//base/startup/init_lite/services/param/base/param_trie.c",
"//base/startup/init_lite/services/param/liteos/param_client.c",
"//base/startup/init_lite/services/param/manager/param_persist.c",
"//base/startup/init_lite/services/utils/init_hashmap.c",
"//base/startup/init_lite/services/utils/list.c",
]
if (enable_ohos_startup_init_lite_use_posix_file_api) { if (enable_ohos_startup_init_lite_use_posix_file_api) {
sources += [ sources += [
"//base/startup/init_lite/services/param/adapter/param_persistadp.c", "//base/startup/init_lite/services/param/adapter/param_persistadp.c",
......
...@@ -78,7 +78,7 @@ int SystemSetParameter(const char *name, const char *value) ...@@ -78,7 +78,7 @@ int SystemSetParameter(const char *name, const char *value)
InitParamClient(); InitParamClient();
int ctrlService = 0; int ctrlService = 0;
int ret = CheckParameterSet(name, value, GetParamSecurityLabel(), &ctrlService); int ret = CheckParameterSet(name, value, GetParamSecurityLabel(), &ctrlService);
PARAM_CHECK(ret == 0, return ret, "Forbit to set parameter %s", name); PARAM_CHECK(ret == 0, return ret, "Forbid to set parameter %s", name);
PARAM_LOGV("SystemSetParameter name %s value: %s ctrlService %d", name, value, ctrlService); PARAM_LOGV("SystemSetParameter name %s value: %s ctrlService %d", name, value, ctrlService);
if ((ctrlService & PARAM_CTRL_SERVICE) != PARAM_CTRL_SERVICE) { // ctrl param if ((ctrlService & PARAM_CTRL_SERVICE) != PARAM_CTRL_SERVICE) { // ctrl param
uint32_t dataIndex = 0; uint32_t dataIndex = 0;
...@@ -152,4 +152,4 @@ int SystemFindParameter(const char *name, ParamHandle *handle) ...@@ -152,4 +152,4 @@ int SystemFindParameter(const char *name, ParamHandle *handle)
PARAM_CHECK(ret == 0, return ret, "Forbid to access parameter %s", name); PARAM_CHECK(ret == 0, return ret, "Forbid to access parameter %s", name);
} }
return ret; return ret;
} }
\ No newline at end of file
...@@ -63,7 +63,7 @@ static int LoadPersistParam(void) ...@@ -63,7 +63,7 @@ static int LoadPersistParam(void)
uint32_t currLen = 0; uint32_t currLen = 0;
while (currLen < fileSize) { while (currLen < fileSize) {
if (buffer[currLen] == '\n') { // splite line if (buffer[currLen] == '\n') { // split line
buffer[currLen] = '\0'; buffer[currLen] = '\0';
int ret = SpliteString(buffer, NULL, 0, LoadOnePersistParam_, NULL); int ret = SpliteString(buffer, NULL, 0, LoadOnePersistParam_, NULL);
PARAM_CHECK(ret == 0, continue, "Failed to set param %d %s", ret, buffer); PARAM_CHECK(ret == 0, continue, "Failed to set param %d %s", ret, buffer);
...@@ -160,4 +160,4 @@ int RegisterPersistParamOps(PersistParamOps *ops) ...@@ -160,4 +160,4 @@ int RegisterPersistParamOps(PersistParamOps *ops)
ops->batchSave = BatchSavePersistParam; ops->batchSave = BatchSavePersistParam;
ops->batchSaveEnd = BatchSavePersistParamEnd; ops->batchSaveEnd = BatchSavePersistParamEnd;
return 0; return 0;
} }
\ No newline at end of file
...@@ -48,7 +48,7 @@ int SystemWriteParam(const char *name, const char *value) ...@@ -48,7 +48,7 @@ int SystemWriteParam(const char *name, const char *value)
{ {
int ctrlService = 0; int ctrlService = 0;
int ret = CheckParameterSet(name, value, GetParamSecurityLabel(), &ctrlService); int ret = CheckParameterSet(name, value, GetParamSecurityLabel(), &ctrlService);
PARAM_CHECK(ret == 0, return ret, "Forbit to set parameter %s", name); PARAM_CHECK(ret == 0, return ret, "Forbid to set parameter %s", name);
PARAM_LOGV("SystemWriteParam name %s value: %s ctrlService %d", name, value, ctrlService); PARAM_LOGV("SystemWriteParam name %s value: %s ctrlService %d", name, value, ctrlService);
if ((ctrlService & PARAM_CTRL_SERVICE) != PARAM_CTRL_SERVICE) { // ctrl param if ((ctrlService & PARAM_CTRL_SERVICE) != PARAM_CTRL_SERVICE) { // ctrl param
uint32_t dataIndex = 0; uint32_t dataIndex = 0;
......
...@@ -171,7 +171,7 @@ void SystemDumpParameters(int verbose) ...@@ -171,7 +171,7 @@ void SystemDumpParameters(int verbose)
if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) {
PARAM_CHECK(ret == 0, return, "Forbid to dump parameters"); PARAM_CHECK(ret == 0, return, "Forbid to dump parameters");
} }
PARAM_DUMP("Dump all paramters begin ...\n"); PARAM_DUMP("Dump all parameters begin ...\n");
if (verbose) { if (verbose) {
PARAM_DUMP("Local sercurity information\n"); PARAM_DUMP("Local sercurity information\n");
PARAM_DUMP("\t pid: %d uid: %d gid: %d \n", PARAM_DUMP("\t pid: %d uid: %d gid: %d \n",
...@@ -185,7 +185,7 @@ void SystemDumpParameters(int verbose) ...@@ -185,7 +185,7 @@ void SystemDumpParameters(int verbose)
HashNodeTraverseForDump(workSpace, verbose); HashNodeTraverseForDump(workSpace, verbose);
workSpace = next; workSpace = next;
} }
PARAM_DUMP("Dump all paramters finish\n"); PARAM_DUMP("Dump all parameters finish\n");
} }
INIT_INNER_API int SysCheckParamExist(const char *name) INIT_INNER_API int SysCheckParamExist(const char *name)
......
...@@ -23,7 +23,7 @@ static int LoadSecurityLabel(const char *fileName) ...@@ -23,7 +23,7 @@ static int LoadSecurityLabel(const char *fileName)
ParamWorkSpace *paramSpace = GetParamWorkSpace(); ParamWorkSpace *paramSpace = GetParamWorkSpace();
PARAM_CHECK(paramSpace != NULL, return -1, "Invalid paramSpace"); PARAM_CHECK(paramSpace != NULL, return -1, "Invalid paramSpace");
PARAM_WORKSPACE_CHECK(paramSpace, return -1, "Invalid space"); PARAM_WORKSPACE_CHECK(paramSpace, return -1, "Invalid space");
PARAM_CHECK(fileName != NULL, return -1, "Invalid fielname for load"); PARAM_CHECK(fileName != NULL, return -1, "Invalid filename for load");
#if !(defined __LITEOS_A__ || defined __LITEOS_M__) #if !(defined __LITEOS_A__ || defined __LITEOS_M__)
// load security label // load security label
ParamSecurityOps *ops = GetParamSecurityOps(PARAM_SECURITY_DAC); ParamSecurityOps *ops = GetParamSecurityOps(PARAM_SECURITY_DAC);
......
...@@ -403,16 +403,16 @@ static int ExecTriggerMatch_(const TriggerWorkSpace *workSpace, ...@@ -403,16 +403,16 @@ static int ExecTriggerMatch_(const TriggerWorkSpace *workSpace,
static int CheckBootMatch_(const TriggerWorkSpace *workSpace, static int CheckBootMatch_(const TriggerWorkSpace *workSpace,
int type, LogicCalculator *calculator, const char *content, uint32_t contentSize) int type, LogicCalculator *calculator, const char *content, uint32_t contentSize)
{ {
PARAM_CHECK(workSpace != NULL, return -1, "Invaid space"); PARAM_CHECK(workSpace != NULL, return -1, "Invalid space");
PARAM_CHECK((type == TRIGGER_BOOT) || (type == TRIGGER_PARAM_WATCH), return -1, "Invaid type"); PARAM_CHECK((type == TRIGGER_BOOT) || (type == TRIGGER_PARAM_WATCH), return -1, "Invalid type");
return ExecTriggerMatch_(workSpace, type, calculator, content, contentSize); return ExecTriggerMatch_(workSpace, type, calculator, content, contentSize);
} }
static int CheckParamMatch_(const TriggerWorkSpace *workSpace, static int CheckParamMatch_(const TriggerWorkSpace *workSpace,
int type, LogicCalculator *calculator, const char *content, uint32_t contentSize) int type, LogicCalculator *calculator, const char *content, uint32_t contentSize)
{ {
PARAM_CHECK(workSpace != NULL, return -1, "Invaid space"); PARAM_CHECK(workSpace != NULL, return -1, "Invalid space");
PARAM_CHECK((type == TRIGGER_PARAM) || (type == TRIGGER_PARAM_WAIT), return -1, "Invaid type"); PARAM_CHECK((type == TRIGGER_PARAM) || (type == TRIGGER_PARAM_WAIT), return -1, "Invalid type");
CalculatorInit(calculator, MAX_CONDITION_NUMBER, sizeof(LogicData), 1); CalculatorInit(calculator, MAX_CONDITION_NUMBER, sizeof(LogicData), 1);
int ret = GetValueFromContent(content, contentSize, 0, calculator->inputName, SUPPORT_DATA_BUFFER_MAX); int ret = GetValueFromContent(content, contentSize, 0, calculator->inputName, SUPPORT_DATA_BUFFER_MAX);
...@@ -427,7 +427,7 @@ static int CheckUnknowMatch_(const TriggerWorkSpace *workSpace, ...@@ -427,7 +427,7 @@ static int CheckUnknowMatch_(const TriggerWorkSpace *workSpace,
int type, LogicCalculator *calculator, const char *content, uint32_t contentSize) int type, LogicCalculator *calculator, const char *content, uint32_t contentSize)
{ {
PARAM_CHECK(workSpace != NULL && content != NULL, return -1, "Failed arg for trigger"); PARAM_CHECK(workSpace != NULL && content != NULL, return -1, "Failed arg for trigger");
PARAM_CHECK(type == TRIGGER_UNKNOW, return -1, "Invaid type"); PARAM_CHECK(type == TRIGGER_UNKNOW, return -1, "Invalid type");
CalculatorInit(calculator, MAX_CONDITION_NUMBER, sizeof(LogicData), 1); CalculatorInit(calculator, MAX_CONDITION_NUMBER, sizeof(LogicData), 1);
int ret = memcpy_s(calculator->triggerContent, sizeof(calculator->triggerContent), content, contentSize); int ret = memcpy_s(calculator->triggerContent, sizeof(calculator->triggerContent), content, contentSize);
...@@ -760,4 +760,4 @@ const char *GetTriggerName(const TriggerNode *trigger) ...@@ -760,4 +760,4 @@ const char *GetTriggerName(const TriggerNode *trigger)
return triggerHead->getTriggerName(trigger); return triggerHead->getTriggerName(trigger);
} }
return ""; return "";
} }
\ No newline at end of file
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
#include <errno.h> #include <errno.h>
#include <dirent.h> #include <dirent.h>
#include <fcntl.h> #include <fcntl.h>
#include <grp.h>
#include <limits.h> #include <limits.h>
#include <pwd.h> #include <pwd.h>
#include <stdlib.h> #include <stdlib.h>
...@@ -48,30 +49,71 @@ float ConvertMicrosecondToSecond(int x) ...@@ -48,30 +49,71 @@ float ConvertMicrosecondToSecond(int x)
return ((x / THOUSAND_UNIT_INT) / THOUSAND_UNIT_FLOAT); return ((x / THOUSAND_UNIT_INT) / THOUSAND_UNIT_FLOAT);
} }
static bool CheckDigit(const char *name)
{
size_t nameLen = strlen(name);
for (size_t i = 0; i < nameLen; ++i) {
if (!isdigit(name[i])) {
return false;
}
}
return true;
}
int StringToUint(const char *name, unsigned int *value)
{
errno = 0;
*value = (unsigned int)strtoul(name, 0, DECIMAL_BASE);
INIT_CHECK_RETURN_VALUE(errno == 0, -1);
return 0;
}
uid_t DecodeUid(const char *name) uid_t DecodeUid(const char *name)
{ {
#ifndef __LITEOS_M__ #ifndef __LITEOS_M__
INIT_CHECK_RETURN_VALUE(name != NULL, -1); INIT_CHECK_RETURN_VALUE(name != NULL, -1);
int digitFlag = 1; uid_t uid = -1;
size_t nameLen = strlen(name); if (CheckDigit(name)) {
for (unsigned int i = 0; i < nameLen; ++i) { if (!StringToUint(name, &uid)) {
if (isalpha(name[i])) { return uid;
digitFlag = 0; } else {
break; INIT_LOGE("Failed to decode uid");
return -1;
} }
} }
if (digitFlag) { struct passwd *p = getpwnam(name);
errno = 0; if (p == NULL) {
uid_t result = strtoul(name, 0, DECIMAL_BASE); INIT_LOGE("Failed to decode uid");
INIT_CHECK_RETURN_VALUE(errno == 0, -1); return -1;
return result; }
} else { return p->pw_uid;
struct passwd *userInf = getpwnam(name); #else
if (userInf == NULL) { return -1;
#endif
}
gid_t DecodeGid(const char *name)
{
#ifndef __LITEOS_M__
INIT_CHECK_RETURN_VALUE(name != NULL, -1);
gid_t gid = -1;
if (CheckDigit(name)) {
if (!StringToUint(name, &gid)) {
return gid;
} else {
INIT_LOGE("Failed to decode gid");
return -1; return -1;
} }
return userInf->pw_uid;
} }
struct group *data = NULL;
while ((data = getgrent()) != NULL) {
if ((data->gr_name != NULL) && (strcmp(data->gr_name, name) == 0)) {
gid = data->gr_gid;
break;
}
}
endgrent();
return gid;
#else #else
return -1; return -1;
#endif #endif
...@@ -220,7 +262,7 @@ char **SplitStringExt(char *buffer, const char *del, int *returnCount, int maxIt ...@@ -220,7 +262,7 @@ char **SplitStringExt(char *buffer, const char *del, int *returnCount, int maxIt
{ {
INIT_CHECK_RETURN_VALUE((maxItemCount >= 0) && (buffer != NULL) && (del != NULL) && (returnCount != NULL), NULL); INIT_CHECK_RETURN_VALUE((maxItemCount >= 0) && (buffer != NULL) && (del != NULL) && (returnCount != NULL), NULL);
// Why is this number? // Why is this number?
// Now we use this function to split a string with a given delimeter // Now we use this function to split a string with a given delimiter
// We do not know how many sub-strings out there after splitting. // We do not know how many sub-strings out there after splitting.
// 50 is just a guess value. // 50 is just a guess value.
const int defaultItemCounts = 50; const int defaultItemCounts = 50;
...@@ -512,4 +554,4 @@ uint32_t GetRandom() ...@@ -512,4 +554,4 @@ uint32_t GetRandom()
} }
close(fd); close(fd);
return ulSeed; return ulSeed;
} }
\ No newline at end of file
...@@ -142,9 +142,9 @@ ListNode *ListFind(const ListNode *head, void *data, ListTraversalProc comparePr ...@@ -142,9 +142,9 @@ ListNode *ListFind(const ListNode *head, void *data, ListTraversalProc comparePr
* @brief Traversal the list with specified function * @brief Traversal the list with specified function
* *
* @param head list head, make sure head is valid pointer. * @param head list head, make sure head is valid pointer.
* @param cookie optinal traversing data. * @param cookie optional traversing data.
* @param traversalProc comparing function, return 0 if matched. * @param traversalProc comparing function, return 0 if matched.
* @param flags optinal traversing flags: * @param flags optional traversing flags:
* TRAVERSE_REVERSE_ORDER: traversing from last node to first node; * TRAVERSE_REVERSE_ORDER: traversing from last node to first node;
* default behaviour is from first node to last node * default behaviour is from first node to last node
* TRAVERSE_STOP_WHEN_ERROR: stop traversing if traversalProc return non-zero * TRAVERSE_STOP_WHEN_ERROR: stop traversing if traversalProc return non-zero
......
...@@ -50,7 +50,7 @@ int main(int argc, char *argv[]) ...@@ -50,7 +50,7 @@ int main(int argc, char *argv[])
}; };
int parameterNum = 2; int parameterNum = 2;
if ((argc != parameterNum) || (argv[1] == nullptr)) { if ((argc != parameterNum) || (argv[1] == nullptr)) {
cout << "Invaild parameter" << endl; cout << "Invalid parameter" << endl;
} }
const string name = argv[1]; const string name = argv[1];
int abilityId = 0; int abilityId = 0;
...@@ -59,7 +59,7 @@ int main(int argc, char *argv[]) ...@@ -59,7 +59,7 @@ int main(int argc, char *argv[])
cout << "sa service name " << item->first << "ability id " << item->second << endl; cout << "sa service name " << item->first << "ability id " << item->second << endl;
abilityId = item->second; abilityId = item->second;
} else { } else {
cout << "Invaild sa service name" << endl; cout << "Invalid sa service name" << endl;
return 0; return 0;
} }
......
...@@ -208,7 +208,8 @@ ohos_unittest("init_unittest") { ...@@ -208,7 +208,8 @@ ohos_unittest("init_unittest") {
"//third_party/cJSON:cjson_static", "//third_party/cJSON:cjson_static",
"//third_party/googletest:gmock", "//third_party/googletest:gmock",
"//third_party/googletest:gtest", "//third_party/googletest:gtest",
"//third_party/openssl:libcrypto_shared", "//third_party/mbedtls:mbedtls_shared",
"//utils/native/base:utils",
] ]
defines = [ defines = [
...@@ -218,6 +219,7 @@ ohos_unittest("init_unittest") { ...@@ -218,6 +219,7 @@ ohos_unittest("init_unittest") {
"PARAM_SUPPORT_DAC", "PARAM_SUPPORT_DAC",
"_GNU_SOURCE", "_GNU_SOURCE",
"PARAM_SUPPORT_TRIGGER", "PARAM_SUPPORT_TRIGGER",
"USE_MBEDTLS",
] ]
defines += [ "_GNU_SOURCE" ] defines += [ "_GNU_SOURCE" ]
...@@ -262,6 +264,7 @@ ohos_unittest("init_unittest") { ...@@ -262,6 +264,7 @@ ohos_unittest("init_unittest") {
if (enable_ohos_startup_init_feature_deviceinfo) { if (enable_ohos_startup_init_feature_deviceinfo) {
sources += [ sources += [
"//base/startup/init_lite/device_info/device_info_kits.cpp", "//base/startup/init_lite/device_info/device_info_kits.cpp",
"//base/startup/init_lite/device_info/device_info_load.cpp",
"//base/startup/init_lite/device_info/device_info_proxy.cpp", "//base/startup/init_lite/device_info/device_info_proxy.cpp",
] ]
defines += [ "PARAM_FEATURE_DEVICEINFO" ] defines += [ "PARAM_FEATURE_DEVICEINFO" ]
......
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "begetctl.h" #include "begetctl.h"
#include "param_stub.h" #include "param_stub.h"
#include "securec.h" #include "securec.h"
#include "shell.h" #include "shell.h"
using namespace std; using namespace std;
using namespace testing::ext; using namespace testing::ext;
namespace init_ut { namespace init_ut {
class BegetctlUnitTest : public testing::Test { class BegetctlUnitTest : public testing::Test {
public: public:
static void SetUpTestCase(void) static void SetUpTestCase(void)
{ {
PrepareInitUnitTestEnv(); PrepareInitUnitTestEnv();
}; };
static void TearDownTestCase(void) {}; static void TearDownTestCase(void) {};
void SetUp(void) {}; void SetUp(void) {};
void TearDown(void) {}; void TearDown(void) {};
}; };
HWTEST_F(BegetctlUnitTest, TestShellInit, TestSize.Level0) HWTEST_F(BegetctlUnitTest, TestShellInit, TestSize.Level0)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param" "param"
}; };
BShellEnvDirectExecute(GetShellHandle(), 1, (char **)args); BShellEnvDirectExecute(GetShellHandle(), 1, (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellLs, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellLs, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "ls" "param", "ls"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellLsWithR, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellLsWithR, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "ls", "-r" "param", "ls", "-r"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellLsGet, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellLsGet, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "get" "param", "get"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellSet, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellSet, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "set", "aaaaa", "1234567" "param", "set", "aaaaa", "1234567"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellGetWithKey, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellGetWithKey, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "get", "aaaaa" "param", "get", "aaaaa"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellWait, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellWait, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "wait", "aaaaa" "param", "wait", "aaaaa"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellWaitFalse, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellWaitFalse, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "wait" "param", "wait"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellWaitWithKey, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellWaitWithKey, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "wait", "aaaaa", "12*", "30" "param", "wait", "aaaaa", "12*", "30"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellParamShell, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellParamShell, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
const char *args[] = { const char *args[] = {
"param", "shell" "param", "shell"
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellLsWithvalue, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellLsWithvalue, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
BShellEnvSetParam(GetShellHandle(), PARAM_REVERESD_NAME_CURR_PARAMETER, "..a", PARAM_STRING, (void *)"..a"); BShellEnvSetParam(GetShellHandle(), PARAM_REVERESD_NAME_CURR_PARAMETER, "..a", PARAM_STRING, (void *)"..a");
const char *args[] = { const char *args[] = {
"param", "ls", PARAM_REVERESD_NAME_CURR_PARAMETER "param", "ls", PARAM_REVERESD_NAME_CURR_PARAMETER
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
HWTEST_F(BegetctlUnitTest, TestShellLsWithvalueExist, TestSize.Level1) HWTEST_F(BegetctlUnitTest, TestShellLsWithvalueExist, TestSize.Level1)
{ {
BShellParamCmdRegister(GetShellHandle(), 0); BShellParamCmdRegister(GetShellHandle(), 0);
BShellEnvSetParam(GetShellHandle(), PARAM_REVERESD_NAME_CURR_PARAMETER, "#", PARAM_STRING, (void *)"#"); BShellEnvSetParam(GetShellHandle(), PARAM_REVERESD_NAME_CURR_PARAMETER, "#", PARAM_STRING, (void *)"#");
const char *args[] = { const char *args[] = {
"param", "ls", "-r", PARAM_REVERESD_NAME_CURR_PARAMETER "param", "ls", "-r", PARAM_REVERESD_NAME_CURR_PARAMETER
}; };
BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args); BShellEnvDirectExecute(GetShellHandle(), sizeof(args) / sizeof(args[0]), (char **)args);
} }
} // namespace init_ut } // namespace init_ut
...@@ -67,11 +67,6 @@ HWTEST_F(DeviceInfoUnittest, GetDevUdidTest, TestSize.Level1) ...@@ -67,11 +67,6 @@ HWTEST_F(DeviceInfoUnittest, GetDevUdidTest, TestSize.Level1)
ASSERT_NE(nullptr, samgr); ASSERT_NE(nullptr, samgr);
sptr<IRemoteObject> object = samgr->GetSystemAbility(SYSPARAM_DEVICE_SERVICE_ID); sptr<IRemoteObject> object = samgr->GetSystemAbility(SYSPARAM_DEVICE_SERVICE_ID);
ASSERT_NE(nullptr, samgr); ASSERT_NE(nullptr, samgr);
OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance();
auto deathRecipientPtr = instance.GetDeathRecipient();
if (deathRecipientPtr) {
deathRecipientPtr->OnRemoteDied(object);
}
} }
HWTEST_F(DeviceInfoUnittest, StubTest, TestSize.Level1) HWTEST_F(DeviceInfoUnittest, StubTest, TestSize.Level1)
{ {
......
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include <sys/statvfs.h> #include <sys/statvfs.h>
#include "init_cmds.h" #include "init_cmds.h"
#include "init_reboot.h" #include "init_reboot.h"
#include "init_param.h" #include "init_param.h"
#include "param_stub.h" #include "param_stub.h"
#include "init_utils.h" #include "init_utils.h"
#include "trigger_manager.h" #include "trigger_manager.h"
#include "init_group_manager.h" #include "init_group_manager.h"
using namespace testing::ext; using namespace testing::ext;
using namespace std; using namespace std;
namespace init_ut { namespace init_ut {
class InitRebootUnitTest : public testing::Test { class InitRebootUnitTest : public testing::Test {
public: public:
static void SetUpTestCase(void) {}; static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {}; static void TearDownTestCase(void) {};
void SetUp() {}; void SetUp() {};
void TearDown() {}; void TearDown() {};
}; };
HWTEST_F(InitRebootUnitTest, TestInitReboot, TestSize.Level1) HWTEST_F(InitRebootUnitTest, TestInitReboot, TestSize.Level1)
{ {
ExecReboot("reboot"); ExecReboot("reboot");
ExecReboot("reboot,shutdown"); ExecReboot("reboot,shutdown");
ExecReboot("reboot,bootloader"); ExecReboot("reboot,bootloader");
ExecReboot("reboot,updater:123"); ExecReboot("reboot,updater:123");
ExecReboot("reboot,flash:123"); ExecReboot("reboot,flash:123");
ExecReboot("reboot,flashd:123"); ExecReboot("reboot,flashd:123");
ExecReboot("reboot,suspend:123"); ExecReboot("reboot,suspend:123");
const char *option = nullptr; const char *option = nullptr;
int ret = DoReboot(option); int ret = DoReboot(option);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
option = "updater"; option = "updater";
ret = DoReboot(option); ret = DoReboot(option);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
ret = DoReboot(DEVICE_CMD_SUSPEND); ret = DoReboot(DEVICE_CMD_SUSPEND);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
ret = DoReboot(DEVICE_CMD_FREEZE); ret = DoReboot(DEVICE_CMD_FREEZE);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
clearMisc(); clearMisc();
} }
} // namespace init_ut } // namespace init_ut
...@@ -273,8 +273,14 @@ HWTEST_F(ServiceUnitTest, TestServiceExec, TestSize.Level1) ...@@ -273,8 +273,14 @@ HWTEST_F(ServiceUnitTest, TestServiceExec, TestSize.Level1)
service->pathArgs.count = 1; service->pathArgs.count = 1;
const char *path = "/data/init_ut/test_service_release"; const char *path = "/data/init_ut/test_service_release";
service->pathArgs.argv[0] = strdup(path); service->pathArgs.argv[0] = strdup(path);
EnterServiceSandbox(service);
service->importance = 20; service->importance = 20;
service->servPerm.gIDCnt = -1;
service->servPerm.uID = 0;
unsigned int *caps = (unsigned int *)calloc(1, sizeof(unsigned int) * 1);
caps[0] = FULL_CAP;
service->servPerm.caps = caps;
service->servPerm.capsCnt = 1;
EnterServiceSandbox(service);
int ret = ServiceExec(service); int ret = ServiceExec(service);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
......
文件模式从 100755 更改为 100644
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "init_cmds.h" #include "init_cmds.h"
#include "init_group_manager.h" #include "init_group_manager.h"
#include "init_hashmap.h" #include "init_hashmap.h"
#include "init_param.h" #include "init_param.h"
#include "init_module_engine.h" #include "init_module_engine.h"
#include "init_cmdexecutor.h" #include "init_cmdexecutor.h"
#include "param_stub.h" #include "param_stub.h"
#include "init_utils.h" #include "init_utils.h"
#include "securec.h" #include "securec.h"
using namespace testing::ext; using namespace testing::ext;
using namespace std; using namespace std;
namespace init_ut { namespace init_ut {
class ModuleMgrUnitTest : public testing::Test { class ModuleMgrUnitTest : public testing::Test {
public: public:
static void SetUpTestCase(void) {}; static void SetUpTestCase(void) {};
static void TearDownTestCase(void) {}; static void TearDownTestCase(void) {};
void SetUp(void) {}; void SetUp(void) {};
void TearDown(void) {}; void TearDown(void) {};
}; };
int g_cmdExecId = 0; int g_cmdExecId = 0;
int TestCmdExecutor(int id, const char *name, int argc, const char **argv) int TestCmdExecutor(int id, const char *name, int argc, const char **argv)
{ {
printf("TestCmdExecutor id %d, name %s \n", id, name); printf("TestCmdExecutor id %d, name %s \n", id, name);
g_cmdExecId = id; g_cmdExecId = id;
return 0; return 0;
} }
HWTEST_F(ModuleMgrUnitTest, PluginAddCmd, TestSize.Level1) HWTEST_F(ModuleMgrUnitTest, PluginAddCmd, TestSize.Level1)
{ {
InitServiceSpace(); InitServiceSpace();
const char *testName = "testCmd1"; const char *testName = "testCmd1";
const char *cmdContent = "testCmd1 test1 test2 test3"; const char *cmdContent = "testCmd1 test1 test2 test3";
const char *cmdContentNotValid = "testCmd1 t e s t 1 t e s t 2 t"; const char *cmdContentNotValid = "testCmd1 t e s t 1 t e s t 2 t";
int cmdExecId1 = AddCmdExecutor(testName, TestCmdExecutor); int cmdExecId1 = AddCmdExecutor(testName, TestCmdExecutor);
ASSERT_NE(cmdExecId1 > 0, 0); ASSERT_NE(cmdExecId1 > 0, 0);
int cmdExecId2 = AddCmdExecutor("testCmd2", TestCmdExecutor); int cmdExecId2 = AddCmdExecutor("testCmd2", TestCmdExecutor);
ASSERT_NE(cmdExecId2 > 0, 0); ASSERT_NE(cmdExecId2 > 0, 0);
cmdExecId2 = AddCmdExecutor("testCmd3", TestCmdExecutor); cmdExecId2 = AddCmdExecutor("testCmd3", TestCmdExecutor);
ASSERT_NE(cmdExecId2 > 0, 0); ASSERT_NE(cmdExecId2 > 0, 0);
int cmdExecId4 = AddCmdExecutor("testCmd4", TestCmdExecutor); int cmdExecId4 = AddCmdExecutor("testCmd4", TestCmdExecutor);
ASSERT_NE(cmdExecId4 > 0, 0); ASSERT_NE(cmdExecId4 > 0, 0);
PluginExecCmd("testCmd4", 0, nullptr); PluginExecCmd("testCmd4", 0, nullptr);
int cmdIndex = 0; int cmdIndex = 0;
const char *cmdName = PluginGetCmdIndex(cmdContent, &cmdIndex); const char *cmdName = PluginGetCmdIndex(cmdContent, &cmdIndex);
ASSERT_EQ(strcmp(cmdName, testName), 0); ASSERT_EQ(strcmp(cmdName, testName), 0);
printf("TestCmdExecutor cmdIndex 0x%04x, name %s \n", cmdIndex, cmdName); printf("TestCmdExecutor cmdIndex 0x%04x, name %s \n", cmdIndex, cmdName);
// exec // exec
g_cmdExecId = -1; g_cmdExecId = -1;
PluginExecCmdByName(cmdName, cmdContent); PluginExecCmdByName(cmdName, cmdContent);
ASSERT_EQ(cmdExecId1, g_cmdExecId); ASSERT_EQ(cmdExecId1, g_cmdExecId);
PluginExecCmdByName(cmdName, nullptr); PluginExecCmdByName(cmdName, nullptr);
PluginExecCmdByName(cmdName, cmdContentNotValid); PluginExecCmdByName(cmdName, cmdContentNotValid);
g_cmdExecId = -1; g_cmdExecId = -1;
PluginExecCmdByCmdIndex(cmdIndex, cmdContent); PluginExecCmdByCmdIndex(cmdIndex, cmdContent);
ASSERT_EQ(cmdExecId1, g_cmdExecId); ASSERT_EQ(cmdExecId1, g_cmdExecId);
const char *argv[] = {"test"}; const char *argv[] = {"test"};
PluginExecCmd("install", 1, argv); PluginExecCmd("install", 1, argv);
PluginExecCmd("uninstall", 1, argv); PluginExecCmd("uninstall", 1, argv);
// del // del
RemoveCmdExecutor("testCmd4", cmdExecId4); RemoveCmdExecutor("testCmd4", cmdExecId4);
} }
HWTEST_F(ModuleMgrUnitTest, ModuleInstallTest, TestSize.Level1) HWTEST_F(ModuleMgrUnitTest, ModuleInstallTest, TestSize.Level1)
{ {
int ret; int ret;
int cnt; int cnt;
// Create module manager // Create module manager
MODULE_MGR *moduleMgr = ModuleMgrCreate("init"); MODULE_MGR *moduleMgr = ModuleMgrCreate("init");
ASSERT_NE(moduleMgr, nullptr); ASSERT_NE(moduleMgr, nullptr);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
// Install one module // Install one module
ret = ModuleMgrInstall(moduleMgr, "libbootchart", 0, NULL); ret = ModuleMgrInstall(moduleMgr, "libbootchart", 0, NULL);
ASSERT_EQ(ret, 0); ASSERT_EQ(ret, 0);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 1); ASSERT_EQ(cnt, 1);
// Uninstall the module // Uninstall the module
ModuleMgrUninstall(moduleMgr, "libbootchart"); ModuleMgrUninstall(moduleMgr, "libbootchart");
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
// Install two module // Install two module
ret = ModuleMgrInstall(moduleMgr, "libbootchart", 0, NULL); ret = ModuleMgrInstall(moduleMgr, "libbootchart", 0, NULL);
ASSERT_EQ(ret, 0); ASSERT_EQ(ret, 0);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 1); ASSERT_EQ(cnt, 1);
ret = ModuleMgrInstall(moduleMgr, "notexist", 0, NULL); ret = ModuleMgrInstall(moduleMgr, "notexist", 0, NULL);
ASSERT_NE(ret, 0); ASSERT_NE(ret, 0);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 1); ASSERT_EQ(cnt, 1);
// Uninstall the module // Uninstall the module
ModuleMgrUninstall(moduleMgr, "libbootchart"); ModuleMgrUninstall(moduleMgr, "libbootchart");
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
ModuleMgrUninstall(moduleMgr, "notexist"); ModuleMgrUninstall(moduleMgr, "notexist");
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
ModuleMgrDestroy(moduleMgr); ModuleMgrDestroy(moduleMgr);
// Scan all modules // Scan all modules
moduleMgr = ModuleMgrScan("init"); moduleMgr = ModuleMgrScan("init");
ASSERT_NE(moduleMgr, nullptr); ASSERT_NE(moduleMgr, nullptr);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_NE(cnt, 0); ASSERT_NE(cnt, 0);
ModuleMgrUninstall(moduleMgr, NULL); ModuleMgrUninstall(moduleMgr, NULL);
cnt = ModuleMgrGetCnt(moduleMgr); cnt = ModuleMgrGetCnt(moduleMgr);
ASSERT_EQ(cnt, 0); ASSERT_EQ(cnt, 0);
ModuleMgrGetArgs(); ModuleMgrGetArgs();
ModuleMgrDestroy(moduleMgr); ModuleMgrDestroy(moduleMgr);
} }
} // namespace init_ut } // namespace init_ut
...@@ -45,7 +45,7 @@ const gid_t TEST_FILE_GID = 999; ...@@ -45,7 +45,7 @@ const gid_t TEST_FILE_GID = 999;
const mode_t TEST_FILE_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; const mode_t TEST_FILE_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
#endif #endif
// init.cfg releated // init.cfg related
const std::string CFG_FILE = "/etc/init.cfg"; const std::string CFG_FILE = "/etc/init.cfg";
const std::string SERVICE_ARR_NAME_IN_JSON = "services"; const std::string SERVICE_ARR_NAME_IN_JSON = "services";
const std::string JOBS_ARR_NAME_IN_JSON = "jobs"; const std::string JOBS_ARR_NAME_IN_JSON = "jobs";
...@@ -62,7 +62,7 @@ const int TEST_MAX_PATH_ARGS_CNT = 20; // max path and args count ...@@ -62,7 +62,7 @@ const int TEST_MAX_PATH_ARGS_CNT = 20; // max path and args count
const int TEST_MAX_ONE_ARG_LEN = 64; // max length of one param/path const int TEST_MAX_ONE_ARG_LEN = 64; // max length of one param/path
const int CAT_BUF_SIZE = 512; // standard Cat buffer size from vfs_shell_cmd const int CAT_BUF_SIZE = 512; // standard Cat buffer size from vfs_shell_cmd
// job test releated // job test related
const std::string PRE_INIT_DIR = ROOT_DIR + "preInitDir/"; const std::string PRE_INIT_DIR = ROOT_DIR + "preInitDir/";
const std::string INIT_DIR = PRE_INIT_DIR + "initDir"; const std::string INIT_DIR = PRE_INIT_DIR + "initDir";
const std::string POST_INIT_DIR = INIT_DIR + "postInitDir"; const std::string POST_INIT_DIR = INIT_DIR + "postInitDir";
......
此差异已折叠。
...@@ -447,7 +447,7 @@ public: ...@@ -447,7 +447,7 @@ public:
int TestServiceCtrl(const char *serviceName, int mode) int TestServiceCtrl(const char *serviceName, int mode)
{ {
// service forbit // service forbid
ParamAuditData auditData = {}; ParamAuditData auditData = {};
auditData.name = "ohos.servicectrl."; auditData.name = "ohos.servicectrl.";
auditData.dacData.gid = 202; // 202 test dac gid auditData.dacData.gid = 202; // 202 test dac gid
...@@ -459,7 +459,7 @@ public: ...@@ -459,7 +459,7 @@ public:
int TestPowerCtrl(const char *reboot, int mode) int TestPowerCtrl(const char *reboot, int mode)
{ {
// service forbit // service forbid
ParamAuditData auditData = {}; ParamAuditData auditData = {};
auditData.name = "ohos.servicectrl."; auditData.name = "ohos.servicectrl.";
auditData.dacData.gid = 202; // 202 test dac gid auditData.dacData.gid = 202; // 202 test dac gid
...@@ -573,4 +573,4 @@ HWTEST_F(ParamServiceUnitTest, TestPowerCtrl, TestSize.Level0) ...@@ -573,4 +573,4 @@ HWTEST_F(ParamServiceUnitTest, TestPowerCtrl, TestSize.Level0)
ret = test.TestPowerCtrl("reboot", 0772); ret = test.TestPowerCtrl("reboot", 0772);
EXPECT_EQ(ret, 0); EXPECT_EQ(ret, 0);
} }
} // namespace init_ut } // namespace init_ut
\ No newline at end of file
此差异已折叠。
...@@ -25,10 +25,10 @@ const.allow.mock.location root:root:0777 ...@@ -25,10 +25,10 @@ const.allow.mock.location root:root:0777
const.debuggable root:root:0777 const.debuggable root:root:0777
persist.sys.usb.config root:root:0777 persist.sys.usb.config root:root:0777
# default forbit other user to start service # default forbid other user to start service
ohos.servicectrl. root:root:0777 ohos.servicectrl. root:root:0777
test.permission. root:root:0770 test.permission. root:root:0770
test.permission.read. root:root:0774 test.permission.read. root:root:0774
test.permission.write. root:root:0772 test.permission.write. root:root:0772
test.permission.watcher. root:root:0771 test.permission.watcher. root:root:0771
\ No newline at end of file
...@@ -25,5 +25,5 @@ const.allow.mock.location root:root:0777 ...@@ -25,5 +25,5 @@ const.allow.mock.location root:root:0777
const.debuggable root:root:0777 const.debuggable root:root:0777
persist.sys.usb.config root:root:0777 persist.sys.usb.config root:root:0777
# default forbit other user to start service # default forbid other user to start service
ohos.servicectrl. root:root:0777 ohos.servicectrl. root:root:0777
\ No newline at end of file
...@@ -36,7 +36,7 @@ function hdc_push_cmd() { ...@@ -36,7 +36,7 @@ function hdc_push_cmd() {
if [ $# -ne 2 ];then if [ $# -ne 2 ];then
return; return;
fi fi
echo "Pushing resouces to device" echo "Pushing resources to device"
hdc file send $@ hdc file send $@
sleep 0.2 sleep 0.2
} }
......
...@@ -169,7 +169,7 @@ static void HandleRequiredDynamicDeviceNodes(const struct Uevent *uevent) ...@@ -169,7 +169,7 @@ static void HandleRequiredDynamicDeviceNodes(const struct Uevent *uevent)
static void HandleUeventRequired(const struct Uevent *uevent, char **devices, int num) static void HandleUeventRequired(const struct Uevent *uevent, char **devices, int num)
{ {
const char *deviceName; const char *deviceName;
INIT_ERROR_CHECK(devices != NULL && num > 0, return, "Fault paramters"); INIT_ERROR_CHECK(devices != NULL && num > 0, return, "Fault parameters");
if (uevent->action == ACTION_ADD) { if (uevent->action == ACTION_ADD) {
ChangeSysAttributePermissions(uevent->syspath); ChangeSysAttributePermissions(uevent->syspath);
} }
...@@ -332,7 +332,7 @@ static void Trigger(const char *path, int sockFd, char **devices, int num) ...@@ -332,7 +332,7 @@ static void Trigger(const char *path, int sockFd, char **devices, int num)
} }
char ueventBuffer[PATH_MAX]; char ueventBuffer[PATH_MAX];
if (snprintf_s(ueventBuffer, PATH_MAX, PATH_MAX - 1, "%s/%s", path, "uevent") == -1) { if (snprintf_s(ueventBuffer, PATH_MAX, PATH_MAX - 1, "%s/%s", path, "uevent") == -1) {
INIT_LOGW("Cannnot build uevent path under %s", path); INIT_LOGW("Cannot build uevent path under %s", path);
continue; continue;
} }
DoTrigger(ueventBuffer, sockFd, devices, num); DoTrigger(ueventBuffer, sockFd, devices, num);
......
...@@ -307,7 +307,7 @@ static char **GetBlockDeviceSymbolLinks(const struct Uevent *uevent) ...@@ -307,7 +307,7 @@ static char **GetBlockDeviceSymbolLinks(const struct Uevent *uevent)
return NULL; return NULL;
} }
// Reverse walk through sysPath, and check subystem file under each directory. // Reverse walk through sysPath, and check subsystem file under each directory.
char *parent = dirname(sysPath); char *parent = dirname(sysPath);
while (parent != NULL && !STRINGEQUAL(parent, "/") && !STRINGEQUAL(parent, ".")) { while (parent != NULL && !STRINGEQUAL(parent, "/") && !STRINGEQUAL(parent, ".")) {
char subsystem[SYSPATH_SIZE]; char subsystem[SYSPATH_SIZE];
......
...@@ -102,7 +102,7 @@ static int ParseDeviceConfig(char *p) ...@@ -102,7 +102,7 @@ static int ParseDeviceConfig(char *p)
INIT_ERROR_CHECK(errno == 0, config->mode = DEVMODE, INIT_ERROR_CHECK(errno == 0, config->mode = DEVMODE,
"Invalid mode in config file for device node %s. use default mode", config->name); "Invalid mode in config file for device node %s. use default mode", config->name);
config->uid = (uid_t)DecodeUid(items[DEVICE_CONFIG_UID_NUM]); config->uid = (uid_t)DecodeUid(items[DEVICE_CONFIG_UID_NUM]);
config->gid = (gid_t)DecodeUid(items[DEVICE_CONFIG_GID_NUM]); config->gid = (gid_t)DecodeGid(items[DEVICE_CONFIG_GID_NUM]);
if (count == expectedCount) { if (count == expectedCount) {
config->parameter = strdup(items[DEVICE_CONFIG_PARAM_NUM]); // device parameter config->parameter = strdup(items[DEVICE_CONFIG_PARAM_NUM]); // device parameter
} else { } else {
...@@ -142,7 +142,7 @@ static int ParseSysfsConfig(char *p) ...@@ -142,7 +142,7 @@ static int ParseSysfsConfig(char *p)
INIT_ERROR_CHECK(errno == 0, config->mode = DEVMODE, INIT_ERROR_CHECK(errno == 0, config->mode = DEVMODE,
"Invalid mode in config file for sys path %s. use default mode", config->sysPath); "Invalid mode in config file for sys path %s. use default mode", config->sysPath);
config->uid = (uid_t)DecodeUid(items[SYS_CONFIG_UID_NUM]); config->uid = (uid_t)DecodeUid(items[SYS_CONFIG_UID_NUM]);
config->gid = (gid_t)DecodeUid(items[SYS_CONFIG_GID_NUM]); config->gid = (gid_t)DecodeGid(items[SYS_CONFIG_GID_NUM]);
ListAddTail(&g_sysDevices, &config->list); ListAddTail(&g_sysDevices, &config->list);
FreeStringVector(items, count); FreeStringVector(items, count);
return 0; return 0;
...@@ -155,7 +155,7 @@ static int ParseFirmwareConfig(char *p) ...@@ -155,7 +155,7 @@ static int ParseFirmwareConfig(char *p)
// Sanity checks // Sanity checks
struct stat st = {}; struct stat st = {};
INIT_ERROR_CHECK(stat(p, &st) == 0, return -1, "Invalid firware file: %s, err = %d", p, errno); INIT_ERROR_CHECK(stat(p, &st) == 0, return -1, "Invalid firmware file: %s, err = %d", p, errno);
INIT_ERROR_CHECK(S_ISDIR(st.st_mode), return -1, "Expect directory in firmware config"); INIT_ERROR_CHECK(S_ISDIR(st.st_mode), return -1, "Expect directory in firmware config");
struct FirmwareUdevConf *config = calloc(1, sizeof(struct FirmwareUdevConf)); struct FirmwareUdevConf *config = calloc(1, sizeof(struct FirmwareUdevConf));
INIT_CHECK(config != NULL, errno = ENOMEM; INIT_CHECK(config != NULL, errno = ENOMEM;
......
...@@ -39,7 +39,7 @@ int UeventdSocketInit(void) ...@@ -39,7 +39,7 @@ int UeventdSocketInit(void)
int on = 1; int on = 1;
if (memset_s(&addr, sizeof(addr), 0, sizeof(addr)) != EOK) { if (memset_s(&addr, sizeof(addr), 0, sizeof(addr)) != EOK) {
INIT_LOGE("Faild to clear socket address"); INIT_LOGE("Failed to clear socket address");
return -1; return -1;
} }
addr.nl_family = AF_NETLINK; addr.nl_family = AF_NETLINK;
......
...@@ -17,10 +17,12 @@ group("watchdog") { ...@@ -17,10 +17,12 @@ group("watchdog") {
if (defined(ohos_lite)) { if (defined(ohos_lite)) {
executable("watchdog_service") { executable("watchdog_service") {
sources = [ "init_watchdog.c" ] sources = [
"//base/startup/init_lite/services/log/init_commlog.c",
"//base/startup/init_lite/watchdog/init_watchdog.c",
]
deps = [ deps = [
"//base/startup/init_lite/services/log:init_log", "//base/startup/init_lite/services/log:init_log",
"//base/startup/init_lite/services/param/base:parameterbase",
"//third_party/bounds_checking_function:libsec_static", "//third_party/bounds_checking_function:libsec_static",
] ]
defines = [ defines = [
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册