diff --git a/adapter/appspawn_ace.cpp b/adapter/appspawn_ace.cpp index 15f465aeb1303e82b3a1285db8ee01c8d41f0ef3..7bb95d58126a8488bf1c50f8085e62625a0b198d 100644 --- a/adapter/appspawn_ace.cpp +++ b/adapter/appspawn_ace.cpp @@ -24,17 +24,14 @@ void LoadExtendLib(AppSpawnContent *content) #else const char *acelibdir("/system/lib/libace.z.so"); #endif - void *AceAbilityLib = nullptr; APPSPAWN_LOGI("MainThread::LoadAbilityLibrary. Start calling dlopen acelibdir."); #ifndef APPSPAWN_TEST + void *AceAbilityLib = NULL; AceAbilityLib = dlopen(acelibdir, RTLD_NOW | RTLD_GLOBAL); + APPSPAWN_CHECK(AceAbilityLib != NULL, return, "Fail to dlopen %s, [%s]", acelibdir, dlerror()); #endif - if (AceAbilityLib == nullptr) { - APPSPAWN_LOGE("Fail to dlopen %s, [%s]", acelibdir, dlerror()); - } else { - APPSPAWN_LOGI("Success to dlopen %s", acelibdir); - } - APPSPAWN_LOGI("MainThread::LoadAbilityLibrary. End calling dlopen."); + APPSPAWN_LOGI("Success to dlopen %s", acelibdir); + APPSPAWN_LOGI("MainThread::LoadAbilityLibrary. End calling dlopen"); } void RunChildProcessor(AppSpawnContent *content, AppSpawnClient *client) diff --git a/adapter/appspawn_adapter.cpp b/adapter/appspawn_adapter.cpp index 74a6e0d6c2d243a4d5589b9fc62b7f476853bb50..a7da57d74924de50e799e32dbd427e34431bf6b0 100644 --- a/adapter/appspawn_adapter.cpp +++ b/adapter/appspawn_adapter.cpp @@ -17,6 +17,7 @@ #include +#include "appspawn_service.h" #include "token_setproc.h" #ifdef WITH_SELINUX #include "hap_restorecon.h" diff --git a/adapter/appspawn_adapter.h b/adapter/appspawn_adapter.h index 9925724dee37c00c12748c39d31ff000278d3bda..bf0928d4a9f03db36d5cb544a8126362f81d3119 100644 --- a/adapter/appspawn_adapter.h +++ b/adapter/appspawn_adapter.h @@ -16,7 +16,7 @@ #ifndef APPSPAWN_ADPATER_CPP #define APPSPAWN_ADPATER_CPP -#include "appspawn_service.h" +#include "appspawn_server.h" #include diff --git a/adapter/appspawn_nweb.cpp b/adapter/appspawn_nweb.cpp index c76354eed88958382b2937a067fca9d49336579e..21c1db963ddc2680adab79cc5429ac84f71baa95 100644 --- a/adapter/appspawn_nweb.cpp +++ b/adapter/appspawn_nweb.cpp @@ -21,6 +21,8 @@ #include #include +#include "appspawn_service.h" + struct RenderProcessNode { RenderProcessNode(time_t now, int exit):recordTime_(now), exitStatus_(exit) {} time_t recordTime_; diff --git a/adapter/appspawn_sandbox.cpp b/adapter/appspawn_sandbox.cpp index 70e6e9c6f31ab64c35def43fedb8986c7329ab77..4d85200034e231c10f4c671c77006af7a48493ff 100644 --- a/adapter/appspawn_sandbox.cpp +++ b/adapter/appspawn_sandbox.cpp @@ -27,6 +27,7 @@ #include #include +#include "appspawn_service.h" #include "json_utils.h" #include "sandbox_utils.h" #include "hilog/log.h" @@ -35,7 +36,6 @@ using namespace std; using namespace OHOS; using namespace OHOS::HiviewDFX; using namespace OHOS::AppSpawn; -static constexpr HiLogLabel LABEL = {LOG_CORE, 0, "AppSpawn_SandboxUtil"}; bool g_isPrivAppSandboxCreated = false; bool g_isAppSandboxCreated = false; @@ -53,24 +53,18 @@ void LoadAppSandboxConfig(void) { // load sandbox config nlohmann::json appSandboxConfig; - bool rc = JsonUtils::GetJsonObjFromJson(appSandboxConfig, APP_JSON_CONFIG); - if (!rc) { - HiLog::Error(LABEL, "AppSpawnServer::Failed to load app private sandbox config"); - } + APPSPAWN_CHECK_ONLY_LOG(rc, "AppSpawnServer::Failed to load app private sandbox config"); SandboxUtils::StoreJsonConfig(appSandboxConfig); rc = JsonUtils::GetJsonObjFromJson(appSandboxConfig, PRODUCT_JSON_CONFIG); - if (!rc) { - HiLog::Error(LABEL, "AppSpawnServer::Failed to load app product sandbox config"); - } + APPSPAWN_CHECK_ONLY_LOG(rc, "AppSpawnServer::Failed to load app product sandbox config"); SandboxUtils::StoreProductJsonConfig(appSandboxConfig); } int32_t SetAppSandboxProperty(struct AppSpawnContent_ *content, AppSpawnClient *client) { APPSPAWN_CHECK(client != NULL, return -1, "Invalid appspwn client"); - AppSpawnClientExt *appProperty = (AppSpawnClientExt *)client; return SandboxUtils::SetAppSandboxProperty(&appProperty->property); } diff --git a/bundle.json b/bundle.json index db9a6a01db841cad1e934d676dade64564399d9f..939b35815a5228155b1ce97f0093ca7ea26e1f78 100644 --- a/bundle.json +++ b/bundle.json @@ -59,7 +59,7 @@ ], "test": [ "//base/startup/appspawn/test:moduletest", - "//base/startup/appspawn/test:unittest" + "//base/startup/appspawn/test/unittest:unittest" ] } } diff --git a/common/appspawn_server.c b/common/appspawn_server.c index 04f3b0bb449ad8618e70937bd031c58979591edd..726f7f26b1456e28d44a8b5e8336c2a6977d9d9b 100644 --- a/common/appspawn_server.c +++ b/common/appspawn_server.c @@ -93,13 +93,8 @@ int DoStartApp(struct AppSpawnContent_ *content, AppSpawnClient *client, char *l return 0; } -int AppSpawnProcessMsg(struct AppSpawnContent_ *content, AppSpawnClient *client, pid_t *childPid) +int ForkChildProc(struct AppSpawnContent_ *content, AppSpawnClient *client, pid_t pid) { - APPSPAWN_CHECK(content != NULL, return -1, "Invalid content for appspawn"); - APPSPAWN_CHECK(client != NULL && childPid != NULL, return -1, "Invalid client for appspawn"); - APPSPAWN_LOGI("AppSpawnProcessMsg id %d 0x%x", client->id, client->flags); - - pid_t pid = fork(); if (pid < 0) { return -errno; } else if (pid == 0) { @@ -120,7 +115,9 @@ int AppSpawnProcessMsg(struct AppSpawnContent_ *content, AppSpawnClient *client, int ret = -1; if (client->flags & APP_COLD_START) { if (content->coldStartApp != NULL && content->coldStartApp(content, client) == 0) { +#ifndef APPSPAWN_TEST _exit(0x7f); // 0x7f user exit +#endif return -1; } else { ret = DoStartApp(content, client, content->longProcName, content->longProcNameLen); @@ -142,6 +139,18 @@ int AppSpawnProcessMsg(struct AppSpawnContent_ *content, AppSpawnClient *client, } ProcessExit(); } + return 0; +} + +int AppSpawnProcessMsg(struct AppSpawnContent_ *content, AppSpawnClient *client, pid_t *childPid) +{ + APPSPAWN_CHECK(content != NULL, return -1, "Invalid content for appspawn"); + APPSPAWN_CHECK(client != NULL && childPid != NULL, return -1, "Invalid client for appspawn"); + APPSPAWN_LOGI("AppSpawnProcessMsg id %d 0x%x", client->id, client->flags); + + pid_t pid = fork(); + int ret = ForkChildProc(content, client, pid); + APPSPAWN_CHECK(ret == 0, return ret, "fork child process error: %d", ret); *childPid = pid; return 0; } diff --git a/common/appspawn_server.h b/common/appspawn_server.h index c344470d65b25e60ca855701a046b557fd8f8237..f91bc28fb49a6f0e51d013c1262e435cf62eec32 100644 --- a/common/appspawn_server.h +++ b/common/appspawn_server.h @@ -72,6 +72,7 @@ typedef struct AppSpawnContent_ { AppSpawnContent *AppSpawnCreateContent(const char *socketName, char *longProcName, uint32_t longProcNameLen, int cold); int AppSpawnProcessMsg(struct AppSpawnContent_ *content, AppSpawnClient *client, pid_t *childPid); int DoStartApp(struct AppSpawnContent_ *content, AppSpawnClient *client, char *longProcName, uint32_t longProcNameLen); +int ForkChildProc(struct AppSpawnContent_ *content, AppSpawnClient *client, pid_t pid); #ifdef OHOS_DEBUG void GetCurTime(struct timespec* tmCur); @@ -109,6 +110,11 @@ void AppspawnLogPrint(AppspawnLogLevel logLevel, const char *file, int line, con exper; \ } +#define APPSPAWN_CHECK_ONLY_LOG(retCode, ...) \ + if (!(retCode)) { \ + APPSPAWN_LOGE(__VA_ARGS__); \ + } + #ifdef __cplusplus } #endif diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn index a8a9000668d5bd434fe203e80bb803813c9ea21e..4df8333cb4ee31e9fcabb40a55391f749974de47 100644 --- a/interfaces/innerkits/BUILD.gn +++ b/interfaces/innerkits/BUILD.gn @@ -24,9 +24,16 @@ ohos_static_library("appspawn_socket_client") { "client/appspawn_socket.cpp", "client/client_socket.cpp", ] - include_dirs = [ "include" ] + include_dirs = [ + "include", + "//base/startup/appspawn/common", + ] + public_configs = [ ":exported_header_files" ] - deps = [ "//utils/native/base:utils" ] + deps = [ + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", + "//utils/native/base:utils", + ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] subsystem_name = "${subsystem_name}" diff --git a/interfaces/innerkits/client/appspawn_socket.cpp b/interfaces/innerkits/client/appspawn_socket.cpp index b1521f0b11227c2a67f8605773de897bd80c367e..9574a2d6901641eec5ca1ee92640ab0ef824c1f1 100644 --- a/interfaces/innerkits/client/appspawn_socket.cpp +++ b/interfaces/innerkits/client/appspawn_socket.cpp @@ -19,6 +19,7 @@ #include #include +#include "appspawn_server.h" #include "hilog/log.h" #include "pubdef.h" #include "securec.h" @@ -26,7 +27,6 @@ namespace OHOS { namespace AppSpawn { using namespace OHOS::HiviewDFX; -static constexpr HiLogLabel LABEL = {LOG_CORE, 0, "AppSpawnSocket"}; AppSpawnSocket::AppSpawnSocket(const std::string &name) { @@ -48,15 +48,10 @@ int AppSpawnSocket::GetSocketFd() const int AppSpawnSocket::PackSocketAddr() { - if (socketName_.empty()) { - HiLog::Error(LABEL, "Invalid socket name: empty"); - return -EINVAL; - } + APPSPAWN_CHECK(!socketName_.empty(), return -EINVAL, "Invalid socket name: empty"); - if (memset_s(&socketAddr_, sizeof(socketAddr_), 0, sizeof(socketAddr_)) != EOK) { - HiLog::Error(LABEL, "Failed to memset socket addr"); - return -1; - } + APPSPAWN_CHECK(memset_s(&socketAddr_, sizeof(socketAddr_), 0, sizeof(socketAddr_)) == EOK, + return -1, "Failed to memset socket addr"); socklen_t pathLen = 0; if (socketName_[0] == '/') { @@ -66,7 +61,7 @@ int AppSpawnSocket::PackSocketAddr() } socklen_t pathSize = sizeof(socketAddr_.sun_path); if (pathLen >= pathSize) { - HiLog::Error(LABEL, "Invalid socket name: '%{public}s' too long", socketName_.c_str()); + APPSPAWN_LOGE("Invalid socket name: '%s' too long", socketName_.c_str()); return -1; } @@ -77,10 +72,7 @@ int AppSpawnSocket::PackSocketAddr() len = snprintf_s(socketAddr_.sun_path, pathSize, (pathSize - 1), "%s%s", socketDir_.c_str(), socketName_.c_str()); } - if (static_cast(pathLen) != len) { - HiLog::Error(LABEL, "Failed to copy socket path"); - return -1; - } + APPSPAWN_CHECK(static_cast(pathLen) == len, return -1, "Failed to copy socket path"); socketAddr_.sun_family = AF_LOCAL; socketAddrLen_ = offsetof(struct sockaddr_un, sun_path) + pathLen + 1; @@ -91,19 +83,16 @@ int AppSpawnSocket::PackSocketAddr() int AppSpawnSocket::CreateSocket() { int socketFd = socket(AF_UNIX, SOCK_STREAM, 0); // SOCK_SEQPACKET - if (socketFd < 0) { - HiLog::Error(LABEL, "Failed to create socket: %{public}d", errno); - return (-errno); - } + APPSPAWN_CHECK(socketFd >= 0, return -errno, "Failed to create socket: %d", errno); - HiLog::Debug(LABEL, "Created socket with fd %{public}d", socketFd); + APPSPAWN_LOGV("Created socket with fd %d", socketFd); return socketFd; } void AppSpawnSocket::CloseSocket(int &socketFd) { if (socketFd >= 0) { - HiLog::Debug(LABEL, "Closed socket with fd %{public}d", socketFd); + APPSPAWN_LOGV("Closed socket with fd %d", socketFd); close(socketFd); socketFd = -1; } @@ -112,20 +101,15 @@ void AppSpawnSocket::CloseSocket(int &socketFd) int AppSpawnSocket::ReadSocketMessage(int socketFd, void *buf, int len) { if (socketFd < 0 || len <= 0 || buf == nullptr) { - HiLog::Error(LABEL, "Invalid args: socket %{public}d, len %{public}d, buf might be nullptr", socketFd, len); + APPSPAWN_LOGE("Invalid args: socket %d, len %d, buf might be nullptr", socketFd, len); return -1; } - if (memset_s(buf, len, 0, len) != EOK) { - HiLog::Warn(LABEL, "Failed to memset read buf"); - return -1; - } + APPSPAWN_CHECK(memset_s(buf, len, 0, len) == EOK, return -1, "Failed to memset read buf"); ssize_t rLen = TEMP_FAILURE_RETRY(read(socketFd, buf, len)); - if (rLen < 0) { - HiLog::Error(LABEL, "Read message from fd %{public}d error %{public}zd: %{public}d", socketFd, rLen, errno); - return -EFAULT; - } + APPSPAWN_CHECK(rLen >= 0, return -EFAULT, "Read message from fd %d error %zd: %d", + socketFd, rLen, errno); return rLen; } @@ -133,7 +117,7 @@ int AppSpawnSocket::ReadSocketMessage(int socketFd, void *buf, int len) int AppSpawnSocket::WriteSocketMessage(int socketFd, const void *buf, int len) { if (socketFd < 0 || len <= 0 || buf == nullptr) { - HiLog::Error(LABEL, "Invalid args: socket %{public}d, len %{public}d, buf might be nullptr", socketFd, len); + APPSPAWN_LOGE("Invalid args: socket %d, len %d, buf might be nullptr", socketFd, len); return -1; } @@ -142,12 +126,10 @@ int AppSpawnSocket::WriteSocketMessage(int socketFd, const void *buf, int len) const uint8_t *offset = reinterpret_cast(buf); for (ssize_t wLen = 0; remain > 0; offset += wLen, remain -= wLen, written += wLen) { wLen = write(socketFd, offset, remain); - HiLog::Debug(LABEL, "socket fd %{public}d, wLen %zd", socketFd, wLen); - if ((wLen <= 0) && (errno != EINTR)) { - HiLog::Error(LABEL, "Failed to write message to fd %{public}d, error %zd: %{public}d", - socketFd, wLen, errno); - return (-errno); - } + APPSPAWN_LOGV("socket fd %d, wLen %zd", socketFd, wLen); + bool isRet = (wLen <= 0) && (errno != EINTR); + APPSPAWN_CHECK(!isRet, return -errno, "Failed to write message to fd %d, error %zd: %d", + socketFd, wLen, errno); } return written; diff --git a/interfaces/innerkits/client/client_socket.cpp b/interfaces/innerkits/client/client_socket.cpp index 12bea8e12939d841c1041fa4cf23816e9ea68332..d6c9da19a6a122c44e2205d6431e933fc0ce8262 100644 --- a/interfaces/innerkits/client/client_socket.cpp +++ b/interfaces/innerkits/client/client_socket.cpp @@ -19,13 +19,13 @@ #include #include +#include "appspawn_server.h" #include "hilog/log.h" #include "securec.h" namespace OHOS { namespace AppSpawn { using namespace OHOS::HiviewDFX; -static constexpr HiLogLabel LABEL = {LOG_CORE, 0, "ClientSocket"}; ClientSocket::ClientSocket(const std::string &client) : AppSpawnSocket(client) {} @@ -34,20 +34,17 @@ int ClientSocket::CreateClient() { if (socketFd_ < 0) { socketFd_ = CreateSocket(); - if (socketFd_ < 0) { - HiLog::Error(LABEL, "Client: Create socket failed"); - return socketFd_; - } + APPSPAWN_CHECK(socketFd_ >= 0, return socketFd_, "Client: Create socket failed"); } - HiLog::Debug(LABEL, "Client: CreateClient socket fd %{public}d", socketFd_); + APPSPAWN_LOGE("Client: CreateClient socket fd %d", socketFd_); return 0; } void ClientSocket::CloseClient() { if (socketFd_ < 0) { - HiLog::Error(LABEL, "Client: Invalid connectFd %{public}d", socketFd_); + APPSPAWN_LOGE("Client: Invalid connectFd %d", socketFd_); return; } @@ -58,27 +55,22 @@ void ClientSocket::CloseClient() int ClientSocket::ConnectSocket(int connectFd) { if (connectFd < 0) { - HiLog::Error(LABEL, "Client: Invalid socket fd: %{public}d", connectFd); + APPSPAWN_LOGE("Client: Invalid socket fd: %d", connectFd); return -1; } - if (PackSocketAddr() != 0) { - return -1; - } + APPSPAWN_CHECK(PackSocketAddr() == 0, return -1, "pack socket failed"); - if ((setsockopt(connectFd, SOL_SOCKET, SO_RCVTIMEO, &SOCKET_TIMEOUT, sizeof(SOCKET_TIMEOUT)) != 0) || - (setsockopt(connectFd, SOL_SOCKET, SO_SNDTIMEO, &SOCKET_TIMEOUT, sizeof(SOCKET_TIMEOUT)) != 0)) { - HiLog::Warn(LABEL, "Client: Failed to set opt of socket %{public}d, err %{public}d", connectFd, errno); - return -1; - } + bool isRet = (setsockopt(connectFd, SOL_SOCKET, SO_RCVTIMEO, &SOCKET_TIMEOUT, sizeof(SOCKET_TIMEOUT)) != 0) || + (setsockopt(connectFd, SOL_SOCKET, SO_SNDTIMEO, &SOCKET_TIMEOUT, sizeof(SOCKET_TIMEOUT)) != 0); + APPSPAWN_CHECK(!isRet, return (-1), "Client: Failed to set opt of socket %d, err %d", connectFd, errno); if (connect(connectFd, reinterpret_cast(&socketAddr_), socketAddrLen_) < 0) { - HiLog::Warn(LABEL, "Client: Connect on socket fd %{public}d, failed: %{public}d", connectFd, errno); + APPSPAWN_LOGW("Client: Connect on socket fd %d, failed: %d", connectFd, errno); return -1; } - HiLog::Debug(LABEL, "Client: Connected on socket fd %{public}d, name '%{public}s'", - connectFd, socketAddr_.sun_path); + APPSPAWN_LOGV("Client: Connected on socket fd %d, name '%s'", connectFd, socketAddr_.sun_path); return 0; } diff --git a/lite/appspawn_message.h b/lite/appspawn_message.h index e7a1ab2ee657692ba58914bcec525ddc0a95e8e6..718a44533523db237347f80a77b5368a46f7a180 100644 --- a/lite/appspawn_message.h +++ b/lite/appspawn_message.h @@ -54,4 +54,4 @@ void FreeMessageSt(MessageSt *targetSt); #endif #endif -#endif // BASE_STARTUP_APPSPAWN_SERVICE_H +#endif // BASE_STARTUP_APPSPAWN_MESSAGE_H diff --git a/lite/appspawn_process.c b/lite/appspawn_process.c index c0206f311272bfaaab9ed86e38b0a2b0727ae19f..bf562f732c9b91bb709ecf183e72bef671e31935 100644 --- a/lite/appspawn_process.c +++ b/lite/appspawn_process.c @@ -143,12 +143,14 @@ static int SetCapabilities(struct AppSpawnContent_ *content, AppSpawnClient *cli return -1; } +#ifndef APPSPAWN_TEST unsigned int tmpCaps[] = {17}; // 17 means CAP_SYS_RAWIO unsigned int tmpsCapCnt = sizeof(tmpCaps) / sizeof(tmpCaps[0]); if (SetCapability(tmpsCapCnt, tmpCaps) != 0) { APPSPAWN_LOGE("[appspawn] setrlimit failed, err: %d.", errno); return -1; } +#endif #else if (SetCapability(appProperty->message.capsCnt, appProperty->message.caps) != 0) { APPSPAWN_LOGE("[appspawn] SetCapability failed, err: %d.", errno); diff --git a/interfaces/innerkits/include/appspawn_service.h b/lite/appspawn_service.h old mode 100644 new mode 100755 similarity index 87% rename from interfaces/innerkits/include/appspawn_service.h rename to lite/appspawn_service.h index 16068f38ceb8dde68025b42dac3064e8d296d804..ee8914fa9f846503bf423f3ac7d6712b7e927a8e --- a/interfaces/innerkits/include/appspawn_service.h +++ b/lite/appspawn_service.h @@ -1,37 +1,37 @@ -/* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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 BASE_STARTUP_APPSPAWN_SERVICE_H -#define BASE_STARTUP_APPSPAWN_SERVICE_H - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif /* __cplusplus */ -#endif /* __cplusplus */ - -#define APPSPAWN_SERVICE_NAME "appspawn" - -enum APPSPAWN_FUNCID { - ID_CALL_CREATE_SERVICE = 0, - ID_CALL_BUT -}; - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif - -#endif // BASE_STARTUP_APPSPAWN_SERVICE_H \ No newline at end of file +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef BASE_STARTUP_APPSPAWN_SERVICE_H +#define BASE_STARTUP_APPSPAWN_SERVICE_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ +#endif /* __cplusplus */ + +#define APPSPAWN_SERVICE_NAME "appspawn" + +enum APPSPAWN_FUNCID { + ID_CALL_CREATE_SERVICE = 0, + ID_CALL_BUT +}; + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif + +#endif // BASE_STARTUP_APPSPAWN_SERVICE_H diff --git a/standard/appspawn_process.c b/standard/appspawn_process.c index 38227397a587dd0b54ce3bbee3e95fcc9af1fe09..b6834ddd6d143c897e0546e88d34afa0777c79c6 100644 --- a/standard/appspawn_process.c +++ b/standard/appspawn_process.c @@ -40,18 +40,14 @@ static int SetProcessName(struct AppSpawnContent_ *content, AppSpawnClient *clie AppSpawnClientExt *appPropertyExt = (AppSpawnClientExt *)client; AppParameter *appProperty = &appPropertyExt->property; int len = strlen(appProperty->processName); - if (longProcName == NULL || len <= 0) { - APPSPAWN_LOGE("process name is nullptr or length error"); - return -EINVAL; - } + bool isRet = longProcName == NULL || len <= 0; + APPSPAWN_CHECK(!isRet, return -EINVAL, "process name is nullptr or length error"); char shortName[MAX_LEN_SHORT_NAME] = {0}; // process short name max length 16 bytes. if (len >= MAX_LEN_SHORT_NAME) { - if (strncpy_s(shortName, MAX_LEN_SHORT_NAME, appProperty->processName, MAX_LEN_SHORT_NAME - 1) != EOK) { - APPSPAWN_LOGE("strncpy_s short name error: %d", errno); - return -EINVAL; - } + isRet = strncpy_s(shortName, MAX_LEN_SHORT_NAME, appProperty->processName, MAX_LEN_SHORT_NAME - 1) != EOK; + APPSPAWN_CHECK(!isRet, return -EINVAL, "strncpy_s short name error: %d", errno); } else { if (strncpy_s(shortName, MAX_LEN_SHORT_NAME, appProperty->processName, len) != EOK) { APPSPAWN_LOGE("strncpy_s short name error: %d", errno); @@ -60,22 +56,17 @@ static int SetProcessName(struct AppSpawnContent_ *content, AppSpawnClient *clie } // set short name - if (prctl(PR_SET_NAME, shortName) == -1) { - APPSPAWN_LOGE("prctl(PR_SET_NAME) error: %d", errno); - return (-errno); - } + isRet = prctl(PR_SET_NAME, shortName) == -1; + APPSPAWN_CHECK(!isRet, return -errno, "prctl(PR_SET_NAME) error: %d", errno); // reset longProcName - if (memset_s(longProcName, (size_t)longProcNameLen, 0, (size_t)longProcNameLen) != EOK) { - APPSPAWN_LOGE("Failed to memset long process name"); - return -EINVAL; - } + isRet = memset_s(longProcName, (size_t)longProcNameLen, 0, (size_t)longProcNameLen) != EOK; + APPSPAWN_CHECK(!isRet, return -EINVAL, "Failed to memset long process name"); // set long process name - if (strncpy_s(longProcName, sizeof(appProperty->processName) - 1, appProperty->processName, len) != EOK) { - APPSPAWN_LOGE("strncpy_s long name error: %d longProcNameLen %u", errno, longProcNameLen); - return -EINVAL; - } + isRet = strncpy_s(longProcName, sizeof(appProperty->processName) - 1, appProperty->processName, len) != EOK; + APPSPAWN_CHECK(!isRet, return -EINVAL, "strncpy_s long name error: %d longProcNameLen %u", errno, longProcNameLen); + return 0; } @@ -84,10 +75,8 @@ static int SetKeepCapabilities(struct AppSpawnContent_ *content, AppSpawnClient AppSpawnClientExt *appProperty = (AppSpawnClientExt *)client; // set keep capabilities when user not root. if (appProperty->property.uid != 0) { - if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) { - APPSPAWN_LOGE("set keepcaps failed: %d", errno); - return (-errno); - } + bool isRet = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1; + APPSPAWN_CHECK(!isRet, return -errno, "set keepcaps failed: %d", errno); } return 0; } @@ -97,18 +86,15 @@ static int SetCapabilities(struct AppSpawnContent_ *content, AppSpawnClient *cli // init cap struct __user_cap_header_struct cap_header; - if (memset_s(&cap_header, sizeof(cap_header), 0, sizeof(cap_header)) != EOK) { - APPSPAWN_LOGE("Failed to memset cap header"); - return -EINVAL; - } + bool isRet = memset_s(&cap_header, sizeof(cap_header), 0, sizeof(cap_header)) != EOK; + APPSPAWN_CHECK(!isRet, return -EINVAL, "Failed to memset cap header"); + cap_header.version = _LINUX_CAPABILITY_VERSION_3; cap_header.pid = 0; struct __user_cap_data_struct cap_data[2]; - if (memset_s(&cap_data, sizeof(cap_data), 0, sizeof(cap_data)) != EOK) { - APPSPAWN_LOGE("Failed to memset cap data"); - return -EINVAL; - } + isRet = memset_s(&cap_data, sizeof(cap_data), 0, sizeof(cap_data)) != EOK; + APPSPAWN_CHECK(!isRet, return -EINVAL, "Failed to memset cap data"); // init inheritable permitted effective zero #ifdef GRAPHIC_PERMISSION_CHECK @@ -129,51 +115,47 @@ static int SetCapabilities(struct AppSpawnContent_ *content, AppSpawnClient *cli cap_data[1].effective = (__u32)(effective >> BITLEN32); // set capabilities - if (capset(&cap_header, &cap_data[0]) == -1) { - APPSPAWN_LOGE("capset failed: %d", errno); - return (-errno); - } + isRet = capset(&cap_header, &cap_data[0]) == -1; + APPSPAWN_CHECK(!isRet, return -errno, "capset failed: %d", errno); return 0; } static void InitDebugParams(struct AppSpawnContent_ *content, AppSpawnClient *client) { +#ifndef APPSPAWN_TEST AppSpawnClientExt *appProperty = (AppSpawnClientExt *)client; #ifdef __aarch64__ const char *debugSoPath = "/system/lib64/libhidebug.so"; #else const char *debugSoPath = "/system/lib/libhidebug.so"; #endif - if (access(debugSoPath, F_OK) != 0) { - return; - } + bool isRet = access(debugSoPath, F_OK) != 0; + APPSPAWN_CHECK(!isRet, return, "access failed, errno = %d", errno); + void *handle = dlopen(debugSoPath, RTLD_LAZY); - if (handle == NULL) { - APPSPAWN_LOGE("Failed to dlopen libhidebug.so, %s", dlerror()); - return; - } + APPSPAWN_CHECK(handle != NULL, return, "Failed to dlopen libhidebug.so, %s", dlerror()); + bool (*initParam)(const char *name); initParam = (bool (*)(const char *name))dlsym(handle, "InitEnvironmentParam"); - if (initParam == NULL) { - APPSPAWN_LOGE("Failed to dlsym InitEnvironmentParam, %s", dlerror()); - dlclose(handle); - return; - } + APPSPAWN_CHECK(initParam != NULL, dlclose(handle); return, "Failed to dlsym InitEnvironmentParam, %s", dlerror()); (*initParam)(appProperty->property.processName); dlclose(handle); +#endif } static void ClearEnvironment(AppSpawnContent *content, AppSpawnClient *client) { APPSPAWN_LOGI("ClearEnvironment id %d", client->id); - AppSpawnClientExt *appProperty = (AppSpawnClientExt *)client; sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); sigaddset(&mask, SIGTERM); sigprocmask(SIG_UNBLOCK, &mask, NULL); // close child fd +#ifndef APPSPAWN_TEST + AppSpawnClientExt *appProperty = (AppSpawnClientExt *)client; close(appProperty->fd[0]); +#endif InitDebugParams(content, client); return; } @@ -183,22 +165,16 @@ static int SetUidGid(struct AppSpawnContent_ *content, AppSpawnClient *client) #ifdef GRAPHIC_PERMISSION_CHECK AppSpawnClientExt *appProperty = (AppSpawnClientExt *)client; // set gids - if (setgroups(appProperty->property.gidCount, (const gid_t *)(&appProperty->property.gidTable[0])) == -1) { - APPSPAWN_LOGE("setgroups failed: %d, gids.size=%u", errno, appProperty->property.gidCount); - return (-errno); - } + bool isRet = setgroups(appProperty->property.gidCount, (const gid_t *)(&appProperty->property.gidTable[0])) == -1; + APPSPAWN_CHECK(!isRet, return -errno, "setgroups failed: %d, gids.size=%u", errno, appProperty->property.gidCount); // set gid - if (setresgid(appProperty->property.gid, appProperty->property.gid, appProperty->property.gid) == -1) { - APPSPAWN_LOGE("setgid(%u) failed: %d", appProperty->property.gid, errno); - return (-errno); - } + isRet = setresgid(appProperty->property.gid, appProperty->property.gid, appProperty->property.gid) == -1; + APPSPAWN_CHECK(!isRet, return -errno, "setgid(%u) failed: %d", appProperty->property.gid, errno); // If the effective user ID is changed from 0 to nonzero, then all capabilities are cleared from the effective set - if (setresuid(appProperty->property.uid, appProperty->property.uid, appProperty->property.uid) == -1) { - APPSPAWN_LOGE("setuid(%u) failed: %d", appProperty->property.uid, errno); - return (-errno); - } + isRet = setresuid(appProperty->property.uid, appProperty->property.uid, appProperty->property.uid) == -1; + APPSPAWN_CHECK(!isRet, return -errno, "setuid(%u) failed: %d", appProperty->property.uid, errno); #endif return 0; } diff --git a/standard/appspawn_service.c b/standard/appspawn_service.c index 570d3d9a82aef926a3a5375acbe22fd9ccb509be..2053379706cdf473df3e079bb757c3d7d20239ac 100644 --- a/standard/appspawn_service.c +++ b/standard/appspawn_service.c @@ -39,22 +39,26 @@ static AppSpawnContentExt *g_appSpawnContent = NULL; +#ifdef APPSPAWN_TEST +static const int TV_SEC = 1; +#else static const int TV_SEC = 60; +#endif -static int AppInfoHashNodeCompare(const HashNode *node1, const HashNode *node2) +APPSPAWN_STATIC int AppInfoHashNodeCompare(const HashNode *node1, const HashNode *node2) { AppInfo *testNode1 = HASHMAP_ENTRY(node1, AppInfo, node); AppInfo *testNode2 = HASHMAP_ENTRY(node2, AppInfo, node); return testNode1->pid - testNode2->pid; } -static int TestHashKeyCompare(const HashNode *node1, const void *key) +APPSPAWN_STATIC int TestHashKeyCompare(const HashNode *node1, const void *key) { AppInfo *testNode1 = HASHMAP_ENTRY(node1, AppInfo, node); return testNode1->pid - *(pid_t *)key; } -static int AppInfoHashNodeFunction(const HashNode *node) +APPSPAWN_STATIC int AppInfoHashNodeFunction(const HashNode *node) { AppInfo *testNode = HASHMAP_ENTRY(node, AppInfo, node); if (testNode == NULL) { @@ -63,20 +67,20 @@ static int AppInfoHashNodeFunction(const HashNode *node) return testNode->pid % APP_HASH_BUTT; } -static int AppInfoHashKeyFunction(const void *key) +APPSPAWN_STATIC int AppInfoHashKeyFunction(const void *key) { pid_t code = *(pid_t *)key; return code % APP_HASH_BUTT; } -static void AppInfoHashNodeFree(const HashNode *node) +APPSPAWN_STATIC void AppInfoHashNodeFree(const HashNode *node) { AppInfo *testNode = HASHMAP_ENTRY(node, AppInfo, node); APPSPAWN_LOGI("AppInfoHashNodeFree %s\n", testNode->name); free(testNode); } -static void AddAppInfo(pid_t pid, const char *processName) +APPSPAWN_STATIC void AddAppInfo(pid_t pid, const char *processName) { size_t len = strlen(processName) + 1; AppInfo *node = (AppInfo *)malloc(sizeof(AppInfo) + len + 1); @@ -99,7 +103,7 @@ static void ProcessTimer(const TimerHandle taskHandle, void *context) LE_StopLoop(LE_GetDefaultLoop()); } -static void RemoveAppInfo(pid_t pid) +APPSPAWN_STATIC void RemoveAppInfo(pid_t pid) { HashNode *node = HashMapGet(g_appSpawnContent->appMap, (const void *)&pid); APPSPAWN_CHECK(node != NULL, return, "Invalid node %d", pid); @@ -169,7 +173,7 @@ static void PrintProcessExitInfo(pid_t pid, uid_t uid, int status) } #endif -static void SignalHandler(const struct signalfd_siginfo *siginfo) +APPSPAWN_STATIC void SignalHandler(const struct signalfd_siginfo *siginfo) { APPSPAWN_LOGI("SignalHandler signum %d", siginfo->ssi_signo); switch (siginfo->ssi_signo) { @@ -244,7 +248,7 @@ static int WaitChild(int fd, int pid, const AppSpawnClientExt *appProperty) return result; } -static void StartColdApp(AppSpawnClientExt *appProperty) +static void CheckColdAppEnabled(AppSpawnClientExt *appProperty) { if (appProperty == NULL) { return; @@ -299,7 +303,7 @@ static void GetProcessTerminationStatus(AppSpawnClientExt *appProperty) } #endif -static void OnReceiveRequest(const TaskHandle taskHandle, const uint8_t *buffer, uint32_t buffLen) +APPSPAWN_STATIC void OnReceiveRequest(const TaskHandle taskHandle, const uint8_t *buffer, uint32_t buffLen) { APPSPAWN_CHECK(buffer != NULL && buffLen >= sizeof(AppParameter), LE_CloseTask(LE_GetDefaultLoop(), taskHandle); return, "Invalid buffer buffLen %u", buffLen); @@ -326,7 +330,7 @@ static void OnReceiveRequest(const TaskHandle taskHandle, const uint8_t *buffer, g_appSpawnContent->timer = NULL; } - StartColdApp(appProperty); + CheckColdAppEnabled(appProperty); // create pipe for commication from child if (pipe(appProperty->fd) == -1) { APPSPAWN_LOGE("create pipe fail, errno = %d", errno); @@ -355,7 +359,10 @@ static void OnReceiveRequest(const TaskHandle taskHandle, const uint8_t *buffer, } } -static int OnConnection(const LoopHandle loopHandle, const TaskHandle server) +#ifdef APPSPAWN_TEST +TaskHandle g_testClientHandle = NULL; +#endif +APPSPAWN_STATIC int OnConnection(const LoopHandle loopHandle, const TaskHandle server) { static uint32_t clientId = 0; APPSPAWN_LOGI("OnConnection "); @@ -364,6 +371,9 @@ static int OnConnection(const LoopHandle loopHandle, const TaskHandle server) TaskHandle stream; LE_StreamInfo info = {}; info.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_CONNECT; +#ifdef APPSPAWN_TEST + info.baseInfo.flags |= TASK_TEST; +#endif info.baseInfo.close = OnClose; info.baseInfo.userDataSize = sizeof(AppSpawnClientExt); info.disConntectComplete = NULL; @@ -377,6 +387,9 @@ static int OnConnection(const LoopHandle loopHandle, const TaskHandle server) client->client.id = ++clientId; client->client.flags = 0; APPSPAWN_LOGI("OnConnection client fd %d Id %d", LE_GetSocketFd(stream), client->client.id); +#ifdef APPSPAWN_TEST + g_testClientHandle = stream; +#endif return 0; } @@ -400,6 +413,7 @@ static void AppSpawnInit(AppSpawnContent *content) if (content->loadExtendLib) { content->loadExtendLib(content); } + content->notifyResToParent = NotifyResToParent; // set private function SetContentFunction(content); @@ -444,8 +458,9 @@ static void AppSpawnRun(AppSpawnContent *content, int argc, char *const argv[]) if (status != 0) { APPSPAWN_LOGE("Failed to add signal %d", status); } - +#ifndef APPSPAWN_TEST LE_RunLoop(LE_GetDefaultLoop()); +#endif APPSPAWN_LOGI("AppSpawnRun exit "); LE_CloseSignalTask(LE_GetDefaultLoop(), appSpawnContent->sigHandler); // release resource diff --git a/standard/appspawn_service.h b/standard/appspawn_service.h index 3ef432fd6401b1eae6631ec46725f3fb389fe5c8..7a758ec4c0877438e96fddd07f2db5abab89938f 100644 --- a/standard/appspawn_service.h +++ b/standard/appspawn_service.h @@ -25,6 +25,12 @@ extern "C" { #endif +#ifdef APPSPAWN_TEST +#define APPSPAWN_STATIC +#else +#define APPSPAWN_STATIC static +#endif + #define APP_HASH_BUTT 32 #define FLAGS_ON_DEMAND 0x1 #define FLAGS_MODE_COLD 0x2 diff --git a/test/BUILD.gn b/test/BUILD.gn index 2ec39d88d8c57ea09a1de2f0c0fd3bfdd1685eeb..54b6beeaa37a4c4c3d9a2b40964e7bb131e07a27 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -14,59 +14,7 @@ import("//base/startup/appspawn/appspawn.gni") import("//build/test.gni") -group("unittest") { - testonly = true - - deps = [ - "unittest/app_spawn_socket_test:unittest", - "unittest/app_spawn_standard_test:unittest", - "unittest/client_socket_test:unittest", - ] -} - group("moduletest") { testonly = true - deps = [ "moduletest:moduletest" ] } - -config("appspawn_test_config") { - configs = [] - - defines = [ "TEST_EXIT" ] - - include_dirs = [ - "${appspawn_path}/test/mock/include", - "${appspawn_path}/common", - "${appspawn_path}/interfaces/innerkits/include", - "${appspawn_path}/util/include", - ] -} - -ohos_source_set("appspawn_test_source") { - testonly = true - - sources = [] - - include_dirs = [ "//third_party/json/include" ] - - public_configs = [ - "//utils/native/base:utils_config", - ":appspawn_test_config", - ] - - public_deps = [ - "//third_party/googletest:gmock_main", - "//third_party/googletest:gtest_main", - "//utils/native/base:utils", - ] - - deps = [] - - external_deps = [ - "ability_base:want", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "hiviewdfx_hilog_native:libhilog", - ] -} diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..f2d29f6f42e13e45baaf8facf08afe007512cbc9 --- /dev/null +++ b/test/unittest/BUILD.gn @@ -0,0 +1,94 @@ +import("//base/startup/appspawn/appspawn.gni") +import("//build/test.gni") + +config("utest_config") { + cflags = [ + "-fprofile-arcs", + "-ftest-coverage", + "-Wno-implicit-fallthrough", + "-Wno-unused-function", + ] + cflags_cc = [ + "-Wno-implicit-fallthrough", + "-fexceptions", + ] + + ldflags = [ "--coverage" ] + + include_dirs = [ + "${appspawn_path}/test/mock/include", + "${appspawn_path}/common", + "${appspawn_path}/standard", + "${appspawn_path}/adapter", + "${appspawn_path}/interfaces/innerkits/include", + "${appspawn_path}/util/include", + "//utils/native/base/include", + "${aafwk_path}/frameworks/kits/appkit/native/app/include", + "${aafwk_path}/interfaces/innerkits/app_manager/include/appmgr", + "${aafwk_path}/interfaces/innerkits/ability_manager/include", + "${aafwk_path}/frameworks/kits/ability/native/include", + "${aafwk_path}/services/abilitymgr/include", + "//base/global/resource_management/interfaces/inner_api/include", + "//base/security/access_token/interfaces/innerkits/token_setproc/include", + "//base/startup/init_lite/services/log", + "//base/startup/init_lite/services/include", + "//base/startup/init_lite/services/loopevent/include", + "//base/startup/init_lite/interfaces/innerkits/include", + "//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include", + "//third_party/json/include", + ] +} + +ohos_unittest("AppSpawn_ut") { + module_out_path = "${module_output_path}" + + defines = [ + "usleep(time) = MockSleep(time)", + "APPSPAWN_TEST", + ] + + sources = [ + "${appspawn_path}/adapter/appspawn_ace.cpp", + "${appspawn_path}/adapter/appspawn_adapter.cpp", + "${appspawn_path}/adapter/appspawn_sandbox.cpp", + "${appspawn_path}/common/appspawn_server.c", + "${appspawn_path}/interfaces/innerkits/client/appspawn_socket.cpp", + "${appspawn_path}/interfaces/innerkits/client/client_socket.cpp", + "${appspawn_path}/util/src/json_utils.cpp", + "${appspawn_path}/util/src/sandbox_utils.cpp", + "${appspawn_path}/standard/appspawn_process.c", + "${appspawn_path}/standard/appspawn_service.c", + ] + + sources += [ + "${appspawn_path}/test/unittest/app_spawn_socket_test/app_spawn_socket_test.cpp", + "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_standard_test.cpp", + "${appspawn_path}/test/unittest/client_socket_test/client_socket_test.cpp", + ] + + configs = [ "//base/startup/appspawn/test/unittest:utest_config" ] + + deps = [ + "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", + "${aafwk_kits_path}/appkit:appkit_native", + ] + + external_deps = [ + "init:libbegetutil", + "ability_base:want", + "ability_runtime:app_manager", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "utils_base:utils", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":AppSpawn_ut" ] +} diff --git a/test/unittest/app_spawn_lite_test/app_spawn_lite_test.cpp b/test/unittest/app_spawn_lite_test/app_spawn_lite_test.cpp index 72d54c75a49f15d736a1d2bfa22fe5d9dc135200..b1af6cd7b54c27678a5710c45145a0b8f5cde5e4 100644 --- a/test/unittest/app_spawn_lite_test/app_spawn_lite_test.cpp +++ b/test/unittest/app_spawn_lite_test/app_spawn_lite_test.cpp @@ -21,7 +21,6 @@ #include #include "gtest/gtest.h" #include "appspawn_message.h" -#include "appspawn_service.h" #include "appspawn_msg.h" using namespace testing::ext; diff --git a/test/unittest/app_spawn_socket_test/BUILD.gn b/test/unittest/app_spawn_socket_test/BUILD.gn deleted file mode 100644 index fd9e3ccabf5a4bb0309e32c7a3ae28c65399daf1..0000000000000000000000000000000000000000 --- a/test/unittest/app_spawn_socket_test/BUILD.gn +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//base/startup/appspawn/appspawn.gni") -import("//build/test.gni") - -ohos_unittest("AppSpawnSocketTest") { - module_out_path = "${module_output_path}" - - sources = - [ "${appspawn_path}/interfaces/innerkits/client/appspawn_socket.cpp" ] - - sources += [ "app_spawn_socket_test.cpp" ] - - configs = [ "${appspawn_path}:appspawn_config" ] - - deps = [ "${appspawn_path}/test:appspawn_test_source" ] - - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] -} - -group("unittest") { - testonly = true - - deps = [ ":AppSpawnSocketTest" ] -} diff --git a/test/unittest/app_spawn_standard_test/BUILD.gn b/test/unittest/app_spawn_standard_test/BUILD.gn deleted file mode 100644 index 7e612617ab6a26ea689f1c74daaccdf66faac283..0000000000000000000000000000000000000000 --- a/test/unittest/app_spawn_standard_test/BUILD.gn +++ /dev/null @@ -1,60 +0,0 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//base/startup/appspawn/appspawn.gni") -import("//build/test.gni") - -ohos_unittest("AppSpawnStandardTest") { - module_out_path = "${module_output_path}" - - defines = [ - "usleep(time) = MockSleep(time)", - "APPSPAWN_TEST", - ] - - include_dirs = [ - "${appspawn_path}/standard/", - "${appspawn_path}/common/", - ] - - configs = [ "${appspawn_path}:appspawn_config" ] - - sources = [ - "${appspawn_path}/adapter/appspawn_ace.cpp", - "${appspawn_path}/standard/appspawn_process.c", - "${appspawn_path}/standard/appspawn_service.c", - "app_spawn_standard_test.cpp", - ] - - deps = [ - "${aafwk_kits_path}/appkit:appkit_native", - "${appspawn_path}:appspawn_server", - "${appspawn_path}/test:appspawn_test_source", - "//base/startup/init_lite/interfaces/innerkits:libbegetutil", - ] - - external_deps = [ - "ability_base:want", - "ability_runtime:app_manager", - "eventhandler:libeventhandler", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "utils_base:utils", - ] -} - -group("unittest") { - testonly = true - - deps = [ ":AppSpawnStandardTest" ] -} diff --git a/test/unittest/app_spawn_standard_test/app_spawn_standard_test.cpp b/test/unittest/app_spawn_standard_test/app_spawn_standard_test.cpp index b68093b0fe4329782e21dedd435ca913fbb8a4dc..7f8b01e081c3f60956a79c6a7e111016a8f43db9 100644 --- a/test/unittest/app_spawn_standard_test/app_spawn_standard_test.cpp +++ b/test/unittest/app_spawn_standard_test/app_spawn_standard_test.cpp @@ -14,24 +14,93 @@ */ #include #include -#include +#include #include -// redefine private and protected since testcase need to invoke and test private function -#define private public -#define protected public -#include "appspawn_service.h" -#undef private -#undef protected - #include "securec.h" #include "appspawn_adapter.h" #include "appspawn_server.h" +#include "appspawn_service.h" +#include "json_utils.h" +#include "init_hashmap.h" +#include "loop_event.h" using namespace testing; using namespace testing::ext; +using namespace OHOS::AppSpawn; +using nlohmann::json; + +#ifdef __cplusplus + extern "C" { +#endif +int OnConnection(const LoopHandle loopHandle, const TaskHandle server); +int AppInfoHashNodeCompare(const HashNode *node1, const HashNode *node2); +int AppInfoHashNodeFunction(const HashNode *node); +int AppInfoHashKeyFunction(const void *key); +void AppInfoHashNodeFree(const HashNode *node); +int TestHashKeyCompare(const HashNode *node1, const void *key); +void AddAppInfo(pid_t pid, const char *processName); +void RemoveAppInfo(pid_t pid); +void OnReceiveRequest(const TaskHandle taskHandle, const uint8_t *buffer, uint32_t buffLen); +extern TaskHandle g_testClientHandle; +#ifdef __cplusplus + } +#endif namespace OHOS { +/* +static void RunChildProcessor(struct AppSpawnContent_ *content, AppSpawnClient *client) +{} +*/ +static void runAppSpawn(struct AppSpawnContent_ *content, int argc, char *const argv[]) +{} + +static int setAppSandbox(struct AppSpawnContent_ *content, AppSpawnClient *client) +{ + return 0; +} + +static int setKeepCapabilities(struct AppSpawnContent_ *content, AppSpawnClient *client) +{ + return 0; +} + +static int setFileDescriptors(struct AppSpawnContent_ *content, AppSpawnClient *client) +{ + return 0; +} + +static int setProcessName(struct AppSpawnContent_ *content, AppSpawnClient *client, + char *longProcName, uint32_t longProcNameLen) +{ + return 0; +} + +static int setUidGid(struct AppSpawnContent_ *content, AppSpawnClient *client) +{ + return 0; +} + +static int setCapabilities(struct AppSpawnContent_ *content, AppSpawnClient *client) +{ + return 0; +} + +static AppInfo *TestCreateHashNode(const char *value, int pid) +{ + AppInfo *node = (AppInfo *)malloc(sizeof(AppInfo) + strlen(value) + 1); + if (node == nullptr) { + return nullptr; + } + node->pid = pid; + int ret = strcpy_s(node->name, strlen(value) + 1, value); + if (ret != 0) { + free(node); + return nullptr; + } + return node; +} + class AppSpawnStandardTest : public testing::Test { public: static void SetUpTestCase(); @@ -55,25 +124,22 @@ void AppSpawnStandardTest::TearDown() HWTEST(AppSpawnStandardTest, App_Spawn_Standard_001, TestSize.Level0) { GTEST_LOG_(INFO) << "App_Spawn_Standard_001 start"; - string longProcName = "AppSpawnStandardTest1"; + string longProcName = "App_Spawn_Standard_001"; int64_t longProcNameLen = longProcName.length(); - int cold = 1; + int cold = 0; AppSpawnContent *content = AppSpawnCreateContent("AppSpawn", (char*)longProcName.c_str(), longProcNameLen, cold); EXPECT_TRUE(content); content->loadExtendLib = LoadExtendLib; content->runChildProcessor = RunChildProcessor; - - char *const argv[] = {}; content->initAppSpawn(content); - AppSpawnColdRun(content, 1, argv); - + content->runAppSpawn(content, 0, nullptr); GTEST_LOG_(INFO) << "App_Spawn_Standard_001 end"; } HWTEST(AppSpawnStandardTest, App_Spawn_Standard_002, TestSize.Level0) { GTEST_LOG_(INFO) << "App_Spawn_Standard_002 start"; - string longProcName = "AppSpawnStandardTest2"; + string longProcName = "App_Spawn_Standard_002"; int64_t longProcNameLen = longProcName.length(); AppSpawnClientExt* client = (AppSpawnClientExt*)malloc(sizeof(AppSpawnClientExt)); @@ -82,14 +148,16 @@ HWTEST(AppSpawnStandardTest, App_Spawn_Standard_002, TestSize.Level0) if (strcpy_s(client->property.apl, APP_APL_MAX_LEN, "system_basic") != 0) { GTEST_LOG_(INFO) << "strcpy_s failed"; } - pid_t pid = 100; - AppSpawnContentExt* appSpawnContent = (AppSpawnContentExt*)calloc(1, sizeof(AppSpawnContentExt)); + + pid_t pid = 0; + AppSpawnContentExt* appSpawnContent = (AppSpawnContentExt*)malloc(sizeof(AppSpawnContentExt)); EXPECT_TRUE(appSpawnContent); appSpawnContent->content.longProcNameLen = longProcNameLen; appSpawnContent->timer = NULL; appSpawnContent->content.runAppSpawn = NULL; - appSpawnContent->content.initAppSpawn = NULL; + AppSpawnProcessMsg(&appSpawnContent->content, &client->client, &pid); + free(appSpawnContent); free(client); GTEST_LOG_(INFO) << "App_Spawn_Standard_002 end"; @@ -98,87 +166,230 @@ HWTEST(AppSpawnStandardTest, App_Spawn_Standard_002, TestSize.Level0) HWTEST(AppSpawnStandardTest, App_Spawn_Standard_003, TestSize.Level0) { GTEST_LOG_(INFO) << "App_Spawn_Standard_003 start"; - char longProcName[124] = "AppSpawnStandardTest3"; + char longProcName[124] = "App_Spawn_Standard_003"; int64_t longProcNameLen = 124; // 124 is str length - std::unique_ptr clientExt = std::make_unique(); - - clientExt->client.id = 1; - clientExt->client.flags = 0; - clientExt->fd[0] = 123; - clientExt->fd[1] = 456; - clientExt->property.uid = 10002; - clientExt->property.gid = 1000; - clientExt->property.gidCount = 1; - if (strcpy_s(clientExt->property.processName, APP_LEN_PROC_NAME, "com.ohos.settingsdata") != 0) { + AppSpawnClientExt* client = (AppSpawnClientExt*)malloc(sizeof(AppSpawnClientExt)); + client->client.id = 8; + client->client.flags = 0; + client->fd[0] = 100; + client->fd[1] = 200; + client->property.uid = 10000; + client->property.gid = 1000; + client->property.gidCount = 1; + if (strcpy_s(client->property.processName, APP_LEN_PROC_NAME, "xxx.xxx.xxx") != 0) { GTEST_LOG_(INFO) << "strcpy_s failed"; } - if (strcpy_s(clientExt->property.bundleName, APP_LEN_BUNDLE_NAME, "com.ohos.settingsdata") != 0) { + if (strcpy_s(client->property.bundleName, APP_LEN_BUNDLE_NAME, "xxx.xxx.xxx") != 0) { GTEST_LOG_(INFO) << "strcpy_s failed"; } - if (strcpy_s(clientExt->property.soPath, APP_LEN_SO_PATH, "/test") != 0) { + if (strcpy_s(client->property.soPath, APP_LEN_SO_PATH, "xxx") != 0) { GTEST_LOG_(INFO) << "strcpy_s failed"; } - clientExt->property.accessTokenId = 671201800; - if (strcpy_s(clientExt->property.apl, APP_APL_MAX_LEN, "system_core") != 0) { + client->property.accessTokenId = 671201800; + if (strcpy_s(client->property.apl, APP_APL_MAX_LEN, "xxx") != 0) { GTEST_LOG_(INFO) << "strcpy_s failed"; } - if (strcpy_s(clientExt->property.renderCmd, APP_RENDER_CMD_MAX_LEN, "cmd_test") != 0) { + if (strcpy_s(client->property.renderCmd, APP_RENDER_CMD_MAX_LEN, "xxx") != 0) { GTEST_LOG_(INFO) << "strcpy_s failed"; } - clientExt->property.flags = 0; + AppSpawnContent *content = AppSpawnCreateContent("AppSpawn", longProcName, longProcNameLen, 1); content->loadExtendLib = LoadExtendLib; content->runChildProcessor = RunChildProcessor; - SetContentFunction(content); - content->clearEnvironment(content, &clientExt->client); - EXPECT_EQ(content->setProcessName(content, &clientExt->client, longProcName, longProcNameLen), 0); - EXPECT_EQ(content->setKeepCapabilities(content, &clientExt->client), 0); - EXPECT_EQ(content->setUidGid(content, &clientExt->client), 0); - EXPECT_EQ(content->setCapabilities(content, &clientExt->client), 0); - content->setAppSandbox(content, &clientExt->client); - content->setAppAccessToken(content, &clientExt->client); - EXPECT_EQ(content->coldStartApp(content, &clientExt->client), 0); - DoStartApp(content, &clientExt->client, longProcName, longProcNameLen); - free(content); + EXPECT_EQ(ForkChildProc(content, &client->client, 0), 0); + EXPECT_NE(ForkChildProc(content, &client->client, -1), 0); + + content->clearEnvironment(content, &client->client); + EXPECT_EQ(content->setProcessName(content, &client->client, (char *)longProcName, longProcNameLen), 0); + + EXPECT_EQ(content->setKeepCapabilities(content, &client->client), 0); + + EXPECT_EQ(content->setUidGid(content, &client->client), 0); + + EXPECT_EQ(content->setCapabilities(content, &client->client), 0); + + content->setAppSandbox(content, &client->client); + + content->setAppAccessToken(content, &client->client); + + EXPECT_EQ(content->coldStartApp(content, &client->client), 0); + GTEST_LOG_(INFO) << "App_Spawn_Standard_003 end"; } HWTEST(AppSpawnStandardTest, App_Spawn_Standard_004, TestSize.Level0) { GTEST_LOG_(INFO) << "App_Spawn_Standard_004 start"; - AppSpawnClientExt* client = (AppSpawnClientExt*)malloc(sizeof(AppSpawnClientExt)); - client->client.id = 1; - client->client.flags = 0; - client->fd[0] = 1; - client->fd[1] = 2; + client->client.id = 8; + client->client.flags = 1; + client->fd[0] = 100; + client->fd[1] = 200; client->property.uid = 10000; client->property.gid = 1000; client->property.gidCount = 1; - if (strcpy_s(client->property.processName, APP_LEN_PROC_NAME, "test4") != 0) { + if (strcpy_s(client->property.processName, APP_LEN_PROC_NAME, "xxx.xxx.xxx") != 0) { GTEST_LOG_(INFO) << "strcpy_s failed"; } - if (strcpy_s(client->property.bundleName, APP_LEN_BUNDLE_NAME, "test4") != 0) { + if (strcpy_s(client->property.bundleName, APP_LEN_BUNDLE_NAME, "xxx.xxx.xxx") != 0) { GTEST_LOG_(INFO) << "strcpy_s failed"; } - if (strcpy_s(client->property.soPath, APP_LEN_SO_PATH, "test4") != 0) { + if (strcpy_s(client->property.soPath, APP_LEN_SO_PATH, "xxx") != 0) { GTEST_LOG_(INFO) << "strcpy_s failed"; } client->property.accessTokenId = 671201800; - if (strcpy_s(client->property.apl, APP_APL_MAX_LEN, "system_core") != 0) { + if (strcpy_s(client->property.apl, APP_APL_MAX_LEN, "xxx") != 0) { GTEST_LOG_(INFO) << "strcpy_s failed"; } - if (strcpy_s(client->property.renderCmd, APP_RENDER_CMD_MAX_LEN, "test4") != 0) { + if (strcpy_s(client->property.renderCmd, APP_RENDER_CMD_MAX_LEN, "xxx") != 0) { GTEST_LOG_(INFO) << "strcpy_s failed"; } client->property.flags = 0; - char* argv[] = {const_cast("AppSpawnStandardTest4"), const_cast("test4")}; + char* argv[] = {const_cast("xxx"), const_cast("xxx")}; int argc = sizeof(argv)/sizeof(argv[0]); EXPECT_EQ(GetAppSpawnClientFromArg(argc, argv, client), -1); free(client); GTEST_LOG_(INFO) << "App_Spawn_Standard_004 end"; } + +HWTEST(AppSpawnStandardTest, App_Spawn_Standard_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "App_Spawn_Standard_005 start"; + string longProcName = "ohos.samples.ecg.default"; + int64_t longProcNameLen = longProcName.length(); + + AppSpawnClientExt* client = (AppSpawnClientExt*)malloc(sizeof(AppSpawnClientExt)); + client->client.id = 20010013; + client->client.flags = 0; + if (strcpy_s(client->property.apl, APP_APL_MAX_LEN, "system_basic") != 0) { + GTEST_LOG_(INFO) << "strcpy_s failed"; + } + pid_t pid = 100; + AppSpawnContentExt* appSpawnContent = (AppSpawnContentExt*)malloc(sizeof(AppSpawnContentExt)); + EXPECT_TRUE(appSpawnContent); + appSpawnContent->content.longProcNameLen = longProcNameLen; + appSpawnContent->timer = NULL; + appSpawnContent->content.runAppSpawn = runAppSpawn; + AppSpawnProcessMsg(&appSpawnContent->content, &client->client, &pid); + free(appSpawnContent); + free(client); + GTEST_LOG_(INFO) << "App_Spawn_Standard_005 end"; +} + +HWTEST(AppSpawnStandardTest, App_Spawn_Standard_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "App_Spawn_Standard_006 start"; + string longProcName = "App_Spawn_Standard_006"; + int64_t longProcNameLen = longProcName.length(); + int cold = 1; + AppSpawnContent *content = AppSpawnCreateContent("AppSpawn", (char*)longProcName.c_str(), longProcNameLen, cold); + EXPECT_TRUE(content); + content->loadExtendLib = LoadExtendLib; + content->runChildProcessor = RunChildProcessor; + + content->runChildProcessor(content, nullptr); + char tmp0[] = "/system/bin/appspawn"; + char tmp1[] = "cold-start"; + char tmp2[] = "1"; + char tmp3[] = "1:1:1:1:0:ohos.samples.ecg.default:ohos.samples.ecg:default:671201800:system_core:default"; + char * const argv[] = {tmp0, tmp1, tmp2, tmp3}; + + AppSpawnColdRun(content, 4, argv); + GTEST_LOG_(INFO) << "App_Spawn_Standard_006 end"; +} + +/* +HWTEST(AppSpawnStandardTest, App_Spawn_Standard_007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "App_Spawn_Standard_007 start"; + RunChildProcessor(nullptr, nullptr); + GTEST_LOG_(INFO) << "App_Spawn_Standard_007 end"; +} +*/ +HWTEST(AppSpawnStandardTest, App_Spawn_Standard_008, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "App_Spawn_Standard_008 start"; + string longProcName = "ohos.samples.ecg.default"; + int64_t longProcNameLen = longProcName.length(); + std::unique_ptr clientExt = std::make_unique(); + AppSpawnContent *content = AppSpawnCreateContent("AppSpawn", (char*)longProcName.c_str(), longProcNameLen, 1); + content->loadExtendLib = LoadExtendLib; + content->runChildProcessor = RunChildProcessor; + content->setAppSandbox = setAppSandbox; + content->setKeepCapabilities = setKeepCapabilities; + content->setProcessName = setProcessName; + content->setUidGid = setUidGid; + content->setFileDescriptors = setFileDescriptors; + content->setCapabilities = setCapabilities; + + int ret = DoStartApp((AppSpawnContent_*)content, &clientExt->client, (char*)"", 0); + EXPECT_EQ(ret, 0); + + free(content); + GTEST_LOG_(INFO) << "App_Spawn_Standard_008 end"; +} + +static int TestClient(int cold, AppOperateType code, const std::string &processName) +{ + char buffer[64] = {0}; // 64 buffer size + AppSpawnContentExt *content = (AppSpawnContentExt *)AppSpawnCreateContent("AppSpawn", buffer, sizeof(buffer), cold); + if (content == NULL) { + return -1; + } + // create connection + OnConnection(LE_GetDefaultLoop(), content->server); + + // process recv message + if (g_testClientHandle == nullptr) { + free(content); + return -1; + } + + AppParameter property = {}; + property.uid = 100; + property.gid = 100; + property.gidCount = 1; + property.gidTable[0] = 101; + (void)strcpy_s(property.processName, sizeof(property.processName), processName.c_str()); + (void)strcpy_s(property.bundleName, sizeof(property.bundleName), processName.c_str()); + (void)strcpy_s(property.renderCmd, sizeof(property.renderCmd), processName.c_str()); + (void)strcpy_s(property.soPath, sizeof(property.soPath), processName.c_str()); + (void)strcpy_s(property.apl, sizeof(property.apl), "system_core"); + property.flags = 0; + property.code = code; + property.accessTokenId = 0; + OnReceiveRequest(g_testClientHandle, (const uint8_t *)&property, sizeof(property)); + LE_CloseTask(LE_GetDefaultLoop(), g_testClientHandle); + free(content); + return 0; +} + +HWTEST(AppSpawnStandardTest, App_Spawn_Standard_009, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "App_Spawn_Standard_009 start"; + int ret = TestClient(0, DEFAULT, "ohos.test.testapp"); + EXPECT_EQ(ret, 0); + GTEST_LOG_(INFO) << "App_Spawn_Standard_009 end"; +} + +HWTEST(AppSpawnStandardTest, App_Spawn_Standard_010, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "App_Spawn_Standard_010 start"; + const char *str1 = "Test hash map node 1"; + const char *str2 = "Test hash map node 2"; + AppInfo *node1 = TestCreateHashNode(str1, 11); + AppInfo *node2 = TestCreateHashNode(str2, 12); + + AppInfoHashNodeCompare((const HashNode *)node1, (const HashNode *)node2); + int value = 13; + TestHashKeyCompare((const HashNode *)node1, &value); + AppInfoHashNodeFunction((const HashNode *)node1); + AppInfoHashKeyFunction(&value); + AppInfoHashNodeFree((const HashNode *)node1); + AppInfoHashNodeFree((const HashNode *)node2); + GTEST_LOG_(INFO) << "App_Spawn_Standard_010 end"; +} } // namespace OHOS diff --git a/test/unittest/client_socket_test/BUILD.gn b/test/unittest/client_socket_test/BUILD.gn deleted file mode 100644 index 24d258cc1575c8e2eb0bd4573d66ba963726b33f..0000000000000000000000000000000000000000 --- a/test/unittest/client_socket_test/BUILD.gn +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//base/startup/appspawn/appspawn.gni") -import("//build/test.gni") - -ohos_unittest("ClientSocketTest") { - module_out_path = "${module_output_path}" - - defines = [ "usleep(time) = MockSleep(time)" ] - - sources = [ - "${appspawn_path}/interfaces/innerkits/client/appspawn_socket.cpp", - "${appspawn_path}/interfaces/innerkits/client/client_socket.cpp", - ] - - sources += [ "client_socket_test.cpp" ] - - configs = [ "${appspawn_path}:appspawn_config" ] - - deps = [ "${appspawn_path}/test:appspawn_test_source" ] - - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] -} - -group("unittest") { - testonly = true - - deps = [ ":ClientSocketTest" ] -} diff --git a/util/src/json_utils.cpp b/util/src/json_utils.cpp index 37111e28830910019e481e505a5934799b6f4691..650df6544a135f9b83c311ad57411bf44e942a55 100644 --- a/util/src/json_utils.cpp +++ b/util/src/json_utils.cpp @@ -21,6 +21,7 @@ using namespace std; using namespace OHOS; using namespace OHOS::HiviewDFX; +using nlohmann::json; static constexpr HiLogLabel LABEL = {LOG_CORE, 0, "AppSpawn_JsonUtil"}; namespace OHOS { diff --git a/util/src/sandbox_utils.cpp b/util/src/sandbox_utils.cpp index 4dc57bcdb57b6a4128e1599997f8cb295f15c115..e4e089bca47dc19a2aff1f7a475d30c23ceed798 100644 --- a/util/src/sandbox_utils.cpp +++ b/util/src/sandbox_utils.cpp @@ -711,12 +711,14 @@ int32_t SandboxUtils::SetAppSandboxProperty(const ClientSocket::AppProperty *app return rc; } +#ifndef APPSPAWN_TEST rc = syscall(SYS_pivot_root, sandboxPackagePath.c_str(), sandboxPackagePath.c_str()); if (rc) { HiLog::Error(LABEL, "pivot root failed, packagename is %{public}s, errno is %{public}d", \ bundleName.c_str(), errno); return rc; } +#endif rc = umount2(".", MNT_DETACH); if (rc) {