diff --git a/ability_runtime.gni b/ability_runtime.gni index 785ee9550c..729ad0ef0f 100644 --- a/ability_runtime.gni +++ b/ability_runtime.gni @@ -18,10 +18,12 @@ ability_runtime_napi_path = "${ability_runtime_path}/frameworks/js/napi" ability_base_path = "//foundation/ability/ability_base" form_fwk_path = "//foundation/ability/form_fwk" ability_runtime_innerkits_path = "${ability_runtime_path}/interfaces/inner_api" +ability_runtime_ndk_path = "${ability_runtime_path}/interfaces/kits/c" ability_runtime_native_path = "${ability_runtime_path}/frameworks/native" ability_runtime_services_path = "${ability_runtime_path}/services" ability_runtime_abilitymgr_path = "${ability_runtime_services_path}/abilitymgr" ability_runtime_test_path = "${ability_runtime_path}/test" +ability_runtime_utils_path = "${ability_runtime_path}/utils" ace_engine_path = "//foundation/arkui/ace_engine" arkui_path = "//foundation/arkui" previewer_path = "//ide/tools/previewer" @@ -73,6 +75,19 @@ srms_inner_api_path = "${ability_runtime_path}/service_router_framework/interfaces/inner_api" fuzz_test_output_path = "ability_runtime/ability_runtime" accessibility_path = "//foundation/barrierfree/accessibility" +relational_store_base_path = "//foundation/distributeddatamgr/relational_store" +relational_store_napi_path = "${relational_store_base_path}/frameworks/js/napi" +common_tool_path = "//foundation/distributeddatamgr/kv_store/frameworks/common" +relational_store_common_path = "${relational_store_base_path}/frameworks/common" +ability_base_path = "//foundation/ability/ability_base" +ability_base_innerapi_path = "${ability_base_path}/interfaces/inner_api" +relational_store_innerapi_path = + "${relational_store_base_path}/interfaces/inner_api" +bgtaskmgr_root_path = "//foundation/resourceschedule/background_task_mgr" +bgtaskmgr_interfaces_path = "${bgtaskmgr_root_path}/interfaces" +bgtaskmgr_frameworks_path = "${bgtaskmgr_root_path}/frameworks" +os_account_path = "//base/account/os_account" +access_token_path = "//base/security/access_token" declare_args() { background_task_mgr_continuous_task_enable = true @@ -92,6 +107,7 @@ declare_args() { "com.ohos.textautofill/entry/TextAutoFillAbility" ability_runtime_use_memmgr_plugin = false ability_runtime_use_memmgr = false + cj_frontend = true if (!defined(global_parts_info) || defined(global_parts_info.account_os_account)) { diff --git a/bundle.json b/bundle.json index c451807a20..1157cd7261 100644 --- a/bundle.json +++ b/bundle.json @@ -64,16 +64,21 @@ "hitrace", "hiview", "i18n", + "icu", "image_framework", "init", "input", "ipc", + "json", + "jsoncpp", "kv_store", + "libuv", "memmgr", "memmgr_override", "memory_utils", "napi", "netmanager_base", + "node", "os_account", "relational_store", "resource_management", @@ -83,16 +88,11 @@ "storage_service", "toolchain", "webview", - "window_manager" + "window_manager", + "zlib" ], "third_party": [ - "icu", - "json", - "jsoncpp", - "libjpeg-turbo", - "libuv", - "node", - "zlib" + "libjpeg-turbo" ] }, "build": { @@ -104,8 +104,10 @@ "//foundation/ability/ability_runtime/interfaces/inner_api:innerkits_target", "//foundation/ability/ability_runtime/frameworks/native/ability/native:ability_thread", "//foundation/ability/ability_runtime/frameworks/native/ability/native:extension_module", + "//foundation/ability/ability_runtime/frameworks/native/child_process:child_process", "//foundation/ability/ability_runtime/frameworks/native/insight_intent:insight_intent_innerkits", "//foundation/ability/ability_runtime/frameworks/js/napi:napi_packages", + "//foundation/ability/ability_runtime/cj_environment/frameworks/cj_environment:cj_environment", "//foundation/ability/ability_runtime/js_environment/frameworks/js_environment:js_environment", "//foundation/ability/ability_runtime/services/abilitymgr/etc:appfwk_etc", "//foundation/ability/ability_runtime/service_router_framework:srms_target", @@ -173,6 +175,15 @@ }, "name": "//foundation/ability/ability_runtime/js_environment/frameworks/js_environment:js_environment" }, + { + "header": { + "header_base": "//foundation/ability/ability_runtime/cj_environment/interfaces/inner_api", + "header_files": [ + "cj_environment.h" + ] + }, + "name": "//foundation/ability/ability_runtime/cj_environment/frameworks/cj_environment:cj_environment" + }, { "header": { "header_base": "//foundation/ability/ability_runtime/interfaces/inner_api/runtime/include/", @@ -302,6 +313,15 @@ }, "name": "//foundation/ability/ability_runtime/frameworks/native/appkit:app_context" }, + { + "header": { + "header_base": "//foundation/ability/ability_runtime/interfaces/kits/c/ability/ability_runtime/child_process", + "header_files": [ + "native_child_process.h" + ] + }, + "name": "//foundation/ability/ability_runtime/frameworks/native/child_process:child_process" + }, { "header": { "header_base": "//foundation/ability/ability_runtime/interfaces/inner_api/uri_permission/include/", @@ -418,6 +438,23 @@ ] }, "name": "//foundation/ability/ability_runtime/interfaces/inner_api/auto_fill_manager:auto_fill_manager" + }, + { + "header": { + "header_base": "//foundation/ability/ability_runtime/interfaces/inner_api/ability_manager/include", + "header_files": [ + "start_options.h" + ] + }, + "name": "//foundation/ability/ability_runtime/interfaces/inner_api/ability_manager:ability_start_options" + }, + { + "header": { + "header_base": "//foundation/ability/ability_runtime/interfaces/kits/native/ability/native/dialog_request_callback", + "header_files": [ + ] + }, + "name": "//foundation/ability/ability_runtime/frameworks/native/ability/native:dialog_request_callback" } ], "test": [ diff --git a/cj_environment/cj_environment.gni b/cj_environment/cj_environment.gni new file mode 100644 index 0000000000..0706e35962 --- /dev/null +++ b/cj_environment/cj_environment.gni @@ -0,0 +1,34 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +cj_config = { + platform_name = "" + common_defines = [] +} + +if (current_os == "ohos") { + cj_config.platform_name = "ohos" + cj_config.common_defines = [ + "__DSU__", + "__OHOS__", + "__LINUX__", + ] +} else if (current_os == "linux") { + cj_config.platform_name = "linux" + cj_config.common_defines = [ "__LINUX__" ] +} else if (current_os == "mingw") { + cj_config.platform_name = "windows" + cj_config.common_defines = [ "__WINDOWS__" ] +} diff --git a/cj_environment/frameworks/cj_environment/BUILD.gn b/cj_environment/frameworks/cj_environment/BUILD.gn new file mode 100644 index 0000000000..c15c50888a --- /dev/null +++ b/cj_environment/frameworks/cj_environment/BUILD.gn @@ -0,0 +1,66 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +import("//foundation/ability/ability_runtime/cj_environment/cj_environment.gni") + +config("cj_rt_public_config") { + include_dirs = [ + "include", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + defines = cj_config.common_defines +} + +ohos_shared_library("cj_environment") { + cflags_cc = [ + "-std=c++17", + "-fvisibility=hidden", + "-fdata-sections", + "-ffunction-sections", + ] + + public_configs = [ ":cj_rt_public_config" ] + + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + + sources = [ "src/cj_environment.cpp" ] + + defines = [] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + ] + + if (current_os == "ohos") { + sources += [ "src/dynamic_loader_ohos.cpp" ] + external_deps += [ "eventhandler:libeventhandler" ] + defines += [ "WITH_EVENT_HANDLER" ] + } else if (current_os == "linux") { + sources += [ "src/dynamic_loader_linux.cpp" ] + } else if (current_os == "mingw") { + sources += [ "src/dynamic_loader_win.cpp" ] + } else { + assert("unsupport platform: ${current_os}") + } + + innerapi_tags = [ "platformsdk" ] + part_name = "ability_runtime" + subsystem_name = "ability" +} diff --git a/cj_environment/frameworks/cj_environment/include/cj_interface.h b/cj_environment/frameworks/cj_environment/include/cj_interface.h new file mode 100644 index 0000000000..bd23a02a31 --- /dev/null +++ b/cj_environment/frameworks/cj_environment/include/cj_interface.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_CJ_ENVIRONMENT_CJ_INTERFACE_H +#define OHOS_ABILITY_CJ_ENVIRONMENT_CJ_INTERFACE_H + +#include + +using CJThreadHandle = void*; + +namespace OHOS { + +enum RTLogLevel { + RTLOG_VERBOSE, + RTLOG_DEBUGY, + RTLOG_INFO, + RTLOG_WARNING, + RTLOG_ERROR, + RTLOG_FATAL_WITHOUT_ABORT, + RTLOG_FATAL, + RTLOG_OFF +}; + +enum RTErrorCode { E_OK = 0, E_ARGS = -1, E_TIMEOUT = -2, E_STATE = -3, E_FAILED = -4 }; + +struct HeapParam { + size_t regionSize; + size_t heapSize; + double exemptionThreshold; + double heapUtilization; + double heapGrowth; + double allocationRate; + size_t allocationWaitTime; +}; + +struct GCParam { + size_t gcThreshold; + double garbageThreshold; + uint64_t gcInterval; + uint64_t backupGCInterval; + int32_t gcThreads; +}; + +struct LogParam { + enum RTLogLevel logLevel; +}; + +struct ConcurrencyParam { + size_t thStackSize; + size_t coStackSize; + uint32_t processorNum; +}; + +struct RuntimeParam { + struct HeapParam heapParam; + struct GCParam gcParam; + struct LogParam logParam; + struct ConcurrencyParam coParam; +}; + +#if defined(__OHOS__) && (__OHOS__ == 1) +using LogHandle = void (*)(const char*); +#endif +} +#endif // OHOS_ABILITY_CJ_ENVIRONMENT_CJ_INTERFACE_H diff --git a/cj_environment/frameworks/cj_environment/include/cj_invoker.h b/cj_environment/frameworks/cj_environment/include/cj_invoker.h new file mode 100644 index 0000000000..96d54ec2de --- /dev/null +++ b/cj_environment/frameworks/cj_environment/include/cj_invoker.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_CJ_INVOKER_H +#define OHOS_ABILITY_RUNTIME_CJ_INVOKER_H + +#include "cj_interface.h" + +#include +#include +#include + +namespace OHOS { +using PostTaskType = bool(*)(void*); +using HasHigherPriorityType = bool(*)(); + +struct CJUncaughtExceptionInfo; + +struct CJRuntimeAPI { + int (*InitCJRuntime)(const struct RuntimeParam*); + void* (*InitUIScheduler)(); + int (*RunUIScheduler)(unsigned long long); + int (*FiniCJRuntime)(); + int (*InitCJLibrary)(const char*); + void (*RegisterEventHandlerCallbacks)(PostTaskType, HasHigherPriorityType); + void (*RegisterCJUncaughtExceptionHandler)(const CJUncaughtExceptionInfo& handle); +}; +} + +#endif //OHOS_ABILITY_RUNTIME_CJ_INVOKER_H diff --git a/cj_environment/frameworks/cj_environment/include/cj_macro.h b/cj_environment/frameworks/cj_environment/include/cj_macro.h new file mode 100644 index 0000000000..7c9887ec3a --- /dev/null +++ b/cj_environment/frameworks/cj_environment/include/cj_macro.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_CJ_MACRO_H +#define OHOS_ABILITY_RUNTIME_CJ_MACRO_H + +#ifndef CJ_EXPORT +#ifndef __WINDOWS__ +#define CJ_EXPORT __attribute__((visibility("default"))) +#else +#define CJ_EXPORT __declspec(dllexport) +#endif +#endif + +#endif //OHOS_ABILITY_RUNTIME_CJ_MACRO_H diff --git a/cj_environment/frameworks/cj_environment/src/cj_environment.cpp b/cj_environment/frameworks/cj_environment/src/cj_environment.cpp new file mode 100644 index 0000000000..8452328736 --- /dev/null +++ b/cj_environment/frameworks/cj_environment/src/cj_environment.cpp @@ -0,0 +1,469 @@ +/* + * Copyright (c) 2024 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 "cj_environment.h" + +#include + +#include "cj_hilog.h" +#include "cj_invoker.h" +#ifdef __OHOS__ +#include +#endif +#include "dynamic_loader.h" +#ifdef WITH_EVENT_HANDLER +#include "event_handler.h" +#endif + +using namespace OHOS; + +namespace { +const char DEBUGGER_LIBNAME[] = "libcj_debugger.z.so"; +const char DEBUGGER_SYMBOL_NAME[] = "StartDebuggerServer"; +const char INIT_CJRUNTIME_SYMBOL_NAME[] = "InitCJRuntime"; +const char INIT_UISCHEDULER_SYMBOL_NAME[] = "InitUIScheduler"; +const char RUN_UISCHEDULER_SYMBOL_NAME[] = "RunUIScheduler"; +const char FINI_CJRUNTIME_SYMBOL_NAME[] = "FiniCJRuntime"; +const char INIT_CJLIBRARY_SYMBOL_NAME[] = "InitCJLibrary"; +const char REGISTER_EVENTHANDLER_CALLBACKS_NAME[] = "RegisterEventHandlerCallbacks"; + +using InitCJRuntimeType = int(*)(const struct RuntimeParam*);; +using InitUISchedulerType = void*(*)(); +using RunUISchedulerType = int(*)(unsigned long long); +using FiniCJRuntimeType = int(*)(); +using InitCJLibraryType = int(*)(const char*); +using RegisterEventHandlerType = void(*)(PostTaskType, HasHigherPriorityType); + +#ifdef __OHOS__ +const char REGISTER_UNCAUGHT_EXCEPTION_NAME[] = "RegisterUncaughtExceptionHandler"; +using RegisterUncaughtExceptionType = void (*)(const CJUncaughtExceptionInfo& handle); +#endif + +#ifdef WITH_EVENT_HANDLER +static std::shared_ptr g_handler = nullptr; +#endif + +bool LoadSymbolInitCJRuntime(void* handle, CJRuntimeAPI& apis) +{ + auto symbol = DynamicFindSymbol(handle, INIT_CJRUNTIME_SYMBOL_NAME); + if (symbol == nullptr) { + LOGE("runtime api not found: %{public}s", INIT_CJRUNTIME_SYMBOL_NAME); + return false; + } + apis.InitCJRuntime = reinterpret_cast(symbol); + return true; +} + +bool LoadSymbolInitUIScheduler(void* handle, CJRuntimeAPI& apis) +{ + auto symbol = DynamicFindSymbol(handle, INIT_UISCHEDULER_SYMBOL_NAME); + if (symbol == nullptr) { + LOGE("runtime api not found: %{public}s", INIT_UISCHEDULER_SYMBOL_NAME); + return false; + } + apis.InitUIScheduler = reinterpret_cast(symbol); + return true; +} + +bool LoadSymbolRunUIScheduler(void* handle, CJRuntimeAPI& apis) +{ + auto symbol = DynamicFindSymbol(handle, RUN_UISCHEDULER_SYMBOL_NAME); + if (symbol == nullptr) { + LOGE("runtime api not found: %{public}s", RUN_UISCHEDULER_SYMBOL_NAME); + return false; + } + apis.RunUIScheduler = reinterpret_cast(symbol); + return true; +} + +bool LoadSymbolFiniCJRuntime(void* handle, CJRuntimeAPI& apis) +{ + auto symbol = DynamicFindSymbol(handle, FINI_CJRUNTIME_SYMBOL_NAME); + if (symbol == nullptr) { + LOGE("runtime api not found: %{public}s", FINI_CJRUNTIME_SYMBOL_NAME); + return false; + } + apis.FiniCJRuntime = reinterpret_cast(symbol); + return true; +} + +bool LoadSymbolInitCJLibrary(void* handle, CJRuntimeAPI& apis) +{ + auto symbol = DynamicFindSymbol(handle, INIT_CJLIBRARY_SYMBOL_NAME); + if (symbol == nullptr) { + LOGE("runtime api not found: %{public}s", INIT_CJLIBRARY_SYMBOL_NAME); + return false; + } + apis.InitCJLibrary = reinterpret_cast(symbol); + return true; +} + +bool LoadSymbolRegisterEventHandlerCallbacks(void* handle, CJRuntimeAPI& apis) +{ + auto symbol = DynamicFindSymbol(handle, REGISTER_EVENTHANDLER_CALLBACKS_NAME); + if (symbol == nullptr) { + LOGE("runtime api not found: %{public}s", REGISTER_EVENTHANDLER_CALLBACKS_NAME); + return false; + } + apis.RegisterEventHandlerCallbacks = reinterpret_cast(symbol); + return true; +} + +#ifdef __OHOS__ +bool LoadSymbolRegisterCJUncaughtExceptionHandler(void* handle, CJRuntimeAPI& apis) +{ + auto symbol = DynamicFindSymbol(handle, REGISTER_UNCAUGHT_EXCEPTION_NAME); + if (symbol == nullptr) { + LOGE("runtime api not found: %{public}s", REGISTER_UNCAUGHT_EXCEPTION_NAME); + return false; + } + apis.RegisterCJUncaughtExceptionHandler = reinterpret_cast(symbol); + return true; +} +#endif + +bool PostTaskWrapper(void* func) +{ + return CJEnvironment::GetInstance()->PostTask(reinterpret_cast(func)); +} + +bool HasHigherPriorityTaskWrapper() +{ + return CJEnvironment::GetInstance()->HasHigherPriorityTask(); +} +} // namespace + +const char *CJEnvironment::cjAppNSName = "cj_app"; +const char *CJEnvironment::cjSDKNSName = "cj_sdk"; +const char *CJEnvironment::cjSysNSName = "cj_system"; +const char *CJEnvironment::cjChipSDKNSName = "cj_chipsdk"; + +CJRuntimeAPI CJEnvironment::lazyApis_ {}; + +CJEnvironment* CJEnvironment::GetInstance() +{ + static CJEnvironment cjEnv; +#ifdef WITH_EVENT_HANDLER + if (g_handler == nullptr) { + g_handler = std::make_shared(AppExecFwk::EventRunner::GetMainEventRunner()); + } +#endif + return &cjEnv; +} + +bool CJEnvironment::LoadRuntimeApis() +{ + static bool isRuntimeApiLoaded {false}; + if (isRuntimeApiLoaded) { + return true; + } +#ifdef __WINDOWS__ +#define RTLIB_NAME "libcangjie-runtime.dll" +#else +#define RTLIB_NAME "libcangjie-runtime.so" +#endif +#ifdef __OHOS__ + Dl_namespace ns; + dlns_get(CJEnvironment::cjSDKNSName, &ns); + auto dso = DynamicLoadLibrary(&ns, RTLIB_NAME, 1); +#else + auto dso = DynamicLoadLibrary(RTLIB_NAME, 1); +#endif + if (!dso) { + LOGE("load library failed: %{public}s", RTLIB_NAME); + return false; + } +#undef RTLIB_NAME + if (!LoadSymbolInitCJRuntime(dso, lazyApis_) || + !LoadSymbolInitUIScheduler(dso, lazyApis_) || + !LoadSymbolRunUIScheduler(dso, lazyApis_) || + !LoadSymbolFiniCJRuntime(dso, lazyApis_) || + !LoadSymbolInitCJLibrary(dso, lazyApis_) || + !LoadSymbolRegisterEventHandlerCallbacks(dso, lazyApis_)) { + LOGE("load symbol failed"); + return false; + } +#ifdef __OHOS__ + if (!LoadSymbolRegisterCJUncaughtExceptionHandler(dso, lazyApis_)) { + LOGE("load symbol RegisterCJUncaughtExceptionHandler failed"); + return false; + } +#endif + isRuntimeApiLoaded = true; + return true; +} + +void CJEnvironment::RegisterCJUncaughtExceptionHandler(const CJUncaughtExceptionInfo& handle) +{ + lazyApis_.RegisterCJUncaughtExceptionHandler(handle); +} + +bool CJEnvironment::PostTask(TaskFuncType task) +{ +#ifdef WITH_EVENT_HANDLER + if (task == nullptr) { + LOGE("null task could not be posted"); + return false; + } + + bool postDone = g_handler->PostTask(task, "spawn-main-task-from-cj", 0, AppExecFwk::EventQueue::Priority::HIGH); + if (!postDone) { + LOGE("event handler support cj ui scheduler"); + return false; + } + return true; +#endif + return true; +} + +bool CJEnvironment::HasHigherPriorityTask() +{ +#ifdef WITH_EVENT_HANDLER + return g_handler->HasPreferEvent(static_cast(AppExecFwk::EventQueue::Priority::HIGH)); +#endif + return false; +} + +void CJEnvironment::InitCJChipSDKNS(const std::string& path) +{ +#ifdef __OHOS__ + LOGI("InitCJChipSDKNS: %{public}s", path.c_str()); + Dl_namespace chip_ndk; + DynamicInitNamespace(&chip_ndk, nullptr, path.c_str(), CJEnvironment::cjChipSDKNSName); + + Dl_namespace ndk; + Dl_namespace current; + dlns_get(nullptr, ¤t); + dlns_get("ndk", &ndk); + dlns_inherit(&chip_ndk, &ndk, "allow_all_shared_libs"); + dlns_inherit(&chip_ndk, ¤t, "allow_all_shared_libs"); +#endif +} + +// Init app namespace +void CJEnvironment::InitCJAppNS(const std::string& path) +{ +#ifdef __OHOS__ + LOGI("InitCJAppNS: %{public}s", path.c_str()); + Dl_namespace ndk; + Dl_namespace ns; + DynamicInitNamespace(&ns, nullptr, path.c_str(), CJEnvironment::cjAppNSName); + dlns_get("ndk", &ndk); + dlns_inherit(&ns, &ndk, "allow_all_shared_libs"); + Dl_namespace current; + dlns_get(nullptr, ¤t); + dlns_inherit(&ndk, ¤t, "allow_all_shared_libs"); + dlns_inherit(¤t, &ndk, "allow_all_shared_libs"); +#endif +} + +// Init cj sdk namespace +void CJEnvironment::InitCJSDKNS(const std::string& path) +{ +#ifdef __OHOS__ + LOGI("InitCJSDKNS: %{public}s", path.c_str()); + Dl_namespace cj_app; + Dl_namespace ns; + dlns_get(CJEnvironment::cjAppNSName, &cj_app); + DynamicInitNamespace(&ns, &cj_app, path.c_str(), CJEnvironment::cjSDKNSName); +#endif +} + +// Init cj system namespace +void CJEnvironment::InitCJSysNS(const std::string& path) +{ +#ifdef __OHOS__ + LOGI("InitCJSysNS: %{public}s", path.c_str()); + Dl_namespace cj_sdk; + Dl_namespace ndk; + Dl_namespace ns; + dlns_get(CJEnvironment::cjSDKNSName, &cj_sdk); + DynamicInitNamespace(&ns, &cj_sdk, path.c_str(), CJEnvironment::cjSysNSName); + dlns_get("ndk", &ndk); + dlns_inherit(&ns, &ndk, "allow_all_shared_libs"); +#endif +} + +bool CJEnvironment::StartRuntime() +{ + if (isRuntimeStarted_) { + return true; + } + + if (!LoadRuntimeApis()) { + LOGE("LoadRuntimeApis failed"); + return false; + } + + RuntimeParam rtParams { + .heapParam = { + .regionSize = 64, + .heapSize = 64 * 1024, + .exemptionThreshold= 0.8, + .heapUtilization = 0.8, + .heapGrowth = 0.15, + .allocationRate = 0, + .allocationWaitTime = 0, + }, + .gcParam = { + .gcThreshold = 0, + .garbageThreshold = 0, + .gcInterval = 0, + .backupGCInterval = 0, + .gcThreads = 0, + }, + .logParam = { + .logLevel = RTLOG_ERROR, + }, + .coParam = { + .thStackSize = 2 * 1024, + .coStackSize = 2 * 1024, + .processorNum = 8, + } + }; + + auto status = lazyApis_.InitCJRuntime(&rtParams); + if (status != E_OK) { + LOGE("init cj runtime failed: %{public}d", status); + return false; + } + + lazyApis_.RegisterEventHandlerCallbacks(PostTaskWrapper, HasHigherPriorityTaskWrapper); + + isRuntimeStarted_ = true; + return true; +} + +void CJEnvironment::StopRuntime() +{ + if (!isRuntimeStarted_) { + return; + } + + if (isUISchedulerStarted_) { + StopUIScheduler(); + } + + auto code = lazyApis_.FiniCJRuntime(); + if (code == E_OK) { + isRuntimeStarted_ = false; + } +} + +bool CJEnvironment::StartUIScheduler() +{ + if (isUISchedulerStarted_) { + return true; + } + + uiScheduler_ = lazyApis_.InitUIScheduler(); + if (!uiScheduler_) { + LOGE("init cj ui scheduler failed"); + return false; + } + + isUISchedulerStarted_ = true; + return true; +} + +void CJEnvironment::StopUIScheduler() +{ + isUISchedulerStarted_ = false; +} + +void* CJEnvironment::LoadCJLibrary(const char* dlName) +{ + if (!StartRuntime()) { + LOGE("StartRuntime failed"); + return nullptr; + } + auto handle = LoadCJLibrary(APP, dlName); + if (!handle) { + LOGE("load cj library failed: %{public}s", DynamicGetError()); + return nullptr; + } + + LOGI("LoadCJLibrary InitCJLibrary: %{public}s", dlName); + auto status = lazyApis_.InitCJLibrary(dlName); + if (status != E_OK) { + LOGE("InitCJLibrary failed: %{public}s", dlName); + UnLoadCJLibrary(handle); + return nullptr; + } + + return handle; +} + +void* CJEnvironment::LoadCJLibrary(OHOS::CJEnvironment::LibraryKind kind, const char* dlName) +{ +#ifdef __OHOS__ + Dl_namespace ns; + switch (kind) { + case APP: + dlns_get(CJEnvironment::cjAppNSName, &ns); + break; + case SYSTEM: + dlns_get(CJEnvironment::cjSysNSName, &ns); + break; + case SDK: + dlns_get(CJEnvironment::cjSDKNSName, &ns); + break; + } + auto handle = DynamicLoadLibrary(&ns, dlName, 1); +#else + auto handle = DynamicLoadLibrary(dlName, 1); +#endif + if (!handle) { + LOGE("load cj library failed: %{public}s", DynamicGetError()); + return nullptr; + } + return handle; +} + +void CJEnvironment::UnLoadCJLibrary(void* handle) +{ + DynamicFreeLibrary(handle); +} + +void* CJEnvironment::GetSymbol(void* dso, const char* symbol) +{ + return DynamicFindSymbol(dso, symbol); +} + +bool CJEnvironment::StartDebugger() +{ +#ifdef __OHOS__ + Dl_namespace ns; + dlns_get(CJEnvironment::cjSysNSName, &ns); + auto handle = DynamicLoadLibrary(&ns, DEBUGGER_LIBNAME, 0); +#else + auto handle = DynamicLoadLibrary(DEBUGGER_LIBNAME, 0); +#endif + if (!handle) { + LOGE("failed to load library: %{public}s", DEBUGGER_LIBNAME); + return false; + } + auto symbol = DynamicFindSymbol(handle, DEBUGGER_SYMBOL_NAME); + if (!symbol) { + LOGE("failed to find symbol: %{public}s", DEBUGGER_SYMBOL_NAME); + DynamicFreeLibrary(handle); + return false; + } + auto func = reinterpret_cast(symbol); + std::string name = "PandaDebugger"; + func(0, name); + return true; +} + diff --git a/cj_environment/frameworks/cj_environment/src/cj_hilog.h b/cj_environment/frameworks/cj_environment/src/cj_hilog.h new file mode 100644 index 0000000000..63396212da --- /dev/null +++ b/cj_environment/frameworks/cj_environment/src/cj_hilog.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_CJ_HILOG_H +#define OHOS_ABILITY_RUNTIME_CJ_HILOG_H + +#include "hilog/log.h" + +#ifdef LOG_DOMAIN +#undef LOG_DOMAIN +#endif +#ifdef LOG_TAG +#undef LOG_TAG +#endif + +#define LOG_DOMAIN 0xD003900 +#define LOG_TAG "CJ-RUNTIME" + +#define LOGI(...) \ +if (HiLogIsLoggable(LOG_DOMAIN, LOG_TAG, LOG_INFO)) { \ + HILOG_INFO(LOG_CORE, ##__VA_ARGS__); \ +} + +#define LOGE(...) \ +if (HiLogIsLoggable(LOG_DOMAIN, LOG_TAG, LOG_ERROR)) { \ + HILOG_ERROR(LOG_CORE, __VA_ARGS__); \ +} + +#endif //OHOS_ABILITY_RUNTIME_CJ_HILOG_H diff --git a/cj_environment/frameworks/cj_environment/src/dynamic_loader_linux.cpp b/cj_environment/frameworks/cj_environment/src/dynamic_loader_linux.cpp new file mode 100644 index 0000000000..2adf02d733 --- /dev/null +++ b/cj_environment/frameworks/cj_environment/src/dynamic_loader_linux.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 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 "dynamic_loader.h" + +#include + +void* DynamicLoadLibrary(const char* dlPath, int mode) +{ + return dlopen(dlPath, mode); +} + +void* DynamicFindSymbol(void* so, const char* symbol) +{ + return dlsym(so, symbol); +} + +void DynamicFreeLibrary(void* so) +{ + (void)dlclose(so); +} + +const char* DynamicGetError() +{ + return dlerror(); +} \ No newline at end of file diff --git a/cj_environment/frameworks/cj_environment/src/dynamic_loader_ohos.cpp b/cj_environment/frameworks/cj_environment/src/dynamic_loader_ohos.cpp new file mode 100644 index 0000000000..f93cd76926 --- /dev/null +++ b/cj_environment/frameworks/cj_environment/src/dynamic_loader_ohos.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2024 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 "dynamic_loader.h" + +#include "cj_hilog.h" +#include +#include +#include +#include +#include + +namespace { +constexpr auto ERROR_BUF_SIZE = 255; +static char g_dlError[ERROR_BUF_SIZE]; +static std::unordered_set HasInited; +} + +enum ErrorCode { + OUT_OF_MEMORY = 12, + FILE_EXISTS = 17, + INVALID_ARGUMENT = 22, +}; + +static void ReadDlError() +{ + char* errMsg = dlerror(); + if (!errMsg) { + return; + } + auto ends = sprintf_s(g_dlError, sizeof(g_dlError), "%s", errMsg); + if (ends >= ERROR_BUF_SIZE) { + g_dlError[ERROR_BUF_SIZE - 1] = '\0'; + } else { + g_dlError[ends] = '\0'; + } +} + +void DynamicInitNamespace(Dl_namespace* ns, void* parent, const char* entries, const char* name) +{ + if (!ns || !entries || !name) { + LOGE("Invaild args for init namespace."); + return; + } + if (HasInited.count(std::string(name))) { + return; + } + dlns_init(ns, name); + auto status = dlns_create2(ns, entries, 0); + std::string errMsg; + if (status != 0) { + switch (status) { + case FILE_EXISTS: + errMsg = "dlns_create failed: File exists"; + break; + case INVALID_ARGUMENT: + errMsg = "dlns_create failed: Invalid argument"; + break; + case OUT_OF_MEMORY: + errMsg = "dlns_create failed: Out of memory"; + break; + default: + errMsg = "dlns_create failed, status: " + std::to_string(status); + } + (void)sprintf_s(g_dlError, sizeof(g_dlError), errMsg.c_str()); + return; + } + if (parent) { + dlns_inherit((Dl_namespace*)parent, ns, "allow_all_shared_libs"); + } + if (strcmp(name, "cj_app") != 0) { + Dl_namespace current; + dlns_get(nullptr, ¤t); + dlns_inherit(ns, ¤t, "allow_all_shared_libs"); + } + HasInited.insert(std::string(name)); +} + +void* DynamicLoadLibrary(Dl_namespace *ns, const char* dlPath, int mode) +{ + if (ns == nullptr) { + dlns_get("cj_app", ns); + } + + auto result = dlopen_ns(ns, dlPath, mode | RTLD_GLOBAL | RTLD_NOW); + if (!result) { + ReadDlError(); + } + return result; +} + +void* DynamicFindSymbol(void* so, const char* symbol) +{ + return dlsym(so, symbol); +} + +void DynamicFreeLibrary(void* so) +{ + (void)dlclose(so); +} + +const char* DynamicGetError() +{ + return g_dlError; +} diff --git a/cj_environment/frameworks/cj_environment/src/dynamic_loader_win.cpp b/cj_environment/frameworks/cj_environment/src/dynamic_loader_win.cpp new file mode 100644 index 0000000000..7d28c374f8 --- /dev/null +++ b/cj_environment/frameworks/cj_environment/src/dynamic_loader_win.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024 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 "dynamic_loader.h" + +#include +#include +#include + +constexpr auto ERROR_BUF_SIZE = 255; +static char g_dlError[ERROR_BUF_SIZE] {0}; + +void* DynamicLoadLibrary(const char* dlPath, int mode) +{ + return LoadLibraryA(dlPath); +} + +void* DynamicFindSymbol(void* so, const char* symbol) +{ + return (void*)GetProcAddress((HMODULE)so, symbol); +} + +void DynamicFreeLibrary(void* so) +{ + (void)FreeLibrary((HMODULE)so); +} + +const char* DynamicGetError() +{ + return g_dlError; +} diff --git a/cj_environment/interfaces/inner_api/cj_environment.h b/cj_environment/interfaces/inner_api/cj_environment.h new file mode 100644 index 0000000000..f8cbff75b4 --- /dev/null +++ b/cj_environment/interfaces/inner_api/cj_environment.h @@ -0,0 +1,97 @@ +/* +* 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 OHOS_ABILITY_RUNTIME_CJ_ENVIRONMENT_H +#define OHOS_ABILITY_RUNTIME_CJ_ENVIRONMENT_H + +#include + +#ifdef WINDOWS_PLATFORM +#define CJ_EXPORT __declspec(dllexport) +#else +#define CJ_EXPORT __attribute__((visibility("default"))) +#endif + +namespace OHOS { +struct CJRuntimeAPI; + +struct CJErrorObject { + const char* name; + const char* message; + const char* stack; +}; + +struct CJUncaughtExceptionInfo { + const char* hapPath; + std::function uncaughtTask; +}; + +using TaskFuncType = void(*)(); + +class CJ_EXPORT CJEnvironment final { +public: + static CJEnvironment* GetInstance(); + + bool IsRuntimeStarted() + { + return isRuntimeStarted_; + } + void InitCJAppNS(const std::string& path); + void InitCJSDKNS(const std::string& path); + void InitCJSysNS(const std::string& path); + void InitCJChipSDKNS(const std::string& path); + bool StartRuntime(); + void StopRuntime(); + void RegisterCJUncaughtExceptionHandler(const CJUncaughtExceptionInfo& handle); + bool IsUISchedulerStarted() + { + return isUISchedulerStarted_; + } + bool StartUIScheduler(); + void StopUIScheduler(); + enum LibraryKind { + SYSTEM, + SDK, + APP, + }; + void* LoadCJLibrary(const char* dlName); + void* LoadCJLibrary(LibraryKind kind, const char* dlName); + void UnLoadCJLibrary(void* handle); + void* GetUIScheduler() + { + if (!isUISchedulerStarted_) { + return nullptr; + } + return uiScheduler_; + } + void* GetSymbol(void* dso, const char* symbol); + bool StartDebugger(); + bool PostTask(TaskFuncType task); + bool HasHigherPriorityTask(); + + static const char *cjAppNSName; + static const char *cjSDKNSName; + static const char *cjSysNSName; + static const char *cjChipSDKNSName; +private: + bool LoadRuntimeApis(); + static CJRuntimeAPI lazyApis_; + bool isRuntimeStarted_{false}; + bool isUISchedulerStarted_{false}; + void* uiScheduler_ {nullptr}; +}; +} + +#endif //OHOS_ABILITY_RUNTIME_CJ_ENVIRONMENT_H diff --git a/cj_environment/interfaces/inner_api/dynamic_loader.h b/cj_environment/interfaces/inner_api/dynamic_loader.h new file mode 100644 index 0000000000..7e5867ebe1 --- /dev/null +++ b/cj_environment/interfaces/inner_api/dynamic_loader.h @@ -0,0 +1,37 @@ +/* +* Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_DYNAMIC_LOADER_H +#define OHOS_ABILITY_RUNTIME_DYNAMIC_LOADER_H + +#ifdef __OHOS__ +#include +#endif + +extern "C" { +#ifdef __OHOS__ +void* DynamicLoadLibrary(Dl_namespace *ns, const char* dlPath, int mode); +#else +void* DynamicLoadLibrary(const char* dlPath, int mode); +#endif +void* DynamicFindSymbol(void* so, const char* symbol); +const char* DynamicGetError(); +void DynamicFreeLibrary(void* so); +#ifdef __OHOS__ +void DynamicInitNamespace(Dl_namespace* ns, void* parent, const char* entries, const char* name); +#endif +}; + +#endif //OHOS_ABILITY_RUNTIME_DYNAMIC_LOADER_H diff --git a/frameworks/js/napi/ability_auto_startup_callback/BUILD.gn b/frameworks/js/napi/ability_auto_startup_callback/BUILD.gn index 525f5f723e..f957a2049e 100644 --- a/frameworks/js/napi/ability_auto_startup_callback/BUILD.gn +++ b/frameworks/js/napi/ability_auto_startup_callback/BUILD.gn @@ -27,6 +27,7 @@ ohos_shared_library("autostartupcallback") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/error_utils:ability_runtime_error_util", "${ability_runtime_innerkits_path}/runtime:runtime", diff --git a/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_callback.cpp b/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_callback.cpp index 9d0f9d888b..1ac5ccf4ce 100644 --- a/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_callback.cpp +++ b/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_callback.cpp @@ -46,7 +46,7 @@ void JsAbilityAutoStartupCallBack::OnAutoStartupOff(const AutoStartupInfo &info) void JsAbilityAutoStartupCallBack::Register(napi_value value) { TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); - std::lock_guard lock(mutexlock); + std::lock_guard lock(mutexlock_); for (const auto &callback : callbacks_) { if (IsJsCallbackEquals(callback, value)) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "The current callback already exists."); @@ -64,7 +64,7 @@ void JsAbilityAutoStartupCallBack::UnRegister(napi_value value) TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); napi_valuetype type = napi_undefined; napi_typeof(env_, value, &type); - std::lock_guard lock(mutexlock); + std::lock_guard lock(mutexlock_); if (type == napi_undefined || type == napi_null) { TAG_LOGD(AAFwkTag::AUTO_STARTUP, "jsCallback is nullptr, delete all callback."); callbacks_.clear(); @@ -105,7 +105,7 @@ void JsAbilityAutoStartupCallBack::JSCallFunction(const AutoStartupInfo &info, c void JsAbilityAutoStartupCallBack::JSCallFunctionWorker(const AutoStartupInfo &info, const std::string &methodName) { - std::lock_guard lock(mutexlock); + std::lock_guard lock(mutexlock_); for (auto callback : callbacks_) { if (callback == nullptr) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "callback is nullptr."); diff --git a/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_callback.h b/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_callback.h index 0e49f5620f..6017641867 100644 --- a/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_callback.h +++ b/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_callback.h @@ -49,7 +49,7 @@ private: napi_env env_; std::vector> callbacks_; - std::mutex mutexlock; + std::mutex mutexlock_; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_manager_utils.cpp b/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_manager_utils.cpp index 2565aac763..e4d1d6fd97 100644 --- a/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_manager_utils.cpp +++ b/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_manager_utils.cpp @@ -72,7 +72,7 @@ napi_value CreateJsAutoStartupInfoArray(napi_env env, const std::vector(AbilityErrorCode::ERROR_CODE_INVALID_PARAM); constexpr const char *ON_OFF_TYPE_SYSTEM = "systemAutoStartup"; } // namespace @@ -91,7 +92,7 @@ napi_value JsAbilityAutoStartupManager::OnRegisterAutoStartupCallback(napi_env e std::string type; if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], type) || type != ON_OFF_TYPE_SYSTEM) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "The param is invalid."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowError(env, INVALID_PARAM, "Parameter error. Convert type fail."); return CreateJsUndefined(env); } @@ -139,7 +140,7 @@ napi_value JsAbilityAutoStartupManager::OnUnregisterAutoStartupCallback(napi_env std::string type; if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], type) || type != ON_OFF_TYPE_SYSTEM) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "Failed to parse type."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowError(env, INVALID_PARAM, "Parameter error. Convert type fail."); return CreateJsUndefined(env); } @@ -189,7 +190,7 @@ napi_value JsAbilityAutoStartupManager::OnSetApplicationAutoStartup(napi_env env AutoStartupInfo autoStartupInfo; if (!UnwrapAutoStartupInfo(env, info.argv[INDEX_ZERO], autoStartupInfo)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowError(env, INVALID_PARAM, "Parameter error. Convert autoStartupInfo fail."); return CreateJsUndefined(env); } @@ -239,7 +240,7 @@ napi_value JsAbilityAutoStartupManager::OnCancelApplicationAutoStartup(napi_env AutoStartupInfo autoStartupInfo; if (!UnwrapAutoStartupInfo(env, info.argv[INDEX_ZERO], autoStartupInfo)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowError(env, INVALID_PARAM, "Parameter error. Convert autoStartupInfo fail."); return CreateJsUndefined(env); } diff --git a/frameworks/js/napi/ability_constant/BUILD.gn b/frameworks/js/napi/ability_constant/BUILD.gn index 97d03fa105..43b2b350cf 100644 --- a/frameworks/js/napi/ability_constant/BUILD.gn +++ b/frameworks/js/napi/ability_constant/BUILD.gn @@ -18,9 +18,6 @@ ohos_shared_library("abilityconstant_napi") { include_dirs = [ "${ability_runtime_innerkits_path}/ability_manager/include", "${ability_runtime_services_path}/common/include", - "${ability_base_kits_path}/uri/include", - "${ability_base_kits_path}/want/include", - "${ability_base_path}/interfaces/inner_api/base/include", "//third_party/json/include", ] @@ -29,12 +26,13 @@ ohos_shared_library("abilityconstant_napi") { deps = [] external_deps = [ + "ability_base:zuri", "c_utils:utils", "hilog:libhilog", "ipc:ipc_core", "napi:ace_napi", ] - + public_external_deps = [ "ability_base:want" ] relative_install_dir = "module/application" subsystem_name = "ability" part_name = "ability_runtime" @@ -44,9 +42,6 @@ ohos_shared_library("abilityconstant") { include_dirs = [ "${ability_runtime_innerkits_path}/ability_manager/include", "${ability_runtime_services_path}/common/include", - "${ability_base_kits_path}/uri/include", - "${ability_base_kits_path}/want/include", - "${ability_base_path}/interfaces/inner_api/base/include", "//third_party/json/include", ] @@ -55,12 +50,13 @@ ohos_shared_library("abilityconstant") { deps = [] external_deps = [ + "ability_base:zuri", "c_utils:utils", "hilog:libhilog", "ipc:ipc_core", "napi:ace_napi", ] - + public_external_deps = [ "ability_base:want" ] defines = [ "ENABLE_ERRCODE" ] relative_install_dir = "module/app/ability" diff --git a/frameworks/js/napi/ability_manager/BUILD.gn b/frameworks/js/napi/ability_manager/BUILD.gn index fabcc40f67..2c4d636bcb 100644 --- a/frameworks/js/napi/ability_manager/BUILD.gn +++ b/frameworks/js/napi/ability_manager/BUILD.gn @@ -29,14 +29,11 @@ template("abilitymanager") { "js_ability_manager_utils.cpp", ] - include_dirs = [ - "./", - "//third_party/icu/icu4c/source/common", - "${ipc_native_path}/src/napi/include", - ] + include_dirs = [ "./" ] deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/napi_base_context:napi_base_context", "${ability_runtime_innerkits_path}/runtime:runtime", @@ -55,6 +52,7 @@ template("abilitymanager") { "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", "hilog:libhilog", + "icu:shared_icuuc", "ipc:ipc_core", "ipc:ipc_napi", "napi:ace_napi", diff --git a/frameworks/js/napi/ability_manager/js_ability_foreground_state_observer.cpp b/frameworks/js/napi/ability_manager/js_ability_foreground_state_observer.cpp index bb19683adf..05698d00cf 100644 --- a/frameworks/js/napi/ability_manager/js_ability_foreground_state_observer.cpp +++ b/frameworks/js/napi/ability_manager/js_ability_foreground_state_observer.cpp @@ -30,7 +30,7 @@ void JSAbilityForegroundStateObserver::OnAbilityStateChanged(const AbilityStateD { TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); if (!valid_) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "The app manager may has destoryed."); + TAG_LOGE(AAFwkTag::ABILITYMGR, "The app manager may has destroyed."); return; } wptr jsObserver = this; @@ -51,7 +51,7 @@ void JSAbilityForegroundStateObserver::OnAbilityStateChanged(const AbilityStateD void JSAbilityForegroundStateObserver::HandleOnAbilityStateChanged(const AbilityStateData &abilityStateData) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); - std::lock_guard lock(mutexlock); + std::lock_guard lock(mutexlock_); for (auto &item : jsObserverObjectSet_) { if (item == nullptr) { continue; @@ -112,7 +112,7 @@ void JSAbilityForegroundStateObserver::AddJsObserverObject(const napi_value &jsO } napi_ref ref = nullptr; napi_create_reference(env_, jsObserverObject, 1, &ref); - std::lock_guard lock(mutexlock); + std::lock_guard lock(mutexlock_); jsObserverObjectSet_.emplace(std::shared_ptr(reinterpret_cast(ref))); } @@ -124,7 +124,7 @@ void JSAbilityForegroundStateObserver::RemoveJsObserverObject(const napi_value & } auto observer = GetObserverObject(jsObserverObject); - std::lock_guard lock(mutexlock); + std::lock_guard lock(mutexlock_); if (observer != nullptr) { jsObserverObjectSet_.erase(observer); } @@ -132,7 +132,7 @@ void JSAbilityForegroundStateObserver::RemoveJsObserverObject(const napi_value & void JSAbilityForegroundStateObserver::RemoveAllJsObserverObject() { - std::lock_guard lock(mutexlock); + std::lock_guard lock(mutexlock_); if (!jsObserverObjectSet_.empty()) { jsObserverObjectSet_.clear(); } @@ -144,7 +144,7 @@ std::shared_ptr JSAbilityForegroundStateObserver::GetObserverOb TAG_LOGE(AAFwkTag::ABILITYMGR, "Observer is null."); return nullptr; } - std::lock_guard lock(mutexlock); + std::lock_guard lock(mutexlock_); for (auto &observer : jsObserverObjectSet_) { if (observer == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid observer."); diff --git a/frameworks/js/napi/ability_manager/js_ability_foreground_state_observer.h b/frameworks/js/napi/ability_manager/js_ability_foreground_state_observer.h index d6f1e00828..3723a0a9ff 100644 --- a/frameworks/js/napi/ability_manager/js_ability_foreground_state_observer.h +++ b/frameworks/js/napi/ability_manager/js_ability_foreground_state_observer.h @@ -47,7 +47,7 @@ public: private: napi_env env_; volatile bool valid_ = true; - std::mutex mutexlock; + std::mutex mutexlock_; std::set> jsObserverObjectSet_; }; } // namespace AbilityRuntime diff --git a/frameworks/js/napi/ability_manager/js_ability_manager_utils.cpp b/frameworks/js/napi/ability_manager/js_ability_manager_utils.cpp index f2fc9411cc..18c915a525 100644 --- a/frameworks/js/napi/ability_manager/js_ability_manager_utils.cpp +++ b/frameworks/js/napi/ability_manager/js_ability_manager_utils.cpp @@ -39,8 +39,8 @@ napi_value CreateJSToken(napi_env env, const sptr target) env, "TokenClass", NAPI_AUTO_LENGTH, constructorcb, nullptr, 0, nullptr, &tokenClass); napi_value jsToken = nullptr; napi_new_instance(env, tokenClass, 0, nullptr, &jsToken); - auto finalizecb = [](napi_env env, void *data, void *hint) {}; - napi_wrap(env, jsToken, static_cast(target.GetRefPtr()), finalizecb, nullptr, nullptr); + auto finalizercb = [](napi_env env, void *data, void *hint) {}; + napi_wrap(env, jsToken, static_cast(target.GetRefPtr()), finalizercb, nullptr, nullptr); return jsToken; } diff --git a/frameworks/js/napi/app/ability_delegator/BUILD.gn b/frameworks/js/napi/app/ability_delegator/BUILD.gn index d1834b0b4a..158c15d814 100644 --- a/frameworks/js/napi/app/ability_delegator/BUILD.gn +++ b/frameworks/js/napi/app/ability_delegator/BUILD.gn @@ -27,7 +27,6 @@ template("delegator") { "${ability_runtime_path}/interfaces/kits/native/appkit/ability_delegator/", "${ability_runtime_path}/interfaces/kits/native/ability/native", "${ability_runtime_path}/tools/aa/include", - "${ipc_native_path}/src/napi/include", ] sources = [ diff --git a/frameworks/js/napi/app/ability_delegator/js_ability_delegator.h b/frameworks/js/napi/app/ability_delegator/js_ability_delegator.h index b972359cfd..663d001214 100644 --- a/frameworks/js/napi/app/ability_delegator/js_ability_delegator.h +++ b/frameworks/js/napi/app/ability_delegator/js_ability_delegator.h @@ -46,7 +46,7 @@ public: ~JSAbilityDelegator() = default; /** - * Destory object. + * Destroy object. * * @param env Indicates the native engine. * @param data Indicates the object to be destroyed. diff --git a/frameworks/js/napi/app/app_manager/BUILD.gn b/frameworks/js/napi/app/app_manager/BUILD.gn index 4e371b4c55..f88d33ccb9 100644 --- a/frameworks/js/napi/app/app_manager/BUILD.gn +++ b/frameworks/js/napi/app/app_manager/BUILD.gn @@ -32,6 +32,7 @@ ohos_shared_library("appmanager_napi") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", diff --git a/frameworks/js/napi/app/app_manager/js_app_manager.cpp b/frameworks/js/napi/app/app_manager/js_app_manager.cpp index cb66c9468c..de626ce7f6 100644 --- a/frameworks/js/napi/app/app_manager/js_app_manager.cpp +++ b/frameworks/js/napi/app/app_manager/js_app_manager.cpp @@ -94,7 +94,7 @@ public: static napi_value KillProcessesByBundleName(napi_env env, napi_callback_info info) { TAG_LOGD(AAFwkTag::APPMGR, "KillProcessesByBundleName start."); - GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnkillProcessByBundleName); + GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnKillProcessByBundleName); } static napi_value ClearUpApplicationData(napi_env env, napi_callback_info info) @@ -130,7 +130,7 @@ private: } static int64_t serialNumber = 0; std::vector bundleNameList; - // unwarp observer + // unwrap observer if (observer_ == nullptr) { observer_ = new JSAppStateObserver(env); } @@ -310,9 +310,9 @@ private: return result; } - napi_value OnkillProcessByBundleName(napi_env env, size_t argc, napi_value* argv) + napi_value OnKillProcessByBundleName(napi_env env, size_t argc, napi_value* argv) { - TAG_LOGD(AAFwkTag::APPMGR, "OnkillProcessByBundleName called"); + TAG_LOGD(AAFwkTag::APPMGR, "called"); int32_t errCode = 0; std::string bundleName; @@ -350,7 +350,7 @@ private: napi_value lastParam = (argc == ARGC_TWO) ? argv[INDEX_ONE] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnkillProcessByBundleName", + NapiAsyncTask::ScheduleHighQos("JSAppManager::OnKillProcessByBundleName", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } diff --git a/frameworks/js/napi/app/app_manager/js_app_state_observer.cpp b/frameworks/js/napi/app/app_manager/js_app_state_observer.cpp index 23e2376bc8..5fe5949d42 100644 --- a/frameworks/js/napi/app/app_manager/js_app_state_observer.cpp +++ b/frameworks/js/napi/app/app_manager/js_app_state_observer.cpp @@ -47,8 +47,7 @@ void JSAppStateObserver::OnForegroundApplicationChanged(const AppStateData &appS void JSAppStateObserver::HandleOnForegroundApplicationChanged(const AppStateData &appStateData) { - TAG_LOGI(AAFwkTag::APPMGR, - "HandleOnForegroundApplicationChanged bundleName:%{public}s, uid:%{public}d, state:%{public}d.", + TAG_LOGI(AAFwkTag::APPMGR, "bundleName:%{public}s, uid:%{public}d, state:%{public}d.", appStateData.bundleName.c_str(), appStateData.uid, appStateData.state); auto tmpMap = jsObserverObjectMap_; for (auto &item : tmpMap) { diff --git a/frameworks/js/napi/app/app_manager/js_app_state_observer.h b/frameworks/js/napi/app/app_manager/js_app_state_observer.h index 34e3adf638..0c838fc3a5 100644 --- a/frameworks/js/napi/app/app_manager/js_app_state_observer.h +++ b/frameworks/js/napi/app/app_manager/js_app_state_observer.h @@ -29,7 +29,7 @@ using OHOS::AppExecFwk::ProcessData; class JSAppStateObserver : public ApplicationStateObserverStub { public: explicit JSAppStateObserver(napi_env engine); - ~JSAppStateObserver(); + virtual ~JSAppStateObserver(); void OnForegroundApplicationChanged(const AppStateData &appStateData) override; void OnAbilityStateChanged(const AbilityStateData &abilityStateData) override; void OnExtensionStateChanged(const AbilityStateData &abilityStateData) override; diff --git a/frameworks/js/napi/app/application_context/application_context.js b/frameworks/js/napi/app/application_context/application_context.js index 885d37f8e8..5c12391586 100644 --- a/frameworks/js/napi/app/application_context/application_context.js +++ b/frameworks/js/napi/app/application_context/application_context.js @@ -189,6 +189,10 @@ class ApplicationContext { return this.__context_impl__.setSupportedProcessCache(isSupport); } + getCurrentAppCloneIndex(){ + return this.__context_impl__.getCurrentAppCloneIndex() + } + set area(mode) { return this.__context_impl__.switchArea(mode); } diff --git a/frameworks/js/napi/app/error_manager/BUILD.gn b/frameworks/js/napi/app/error_manager/BUILD.gn index 8949155520..549a7041f7 100644 --- a/frameworks/js/napi/app/error_manager/BUILD.gn +++ b/frameworks/js/napi/app/error_manager/BUILD.gn @@ -34,6 +34,7 @@ template("errormanager") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_native_path}/appkit:appkit_native", diff --git a/frameworks/js/napi/app/error_manager/js_error_manager.cpp b/frameworks/js/napi/app/error_manager/js_error_manager.cpp index c5189a6c2b..6675901b8e 100644 --- a/frameworks/js/napi/app/error_manager/js_error_manager.cpp +++ b/frameworks/js/napi/app/error_manager/js_error_manager.cpp @@ -211,7 +211,7 @@ private: if (type == ON_OFF_TYPE_SYNC_LOOP) { if (!AppExecFwk::EventRunner::IsAppMainThread()) { TAG_LOGE(AAFwkTag::JSNAPI, "LoopObserver can only be set from main thread."); - ThrowInvaildCallerError(env); + ThrowInvalidCallerError(env); return CreateJsUndefined(env); } return OnSetLoopWatch(env, argc, argv); @@ -219,7 +219,7 @@ private: if (type == ON_OFF_TYPE_UNHANDLED_REJECTION) { if (!AppExecFwk::EventRunner::IsAppMainThread()) { TAG_LOGE(AAFwkTag::JSNAPI, "UnhandledRejectionObserver can only be set from main thread."); - ThrowInvaildCallerError(env); + ThrowInvalidCallerError(env); return CreateJsUndefined(env); } if (argc != ARGC_TWO) { @@ -327,7 +327,7 @@ private: if (type == ON_OFF_TYPE_SYNC_LOOP) { if (!AppExecFwk::EventRunner::IsAppMainThread()) { TAG_LOGE(AAFwkTag::JSNAPI, "LoopObserver can only be set from main thread."); - ThrowInvaildCallerError(env); + ThrowInvalidCallerError(env); return CreateJsUndefined(env); } return OnRemoveLoopWatch(env, argc, argv); @@ -335,7 +335,7 @@ private: if (type == ON_OFF_TYPE_UNHANDLED_REJECTION) { if (!AppExecFwk::EventRunner::IsAppMainThread()) { TAG_LOGE(AAFwkTag::JSNAPI, "UnhandledRejectionObserver can only be unset from main thread."); - ThrowInvaildCallerError(env); + ThrowInvalidCallerError(env); return CreateJsUndefined(env); } if (argc != ARGC_TWO && argc != ARGC_ONE) { @@ -418,7 +418,7 @@ private: return res; } } - TAG_LOGE(AAFwkTag::JSNAPI, "Remove UnhandledRjectionObserver failed"); + TAG_LOGE(AAFwkTag::JSNAPI, "Remove UnhandledRejectionObserver failed"); ThrowError(env, AbilityErrorCode::ERROR_CODE_OBSERVER_NOT_FOUND); return res; } @@ -479,15 +479,15 @@ private: std::unique_ptr complete = std::make_unique ([number](napi_env env, NapiAsyncTask &task, int32_t status) { if (loopObserver_ == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "CallbackTimeout: loopObserver_ is null."); + TAG_LOGE(AAFwkTag::JSNAPI, "loopObserver_ is null."); return; } if (loopObserver_->env == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "CallbackTimeout: env is null."); + TAG_LOGE(AAFwkTag::JSNAPI, "env is null."); return; } if (loopObserver_->observerObject == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "CallbackTimeout: observerObject is null."); + TAG_LOGE(AAFwkTag::JSNAPI, "observerObject is null."); return; } napi_value jsValue[] = { CreateJsValue(loopObserver_->env, number) }; diff --git a/frameworks/js/napi/app/js_app_manager/BUILD.gn b/frameworks/js/napi/app/js_app_manager/BUILD.gn index 7f9e7601b1..61a3b604aa 100644 --- a/frameworks/js/napi/app/js_app_manager/BUILD.gn +++ b/frameworks/js/napi/app/js_app_manager/BUILD.gn @@ -37,6 +37,7 @@ ohos_shared_library("appmanager") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/error_utils:ability_runtime_error_util", "${ability_runtime_innerkits_path}/runtime:runtime", diff --git a/frameworks/js/napi/app/js_app_manager/js_app_foreground_state_observer.cpp b/frameworks/js/napi/app/js_app_manager/js_app_foreground_state_observer.cpp index ae877cf792..6b33ee615a 100644 --- a/frameworks/js/napi/app/js_app_manager/js_app_foreground_state_observer.cpp +++ b/frameworks/js/napi/app/js_app_manager/js_app_foreground_state_observer.cpp @@ -29,7 +29,7 @@ void JSAppForegroundStateObserver::OnAppStateChanged(const AppStateData &appStat { TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (!valid_) { - TAG_LOGE(AAFwkTag::APPMGR, "The app manager may has destoryed."); + TAG_LOGE(AAFwkTag::APPMGR, "The app manager may has destroyed."); return; } wptr self = this; diff --git a/frameworks/js/napi/app/js_app_manager/js_app_manager.cpp b/frameworks/js/napi/app/js_app_manager/js_app_manager.cpp index add1fc82bf..95e033bb63 100644 --- a/frameworks/js/napi/app/js_app_manager/js_app_manager.cpp +++ b/frameworks/js/napi/app/js_app_manager/js_app_manager.cpp @@ -110,6 +110,11 @@ public: GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnIsRunningInStabilityTest); } + static napi_value GetRunningMultiAppInfo(napi_env env, napi_callback_info info) + { + GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnGetRunningMultiAppInfo); + } + static napi_value KillProcessWithAccount(napi_env env, napi_callback_info info) { GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnKillProcessWithAccount); @@ -117,7 +122,7 @@ public: static napi_value KillProcessesByBundleName(napi_env env, napi_callback_info info) { - GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnkillProcessesByBundleName); + GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnKillProcessesByBundleName); } static napi_value ClearUpApplicationData(napi_env env, napi_callback_info info) @@ -178,8 +183,8 @@ public: } napi_ref ref = nullptr; napi_create_reference(env, para, 1, &ref); - NativeReference* nativeReferece = reinterpret_cast(ref); - auto object = nativeReferece->GetNapiValue(); + NativeReference* nativeReference = reinterpret_cast(ref); + auto object = nativeReference->GetNapiValue(); napi_value method = nullptr; napi_get_named_property(env, object, methodName.c_str(), &method); if (method == nullptr) { @@ -478,7 +483,7 @@ private: int64_t observerId = -1; napi_get_value_int64(env, argv[INDEX_ONE], &observerId); if (observer_ == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "observer_ is nullptr, please register first"); + TAG_LOGE(AAFwkTag::APPMGR, "observer is nullptr, please register first"); ThrowInvalidParamError(env, "observer is nullptr, please register first"); return CreateJsUndefined(env); } @@ -640,6 +645,52 @@ private: return result; } + napi_value OnGetRunningMultiAppInfo(napi_env env, size_t argc, napi_value* argv) + { + TAG_LOGD(AAFwkTag::APPMGR, "called"); + if (!CheckCallerIsSystemApp()) { + TAG_LOGE(AAFwkTag::APPMGR, "Current app is not system app"); + ThrowError(env, AbilityErrorCode::ERROR_CODE_NOT_SYSTEM_APP); + return CreateJsUndefined(env); + } + // only support 1 params + if (argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::APPMGR, "Not enough arguments"); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + std::string bundleName; + if (!ConvertFromJsValue(env, argv[0], bundleName)) { + TAG_LOGE(AAFwkTag::APPMGR, "get bundleName failed!"); + ThrowInvalidParamError(env, "Parse param bundleName failed, must be a string"); + return CreateJsUndefined(env); + } + auto info = std::make_shared(); + auto innerErrorCode = std::make_shared(ERR_OK); + NapiAsyncTask::ExecuteCallback execute = + [appManager = appManager_, bundleName, innerErrorCode, info]() { + if (appManager == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "appManager nullptr"); + *innerErrorCode = static_cast(AbilityErrorCode::ERROR_CODE_INNER); + return; + } + *innerErrorCode = appManager->GetRunningMultiAppInfoByBundleName(bundleName, *info); + }; + NapiAsyncTask::CompleteCallback complete = + [innerErrorCode, info](napi_env env, NapiAsyncTask &task, int32_t status) { + if (*innerErrorCode == ERR_OK) { + task.ResolveWithNoError(env, CreateJsRunningMultiAppInfo(env, *info)); + } else { + task.Reject(env, CreateJsErrorByNativeErr(env, *innerErrorCode)); + } + }; + napi_value lastParam = nullptr; + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("JSAppManager::OnGetRunningMultiAppInfo", + env, CreateAsyncTaskWithLastParam(env, lastParam, std::move(execute), std::move(complete), &result)); + return result; + } + napi_value OnGetRunningProcessInformationByBundleType(napi_env env, size_t argc, napi_value* argv) { TAG_LOGD(AAFwkTag::APPMGR, "called"); @@ -694,7 +745,7 @@ private: return; } bool ret = abilityManager->IsRunningInStabilityTest(); - TAG_LOGI(AAFwkTag::APPMGR, "result:%{public}d", ret); + TAG_LOGD(AAFwkTag::APPMGR, "result:%{public}d", ret); task.ResolveWithNoError(env, CreateJsValue(env, ret)); }; @@ -705,9 +756,9 @@ private: return result; } - napi_value OnkillProcessesByBundleName(napi_env env, size_t argc, napi_value* argv) + napi_value OnKillProcessesByBundleName(napi_env env, size_t argc, napi_value* argv) { - TAG_LOGD(AAFwkTag::APPMGR, "OnkillProcessesByBundleName called"); + TAG_LOGD(AAFwkTag::APPMGR, "OnKillProcessesByBundleName called"); if (argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::APPMGR, "Params not match"); ThrowTooFewParametersError(env); @@ -739,7 +790,7 @@ private: napi_value lastParam = (argc == ARGC_TWO) ? argv[INDEX_ONE] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnkillProcessesByBundleName", + NapiAsyncTask::ScheduleHighQos("JSAppManager::OnKillProcessesByBundleName", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -1176,20 +1227,15 @@ napi_value JsAppManagerInit(napi_env env, napi_value exportObj) JsAppManager::KillProcessesByBundleName); BindNativeFunction(env, exportObj, "clearUpApplicationData", moduleName, JsAppManager::ClearUpApplicationData); - BindNativeFunction(env, exportObj, "getAppMemorySize", moduleName, - JsAppManager::GetAppMemorySize); - BindNativeFunction(env, exportObj, "isRamConstrainedDevice", moduleName, - JsAppManager::IsRamConstrainedDevice); - BindNativeFunction(env, exportObj, "isSharedBundleRunning", moduleName, - JsAppManager::IsSharedBundleRunning); - BindNativeFunction(env, exportObj, "getProcessMemoryByPid", moduleName, - JsAppManager::GetProcessMemoryByPid); + BindNativeFunction(env, exportObj, "getAppMemorySize", moduleName, JsAppManager::GetAppMemorySize); + BindNativeFunction(env, exportObj, "isRamConstrainedDevice", moduleName, JsAppManager::IsRamConstrainedDevice); + BindNativeFunction(env, exportObj, "isSharedBundleRunning", moduleName, JsAppManager::IsSharedBundleRunning); + BindNativeFunction(env, exportObj, "getProcessMemoryByPid", moduleName, JsAppManager::GetProcessMemoryByPid); BindNativeFunction(env, exportObj, "getRunningProcessInfoByBundleName", moduleName, JsAppManager::GetRunningProcessInfoByBundleName); - BindNativeFunction(env, exportObj, "isApplicationRunning", moduleName, - JsAppManager::IsApplicationRunning); - BindNativeFunction(env, exportObj, "preloadApplication", moduleName, - JsAppManager::PreloadApplication); + BindNativeFunction(env, exportObj, "getRunningMultiAppInfo", moduleName, JsAppManager::GetRunningMultiAppInfo); + BindNativeFunction(env, exportObj, "isApplicationRunning", moduleName, JsAppManager::IsApplicationRunning); + BindNativeFunction(env, exportObj, "preloadApplication", moduleName, JsAppManager::PreloadApplication); BindNativeFunction(env, exportObj, "getRunningProcessInformationByBundleType", moduleName, JsAppManager::GetRunningProcessInformationByBundleType); TAG_LOGD(AAFwkTag::APPMGR, "end"); diff --git a/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.cpp b/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.cpp index 7bc476e546..6ea784dc13 100644 --- a/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.cpp +++ b/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.cpp @@ -150,6 +150,47 @@ napi_value CreateJsRunningProcessInfo(napi_env env, const RunningProcessInfo &in return object; } +napi_value CreateJsRunningMultiAppInfo(napi_env env, const RunningMultiAppInfo &info) +{ + napi_value object = nullptr; + napi_create_object(env, &object); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "objValue nullptr."); + return nullptr; + } + napi_set_named_property(env, object, "bundleName", CreateJsValue(env, info.bundleName)); + napi_set_named_property(env, object, "mode", CreateJsValue(env, info.mode)); + napi_set_named_property(env, object, "runningAppClones", CreateJsRunningAppCloneArray(env, info.runningAppClones)); + + return object; +} + +napi_value CreateJsRunningAppCloneArray(napi_env env, const std::vector& data) +{ + napi_value arrayValue = nullptr; + napi_create_array_with_length(env, data.size(), &arrayValue); + uint32_t index = 0; + for (const auto &item : data) { + napi_set_element(env, arrayValue, index++, CreateJsRunningAppClone(env, item)); + } + return arrayValue; +} + +napi_value CreateJsRunningAppClone(napi_env env, const RunningAppClone &info) +{ + napi_value object = nullptr; + napi_create_object(env, &object); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "objValue nullptr."); + return nullptr; + } + napi_set_named_property(env, object, "appCloneIndex", CreateJsValue(env, info.appCloneIndex)); + napi_set_named_property(env, object, "uid", CreateJsValue(env, info.uid)); + napi_set_named_property(env, object, "pids", CreateNativeArray(env, info.pids)); + + return object; +} + napi_value ApplicationStateInit(napi_env env) { TAG_LOGD(AAFwkTag::APPMGR, "ApplicationStateInit enter"); diff --git a/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.h b/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.h index 4bb29199cc..e2d0ad9297 100644 --- a/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.h +++ b/frameworks/js/napi/app/js_app_manager/js_app_manager_utils.h @@ -19,6 +19,7 @@ #include "application_state_observer_stub.h" #include "native_engine/native_engine.h" #include "running_process_info.h" +#include "running_multi_info.h" #ifdef SUPPORT_GRAPHICS #include "ability_first_frame_state_data.h" #endif @@ -29,6 +30,8 @@ using OHOS::AppExecFwk::AppStateData; using OHOS::AppExecFwk::AbilityStateData; using OHOS::AppExecFwk::ProcessData; using OHOS::AppExecFwk::RunningProcessInfo; +using OHOS::AppExecFwk::RunningMultiAppInfo; +using OHOS::AppExecFwk::RunningAppClone; #ifdef SUPPORT_GRAPHICS using OHOS::AppExecFwk::AbilityFirstFrameStateData; #endif @@ -63,6 +66,9 @@ bool ConvertPreloadApplicationParam(napi_env env, size_t argc, napi_value *argv, std::string &errorMsg); JsAppProcessState ConvertToJsAppProcessState( const AppExecFwk::AppProcessState &appProcessState, const bool &isFocused); +napi_value CreateJsRunningMultiAppInfo(napi_env env, const RunningMultiAppInfo &info); +napi_value CreateJsRunningAppCloneArray(napi_env env, const std::vector& data); +napi_value CreateJsRunningAppClone(napi_env env, const RunningAppClone &info); } // namespace AbilityRuntime } // namespace OHOS #endif // OHOS_ABILITY_RUNTIME_JS_APP_MANAGER_UTILS_H diff --git a/frameworks/js/napi/app/js_app_manager/js_app_state_observer.cpp b/frameworks/js/napi/app/js_app_manager/js_app_state_observer.cpp index 817a8dafbc..de7aa3cc66 100644 --- a/frameworks/js/napi/app/js_app_manager/js_app_state_observer.cpp +++ b/frameworks/js/napi/app/js_app_manager/js_app_state_observer.cpp @@ -29,10 +29,10 @@ JSAppStateObserver::~JSAppStateObserver() = default; void JSAppStateObserver::OnForegroundApplicationChanged(const AppStateData &appStateData) { - TAG_LOGD(AAFwkTag::APPMGR, "onForegroundApplicationChanged bundleName:%{public}s, uid:%{public}d, state:%{public}d", + TAG_LOGD(AAFwkTag::APPMGR, "bundleName:%{public}s, uid:%{public}d, state:%{public}d", appStateData.bundleName.c_str(), appStateData.uid, appStateData.state); if (!valid_) { - TAG_LOGE(AAFwkTag::APPMGR, "the app manager may has destoryed"); + TAG_LOGE(AAFwkTag::APPMGR, "the app manager may has destroyed"); return; } wptr jsObserver = this; @@ -53,8 +53,7 @@ void JSAppStateObserver::OnForegroundApplicationChanged(const AppStateData &appS void JSAppStateObserver::HandleOnForegroundApplicationChanged(const AppStateData &appStateData) { - TAG_LOGD(AAFwkTag::APPMGR, - "HandleOnForegroundApplicationChanged bundleName:%{public}s, uid:%{public}d, state:%{public}d", + TAG_LOGD(AAFwkTag::APPMGR, "bundleName:%{public}s, uid:%{public}d, state:%{public}d", appStateData.bundleName.c_str(), appStateData.uid, appStateData.state); auto tmpMap = jsObserverObjectMap_; for (auto &item : tmpMap) { @@ -102,7 +101,7 @@ void JSAppStateObserver::OnExtensionStateChanged(const AbilityStateData &ability { TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!valid_) { - TAG_LOGE(AAFwkTag::APPMGR, "the app manager may has destoryed"); + TAG_LOGE(AAFwkTag::APPMGR, "the app manager may has destroyed"); return; } wptr jsObserver = this; @@ -170,7 +169,7 @@ void JSAppStateObserver::OnProcessStateChanged(const ProcessData &processData) { TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!valid_) { - TAG_LOGE(AAFwkTag::APPMGR, "the app manager may has destoryed"); + TAG_LOGE(AAFwkTag::APPMGR, "the app manager may has destroyed"); return; } wptr jsObserver = this; @@ -204,7 +203,7 @@ void JSAppStateObserver::OnProcessDied(const ProcessData &processData) { TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!valid_) { - TAG_LOGE(AAFwkTag::APPMGR, "the app manager may has destoryed"); + TAG_LOGE(AAFwkTag::APPMGR, "the app manager may has destroyed"); return; } wptr jsObserver = this; @@ -239,7 +238,7 @@ void JSAppStateObserver::OnAppStarted(const AppStateData &appStateData) TAG_LOGD(AAFwkTag::APPMGR, "onAppStarted bundleName:%{public}s, uid:%{public}d, state:%{public}d", appStateData.bundleName.c_str(), appStateData.uid, appStateData.state); if (!valid_) { - TAG_LOGE(AAFwkTag::APPMGR, "the app manager may has destoryed"); + TAG_LOGE(AAFwkTag::APPMGR, "the app manager may has destroyed"); return; } wptr jsObserver = this; @@ -279,7 +278,7 @@ void JSAppStateObserver::OnAppStopped(const AppStateData &appStateData) TAG_LOGD(AAFwkTag::APPMGR, "OnAppStopped bundleName:%{public}s, uid:%{public}d, state:%{public}d", appStateData.bundleName.c_str(), appStateData.uid, appStateData.state); if (!valid_) { - TAG_LOGE(AAFwkTag::APPMGR, "the app manager may has destoryed"); + TAG_LOGE(AAFwkTag::APPMGR, "the app manager may has destroyed"); return; } wptr jsObserver = this; diff --git a/frameworks/js/napi/app/recovery/BUILD.gn b/frameworks/js/napi/app/recovery/BUILD.gn index 27e1be5244..86a45387b1 100644 --- a/frameworks/js/napi/app/recovery/BUILD.gn +++ b/frameworks/js/napi/app/recovery/BUILD.gn @@ -32,6 +32,7 @@ ohos_shared_library("apprecovery_napi") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", diff --git a/frameworks/js/napi/app_startup/async_task_callback/async_task_callback.ts b/frameworks/js/napi/app_startup/async_task_callback/async_task_callback.ts index a27cc37299..6a7530ab1d 100644 --- a/frameworks/js/napi/app_startup/async_task_callback/async_task_callback.ts +++ b/frameworks/js/napi/app_startup/async_task_callback/async_task_callback.ts @@ -16,13 +16,13 @@ class AsyncTaskCallback { private __impl__: AsyncTaskCallback; constructor(object) { - "use sendable" + 'use sendable'; this.__impl__ = object; } - onAsyncTaskCompleted(startupName) { + onAsyncTaskCompleted(startupName, startupResult) { console.log('AsyncTaskCallback onAsyncTaskCompleted called, startupName: ' + startupName); - this.__impl__.onAsyncTaskCompleted(startupName); + this.__impl__.onAsyncTaskCompleted(startupName, startupResult); } } diff --git a/frameworks/js/napi/app_startup/async_task_excutor/async_task_excutor.ts b/frameworks/js/napi/app_startup/async_task_excutor/async_task_excutor.ts index d7cad8eea9..58aee08eda 100644 --- a/frameworks/js/napi/app_startup/async_task_excutor/async_task_excutor.ts +++ b/frameworks/js/napi/app_startup/async_task_excutor/async_task_excutor.ts @@ -13,26 +13,34 @@ * limitations under the License. */ -function concurrentFunc(startup, asyncCallback, context, startupName) { - "use concurrent"; +async function concurrentFunc(startup, asyncCallback, context, startupName) { + 'use concurrent'; console.log('concurrentFunc start.'); - let taskPool = requireNapi('taskpool'); - startup.init(context); - taskPool.Task.sendData(asyncCallback, startupName); + let startupResult; + await startup.init(context).then((result: Object) => { + startupResult = result + let taskPool = requireNapi('taskpool'); + taskPool.Task.sendData(asyncCallback, startupName, startupResult); + }); console.log('concurrentFunc end.'); } -function receiveResult(asyncCallback, startupName) { +function receiveResult(asyncCallback, startupName, startupResult) { console.log('receiveResult called.'); - asyncCallback.onAsyncTaskCompleted(startupName); + asyncCallback.onAsyncTaskCompleted(startupName, startupResult); + console.log('receiveResult end.'); } function pushTask(startup, asyncCallback, context, startupName) { console.log('pushTask start.'); let taskPool = requireNapi('taskpool'); - let task = new taskPool.Task(concurrentFunc, startup, asyncCallback, context, startupName); - task.onReceiveData(receiveResult); - taskPool.execute(task); + try { + let task = new taskPool.Task(concurrentFunc, startup, asyncCallback, context, startupName); + task.onReceiveData(receiveResult); + taskPool.execute(task); + } catch (error) { + console.log('new taskPool failed message:' + error); + } console.log('pushTask end.'); } diff --git a/frameworks/js/napi/app_startup/startup_task/startup_task.ts b/frameworks/js/napi/app_startup/startup_task/startup_task.ts index f2cdd0cef4..eee4a24f6f 100644 --- a/frameworks/js/napi/app_startup/startup_task/startup_task.ts +++ b/frameworks/js/napi/app_startup/startup_task/startup_task.ts @@ -14,8 +14,8 @@ */ class StartupTask { - constructor () { - "use sendable" + constructor() { + 'use sendable'; } onDependenceCompleted(dependence, result) { diff --git a/frameworks/js/napi/auto_fill_manager/BUILD.gn b/frameworks/js/napi/auto_fill_manager/BUILD.gn index bd0411f27e..2d6d8c3cf5 100644 --- a/frameworks/js/napi/auto_fill_manager/BUILD.gn +++ b/frameworks/js/napi/auto_fill_manager/BUILD.gn @@ -13,7 +13,6 @@ import("//build/ohos.gni") import("//foundation/ability/ability_runtime/ability_runtime.gni") -import("//foundation/arkui/ace_engine/ace_config.gni") ohos_shared_library("autofillmanager_napi") { sources = [ diff --git a/frameworks/js/napi/auto_fill_manager/js_auto_fill_manager.cpp b/frameworks/js/napi/auto_fill_manager/js_auto_fill_manager.cpp index 58b0ab586f..ddd4ca8dfe 100644 --- a/frameworks/js/napi/auto_fill_manager/js_auto_fill_manager.cpp +++ b/frameworks/js/napi/auto_fill_manager/js_auto_fill_manager.cpp @@ -53,13 +53,15 @@ napi_value JsAutoFillManager::OnRequestAutoSave(napi_env env, NapiCallbackInfo & napi_value instanceIdValue = nullptr; if (napi_get_named_property(env, info.argv[INDEX_ZERO], "instanceId_", &instanceIdValue) != napi_ok) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Get function by name failed."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowError(env, static_cast(AbilityErrorCode::ERROR_CODE_INVALID_PARAM), + "Parameter error. Get instance id failed."); return CreateJsUndefined(env); } int32_t instanceId = -1; if (!ConvertFromJsValue(env, instanceIdValue, instanceId)) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Failed to parse type."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowError(env, static_cast(AbilityErrorCode::ERROR_CODE_INVALID_PARAM), + "Parameter error. Parse instance id failed."); return CreateJsUndefined(env); } @@ -81,7 +83,8 @@ napi_value JsAutoFillManager::OnRequestAutoSave(napi_env env, NapiCallbackInfo & if (info.argc != ARGC_ONE) { if (!CheckTypeForNapiValue(env, info.argv[INDEX_ONE], napi_object)) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Second input parameter error."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowError(env, static_cast(AbilityErrorCode::ERROR_CODE_INVALID_PARAM), + "Parameter error. The second parameter is not of type callback."); return CreateJsUndefined(env); } saveCallback->Register(info.argv[INDEX_ONE]); diff --git a/frameworks/js/napi/callee/callee.js b/frameworks/js/napi/callee/callee.js index f527037bbe..6a573b38c8 100644 --- a/frameworks/js/napi/callee/callee.js +++ b/frameworks/js/napi/callee/callee.js @@ -51,10 +51,9 @@ class BusinessError extends Error { class ThrowInvalidParamError extends Error { constructor(msg) { - let code = ERROR_CODE_INVALID_PARAM; - let oriMsg = ERROR_MSG_INVALID_PARAM; - super(code); - this.msg = oriMsg + msg; + let message = ERROR_MSG_INVALID_PARAM + msg; + super(message); + this.code = ERROR_CODE_INVALID_PARAM; } } diff --git a/frameworks/js/napi/caller/caller.js b/frameworks/js/napi/caller/caller.js index a292e8eec3..f0e3a9cdfb 100644 --- a/frameworks/js/napi/caller/caller.js +++ b/frameworks/js/napi/caller/caller.js @@ -48,10 +48,9 @@ class BusinessError extends Error { class ThrowInvalidParamError extends Error { constructor(msg) { - let code = ERROR_CODE_INVALID_PARAM; - let oriMsg = ERROR_MSG_INVALID_PARAM; - super(code); - this.msg = oriMsg + msg; + let message = ERROR_MSG_INVALID_PARAM + msg; + super(message); + this.code = ERROR_CODE_INVALID_PARAM; } } diff --git a/frameworks/js/napi/featureAbility/BUILD.gn b/frameworks/js/napi/featureAbility/BUILD.gn index 89e2edc429..7470b9ac80 100644 --- a/frameworks/js/napi/featureAbility/BUILD.gn +++ b/frameworks/js/napi/featureAbility/BUILD.gn @@ -13,7 +13,6 @@ import("//build/ohos.gni") import("//foundation/ability/ability_runtime/ability_runtime.gni") -import("//foundation/distributeddatamgr/relational_store/relational_store.gni") ohos_shared_library("featureability") { include_dirs = [ "./" ] @@ -28,6 +27,7 @@ ohos_shared_library("featureability") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", "${ability_runtime_innerkits_path}/dataobs_manager:dataobs_manager", "${ability_runtime_innerkits_path}/napi_base_context:napi_base_context", @@ -37,7 +37,6 @@ ohos_shared_library("featureability") { "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_native_path}/ability/native:data_ability_helper", "${ability_runtime_native_path}/appkit:appkit_native", - "//third_party/libuv:uv", ] external_deps = [ @@ -50,6 +49,7 @@ ohos_shared_library("featureability") { "hilog:libhilog", "hitrace:hitrace_meter", "ipc:ipc_core", + "libuv:uv", "napi:ace_napi", ] diff --git a/frameworks/js/napi/featureAbility/feature_ability.cpp b/frameworks/js/napi/featureAbility/feature_ability.cpp index 3629c15949..71a34d8756 100644 --- a/frameworks/js/napi/featureAbility/feature_ability.cpp +++ b/frameworks/js/napi/featureAbility/feature_ability.cpp @@ -48,14 +48,6 @@ CallbackInfo g_aceCallbackInfo; const int PARA_SIZE_IS_ONE = 1; const int PARA_SIZE_IS_TWO = 2; -/** - * @brief FeatureAbility NAPI module registration. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ napi_value FeatureAbilityInit(napi_env env, napi_value exports) { TAG_LOGD(AAFwkTag::FA, "called"); @@ -441,14 +433,6 @@ napi_value JsFeatureAbility::OnGetWindow(napi_env env, napi_callback_info info) } #endif -/** - * @brief FeatureAbility NAPI method : setResult. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ napi_value NAPI_SetResult(napi_env env, napi_callback_info info) { TAG_LOGI(AAFwkTag::FA, "%{public}s,called", __func__); @@ -471,14 +455,6 @@ napi_value NAPI_SetResult(napi_env env, napi_callback_info info) return ret; } -/** - * @brief SetResult processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param asyncCallbackInfo Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ napi_value SetResultWrap(napi_env env, napi_callback_info info, AsyncCallbackInfo *asyncCallbackInfo) { TAG_LOGI(AAFwkTag::FA, "%{public}s,called", __func__); @@ -633,16 +609,6 @@ napi_value SetResultPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) } EXTERN_C_START -/** - * @brief The interface of onAbilityResult provided for ACE to call back to JS. - * - * @param requestCode Indicates the request code returned after the ability is started. - * @param resultCode Indicates the result code returned after the ability is started. - * @param resultData Indicates the data returned after the ability is started. - * @param cb The environment and call back info that the Node-API call is invoked under. - * - * @return The return value from NAPI C++ to JS for the module. - */ void CallOnAbilityResult(int requestCode, int resultCode, const Want &resultData, CallbackInfo callbackInfo) { TAG_LOGI(AAFwkTag::FA, "%{public}s,called", __func__); @@ -758,15 +724,6 @@ bool InnerUnwrapWant(napi_env env, napi_value args, Want &want) return UnwrapWant(env, jsWant, want); } -/** - * @brief Parse the parameters. - * - * @param param Indicates the parameters saved the parse result. - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * - * @return The return value from NAPI C++ to JS for the module. - */ napi_value UnwrapForResultParam(CallAbilityParam ¶m, napi_env env, napi_value args) { TAG_LOGI(AAFwkTag::FA, "%{public}s,called", __func__); @@ -804,15 +761,6 @@ napi_value UnwrapForResultParam(CallAbilityParam ¶m, napi_env env, napi_valu return result; } -/** - * @brief Parse the abilityResult parameters. - * - * @param param Indicates the want parameters saved the parse result. - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * - * @return The return value from NAPI C++ to JS for the module. - */ napi_value UnwrapAbilityResult(CallAbilityParam ¶m, napi_env env, napi_value args) { TAG_LOGI(AAFwkTag::FA, "%{public}s,called", __func__); diff --git a/frameworks/js/napi/featureAbility/feature_ability_constant.cpp b/frameworks/js/napi/featureAbility/feature_ability_constant.cpp index eab8f55e56..32b59b35f2 100644 --- a/frameworks/js/napi/featureAbility/feature_ability_constant.cpp +++ b/frameworks/js/napi/featureAbility/feature_ability_constant.cpp @@ -23,14 +23,6 @@ namespace OHOS { namespace AppExecFwk { -/** - * @brief FeatureAbilityConstantInit NAPI module registration. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ napi_value FAConstantInit(napi_env env, napi_value exports) { const int Window_Configuration_Zero = 100; diff --git a/frameworks/js/napi/featureAbility/napi_data_ability_helper.cpp b/frameworks/js/napi/featureAbility/napi_data_ability_helper.cpp index 1845dce9d3..818e630bbd 100644 --- a/frameworks/js/napi/featureAbility/napi_data_ability_helper.cpp +++ b/frameworks/js/napi/featureAbility/napi_data_ability_helper.cpp @@ -263,7 +263,7 @@ void AnalysisValuesBucket(NativeRdb::ValuesBucket &valuesBucket, const napi_env uint32_t arrLen = 0; napi_status status = napi_get_array_length(env, keys, &arrLen); if (status != napi_ok) { - TAG_LOGE(AAFwkTag::FA, "ValuesBucket errr"); + TAG_LOGE(AAFwkTag::FA, "ValuesBucket error"); return; } TAG_LOGI(AAFwkTag::FA, "ValuesBucket num:%{public}d ", arrLen); @@ -419,7 +419,7 @@ void InsertAsyncCompleteCB(napi_env env, napi_status status, void *data) void InsertPromiseCompleteCB(napi_env env, napi_status status, void *data) { - TAG_LOGI(AAFwkTag::FA, "NAPI_Insert, main event thread complete."); + TAG_LOGI(AAFwkTag::FA, "NAPI_Insert, main event thread complete."); DAHelperInsertCB *insertCB = static_cast(data); napi_value result = nullptr; napi_create_int32(env, insertCB->result, &result); diff --git a/frameworks/js/napi/featureAbility/napi_data_ability_operation.cpp b/frameworks/js/napi/featureAbility/napi_data_ability_operation.cpp index 58bb0c322e..2df1518915 100644 --- a/frameworks/js/napi/featureAbility/napi_data_ability_operation.cpp +++ b/frameworks/js/napi/featureAbility/napi_data_ability_operation.cpp @@ -103,7 +103,7 @@ napi_value BuildDataAbilityOperation( UnwrapDataAbilityPredicates(*predicates, env, jsPredicates); builder->WithPredicates(predicates); - // get expectedcount property + // get expectedCount property int expectedCount = 0; UnwrapInt32ByPropertyName(env, param, "expectedCount", expectedCount); TAG_LOGI(AAFwkTag::FA, "%{public}s, expectedCount:%{public}d", __func__, expectedCount); diff --git a/frameworks/js/napi/inner/napi_ability_common/BUILD.gn b/frameworks/js/napi/inner/napi_ability_common/BUILD.gn index 3017b49183..d76f8bae2e 100644 --- a/frameworks/js/napi/inner/napi_ability_common/BUILD.gn +++ b/frameworks/js/napi/inner/napi_ability_common/BUILD.gn @@ -32,6 +32,7 @@ ohos_shared_library("napi_ability_common") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", "${ability_runtime_innerkits_path}/napi_base_context:napi_base_context", "${ability_runtime_innerkits_path}/runtime:runtime", diff --git a/frameworks/js/napi/inner/napi_ability_common/feature_ability_common.h b/frameworks/js/napi/inner/napi_ability_common/feature_ability_common.h index 76ab0cc20d..2a090add85 100644 --- a/frameworks/js/napi/inner/napi_ability_common/feature_ability_common.h +++ b/frameworks/js/napi/inner/napi_ability_common/feature_ability_common.h @@ -15,6 +15,7 @@ #ifndef OHOS_ABILITY_RUNTIME_FEATURE_ABILITY_COMMON_H #define OHOS_ABILITY_RUNTIME_FEATURE_ABILITY_COMMON_H + #include "ability.h" #include "ability_info.h" #include "application_info.h" diff --git a/frameworks/js/napi/inner/napi_ability_common/js_feature_ability_common.h b/frameworks/js/napi/inner/napi_ability_common/js_feature_ability_common.h index 0e4cded4d7..f5405635fb 100644 --- a/frameworks/js/napi/inner/napi_ability_common/js_feature_ability_common.h +++ b/frameworks/js/napi/inner/napi_ability_common/js_feature_ability_common.h @@ -15,6 +15,7 @@ #ifndef OHOS_ABILITY_RUNTIME_JS_FEATURE_ABILITY_COMMON_H #define OHOS_ABILITY_RUNTIME_JS_FEATURE_ABILITY_COMMON_H + #include "ability.h" #include "ability_info.h" #include "abs_shared_result_set.h" diff --git a/frameworks/js/napi/inner/napi_ability_common/js_napi_common_ability.h b/frameworks/js/napi/inner/napi_ability_common/js_napi_common_ability.h index bcff1450ce..9d982dd686 100644 --- a/frameworks/js/napi/inner/napi_ability_common/js_napi_common_ability.h +++ b/frameworks/js/napi/inner/napi_ability_common/js_napi_common_ability.h @@ -127,7 +127,7 @@ public: napi_value CreateAbilityInfos(napi_env env, const std::vector &abilityInfos); napi_value CreateAppVersionInfo(napi_env env, const std::shared_ptr &appInfo); napi_value CreateWant(napi_env env, const std::shared_ptr &want); - bool UnwarpVerifyPermissionParams(napi_env env, napi_callback_info info, JsPermissionOptions &options); + bool UnwrapVerifyPermissionParams(napi_env env, napi_callback_info info, JsPermissionOptions &options); bool GetStringsValue(napi_env env, napi_value object, std::vector &strList); bool GetPermissionOptions(napi_env env, napi_value object, JsPermissionOptions &options); void AddFreeInstallObserver(napi_env env, const AAFwk::Want &want, napi_value callback, napi_value* result); diff --git a/frameworks/js/napi/inner/napi_ability_common/napi_common_ability.cpp b/frameworks/js/napi/inner/napi_ability_common/napi_common_ability.cpp index 19b179a514..b05d71c323 100644 --- a/frameworks/js/napi/inner/napi_ability_common/napi_common_ability.cpp +++ b/frameworks/js/napi/inner/napi_ability_common/napi_common_ability.cpp @@ -2991,20 +2991,20 @@ napi_value GetAbilityNameWrap(napi_env env, napi_callback_info info, AbilityName napi_value NAPI_GetAbilityNameCommon(napi_env env, napi_callback_info info, AbilityType abilityType) { TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s called.", __func__); - AbilityNameCB *ablityNameCB = CreateAbilityNameCBInfo(env); - if (ablityNameCB == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s ablityNameCB == nullptr", __func__); + AbilityNameCB *abilityNameCB = CreateAbilityNameCBInfo(env); + if (abilityNameCB == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s abilityNameCB == nullptr", __func__); return WrapVoidToJS(env); } - ablityNameCB->cbBase.errCode = NAPI_ERR_NO_ERROR; - ablityNameCB->cbBase.abilityType = abilityType; - napi_value ret = GetAbilityNameWrap(env, info, ablityNameCB); + abilityNameCB->cbBase.errCode = NAPI_ERR_NO_ERROR; + abilityNameCB->cbBase.abilityType = abilityType; + napi_value ret = GetAbilityNameWrap(env, info, abilityNameCB); if (ret == nullptr) { TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s ret == nullptr", __func__); - if (ablityNameCB != nullptr) { - delete ablityNameCB; - ablityNameCB = nullptr; + if (abilityNameCB != nullptr) { + delete abilityNameCB; + abilityNameCB = nullptr; } ret = WrapVoidToJS(env); } @@ -3131,7 +3131,7 @@ bool UnwrapParamForWant(napi_env env, napi_value args, AbilityType, CallAbilityP if (jsSettingObj != nullptr) { param.setting = AbilityStartSetting::GetEmptySetting(); if (!UnwrapAbilityStartSetting(env, jsSettingObj, *(param.setting))) { - TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, unwrap abilityStartSetting falied.", __func__); + TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, unwrap abilityStartSetting failed.", __func__); } TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s abilityStartSetting", __func__); } @@ -3743,7 +3743,7 @@ void StartBackgroundRunningExecuteCB(napi_env env, void *data) } const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); if (info == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "abilityinfo is null"); + TAG_LOGE(AAFwkTag::JSNAPI, "ability info is null"); asyncCallbackInfo->errCode = NAPI_ERR_ACE_ABILITY; return; } @@ -3900,7 +3900,7 @@ napi_value NAPI_StartBackgroundRunningCommon(napi_env env, napi_callback_info in TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s called.", __func__); AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); if (asyncCallbackInfo == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s asyncCallbackInfo == nullpter", __func__); + TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s asyncCallbackInfo == nullptr", __func__); return WrapVoidToJS(env); } @@ -4018,14 +4018,14 @@ napi_value NAPI_CancelBackgroundRunningCommon(napi_env env, napi_callback_info i TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s called.", __func__); AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); if (asyncCallbackInfo == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s asyncCallbackInfo == nullpter", __func__); + TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s asyncCallbackInfo == nullptr", __func__); return WrapVoidToJS(env); } asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; napi_value ret = CancelBackgroundRunningWrap(env, info, asyncCallbackInfo); if (ret == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s ret == nullpter", __func__); + TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s ret == nullptr", __func__); if (asyncCallbackInfo != nullptr) { delete asyncCallbackInfo; asyncCallbackInfo = nullptr; @@ -4119,7 +4119,7 @@ napi_value JsNapiCommon::JsConnectAbility(napi_env env, napi_callback_info info, connectionCallback->Reset(); RemoveConnectionLocked(want); } - // free failedcallback here, avoid possible multi-threading problems when disconnect success + // free failed callback here, avoid possible multi-threading problems when disconnect success napi_delete_reference(env, connectionCallback->failedCallbackRef); connectionCallback->failedCallbackRef = nullptr; return CreateJsValue(env, id); @@ -4454,7 +4454,7 @@ napi_value JsNapiCommon::JsGetCacheDir(napi_env env, napi_callback_info info, co auto context = obj->ability_->GetAbilityContext(); if (context == nullptr) { *value = static_cast(NAPI_ERR_ABILITY_CALL_INVALID); - TAG_LOGE(AAFwkTag::JSNAPI, "JsGetCacheDir task execute error, the abilitycontext is nullptr"); + TAG_LOGE(AAFwkTag::JSNAPI, "JsGetCacheDir task execute error, the ability context is nullptr"); return; } dir->name = context->GetCacheDir(); @@ -4706,7 +4706,7 @@ napi_value JsNapiCommon::JsGetOrCreateDistributedDir( auto context = obj->ability_->GetAbilityContext(); if (context == nullptr) { *value = static_cast(NAPI_ERR_ACE_ABILITY); - TAG_LOGE(AAFwkTag::JSNAPI, "task execute error, the abilitycontext is nullptr"); + TAG_LOGE(AAFwkTag::JSNAPI, "task execute error, the ability context is nullptr"); return; } dir->name = context->GetDistributedFilesDir(); @@ -5041,7 +5041,7 @@ napi_value JsNapiCommon::CreateAppVersionInfo(napi_env env, const std::shared_pt return objContext; } -bool JsNapiCommon::UnwarpVerifyPermissionParams(napi_env env, napi_callback_info info, JsPermissionOptions &options) +bool JsNapiCommon::UnwrapVerifyPermissionParams(napi_env env, napi_callback_info info, JsPermissionOptions &options) { bool flagCall = true; size_t argc = ARGS_MAX_COUNT; diff --git a/frameworks/js/napi/inner/napi_ability_common/napi_context.cpp b/frameworks/js/napi/inner/napi_ability_common/napi_context.cpp index 652973bce6..6452bda319 100644 --- a/frameworks/js/napi/inner/napi_ability_common/napi_context.cpp +++ b/frameworks/js/napi/inner/napi_ability_common/napi_context.cpp @@ -2879,12 +2879,12 @@ static napi_value ConstructNapiJSContext(napi_env env) TAG_LOGE(AAFwkTag::JSNAPI, "CreateObject failed"); return nullptr; } - auto jsCalss = std::make_unique(); - if (!jsCalss->DataInit(env)) { + auto jsClass = std::make_unique(); + if (!jsClass->DataInit(env)) { TAG_LOGE(AAFwkTag::JSNAPI, "NapiJsContext init failed"); return nullptr; } - napi_wrap(env, objContext, jsCalss.release(), NapiJsContext::Finalizer, nullptr, nullptr); + napi_wrap(env, objContext, jsClass.release(), NapiJsContext::Finalizer, nullptr, nullptr); napi_set_named_property(env, objContext, "stageMode", CreateJsValue(env, false)); if (!BindNapiJSContextFunction(env, objContext)) { TAG_LOGE(AAFwkTag::JSNAPI, "bind func failed"); @@ -3318,7 +3318,7 @@ napi_value NapiJsContext::OnVerifyPermission(napi_env env, napi_callback_info in return CreateJsNull(env); } JsPermissionOptions options; - bool flagCall = UnwarpVerifyPermissionParams(env, info, options); + bool flagCall = UnwrapVerifyPermissionParams(env, info, options); auto execute = [obj = this, permission, options, value = errorVal] () { if (obj->ability_ == nullptr) { *value = static_cast(NAPI_ERR_ACE_ABILITY); @@ -3599,7 +3599,7 @@ napi_value NapiJsContext::OnGetOrCreateLocalDir(napi_env env, napi_callback_info auto context = obj->ability_->GetAbilityContext(); if (context == nullptr || dir == nullptr) { *value = static_cast(NAPI_ERR_ABILITY_CALL_INVALID); - TAG_LOGE(AAFwkTag::JSNAPI, "task execute error, the abilitycontext is nullptr"); + TAG_LOGE(AAFwkTag::JSNAPI, "task execute error, the ability context is nullptr"); return; } dir->name = context->GetBaseDir(); diff --git a/frameworks/js/napi/inner/napi_common/BUILD.gn b/frameworks/js/napi/inner/napi_common/BUILD.gn index 24ecbcb124..cbc06d8d9f 100644 --- a/frameworks/js/napi/inner/napi_common/BUILD.gn +++ b/frameworks/js/napi/inner/napi_common/BUILD.gn @@ -42,9 +42,9 @@ ohos_shared_library("napi_common") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:process_options", "${ability_runtime_innerkits_path}/runtime:runtime", - "//third_party/libuv:uv", ] external_deps = [ @@ -57,6 +57,7 @@ ohos_shared_library("napi_common") { "hilog:libhilog", "ipc:ipc_core", "ipc:ipc_napi", + "libuv:uv", "napi:ace_napi", ] diff --git a/frameworks/js/napi/inner/napi_common/napi_common_execute_result.cpp b/frameworks/js/napi/inner/napi_common/napi_common_execute_result.cpp index 4fad091ba5..8f1c3c1f7a 100644 --- a/frameworks/js/napi/inner/napi_common/napi_common_execute_result.cpp +++ b/frameworks/js/napi/inner/napi_common/napi_common_execute_result.cpp @@ -36,7 +36,7 @@ bool UnwrapExecuteResult(napi_env env, napi_value param, InsightIntentExecuteRes } int32_t code = 0; if (!UnwrapInt32ByPropertyName(env, param, "code", code)) { - TAG_LOGE(AAFwkTag::JSNAPI, "Intent result must contian a code."); + TAG_LOGE(AAFwkTag::JSNAPI, "Intent result must contain a code."); return false; } executeResult.code = code; diff --git a/frameworks/js/napi/inner/napi_common/open_link/napi_common_open_link_options.cpp b/frameworks/js/napi/inner/napi_common/open_link/napi_common_open_link_options.cpp index 611b19ba65..0f6c415565 100644 --- a/frameworks/js/napi/inner/napi_common/open_link/napi_common_open_link_options.cpp +++ b/frameworks/js/napi/inner/napi_common/open_link/napi_common_open_link_options.cpp @@ -46,6 +46,9 @@ bool UnwrapOpenLinkOptions(napi_env env, napi_value param, AAFwk::OpenLinkOption openLinkOptions.SetAppLinkingOnly(appLinkingOnly); want.SetParam(APP_LINKING_ONLY, appLinkingOnly); } + if (!want.HasParameter(APP_LINKING_ONLY)) { + want.SetParam(APP_LINKING_ONLY, false); + } return true; } diff --git a/frameworks/js/napi/insight_intent/insight_intent_driver/BUILD.gn b/frameworks/js/napi/insight_intent/insight_intent_driver/BUILD.gn index d7c8410cac..d8b47e45fa 100644 --- a/frameworks/js/napi/insight_intent/insight_intent_driver/BUILD.gn +++ b/frameworks/js/napi/insight_intent/insight_intent_driver/BUILD.gn @@ -25,6 +25,7 @@ ohos_shared_library("insightintentdriver_napi") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/ability/native:ability_business_error", diff --git a/frameworks/js/napi/js_dialog_request/js_dialog_request.cpp b/frameworks/js/napi/js_dialog_request/js_dialog_request.cpp index 2dd74532f0..ff9d5239f5 100755 --- a/frameworks/js/napi/js_dialog_request/js_dialog_request.cpp +++ b/frameworks/js/napi/js_dialog_request/js_dialog_request.cpp @@ -105,8 +105,8 @@ private: auto requestInfo = new RequestInfo(callerToken, left, top, width, height); auto jsRequestInfo = RequestInfo::WrapRequestInfo(env, requestInfo); if (jsRequestInfo == nullptr) { - TAG_LOGE(AAFwkTag::DIALOG, "Can not wrap requestinfo from target request."); - ThrowInvalidParamError(env, "Parameter error: Can not wrap requestinfo from target request."); + TAG_LOGE(AAFwkTag::DIALOG, "Can not wrap request info from target request."); + ThrowInvalidParamError(env, "Parameter error: Can not wrap request info from target request."); return CreateJsUndefined(env); } diff --git a/frameworks/js/napi/js_dialog_session/BUILD.gn b/frameworks/js/napi/js_dialog_session/BUILD.gn index f9f13c8882..1e92d32013 100644 --- a/frameworks/js/napi/js_dialog_session/BUILD.gn +++ b/frameworks/js/napi/js_dialog_session/BUILD.gn @@ -27,11 +27,10 @@ ohos_shared_library("dialogsession_napi") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/appkit:app_context", - "//third_party/json:nlohmann_json_static", - "//third_party/jsoncpp:jsoncpp", ] external_deps = [ @@ -45,6 +44,8 @@ ohos_shared_library("dialogsession_napi") { "hilog:libhilog", "init:libbegetutil", "ipc:ipc_core", + "json:nlohmann_json_static", + "jsoncpp:jsoncpp", "napi:ace_napi", "samgr:samgr_proxy", ] diff --git a/frameworks/js/napi/js_dialog_session/js_dialog_session_utils.cpp b/frameworks/js/napi/js_dialog_session/js_dialog_session_utils.cpp index 6ce7948f5b..a67fcee65f 100644 --- a/frameworks/js/napi/js_dialog_session/js_dialog_session_utils.cpp +++ b/frameworks/js/napi/js_dialog_session/js_dialog_session_utils.cpp @@ -66,6 +66,8 @@ napi_value WrapDialogAbilityInfo(napi_env env, const AAFwk::DialogAbilityInfo &d SetPropertyValueByPropertyName(env, jsObject, "abilityIconId", jsValue); jsValue = WrapInt32ToJS(env, dialogAbilityInfo.abilityLabelId); SetPropertyValueByPropertyName(env, jsObject, "abilityLabelId", jsValue); + jsValue = WrapBoolToJS(env, dialogAbilityInfo.visible); + SetPropertyValueByPropertyName(env, jsObject, "visible", jsValue); return jsObject; } diff --git a/frameworks/js/napi/js_mission_manager/BUILD.gn b/frameworks/js/napi/js_mission_manager/BUILD.gn index 1fe7df0ec1..2353569778 100755 --- a/frameworks/js/napi/js_mission_manager/BUILD.gn +++ b/frameworks/js/napi/js_mission_manager/BUILD.gn @@ -28,6 +28,7 @@ ohos_shared_library("missionmanager") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", @@ -46,9 +47,9 @@ ohos_shared_library("missionmanager") { ] if (ability_runtime_graphics) { - include_dirs += [ "//third_party/icu/icu4c/source/common" ] external_deps += [ "graphic_2d:color_manager", + "icu:shared_icuuc", "image_framework:image", ] defines = [ "SUPPORT_GRAPHICS" ] diff --git a/frameworks/js/napi/js_mission_manager/mission_manager.cpp b/frameworks/js/napi/js_mission_manager/mission_manager.cpp index dcad35035d..9358a6111d 100755 --- a/frameworks/js/napi/js_mission_manager/mission_manager.cpp +++ b/frameworks/js/napi/js_mission_manager/mission_manager.cpp @@ -265,7 +265,7 @@ private: napi_value lastParam = (argc <= ARG_COUNT_TWO) ? nullptr : argv[INDEX_TWO]; napi_value result = nullptr; - NapiAsyncTask::Schedule("MissioManager::OnUnregisterMissionListener", + NapiAsyncTask::Schedule("MissionManager::OnUnregisterMissionListener", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -350,7 +350,7 @@ private: napi_value lastParam = (argc <= 2) ? nullptr : argv[2]; napi_value result = nullptr; - NapiAsyncTask::Schedule("MissioManager::OnGetMissionInfos", + NapiAsyncTask::Schedule("MissionManager::OnGetMissionInfos", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -390,7 +390,7 @@ private: napi_value lastParam = (argc <= 2) ? nullptr : argv[2]; napi_value result = nullptr; - NapiAsyncTask::Schedule("MissioManager::OnGetMissionInfo", + NapiAsyncTask::Schedule("MissionManager::OnGetMissionInfo", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -423,7 +423,7 @@ private: }; std::shared_ptr snapshotWrap = std::make_shared(); - auto excute = [deviceId, missionId, isLowResolution, snapshotWrap]() { + auto execute = [deviceId, missionId, isLowResolution, snapshotWrap]() { snapshotWrap->result = AbilityManagerClient::GetInstance()->GetMissionSnapshot( deviceId, missionId, snapshotWrap->missionSnapshot, isLowResolution); }; @@ -452,8 +452,8 @@ private: }; napi_value lastParam = (argc > ARG_COUNT_TWO) ? argv[ARG_COUNT_TWO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::Schedule("MissioManager::OnGetMissionSnapShot", - env, CreateAsyncTaskWithLastParam(env, lastParam, std::move(excute), std::move(complete), &result)); + NapiAsyncTask::Schedule("MissionManager::OnGetMissionSnapShot", + env, CreateAsyncTaskWithLastParam(env, lastParam, std::move(execute), std::move(complete), &result)); return result; } @@ -508,7 +508,7 @@ private: napi_value lastParam = (argc > 1) ? argv[1] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("MissioManager::OnLockMission", + NapiAsyncTask::ScheduleHighQos("MissionManager::OnLockMission", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -541,7 +541,7 @@ private: napi_value lastParam = (argc > 1) ? argv[1] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("MissioManager::OnUnlockMission", + NapiAsyncTask::ScheduleHighQos("MissionManager::OnUnlockMission", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -574,7 +574,7 @@ private: napi_value lastParam = (argc > 1) ? argv[1] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("MissioManager::OnClearMission", + NapiAsyncTask::ScheduleHighQos("MissionManager::OnClearMission", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -595,7 +595,7 @@ private: napi_value lastParam = (argc > 0) ? argv[0] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("MissioManager::OnMoveMissionToFront", + NapiAsyncTask::ScheduleHighQos("MissionManager::OnMoveMissionToFront", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -636,7 +636,7 @@ private: napi_value lastParam = (argc > unwrapArgc) ? argv[unwrapArgc] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("MissioManager::OnMoveMissionToFront", + NapiAsyncTask::ScheduleHighQos("MissionManager::OnMoveMissionToFront", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -694,7 +694,7 @@ private: napi_value lastParam = (argc > unwrapArgc) ? argv[unwrapArgc] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("MissioManager::OnMoveMissionsToForeground", env, + NapiAsyncTask::ScheduleHighQos("MissionManager::OnMoveMissionsToForeground", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -748,7 +748,7 @@ private: napi_value lastParam = (argc <= 1) ? nullptr : argv[1]; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("MissioManager::OnMoveMissionsToBackground", + NapiAsyncTask::ScheduleHighQos("MissionManager::OnMoveMissionsToBackground", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } diff --git a/frameworks/js/napi/mission_manager/BUILD.gn b/frameworks/js/napi/mission_manager/BUILD.gn index d6d34b212e..63f104937b 100644 --- a/frameworks/js/napi/mission_manager/BUILD.gn +++ b/frameworks/js/napi/mission_manager/BUILD.gn @@ -28,6 +28,7 @@ ohos_shared_library("missionmanager_napi") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", @@ -45,9 +46,9 @@ ohos_shared_library("missionmanager_napi") { ] if (ability_runtime_graphics) { - include_dirs += [ "//third_party/icu/icu4c/source/common" ] external_deps += [ "graphic_2d:color_manager", + "icu:shared_icuuc", "image_framework:image", ] defines = [ "SUPPORT_GRAPHICS" ] @@ -60,10 +61,7 @@ ohos_shared_library("missionmanager_napi") { } ohos_shared_library("distributedmissionmanager") { - include_dirs = [ - "//third_party/libuv/include", - "//third_party/node/src", - ] + include_dirs = [] configs = [ "${ability_runtime_services_path}/common:common_config" ] @@ -81,6 +79,7 @@ ohos_shared_library("distributedmissionmanager") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_napi_path}/inner/napi_common:napi_common", @@ -96,7 +95,9 @@ ohos_shared_library("distributedmissionmanager") { "hilog:libhilog", "init:libbegetutil", "ipc:ipc_core", + "libuv:uv", "napi:ace_napi", + "node:node_header_notice", "samgr:samgr_proxy", ] diff --git a/frameworks/js/napi/mission_manager/distributed_mission_manager.cpp b/frameworks/js/napi/mission_manager/distributed_mission_manager.cpp index 9fc59d5a4a..9906b0b7fa 100644 --- a/frameworks/js/napi/mission_manager/distributed_mission_manager.cpp +++ b/frameworks/js/napi/mission_manager/distributed_mission_manager.cpp @@ -2066,6 +2066,7 @@ void UvWorkOnContinueDone(uv_work_t *work, int status) result = WrapInt32(continueAbilityCB->cbBase.cbInfo.env, continueAbilityCB->resultCode, "code"); } if (continueAbilityCB->cbBase.deferred == nullptr) { + std::lock_guard autoLock(registrationLock_); napi_value callback = nullptr; napi_value undefined = nullptr; napi_get_undefined(continueAbilityCB->cbBase.cbInfo.env, &undefined); @@ -2075,6 +2076,7 @@ void UvWorkOnContinueDone(uv_work_t *work, int status) napi_call_function(continueAbilityCB->cbBase.cbInfo.env, undefined, callback, 1, &result, &callResult); if (continueAbilityCB->cbBase.cbInfo.callback != nullptr) { napi_delete_reference(continueAbilityCB->cbBase.cbInfo.env, continueAbilityCB->cbBase.cbInfo.callback); + continueAbilityCB->cbBase.cbInfo.callback = nullptr; } } else { napi_value result[2] = { nullptr }; diff --git a/frameworks/js/napi/mission_manager/mission_manager.cpp b/frameworks/js/napi/mission_manager/mission_manager.cpp index 7fa84622cc..8c5f1b146a 100644 --- a/frameworks/js/napi/mission_manager/mission_manager.cpp +++ b/frameworks/js/napi/mission_manager/mission_manager.cpp @@ -182,7 +182,7 @@ private: napi_value lastParam = (argc <= 1) ? nullptr : argv[1]; napi_value result = nullptr; - NapiAsyncTask::Schedule("MissioManager::OnUnregisterMissionListener", + NapiAsyncTask::Schedule("MissionManager::OnUnregisterMissionListener", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -222,7 +222,7 @@ private: napi_value lastParam = (argc <= 2) ? nullptr : argv[2]; napi_value result = nullptr; - NapiAsyncTask::Schedule("MissioManager::OnGetMissionInfos", + NapiAsyncTask::Schedule("MissionManager::OnGetMissionInfos", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -262,7 +262,7 @@ private: napi_value lastParam = (argc <= 2) ? nullptr : argv[2]; napi_value result = nullptr; - NapiAsyncTask::Schedule("MissioManager::OnGetMissionInfo", + NapiAsyncTask::Schedule("MissionManager::OnGetMissionInfo", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -323,7 +323,7 @@ private: }; napi_value lastParam = (argc > ARG_COUNT_TWO) ? argv[ARG_COUNT_TWO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::Schedule("MissioManager::GetMissionSnapShot", + NapiAsyncTask::Schedule("MissionManager::GetMissionSnapShot", env, CreateAsyncTaskWithLastParam(env, lastParam, std::move(excute), std::move(complete), &result)); return result; } @@ -379,7 +379,7 @@ private: napi_value lastParam = (argc > 1) ? argv[1] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("MissioManager::OnLockMission", + NapiAsyncTask::ScheduleHighQos("MissionManager::OnLockMission", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -412,7 +412,7 @@ private: napi_value lastParam = (argc > 1) ? argv[1] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("MissioManager::OnUnlockMission", + NapiAsyncTask::ScheduleHighQos("MissionManager::OnUnlockMission", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -445,7 +445,7 @@ private: napi_value lastParam = (argc > 1) ? argv[1] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("MissioManager::OnClearMission", + NapiAsyncTask::ScheduleHighQos("MissionManager::OnClearMission", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -466,7 +466,7 @@ private: napi_value lastParam = (argc > 0) ? argv[0] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("MissioManager::OnMoveMissionToFront", + NapiAsyncTask::ScheduleHighQos("MissionManager::OnMoveMissionToFront", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } @@ -507,7 +507,7 @@ private: napi_value lastParam = (argc > unwrapArgc) ? argv[unwrapArgc] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("MissioManager::OnMoveMissionToFront", + NapiAsyncTask::ScheduleHighQos("MissionManager::OnMoveMissionToFront", env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); return result; } diff --git a/frameworks/js/napi/particleAbility/BUILD.gn b/frameworks/js/napi/particleAbility/BUILD.gn index 2bd41b9641..d8be1e9f79 100644 --- a/frameworks/js/napi/particleAbility/BUILD.gn +++ b/frameworks/js/napi/particleAbility/BUILD.gn @@ -13,15 +13,11 @@ import("//build/ohos.gni") import("//foundation/ability/ability_runtime/ability_runtime.gni") -import("//foundation/distributeddatamgr/relational_store/relational_store.gni") ohos_shared_library("particleability") { include_dirs = [ - "//third_party/node/src", "${ability_runtime_napi_path}/featureAbility", "${ability_runtime_services_path}/common/include", - "//third_party/jsoncpp", - "//third_party/jsoncpp/include/json", ] sources = [ @@ -35,6 +31,7 @@ ohos_shared_library("particleability") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/dataobs_manager:dataobs_manager", "${ability_runtime_innerkits_path}/napi_base_context:napi_base_context", "${ability_runtime_innerkits_path}/runtime:runtime", @@ -44,8 +41,6 @@ ohos_shared_library("particleability") { "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_native_path}/ability/native:data_ability_helper", "${ability_runtime_native_path}/appkit:appkit_native", - "//third_party/jsoncpp:jsoncpp", - "//third_party/libuv:uv", ] external_deps = [ @@ -58,7 +53,10 @@ ohos_shared_library("particleability") { "hilog:libhilog", "hitrace:hitrace_meter", "ipc:ipc_core", + "jsoncpp:jsoncpp", + "libuv:uv", "napi:ace_napi", + "node:node_header_notice", ] if (ability_runtime_relational) { diff --git a/frameworks/js/napi/uri_permission/js_uri_perm_mgr.cpp b/frameworks/js/napi/uri_permission/js_uri_perm_mgr.cpp index a3df8ef79a..9e462b7363 100644 --- a/frameworks/js/napi/uri_permission/js_uri_perm_mgr.cpp +++ b/frameworks/js/napi/uri_permission/js_uri_perm_mgr.cpp @@ -175,7 +175,7 @@ private: napi_value CreateJsUriPermMgr(napi_env env, napi_value exportObj) { - TAG_LOGI(AAFwkTag::URIPERMMGR, "CreateJsUriPermMgr is called"); + TAG_LOGD(AAFwkTag::URIPERMMGR, "CreateJsUriPermMgr is called"); if (env == nullptr || exportObj == nullptr) { TAG_LOGI(AAFwkTag::URIPERMMGR, "Invalid input parameters"); return nullptr; diff --git a/frameworks/js/napi/wantagent/BUILD.gn b/frameworks/js/napi/wantagent/BUILD.gn index 61b9d1020e..d27b8302b5 100644 --- a/frameworks/js/napi/wantagent/BUILD.gn +++ b/frameworks/js/napi/wantagent/BUILD.gn @@ -16,9 +16,7 @@ import("//foundation/ability/ability_runtime/ability_runtime.gni") ohos_shared_library("wantagent") { include_dirs = [ - "//third_party/node/src", "${ability_runtime_services_path}/common/include", - "//third_party/libuv/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime", "${ability_runtime_services_path}/abilitymgr/include", "./", @@ -30,7 +28,7 @@ ohos_shared_library("wantagent") { ] deps = [ - "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/error_utils:ability_runtime_error_util", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_innerkits_path}/wantagent:wantagent_innerkits", @@ -46,7 +44,9 @@ ohos_shared_library("wantagent") { "common_event_service:cesfwk_innerkits", "hilog:libhilog", "ipc:ipc_core", + "libuv:uv", "napi:ace_napi", + "node:node_header_notice", ] relative_install_dir = "module" diff --git a/frameworks/js/napi/wantagent/ability_want_agent/BUILD.gn b/frameworks/js/napi/wantagent/ability_want_agent/BUILD.gn index 6a861361f8..bdde0232e8 100644 --- a/frameworks/js/napi/wantagent/ability_want_agent/BUILD.gn +++ b/frameworks/js/napi/wantagent/ability_want_agent/BUILD.gn @@ -16,9 +16,7 @@ import("//foundation/ability/ability_runtime/ability_runtime.gni") ohos_shared_library("wantagent_napi") { include_dirs = [ - "//third_party/node/src", "${ability_runtime_services_path}/common/include", - "//third_party/libuv/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime", "${ability_runtime_services_path}/abilitymgr/include", "./", @@ -31,7 +29,7 @@ ohos_shared_library("wantagent_napi") { ] deps = [ - "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/error_utils:ability_runtime_error_util", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_innerkits_path}/wantagent:wantagent_innerkits", @@ -47,7 +45,9 @@ ohos_shared_library("wantagent_napi") { "common_event_service:cesfwk_innerkits", "hilog:libhilog", "ipc:ipc_core", + "libuv:uv", "napi:ace_napi", + "node:node_header_notice", ] relative_install_dir = "module/app/ability" diff --git a/frameworks/native/ability/BUILD.gn b/frameworks/native/ability/BUILD.gn index f9e1e89693..484572aa82 100644 --- a/frameworks/native/ability/BUILD.gn +++ b/frameworks/native/ability/BUILD.gn @@ -24,7 +24,6 @@ config("ability_context_public_config") { "${user_file_service_innerkits_path}/file_access/*", ] include_dirs = [ - "${ability_base_kits_path}/extractortool/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", "${ability_runtime_path}/interfaces/kits/native/ability/ability_runtime", "${ability_runtime_path}/interfaces/kits/native/ability/ability_runtime/context", @@ -61,6 +60,7 @@ ohos_shared_library("ability_context_native") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", @@ -83,7 +83,10 @@ ohos_shared_library("ability_context_native") { "ipc:ipc_core", "napi:ace_napi", ] - + public_external_deps = [ + "ability_base:extractortool", + "background_task_mgr:bgtaskmgr_innerkits", + ] if (ability_runtime_graphics) { external_deps += [ "ace_engine:ace_uicontent", diff --git a/frameworks/native/ability/ability_runtime/connection_manager.cpp b/frameworks/native/ability/ability_runtime/connection_manager.cpp index 72e3be8d82..dd30aeed4b 100644 --- a/frameworks/native/ability/ability_runtime/connection_manager.cpp +++ b/frameworks/native/ability/ability_runtime/connection_manager.cpp @@ -255,8 +255,7 @@ void ConnectionManager::DisconnectNonexistentService( for (auto &&abilityConnection : abilityConnections) { ConnectionInfo connectionInfo = abilityConnection.first; if (connectionInfo.abilityConnection == connection && - connectionInfo.connectReceiver.GetBundleName() == element.GetBundleName() && - connectionInfo.connectReceiver.GetAbilityName() == element.GetAbilityName()) { + connectionInfo.connectReceiver.GetBundleName() == element.GetBundleName()) { HILOG_DEBUG("find connection."); exit = true; break; diff --git a/frameworks/native/ability/native/BUILD.gn b/frameworks/native/ability/native/BUILD.gn index 715862aa79..2f23d8b54e 100644 --- a/frameworks/native/ability/native/BUILD.gn +++ b/frameworks/native/ability/native/BUILD.gn @@ -13,7 +13,6 @@ import("//build/ohos.gni") import("//foundation/ability/ability_runtime/ability_runtime.gni") -import("//foundation/distributeddatamgr/relational_store/relational_store.gni") config("ability_config") { visibility = [ ":*" ] @@ -38,9 +37,7 @@ config("ability_config") { "${ability_runtime_services_path}/abilitymgr/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/app", "${ability_runtime_path}/interfaces/kits/native/appkit/app", - "${form_fwk_path}/interfaces/kits/native/include", "${ability_runtime_path}/interfaces/kits/native/appkit/app", - "//third_party/node/src", "${ability_runtime_innerkits_path}/ability_manager/include/continuation", "${ability_runtime_path}/interfaces/kits/native/appkit/app/task", "${ability_runtime_napi_path}/inner/napi_common", @@ -89,12 +86,9 @@ config("ability_public_config") { "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime", "${ability_runtime_path}/interfaces/kits/native/ability/native/recovery/", - "${accessibility_path}/interfaces/innerkits/common/include/", - "//third_party/libuv/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", "${ability_runtime_innerkits_path}/ability_manager/include/continuation", "${ability_runtime_services_path}/common/include", - "//third_party/jsoncpp/include", "//third_party/json/include", ] @@ -121,19 +115,10 @@ config("abilitykit_utils_public_config") { "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_innerkits_path}/app_manager/include/appmgr", "${bundlefwk_inner_api_path}/appexecfwk_base/include", - "//third_party/jsoncpp/include", "//third_party/json/include", ] if (ability_runtime_graphics) { - include_dirs += [ - "${form_fwk_path}/interfaces/inner_api/include", - "${graphic_path}/utils/color_manager/export", - "${multimedia_path}/interfaces/innerkits/include", - "${windowmanager_path}/interfaces/innerkits/wm", - "${windowmanager_path}/interfaces/innerkits/dm", - "${windowmanager_path}/utils/include", - ] defines = [ "SUPPORT_GRAPHICS" ] } } @@ -162,7 +147,6 @@ ohos_shared_library("abilitykit_utils") { "ability_base:configuration", "ability_base:want", "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", "c_utils:utils", "eventhandler:libeventhandler", "hilog:libhilog", @@ -172,15 +156,25 @@ ohos_shared_library("abilitykit_utils") { "resource_management:global_resmgr", ] - public_external_deps = [ "bundle_framework:appexecfwk_core" ] + public_external_deps = [ + "bundle_framework:appexecfwk_core", + "jsoncpp:jsoncpp", + "window_manager:libwm", + ] if (ability_runtime_graphics) { - deps += [ "//third_party/icu/icu4c:shared_icuuc" ] external_deps += [ "ability_base:session_info", - "window_manager:libdm", + "icu:shared_icuuc", "window_manager:libwm", ] + public_external_deps += [ + "form_fwk:form_manager", + "graphic_2d:color_manager", + "image_framework:image_native", + "window_manager:libdm", + "window_manager:libwmutil", + ] } innerapi_tags = [ "platformsdk" ] @@ -189,13 +183,7 @@ ohos_shared_library("abilitykit_utils") { } ohos_shared_library("abilitykit_native") { - include_dirs = [ - "${ability_base_kits_path}/extractortool/include", - "${ability_runtime_path}/utils/global/time/include", - "${relational_store_napi_path}/rdb/include", - "${relational_store_napi_path}/common/include", - "${relational_store_napi_path}/dataability/include", - ] + include_dirs = [ "${ability_runtime_path}/utils/global/time/include" ] sources = [ "${ability_runtime_innerkits_path}/app_manager/src/appmgr/process_info.cpp", @@ -241,6 +229,7 @@ ohos_shared_library("abilitykit_native") { ":continuation_ipc", ":extension_blocklist_config", "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_innerkits_path}/dataobs_manager:dataobs_manager", @@ -262,6 +251,7 @@ ohos_shared_library("abilitykit_native") { external_deps = [ "ability_base:base", "ability_base:configuration", + "ability_base:extractortool", "ability_base:session_info", "ability_base:want", "ability_base:zuri", @@ -279,12 +269,18 @@ ohos_shared_library("abilitykit_native") { "ipc:ipc_napi", "ipc:rpc", "napi:ace_napi", + "node:node_header_notice", "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", ] - public_external_deps = [ "bundle_framework:appexecfwk_core" ] + public_external_deps = [ + "accessibility:accessibility_common", + "bundle_framework:appexecfwk_core", + "jsoncpp:jsoncpp", + "libuv:uv", + ] defines = [] @@ -310,11 +306,11 @@ ohos_shared_library("abilitykit_native") { "${ability_runtime_native_path}/ability/native/ability_window.cpp", "${ability_runtime_native_path}/ability/native/page_ability_impl.cpp", ] - deps += [ "//third_party/icu/icu4c:shared_icuuc" ] external_deps += [ "ability_base:session_info", "form_fwk:form_manager", + "icu:shared_icuuc", "image_framework:image", "image_framework:image", "image_framework:image_native", @@ -342,17 +338,12 @@ config("extensionkit_public_config") { "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_innerkits_path}/app_manager/include/appmgr", "${bundlefwk_inner_api_path}/appexecfwk_base/include", - "//third_party/jsoncpp/include", "//third_party/json/include", ] if (ability_runtime_graphics) { include_dirs += [ - "${form_fwk_path}/interfaces/inner_api/include", - "${graphic_path}/utils/color_manager/export", - "${multimedia_path}/interfaces/innerkits/include", "${windowmanager_path}/interfaces/innerkits/wm", - "${windowmanager_path}/interfaces/innerkits/dm", "${windowmanager_path}/utils/include", ] defines = [ "SUPPORT_GRAPHICS" ] @@ -383,6 +374,7 @@ ohos_shared_library("extensionkit_native") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/ability:ability_context_native", @@ -400,10 +392,19 @@ ohos_shared_library("extensionkit_native") { public_deps = [ ":abilitykit_utils" ] - public_external_deps = [ "bundle_framework:appexecfwk_core" ] + public_external_deps = [ + "bundle_framework:appexecfwk_core", + "jsoncpp:jsoncpp", + ] if (ability_runtime_graphics) { external_deps += [ "ability_base:session_info" ] + public_external_deps += [ + "form_fwk:form_manager", + "graphic_2d:color_manager", + "image_framework:image_native", + "window_manager:libdm", + ] } innerapi_tags = [ "platformsdk" ] @@ -427,6 +428,7 @@ ohos_shared_library("insight_intent_executor") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/ability/native:ability_business_error", @@ -462,19 +464,11 @@ config("uiability_config") { "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/app", "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_services_path}/abilitymgr/include", - "${arkui_path}/napi", - "${arkui_path}/napi/interfaces/kits", "${bundlefwk_inner_api_path}/appexecfwk_base/include", - "//third_party/libuv/include", - "//third_party/node/src", ] if (ability_runtime_graphics) { include_dirs += [ - "${form_fwk_path}/interfaces/inner_api/include", - "${graphic_path}/utils/color_manager/export", - "${multimedia_path}/interfaces/innerkits/include", - "${windowmanager_path}/interfaces/innerkits/dm", "${windowmanager_path}/interfaces/innerkits/wm", "${windowmanager_path}/utils/include", ] @@ -509,6 +503,7 @@ ohos_shared_library("uiabilitykit_native") { ":continuation_ipc", ":ui_extension", "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", "${ability_runtime_innerkits_path}/ability_manager:process_options", "${ability_runtime_innerkits_path}/runtime:runtime", @@ -534,21 +529,29 @@ ohos_shared_library("uiabilitykit_native") { "hitrace:hitrace_meter", "ipc:ipc_core", "ipc:ipc_napi", - "napi:ace_napi", "resource_management:global_resmgr", ] - - public_external_deps = [ "bundle_framework:appexecfwk_core" ] + public_external_deps = [ + "bundle_framework:appexecfwk_core", + "libuv:uv", + "napi:ace_napi", + "node:node_header_notice", + ] if (ability_runtime_graphics) { - deps += [ "//third_party/icu/icu4c:shared_icuuc" ] external_deps += [ "ability_base:session_info", - "window_manager:libdm", + "icu:shared_icuuc", "window_manager:libwm", "window_manager:libwsutils", "window_manager:windowstage_kit", ] + public_external_deps += [ + "form_fwk:form_manager", + "graphic_2d:color_manager", + "image_framework:image_native", + "window_manager:libdm", + ] } innerapi_tags = [ "platformsdk" ] @@ -574,6 +577,7 @@ ohos_shared_library("ability_thread") { ":extensionkit_native", ":uiabilitykit_native", "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/dataobs_manager:dataobs_manager", "${ability_runtime_native_path}/ability:ability_context_native", "${ability_runtime_native_path}/appkit:app_context", @@ -705,6 +709,7 @@ ohos_shared_library("service_extension") { deps = [ ":abilitykit_native", "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/ability:ability_context_native", @@ -734,6 +739,7 @@ ohos_shared_library("service_extension") { external_deps += [ "image_framework:image", "window_manager:libdm", + "window_manager:libwm", ] } @@ -769,6 +775,7 @@ ohos_shared_library("continuation_ipc") { deps = [ ":abilitykit_utils", "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", ] external_deps = [ @@ -778,8 +785,13 @@ ohos_shared_library("continuation_ipc") { "eventhandler:libeventhandler", "hilog:libhilog", "ipc:ipc_core", + "node:node_header_notice", "resource_management:global_resmgr", ] + public_external_deps = [ + "accessibility:accessibility_common", + "libuv:uv", + ] defines = [] @@ -977,6 +989,7 @@ ohos_shared_library("ui_extension") { deps = [ ":abilitykit_native", "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/ability:ability_context_native", @@ -1066,6 +1079,7 @@ ohos_shared_library("share_extension") { ":abilitykit_native", ":ui_extension", "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/ability:ability_context_native", @@ -1116,6 +1130,7 @@ ohos_shared_library("action_extension") { ":abilitykit_native", ":ui_extension", "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/ability:ability_context_native", @@ -1317,6 +1332,7 @@ ohos_shared_library("embedded_ui_extension") { ":abilitykit_native", ":ui_extension", "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/ability:ability_context_native", @@ -1410,6 +1426,7 @@ ohos_shared_library("auto_fill_extension") { ":insight_intent_executor", ":ui_extension", "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/ability:ability_context_native", diff --git a/frameworks/native/ability/native/ability.cpp b/frameworks/native/ability/native/ability.cpp index 93191641d0..60888cf707 100644 --- a/frameworks/native/ability/native/ability.cpp +++ b/frameworks/native/ability/native/ability.cpp @@ -72,7 +72,6 @@ const int Ability::DEFAULT_DMS_SESSION_ID(0); const std::string LAUNCHER_BUNDLE_NAME = "com.ohos.launcher"; const std::string LAUNCHER_ABILITY_NAME = "com.ohos.launcher.MainAbility"; const std::string SHOW_ON_LOCK_SCREEN = "ShowOnLockScreen"; -const std::string DLP_INDEX = "ohos.dlp.params.index"; const std::string DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag"; const std::string COMPONENT_STARTUP_NEW_RULES = "component.startup.newRules"; @@ -165,8 +164,6 @@ void Ability::OnStart(const Want &want, sptr sessionInfo) return; } - appIndex_ = want.GetIntParam(DLP_INDEX, 0); - (const_cast(want)).RemoveParam(DLP_INDEX); securityFlag_ = want.GetBoolParam(DLP_PARAMS_SECURITY_FLAG, false); (const_cast(want)).RemoveParam(DLP_PARAMS_SECURITY_FLAG); SetWant(want); @@ -340,11 +337,6 @@ bool Ability::IsRestoredInContinuation() const return false; } - if (abilityContext_->GetContentStorage() == nullptr) { - TAG_LOGD(AAFwkTag::ABILITY, "not Restored In Continuation"); - return false; - } - TAG_LOGD(AAFwkTag::ABILITY, "Is Restored In Continuation"); return true; } @@ -1657,7 +1649,7 @@ std::string Ability::GetContentInfo() if (scene_ == nullptr) { return ""; } - return scene_->GetContentInfo(); + return scene_->GetContentInfo(Rosen::BackupAndRestoreType::CONTINUATION); } void Ability::OnWindowFocusChanged(bool hasFocus) diff --git a/frameworks/native/ability/native/ability_business_error/ability_business_error.cpp b/frameworks/native/ability/native/ability_business_error/ability_business_error.cpp index 8c4c18d0c3..9f9e0b3071 100644 --- a/frameworks/native/ability/native/ability_business_error/ability_business_error.cpp +++ b/frameworks/native/ability/native/ability_business_error/ability_business_error.cpp @@ -78,6 +78,10 @@ constexpr const char* ERROR_MSG_TARGET_BUNDLE_NOT_EXIST = "The target bundle doe constexpr const char* ERROR_MSG_SET_SUPPORTED_PROCESS_CACHE_AGAIN = "Can not set process cache state more than once."; constexpr const char* ERROR_MSG_NO_RESIDENT_PERMISSION = "The caller application can only set the resident status of the configured process."; +constexpr const char* ERROR_MSG_MULTI_APP_NOT_SUPPORTED = "App clone or multi-instance is not supported."; +constexpr const char* ERROR_MSG_APP_CLONE_INDEX_INVALID = + "The target app clone with the specified index does not exist."; +constexpr const char* ERROR_MSG_NOT_APP_CLONE = "The target app is not Clone."; // follow ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST of appexecfwk_errors.h in bundle_framework constexpr int32_t ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST = 8521220; @@ -131,6 +135,9 @@ static std::unordered_map ERR_CODE_MAP = { { AbilityErrorCode::ERROR_CODE_TARGET_BUNDLE_NOT_EXIST, ERROR_MSG_TARGET_BUNDLE_NOT_EXIST }, { AbilityErrorCode::ERROR_CODE_SET_SUPPORTED_PROCESS_CACHE_AGAIN, ERROR_MSG_SET_SUPPORTED_PROCESS_CACHE_AGAIN }, { AbilityErrorCode::ERROR_CODE_NO_RESIDENT_PERMISSION, ERROR_MSG_NO_RESIDENT_PERMISSION }, + { AbilityErrorCode::ERROR_CODE_MULTI_APP_NOT_SUPPORTED, ERROR_MSG_MULTI_APP_NOT_SUPPORTED }, + { AbilityErrorCode::ERROR_APP_CLONE_INDEX_INVALID, ERROR_MSG_APP_CLONE_INDEX_INVALID }, + { AbilityErrorCode::ERROR_NOT_APP_CLONE, ERROR_MSG_NOT_APP_CLONE }, }; static std::unordered_map INNER_TO_JS_ERROR_CODE_MAP { @@ -187,6 +194,8 @@ static std::unordered_map INNER_TO_JS_ERROR_CODE_MAP {ERR_TARGET_BUNDLE_NOT_EXIST, AbilityErrorCode::ERROR_CODE_TARGET_BUNDLE_NOT_EXIST}, {ERR_SET_SUPPORTED_PROCESS_CACHE_AGAIN, AbilityErrorCode::ERROR_CODE_SET_SUPPORTED_PROCESS_CACHE_AGAIN}, {ERR_NO_RESIDENT_PERMISSION, AbilityErrorCode::ERROR_CODE_NO_RESIDENT_PERMISSION}, + {ERR_MULTI_APP_NOT_SUPPORTED, AbilityErrorCode::ERROR_CODE_MULTI_APP_NOT_SUPPORTED}, + {ERR_APP_CLONE_INDEX_INVALID, AbilityErrorCode::ERROR_APP_CLONE_INDEX_INVALID}, }; } diff --git a/frameworks/native/ability/native/ability_runtime/js_ability.cpp b/frameworks/native/ability/native/ability_runtime/js_ability.cpp index 508017d1a2..cfb1df8e6a 100644 --- a/frameworks/native/ability/native/ability_runtime/js_ability.cpp +++ b/frameworks/native/ability/native/ability_runtime/js_ability.cpp @@ -609,7 +609,7 @@ void JsAbility::RestorePageStack(const Want &want) auto env = jsRuntime_.GetNapiEnv(); if (abilityContext_->GetContentStorage()) { scene_->GetMainWindow()->NapiSetUIContent(pageStack, env, - abilityContext_->GetContentStorage()->GetNapiValue(), true); + abilityContext_->GetContentStorage()->GetNapiValue(), Rosen::BackupAndRestoreType::CONTINUATION); } else { TAG_LOGE(AAFwkTag::ABILITY, "restore: content storage is nullptr"); } diff --git a/frameworks/native/ability/native/ability_runtime/js_ability_context.cpp b/frameworks/native/ability/native/ability_runtime/js_ability_context.cpp index b2f4c3ac1b..14bd12a881 100644 --- a/frameworks/native/ability/native/ability_runtime/js_ability_context.cpp +++ b/frameworks/native/ability/native/ability_runtime/js_ability_context.cpp @@ -1174,7 +1174,7 @@ napi_value JsAbilityContext::OnConnectAbility(napi_env env, NapiCallbackInfo& in // unwrap want AAFwk::Want want; OHOS::AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want); - TAG_LOGI(AAFwkTag::CONTEXT, "ConnectAbility, callee:%{public}s.%{public}s", + TAG_LOGD(AAFwkTag::CONTEXT, "ConnectAbility, callee:%{public}s.%{public}s", want.GetBundle().c_str(), want.GetElement().GetAbilityName().c_str()); @@ -1224,8 +1224,7 @@ napi_value JsAbilityContext::OnConnectAbilityWithAccount(napi_env env, NapiCallb AAFwk::Want want; OHOS::AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want); TAG_LOGI(AAFwkTag::CONTEXT, "ConnectAbilityWithAccount, bundlename:%{public}s abilityname:%{public}s", - want.GetBundle().c_str(), - want.GetElement().GetAbilityName().c_str()); + want.GetBundle().c_str(), want.GetElement().GetAbilityName().c_str()); int32_t accountId = 0; if (!OHOS::AppExecFwk::UnwrapInt32FromJS2(env, info.argv[INDEX_ONE], accountId)) { @@ -1685,7 +1684,7 @@ void JSAbilityConnection::SetConnectionId(int64_t id) void JSAbilityConnection::OnAbilityConnectDone(const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) { - TAG_LOGI(AAFwkTag::CONTEXT, "OnAbilityConnectDone, resultCode:%{public}d", resultCode); + TAG_LOGD(AAFwkTag::CONTEXT, "OnAbilityConnectDone, resultCode:%{public}d", resultCode); wptr connection = this; std::unique_ptr complete = std::make_unique ([connection, element, remoteObject, resultCode](napi_env env, NapiAsyncTask &task, int32_t status) { @@ -1706,7 +1705,7 @@ void JSAbilityConnection::OnAbilityConnectDone(const AppExecFwk::ElementName &el void JSAbilityConnection::HandleOnAbilityConnectDone(const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) { - TAG_LOGI(AAFwkTag::CONTEXT, "HandleOnAbilityConnectDone, resultCode:%{public}d", resultCode); + TAG_LOGD(AAFwkTag::CONTEXT, "HandleOnAbilityConnectDone, resultCode:%{public}d", resultCode); if (jsConnectionObject_ == nullptr) { TAG_LOGE(AAFwkTag::CONTEXT, "jsConnectionObject_ nullptr"); return; @@ -1732,7 +1731,7 @@ void JSAbilityConnection::HandleOnAbilityConnectDone(const AppExecFwk::ElementNa void JSAbilityConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) { - TAG_LOGI(AAFwkTag::CONTEXT, "OnAbilityDisconnectDone, resultCode:%{public}d", resultCode); + TAG_LOGD(AAFwkTag::CONTEXT, "OnAbilityDisconnectDone, resultCode:%{public}d", resultCode); wptr connection = this; std::unique_ptr complete = std::make_unique ([connection, element, resultCode](napi_env env, NapiAsyncTask &task, int32_t status) { diff --git a/frameworks/native/ability/native/ability_runtime/js_ui_ability.cpp b/frameworks/native/ability/native/ability_runtime/js_ui_ability.cpp index 4fb51a3edf..a82ba5f587 100644 --- a/frameworks/native/ability/native/ability_runtime/js_ui_ability.cpp +++ b/frameworks/native/ability/native/ability_runtime/js_ui_ability.cpp @@ -706,7 +706,7 @@ void JsUIAbility::RestorePageStack(const Want &want) auto env = jsRuntime_.GetNapiEnv(); if (abilityContext_->GetContentStorage()) { scene_->GetMainWindow()->NapiSetUIContent(pageStack, env, - abilityContext_->GetContentStorage()->GetNapiValue(), true); + abilityContext_->GetContentStorage()->GetNapiValue(), Rosen::BackupAndRestoreType::CONTINUATION); } else { TAG_LOGE(AAFwkTag::UIABILITY, "Content storage is nullptr."); } @@ -728,7 +728,8 @@ void JsUIAbility::AbilityContinuationOrRecover(const Want &want) auto env = jsRuntime_.GetNapiEnv(); auto mainWindow = scene_->GetMainWindow(); if (mainWindow != nullptr) { - mainWindow->NapiSetUIContent(pageStack, env, abilityContext_->GetContentStorage()->GetNapiValue(), true); + mainWindow->NapiSetUIContent(pageStack, env, abilityContext_->GetContentStorage()->GetNapiValue(), + Rosen::BackupAndRestoreType::CONTINUATION); } else { TAG_LOGE(AAFwkTag::UIABILITY, "MainWindow is nullptr."); } @@ -793,9 +794,10 @@ void JsUIAbility::DoOnForegroundForSceneIsNull(const Want &want) auto option = GetWindowOption(want); Rosen::WMError ret = Rosen::WMError::WM_OK; auto sessionToken = GetSessionToken(); + auto identityToken = GetIdentityToken(); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && sessionToken != nullptr) { abilityContext_->SetWeakSessionToken(sessionToken); - ret = scene_->Init(displayId, abilityContext_, sceneListener_, option, sessionToken); + ret = scene_->Init(displayId, abilityContext_, sceneListener_, option, sessionToken, identityToken); } else { ret = scene_->Init(displayId, abilityContext_, sceneListener_, option); } diff --git a/frameworks/native/ability/native/child_process_manager/child_process_manager.cpp b/frameworks/native/ability/native/child_process_manager/child_process_manager.cpp index c377797192..28de904cb1 100644 --- a/frameworks/native/ability/native/child_process_manager/child_process_manager.cpp +++ b/frameworks/native/ability/native/child_process_manager/child_process_manager.cpp @@ -29,6 +29,7 @@ #include "bundle_info.h" #include "bundle_mgr_interface.h" #include "child_process.h" +#include "native_child_ipc_process.h" #include "child_process_manager_error_utils.h" #include "child_process_start_info.h" #include "constants.h" @@ -115,6 +116,37 @@ ChildProcessManagerErrorCode ChildProcessManager::StartChildProcessByAppSpawnFor return ChildProcessManagerErrorCode::ERR_OK; } +ChildProcessManagerErrorCode ChildProcessManager::StartNativeChildProcessByAppSpawnFork( + const std::string &libName, const sptr &callbackStub) +{ + TAG_LOGI(AAFwkTag::PROCESSMGR, "called, libName:%{private}s", libName.c_str()); + ChildProcessManagerErrorCode errorCode = PreCheckNativeProcess(); + if (errorCode != ChildProcessManagerErrorCode::ERR_OK) { + return errorCode; + } + + sptr appMgr = GetAppMgr(); + if (appMgr == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "GetAppMgr for native child process failed."); + return ChildProcessManagerErrorCode::ERR_GET_APP_MGR_FAILED; + } + + auto ret = appMgr->StartNativeChildProcess(libName, childProcessCount_, callbackStub); + TAG_LOGD(AAFwkTag::PROCESSMGR, "AppMgr StartNativeChildProcess ret:%{public}d", ret); + + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "AppMgr StartNativeChildProcess failed, ret:%{public}d", ret); + if (ret == ERR_OVERFLOW) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Max native child processes readched"); + return ChildProcessManagerErrorCode::ERR_MAX_NATIVE_CHILD_PROCESSES; + } + return ChildProcessManagerErrorCode::ERR_GET_APP_MGR_START_PROCESS_FAILED; + } + + ++childProcessCount_; + return ChildProcessManagerErrorCode::ERR_OK; +} + void ChildProcessManager::RegisterSignal() { if (!signalRegistered_) { @@ -144,6 +176,21 @@ ChildProcessManagerErrorCode ChildProcessManager::PreCheck() return ChildProcessManagerErrorCode::ERR_OK; } +ChildProcessManagerErrorCode ChildProcessManager::PreCheckNativeProcess() +{ + ChildProcessManagerErrorCode errCode = PreCheck(); + if (errCode != ChildProcessManagerErrorCode::ERR_OK) { + return errCode; + } + + if (!AAFwk::AppUtils::GetInstance().IsSupportNativeChildProcess()) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Unsupport native child process"); + return ChildProcessManagerErrorCode::ERR_UNSUPPORT_NATIVE_CHILD_PROCESS; + } + + return ChildProcessManagerErrorCode::ERR_OK; +} + bool ChildProcessManager::IsChildProcess() { return isChildProcessBySelfFork_ || hasChildProcessRecord(); @@ -207,6 +254,28 @@ bool ChildProcessManager::LoadJsFile(const std::string &srcEntry, const AppExecF return true; } +bool ChildProcessManager::LoadNativeLib(const std::string &libPath, const sptr &mainProcessCb) +{ + auto childProcess = NativeChildIpcProcess::Create(); + if (childProcess == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Failed create NativeChildIpcProcess"); + return false; + } + + std::shared_ptr processStartInfo = std::make_shared(); + processStartInfo->name = std::filesystem::path(libPath).stem(); + processStartInfo->srcEntry = libPath; + processStartInfo->ipcObj = mainProcessCb; + if (!childProcess->Init(processStartInfo)) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "NativeChildIpcProcess init failed."); + return false; + } + + childProcess->OnStart(); + TAG_LOGD(AAFwkTag::PROCESSMGR, "LoadNativeLib end."); + return true; +} + std::unique_ptr ChildProcessManager::CreateRuntime(const AppExecFwk::BundleInfo &bundleInfo, const AppExecFwk::HapModuleInfo &hapModuleInfo, const bool fromAppSpawn, const bool jitEnabled) { diff --git a/frameworks/native/ability/native/child_process_manager/native_child_ipc_process.cpp b/frameworks/native/ability/native/child_process_manager/native_child_ipc_process.cpp new file mode 100644 index 0000000000..29b4bdc376 --- /dev/null +++ b/frameworks/native/ability/native/child_process_manager/native_child_ipc_process.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_child_ipc_process.h" +#include +#include +#include +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" +#include "child_process_manager_error_utils.h" + +namespace OHOS { +namespace AbilityRuntime { + +std::shared_ptr NativeChildIpcProcess::Create() +{ + return std::make_shared(); +} + +NativeChildIpcProcess::~NativeChildIpcProcess() +{ + UnloadNativeLib(); +} + +bool NativeChildIpcProcess::Init(const std::shared_ptr &info) +{ + TAG_LOGD(AAFwkTag::PROCESSMGR, "NativeChildIpcProcess init"); + if (info == nullptr || info->ipcObj == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "info or ipc callback is null"); + return false; + } + + if (!ChildProcess::Init(info)) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Base class init failed."); + return false; + } + + auto iNotify = iface_cast(info->ipcObj); + if (iNotify == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Faild cvt interface to INativeChildNotify"); + return false; + } + + if (!LoadNativeLib(info)) { + iNotify->OnError(static_cast(ChildProcessManagerErrorCode::ERR_LIB_LOADING_FAILED)); + return false; + } + + mainProcessCb_ = iNotify; + return true; +} + +void NativeChildIpcProcess::OnStart() +{ + if (funcNativeLibOnConnect_ == nullptr || funcNativeLibMainProc_ == nullptr || mainProcessCb_ == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "No init"); + return; + } + + ChildProcess::OnStart(); + OHIPCRemoteStub *ipcStub = funcNativeLibOnConnect_(); + if (ipcStub == nullptr || ipcStub->remote == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Native lib OnConnect function return null stub"); + mainProcessCb_->OnError(static_cast(ChildProcessManagerErrorCode::ERR_CONNECTION_FAILED)); + return; + } + + std::thread cbThread([this, childIpcStub = std::move(ipcStub->remote)] () -> void { + // Wait MainProc run first + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + TAG_LOGI(AAFwkTag::PROCESSMGR, "Notify native child process started"); + mainProcessCb_->OnNativeChildStarted(childIpcStub); + }); + + TAG_LOGI(AAFwkTag::PROCESSMGR, "Enter native lib MainProc"); + funcNativeLibMainProc_(); + TAG_LOGI(AAFwkTag::PROCESSMGR, "Native lib MainProc returned"); + + if (cbThread.joinable()) { + cbThread.join(); + } +} + +bool NativeChildIpcProcess::LoadNativeLib(const std::shared_ptr &info) +{ + if (nativeLibHandle_ != nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Native lib already loaded"); + return false; + } + + void *libHandle = dlopen(info->srcEntry.c_str(), RTLD_LAZY); + if (libHandle == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Load lib file %{private}s failed, err %{public}s", + info->srcEntry.c_str(), dlerror()); + return false; + } + + do { + NativeChildProcess_OnConnect funcOnConnect = + reinterpret_cast(dlsym(libHandle, "NativeChildProcess_OnConnect")); + if (funcOnConnect == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Get OnConnect function address failed, err %{public}s", dlerror()); + break; + } + + NativeChildProcess_MainProc funcMainProc = + reinterpret_cast(dlsym(libHandle, "NativeChildProcess_MainProc")); + if (funcMainProc == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Get MainProc function address failed, err %{public}s", dlerror()); + break; + } + + funcNativeLibOnConnect_ = funcOnConnect; + funcNativeLibMainProc_ = funcMainProc; + nativeLibHandle_ = libHandle; + return true; + } while (false); + + dlclose(libHandle); + return false; +} + +void NativeChildIpcProcess::UnloadNativeLib() +{ + if (nativeLibHandle_ != nullptr) { + dlclose(nativeLibHandle_); + nativeLibHandle_ = nullptr; + funcNativeLibOnConnect_ = nullptr; + funcNativeLibMainProc_ = nullptr; + } +} + +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/frameworks/native/ability/native/configuration_utils.cpp b/frameworks/native/ability/native/configuration_utils.cpp index ec2ecbe14f..61e25c6a25 100644 --- a/frameworks/native/ability/native/configuration_utils.cpp +++ b/frameworks/native/ability/native/configuration_utils.cpp @@ -41,6 +41,7 @@ void ConfigurationUtils::UpdateGlobalConfig(const Configuration &configuration, std::string colormode; std::string hasPointerDevice; GetGlobalConfig(configuration, language, colormode, hasPointerDevice); + std::string colorModeIsSetByApp = configuration.GetItem(AAFwk::GlobalConfigurationKey::COLORMODE_IS_SET_BY_APP); std::unique_ptr resConfig(Global::Resource::CreateResConfig()); if (resConfig == nullptr) { TAG_LOGE(AAFwkTag::ABILITY, "Create resource config failed."); @@ -75,6 +76,11 @@ void ConfigurationUtils::UpdateGlobalConfig(const Configuration &configuration, TAG_LOGD(AAFwkTag::ABILITY, "Update config, hasPointerDevice: %{public}d", resConfig->GetInputDevice()); } + if (!colorModeIsSetByApp.empty()) { + TAG_LOGD(AAFwkTag::ABILITY, "set app true"); + resConfig->SetAppColorMode(true); + } + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "resourceManager->UpdateResConfig"); Global::Resource::RState ret = resourceManager->UpdateResConfig(*resConfig); if (ret != Global::Resource::RState::SUCCESS) { diff --git a/frameworks/native/ability/native/data_ability_operation.cpp b/frameworks/native/ability/native/data_ability_operation.cpp index 12ba97882b..86c8a156dc 100644 --- a/frameworks/native/ability/native/data_ability_operation.cpp +++ b/frameworks/native/ability/native/data_ability_operation.cpp @@ -351,8 +351,7 @@ bool DataAbilityOperation::Marshalling(Parcel &out) const } int referenceSize = (int)dataAbilityPredicatesBackReferences_.size(); if (dataAbilityPredicatesBackReferences_.empty()) { - TAG_LOGD( - AAFwkTag::DATA_ABILITY, "DataAbilityOperation::Marshalling dataAbilityPredicatesBackReferences_ is empty"); + TAG_LOGD(AAFwkTag::DATA_ABILITY, "DataAbilityOperation::Marshalling dataAbilityPredicatesBackReferences_:null"); if (!out.WriteInt32(referenceSize)) { TAG_LOGE(AAFwkTag::DATA_ABILITY, "DataAbilityOperation::Marshalling WriteInt32(VALUE_OBJECT) error"); return false; diff --git a/frameworks/native/ability/native/js_service_extension.cpp b/frameworks/native/ability/native/js_service_extension.cpp index 42e69ddfb0..7a2992b76a 100644 --- a/frameworks/native/ability/native/js_service_extension.cpp +++ b/frameworks/native/ability/native/js_service_extension.cpp @@ -219,7 +219,13 @@ void JsServiceExtension::ListenWMS() return; } - auto listener = sptr::MakeSptr(displayListener_); + auto context = GetContext(); + if (context == nullptr || context->GetToken()) { + TAG_LOGE(AAFwkTag::SERVICE_EXT, "Param invalid."); + return; + } + + auto listener = sptr::MakeSptr(displayListener_, context->GetToken()); if (listener == nullptr) { TAG_LOGE(AAFwkTag::SERVICE_EXT, "Failed to create status change listener."); return; @@ -237,7 +243,8 @@ void JsServiceExtension::SystemAbilityStatusChangeListener::OnAddSystemAbility(i { TAG_LOGD(AAFwkTag::SERVICE_EXT, "systemAbilityId: %{public}d add", systemAbilityId); if (systemAbilityId == WINDOW_MANAGER_SERVICE_ID) { - Rosen::DisplayManager::GetInstance().RegisterDisplayListener(tmpDisplayListener_); + TAG_LOGI(AAFwkTag::SERVICE_EXT, "RegisterDisplayInfoChangedListener"); + Rosen::WindowManager::GetInstance().RegisterDisplayInfoChangedListener(token_, tmpDisplayListener_); } } @@ -315,7 +322,14 @@ void JsServiceExtension::OnStop() ConnectionManager::GetInstance().ReportConnectionLeakEvent(getpid(), gettid()); TAG_LOGD(AAFwkTag::SERVICE_EXT, "The service extension connection is not disconnected."); } - Rosen::DisplayManager::GetInstance().UnregisterDisplayListener(displayListener_); + TAG_LOGI(AAFwkTag::SERVICE_EXT, "UnregisterDisplayInfoChangedListener"); + auto context = GetContext(); + if (context == nullptr || context->GetToken()) { + TAG_LOGE(AAFwkTag::SERVICE_EXT, "Param invalid."); + return; + } + Rosen::WindowManager::GetInstance() + .UnregisterDisplayInfoChangedListener(context->GetToken(), displayListener_); TAG_LOGD(AAFwkTag::SERVICE_EXT, "ok"); } @@ -451,8 +465,7 @@ bool JsServiceExtension::HandleInsightIntent(const AAFwk::Want &want) static_cast(AbilityErrorCode::ERROR_CODE_INVALID_PARAM)); return false; } - TAG_LOGD(AAFwkTag::SERVICE_EXT, - "Insight intent bundleName: %{public}s, moduleName: %{public}s, abilityName: %{public}s" + TAG_LOGD(AAFwkTag::SERVICE_EXT, "Insight bundleName: %{public}s, moduleName: %{public}s, abilityName: %{public}s" "insightIntentName: %{public}s, executeMode: %{public}d, intentId: %{public}" PRIu64 "", executeParam->bundleName_.c_str(), executeParam->moduleName_.c_str(), executeParam->abilityName_.c_str(), executeParam->insightIntentName_.c_str(), executeParam->executeMode_, executeParam->insightIntentId_); @@ -799,6 +812,43 @@ void JsServiceExtension::OnDestroy(Rosen::DisplayId displayId) TAG_LOGD(AAFwkTag::SERVICE_EXT, "exit."); } +void JsServiceExtension::OnDisplayInfoChange(const sptr& token, Rosen::DisplayId displayId, + float density, Rosen::DisplayOrientation orientation) +{ + TAG_LOGI(AAFwkTag::SERVICE_EXT, "displayId: %{public}" PRIu64, displayId); + auto context = GetContext(); + if (context == nullptr) { + TAG_LOGE(AAFwkTag::SERVICE_EXT, "Context is invalid."); + return; + } + + auto contextConfig = context->GetConfiguration(); + if (contextConfig == nullptr) { + TAG_LOGE(AAFwkTag::SERVICE_EXT, "Configuration is invalid."); + return; + } + + TAG_LOGD(AAFwkTag::SERVICE_EXT, "Config dump: %{public}s", contextConfig->GetName().c_str()); + bool configChanged = false; + auto configUtils = std::make_shared(); + configUtils->UpdateDisplayConfig(displayId, contextConfig, context->GetResourceManager(), configChanged); + TAG_LOGD(AAFwkTag::SERVICE_EXT, "Config dump after update: %{public}s", contextConfig->GetName().c_str()); + + if (configChanged) { + auto jsServiceExtension = std::static_pointer_cast(shared_from_this()); + auto task = [jsServiceExtension]() { + if (jsServiceExtension) { + jsServiceExtension->ConfigurationUpdated(); + } + }; + if (handler_ != nullptr) { + handler_->PostTask(task, "JsServiceExtension:OnChange"); + } + } + + TAG_LOGD(AAFwkTag::SERVICE_EXT, "finished."); +} + void JsServiceExtension::OnChange(Rosen::DisplayId displayId) { TAG_LOGD(AAFwkTag::SERVICE_EXT, "displayId: %{public}" PRIu64"", displayId); diff --git a/frameworks/native/ability/native/js_service_extension_context.cpp b/frameworks/native/ability/native/js_service_extension_context.cpp index 8a8bbdb1fa..3477b0dddf 100644 --- a/frameworks/native/ability/native/js_service_extension_context.cpp +++ b/frameworks/native/ability/native/js_service_extension_context.cpp @@ -210,7 +210,7 @@ private: napi_value OnStartAbility(napi_env env, NapiCallbackInfo& info, bool isStartRecent = false) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGI(AAFwkTag::SERVICE_EXT, "StartAbility"); + TAG_LOGD(AAFwkTag::SERVICE_EXT, "StartAbility"); if (info.argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::SERVICE_EXT, "Start ability failed, not enough params."); ThrowTooFewParametersError(env); @@ -782,7 +782,7 @@ private: napi_value OnDisconnectAbility(napi_env env, NapiCallbackInfo& info) { - TAG_LOGI(AAFwkTag::SERVICE_EXT, "DisconnectAbility start"); + TAG_LOGD(AAFwkTag::SERVICE_EXT, "DisconnectAbility start"); if (info.argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::SERVICE_EXT, "Disconnect ability error, not enough params."); ThrowTooFewParametersError(env); @@ -1077,7 +1077,7 @@ private: return; } if (*retCode == 0) { - TAG_LOGI(AAFwkTag::SERVICE_EXT, "StartAbility is success"); + TAG_LOGD(AAFwkTag::SERVICE_EXT, "StartAbility is success"); task.Resolve(env, CreateJsUndefined(env)); } else { task.Reject(env, CreateJsErrorByNativeErr(env, *retCode)); @@ -1277,7 +1277,7 @@ void JSServiceExtensionConnection::OnAbilityDisconnectDone(const AppExecFwk::Ele void JSServiceExtensionConnection::HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) { - TAG_LOGI(AAFwkTag::SERVICE_EXT, "HandleOnAbilityDisconnectDone, resultCode:%{public}d", resultCode); + TAG_LOGD(AAFwkTag::SERVICE_EXT, "HandleOnAbilityDisconnectDone, resultCode:%{public}d", resultCode); napi_value napiElementName = OHOS::AppExecFwk::WrapElementName(env_, element); napi_value argv[] = {napiElementName}; if (jsConnectionObject_ == nullptr) { diff --git a/frameworks/native/ability/native/ui_ability.cpp b/frameworks/native/ability/native/ui_ability.cpp index 295c4ea36b..ccd65d0b36 100644 --- a/frameworks/native/ability/native/ui_ability.cpp +++ b/frameworks/native/ability/native/ui_ability.cpp @@ -36,7 +36,6 @@ constexpr int32_t DEFAULT_DMS_SESSION_ID = 0; constexpr char LAUNCHER_BUNDLE_NAME[] = "com.ohos.launcher"; constexpr char LAUNCHER_ABILITY_NAME[] = "com.ohos.launcher.MainAbility"; constexpr char SHOW_ON_LOCK_SCREEN[] = "ShowOnLockScreen"; -constexpr char DLP_INDEX[] = "ohos.dlp.params.index"; constexpr char DLP_PARAMS_SECURITY_FLAG[] = "ohos.dlp.params.securityFlag"; constexpr char COMPONENT_STARTUP_NEW_RULES[] = "component.startup.newRules"; constexpr int32_t ERR_INVALID_VALUE = -1; @@ -94,7 +93,8 @@ void UIAbility::Init(std::shared_ptr record, TAG_LOGE(AAFwkTag::UIABILITY, "abilityDisplayListener_ is nullptr."); return; } - Rosen::DisplayManager::GetInstance().RegisterDisplayListener(abilityDisplayListener_); + TAG_LOGI(AAFwkTag::UIABILITY, "RegisterDisplayInfoChangedListener."); + Rosen::WindowManager::GetInstance().RegisterDisplayInfoChangedListener(token_, abilityDisplayListener_); #endif lifecycle_ = std::make_shared(); abilityLifecycleExecutor_ = std::make_shared(); @@ -152,8 +152,6 @@ void UIAbility::OnStart(const AAFwk::Want &want, sptr sessio return; } - appIndex_ = want.GetIntParam(DLP_INDEX, 0); - (const_cast(want)).RemoveParam(DLP_INDEX); securityFlag_ = want.GetBoolParam(DLP_PARAMS_SECURITY_FLAG, false); (const_cast(want)).RemoveParam(DLP_PARAMS_SECURITY_FLAG); SetWant(want); @@ -161,6 +159,7 @@ void UIAbility::OnStart(const AAFwk::Want &want, sptr sessio #ifdef SUPPORT_GRAPHICS if (sessionInfo != nullptr) { SetSessionToken(sessionInfo->sessionToken); + SetIdentityToken(sessionInfo->identityToken); } OnStartForSupportGraphics(want); #endif @@ -187,7 +186,8 @@ void UIAbility::OnStop() if (abilityRecovery_ != nullptr) { abilityRecovery_->ScheduleSaveAbilityState(AppExecFwk::StateReason::LIFECYCLE); } - (void)Rosen::DisplayManager::GetInstance().UnregisterDisplayListener(abilityDisplayListener_); + TAG_LOGI(AAFwkTag::UIABILITY, "UnregisterDisplayInfoChangedListener."); + (void)Rosen::WindowManager::GetInstance().UnregisterDisplayInfoChangedListener(token_, abilityDisplayListener_); auto &&window = GetWindow(); if (window != nullptr) { TAG_LOGD(AAFwkTag::UIABILITY, "Call UnregisterDisplayMoveListener."); @@ -242,10 +242,6 @@ bool UIAbility::IsRestoredInContinuation() const return false; } - if (abilityContext_->GetContentStorage() == nullptr) { - TAG_LOGD(AAFwkTag::UIABILITY, "Get content failed."); - return false; - } TAG_LOGD(AAFwkTag::UIABILITY, "End."); return true; } @@ -295,6 +291,7 @@ void UIAbility::OnConfigurationUpdatedNotify(const AppExecFwk::Configuration &co std::string colormode; std::string hasPointerDevice; InitConfigurationProperties(configuration, language, colormode, hasPointerDevice); + std::string colorModeIsSetByApp = configuration.GetItem(AAFwk::GlobalConfigurationKey::COLORMODE_IS_SET_BY_APP); // Notify ResourceManager std::unique_ptr resConfig(Global::Resource::CreateResConfig()); if (resConfig == nullptr) { @@ -320,6 +317,10 @@ void UIAbility::OnConfigurationUpdatedNotify(const AppExecFwk::Configuration &co if (!hasPointerDevice.empty()) { resConfig->SetInputDevice(AppExecFwk::ConvertHasPointerDevice(hasPointerDevice)); } + if (!colorModeIsSetByApp.empty()) { + TAG_LOGD(AAFwkTag::UIABILITY, "set app true"); + resConfig->SetAppColorMode(true); + } resourceManager->UpdateResConfig(*resConfig); TAG_LOGD(AAFwkTag::UIABILITY, "Current colorMode: %{public}d, hasPointerDevice: %{public}d.", resConfig->GetColorMode(), resConfig->GetInputDevice()); @@ -800,6 +801,49 @@ void UIAbility::OnDestroy(Rosen::DisplayId displayId) TAG_LOGD(AAFwkTag::UIABILITY, "Called."); } +void UIAbility::OnDisplayInfoChange(const sptr& token, Rosen::DisplayId displayId, float density, + Rosen::DisplayOrientation orientation) +{ + TAG_LOGI(AAFwkTag::UIABILITY, "Begin displayId: %{public}" PRIu64, displayId); + // Get display + auto display = Rosen::DisplayManager::GetInstance().GetDisplayById(displayId); + if (!display) { + TAG_LOGE(AAFwkTag::UIABILITY, "Get display by displayId %{public}" PRIu64 " failed.", displayId); + return; + } + + // Notify ResourceManager + int32_t width = display->GetWidth(); + int32_t height = display->GetHeight(); + std::unique_ptr resConfig(Global::Resource::CreateResConfig()); + if (resConfig != nullptr) { + auto resourceManager = GetResourceManager(); + if (resourceManager != nullptr) { + resourceManager->GetResConfig(*resConfig); + resConfig->SetScreenDensity(density); + resConfig->SetDirection(AppExecFwk::ConvertDirection(height, width)); + resourceManager->UpdateResConfig(*resConfig); + TAG_LOGD(AAFwkTag::UIABILITY, "Notify ResourceManager, Density: %{public}f, Direction: %{public}d", + resConfig->GetScreenDensity(), resConfig->GetDirection()); + } + } + + // Notify ability + Configuration newConfig; + newConfig.AddItem( + displayId, AppExecFwk::ConfigurationInner::APPLICATION_DIRECTION, AppExecFwk::GetDirectionStr(height, width)); + newConfig.AddItem( + displayId, AppExecFwk::ConfigurationInner::APPLICATION_DENSITYDPI, AppExecFwk::GetDensityStr(density)); + + if (application_ == nullptr) { + TAG_LOGE(AAFwkTag::UIABILITY, "application_ is nullptr."); + return; + } + + OnChangeForUpdateConfiguration(newConfig); + TAG_LOGD(AAFwkTag::UIABILITY, "End."); +} + void UIAbility::OnChange(Rosen::DisplayId displayId) { TAG_LOGD(AAFwkTag::UIABILITY, "Begin displayId: %{public}" PRIu64 "", displayId); @@ -1023,11 +1067,6 @@ void UIAbility::OnChangeForUpdateConfiguration(const AppExecFwk::Configuration & ability->OnConfigurationUpdated(configuration); }; handler_->PostTask(task); - - auto diffConfiguration = std::make_shared(newConfig); - TAG_LOGD(AAFwkTag::UIABILITY, "Update display config %{public}s for all windows.", - diffConfiguration->GetName().c_str()); - Rosen::Window::UpdateConfigurationForAll(diffConfiguration); } } @@ -1095,6 +1134,16 @@ void UIAbility::EraseUIExtension(int32_t sessionId) } abilityContextImpl->EraseUIExtension(sessionId); } + +void UIAbility::SetIdentityToken(const std::string &identityToken) +{ + identityToken_ = identityToken; +} + +std::string UIAbility::GetIdentityToken() const +{ + return identityToken_; +} #endif } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/ability/native/ui_ability_impl.cpp b/frameworks/native/ability/native/ui_ability_impl.cpp index 7cec9fefc2..43a83fc531 100644 --- a/frameworks/native/ability/native/ui_ability_impl.cpp +++ b/frameworks/native/ability/native/ui_ability_impl.cpp @@ -368,7 +368,7 @@ void UIAbilityImpl::UpdateSilentForeground(const AAFwk::LifeCycleStateInfo &targ } if (lifecycleState_ == AAFwk::ABILITY_STATE_INITIAL && sessionInfo && sessionInfo->processOptions && - AAFwk::ProcessOptions::IsNewProcessMode(sessionInfo->processOptions->processMode) && + AAFwk::ProcessOptions::IsValidProcessMode(sessionInfo->processOptions->processMode) && sessionInfo->processOptions->startupVisibility == AAFwk::StartupVisibility::STARTUP_HIDE) { TAG_LOGI(AAFwkTag::UIABILITY, "Set IsSilentForeground to true."); ability_->SetIsSilentForeground(true); diff --git a/frameworks/native/ability/native/ui_extension_ability/js_ui_extension.cpp b/frameworks/native/ability/native/ui_extension_ability/js_ui_extension.cpp index eaac751d7a..a4e679a252 100755 --- a/frameworks/native/ability/native/ui_extension_ability/js_ui_extension.cpp +++ b/frameworks/native/ability/native/ui_extension_ability/js_ui_extension.cpp @@ -782,7 +782,7 @@ void JsUIExtension::DestroyWindow(const sptr &sessionInfo) CallObjectMethod("onSessionDestroy", argv, ARGC_ONE); } } - auto& uiWindow = uiWindowMap_[componentId]; + auto uiWindow = uiWindowMap_[componentId]; if (uiWindow) { uiWindow->Destroy(); } diff --git a/frameworks/native/ability/native/ui_extension_ability/js_ui_extension_content_session.cpp b/frameworks/native/ability/native/ui_extension_ability/js_ui_extension_content_session.cpp index d88c510d1e..a7d663619c 100644 --- a/frameworks/native/ability/native/ui_extension_ability/js_ui_extension_content_session.cpp +++ b/frameworks/native/ability/native/ui_extension_ability/js_ui_extension_content_session.cpp @@ -564,26 +564,8 @@ napi_value JsUIExtensionContentSession::OnTerminateSelfWithResult(napi_env env, return CreateJsUndefined(env); } - NapiAsyncTask::CompleteCallback complete = - [uiWindow = uiWindow_, sessionInfo = sessionInfo_, want, resultCode](napi_env env, - NapiAsyncTask& task, int32_t status) { - if (uiWindow == nullptr) { - TAG_LOGE(AAFwkTag::UI_EXT, "uiWindow is nullptr."); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - auto ret = uiWindow->TransferAbilityResult(resultCode, want); - if (ret != Rosen::WMError::WM_OK) { - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - auto errorCode = AAFwk::AbilityManagerClient::GetInstance()->TerminateUIExtensionAbility(sessionInfo); - if (errorCode == 0) { - task.ResolveWithNoError(env, CreateJsUndefined(env)); - } else { - task.Reject(env, CreateJsErrorByNativeErr(env, errorCode)); - } - }; + NapiAsyncTask::CompleteCallback complete; + SetCallbackForTerminateWithResult(resultCode, want, complete); napi_value lastParam = (info.argc > ARGC_ONE) ? info.argv[INDEX_ONE] : nullptr; napi_value result = nullptr; @@ -633,7 +615,7 @@ napi_value JsUIExtensionContentSession::OnSetReceiveDataCallback(napi_env env, N ThrowTooFewParametersError(env); return CreateJsUndefined(env); } - + if (!CheckTypeForNapiValue(env, info.argv[INDEX_ZERO], napi_function)) { TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); ThrowInvalidParamError(env, "Parameter error: Callback must be a function."); @@ -681,7 +663,7 @@ napi_value JsUIExtensionContentSession::OnSetReceiveDataForResultCallback(napi_e ThrowTooFewParametersError(env); return CreateJsUndefined(env); } - + if (!CheckTypeForNapiValue(env, info.argv[INDEX_ZERO], napi_function)) { TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); ThrowInvalidParamError(env, "Parameter error: Callback must be a function."); @@ -733,7 +715,7 @@ napi_value JsUIExtensionContentSession::OnLoadContent(napi_env env, NapiCallback ThrowTooFewParametersError(env); return CreateJsUndefined(env); } - + if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], contextPath)) { TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); ThrowInvalidParamError(env, "Parameter error: Path must be a string."); @@ -761,7 +743,8 @@ napi_value JsUIExtensionContentSession::OnLoadContent(napi_env env, NapiCallback isFirstTriggerBindModal_ = false; } sptr parentToken = sessionInfo_->parentToken; - Rosen::WMError ret = uiWindow_->NapiSetUIContent(contextPath, env, storage, false, parentToken); + Rosen::WMError ret = uiWindow_->NapiSetUIContent(contextPath, env, storage, + Rosen::BackupAndRestoreType::NONE, parentToken); if (ret == Rosen::WMError::WM_OK) { TAG_LOGD(AAFwkTag::UI_EXT, "NapiSetUIContent success"); } else { @@ -781,7 +764,7 @@ napi_value JsUIExtensionContentSession::OnSetWindowBackgroundColor(napi_env env, ThrowTooFewParametersError(env); return CreateJsUndefined(env); } - + if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], color)) { TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); ThrowInvalidParamError(env, "Parameter error: Parse color failed! Color must be a string."); @@ -812,7 +795,7 @@ napi_value JsUIExtensionContentSession::OnSetWindowPrivacyMode(napi_env env, Nap ThrowTooFewParametersError(env); return CreateJsUndefined(env); } - + if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], isPrivacyMode)) { TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); ThrowInvalidParamError(env, "Parameter error: Failed to parse isPrivacyMode! IsPrivacyMode must be a boolean."); @@ -849,7 +832,7 @@ napi_value JsUIExtensionContentSession::OnSetWindowPrivacyMode(napi_env env, Nap napi_value JsUIExtensionContentSession::OnStartAbilityByType(napi_env env, NapiCallbackInfo& info) { TAG_LOGI(AAFwkTag::UI_EXT, "called"); - + std::string type; AAFwk::WantParams wantParam; @@ -1084,5 +1067,38 @@ void JsUIExtensionContentSession::AddFreeInstallObserver(napi_env env, bundleName, abilityName, startTime, callback, result, isAbilityResult); } } + +void JsUIExtensionContentSession::SetCallbackForTerminateWithResult(int32_t resultCode, AAFwk::Want& want, + NapiAsyncTask::CompleteCallback& complete) +{ + complete = + [weak = context_, uiWindow = uiWindow_, sessionInfo = sessionInfo_, want, resultCode](napi_env env, + NapiAsyncTask& task, int32_t status) { + auto extensionContext = AbilityRuntime::Context::ConvertTo(weak.lock()); + if (!extensionContext) { + TAG_LOGE(AAFwkTag::UI_EXT, "extensionContext is nullptr"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT)); + return; + } + auto token = extensionContext->GetToken(); + AAFwk::AbilityManagerClient::GetInstance()->TransferAbilityResultForExtension(token, resultCode, want); + if (uiWindow == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "uiWindow is nullptr."); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + return; + } + auto ret = uiWindow->TransferAbilityResult(resultCode, want); + if (ret != Rosen::WMError::WM_OK) { + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + return; + } + auto errorCode = AAFwk::AbilityManagerClient::GetInstance()->TerminateUIExtensionAbility(sessionInfo); + if (errorCode == 0) { + task.ResolveWithNoError(env, CreateJsUndefined(env)); + } else { + task.Reject(env, CreateJsErrorByNativeErr(env, errorCode)); + } + }; +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/ability/native/ui_extension_ability/js_ui_extension_context.cpp b/frameworks/native/ability/native/ui_extension_ability/js_ui_extension_context.cpp index e05adf9bd9..2a8bf4454a 100755 --- a/frameworks/native/ability/native/ui_extension_ability/js_ui_extension_context.cpp +++ b/frameworks/native/ability/native/ui_extension_ability/js_ui_extension_context.cpp @@ -428,33 +428,8 @@ napi_value JsUIExtensionContext::OnTerminateSelfWithResult(napi_env env, NapiCal return CreateJsUndefined(env); } - NapiAsyncTask::CompleteCallback complete = - [weak = context_, want, resultCode](napi_env env, NapiAsyncTask& task, int32_t status) { - auto context = weak.lock(); - if (!context) { - TAG_LOGW(AAFwkTag::UI_EXT, "context is released"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM)); - return; - } - sptr uiWindow = context->GetWindow(); - if (uiWindow == nullptr) { - TAG_LOGE(AAFwkTag::UI_EXT, "uiWindow is nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM)); - return; - } - auto ret = uiWindow->TransferAbilityResult(resultCode, want); - if (ret != Rosen::WMError::WM_OK) { - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM)); - return; - } - auto errorCode = context->TerminateSelf(); - if (errorCode == 0) { - task.ResolveWithNoError(env, CreateJsUndefined(env)); - } else { - task.Reject(env, CreateJsErrorByNativeErr(env, errorCode)); - } - }; - + NapiAsyncTask::CompleteCallback complete; + SetCallbackForTerminateWithResult(resultCode, want, complete); napi_value lastParam = (info.argc > ARGC_ONE) ? info.argv[INDEX_ONE] : nullptr; napi_value result = nullptr; NapiAsyncTask::ScheduleHighQos("JsUIExtensionContext::OnTerminateSelfWithResult", @@ -666,6 +641,45 @@ napi_value JsUIExtensionContext::OnOpenAtomicService(napi_env env, NapiCallbackI return OpenAtomicServiceInner(env, info, want, startOptions, unwrapArgc); } +void JsUIExtensionContext::SetCallbackForTerminateWithResult(int32_t resultCode, AAFwk::Want& want, + NapiAsyncTask::CompleteCallback& complete) +{ + complete = + [weak = context_, want, resultCode](napi_env env, NapiAsyncTask& task, int32_t status) { + auto context = weak.lock(); + if (!context) { + TAG_LOGE(AAFwkTag::UI_EXT, "context is released"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT)); + return; + } + auto extensionContext = AbilityRuntime::Context::ConvertTo(context); + if (!extensionContext) { + TAG_LOGE(AAFwkTag::UI_EXT, "extensionContext is nullptr"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM)); + return; + } + auto token = extensionContext->GetToken(); + AAFwk::AbilityManagerClient::GetInstance()->TransferAbilityResultForExtension(token, resultCode, want); + sptr uiWindow = context->GetWindow(); + if (!uiWindow) { + TAG_LOGE(AAFwkTag::UI_EXT, "uiWindow is nullptr"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM)); + return; + } + auto ret = uiWindow->TransferAbilityResult(resultCode, want); + if (ret != Rosen::WMError::WM_OK) { + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM)); + return; + } + auto errorCode = context->TerminateSelf(); + if (errorCode == 0) { + task.ResolveWithNoError(env, CreateJsUndefined(env)); + } else { + task.Reject(env, CreateJsErrorByNativeErr(env, errorCode)); + } + }; +} + napi_value JsUIExtensionContext::OpenAtomicServiceInner(napi_env env, NapiCallbackInfo& info, Want &want, const AAFwk::StartOptions &options, size_t unwrapArgc) { diff --git a/frameworks/native/appkit/BUILD.gn b/frameworks/native/appkit/BUILD.gn index fa2712f127..11c685f40e 100644 --- a/frameworks/native/appkit/BUILD.gn +++ b/frameworks/native/appkit/BUILD.gn @@ -48,29 +48,21 @@ config("appkit_config") { "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_path}/interfaces/kits/native/appkit/dfr", "${ability_runtime_path}/interfaces/kits/native/ability/native", - "//third_party/json/include", ] } config("appkit_public_config") { visibility = [ ":*" ] include_dirs = [ - "${ability_base_kits_path}/configuration/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_delegator", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/app", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_path}/interfaces/kits/native/appkit/dfr", - "${global_path}/resource_management/interfaces/inner_api/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", ] if (ability_runtime_graphics) { - include_dirs += [ - "${global_path}/i18n/frameworks/intl/include", - "//third_party/icu/icu4c/source/common", - ] - defines = [ "SUPPORT_GRAPHICS", "SUPPORT_APP_PREFERRED_LANGUAGE", @@ -97,6 +89,7 @@ ohos_shared_library("appkit_native") { "${ability_runtime_path}/utils/global/time/include", "${ability_runtime_services_path}/abilitymgr/include", "${ability_runtime_napi_path}/inner/napi_common", + "${ability_runtime_utils_path}/global/constant", ] if (ability_runtime_graphics) { @@ -125,6 +118,7 @@ ohos_shared_library("appkit_native") { "${ability_runtime_native_path}/appkit/app/assert_fault_callback.cpp", "${ability_runtime_native_path}/appkit/app/assert_fault_task_thread.cpp", "${ability_runtime_native_path}/appkit/app/child_main_thread.cpp", + "${ability_runtime_native_path}/appkit/app/dump_ffrt_helper.cpp", "${ability_runtime_native_path}/appkit/app/dump_ipc_helper.cpp", "${ability_runtime_native_path}/appkit/app/extension_plugin_info.cpp", "${ability_runtime_native_path}/appkit/app/idle_time.cpp", @@ -155,6 +149,7 @@ ohos_shared_library("appkit_native") { ":appkit_delegator", "${ability_runtime_abilitymgr_path}/:abilityms", "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/child_process_manager:child_process_manager", "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", @@ -173,7 +168,6 @@ ohos_shared_library("appkit_native") { external_deps = [ "ability_base:base", - "ability_base:configuration", "ability_base:extractresourcemanager", "ability_base:string_utils", "ability_base:want", @@ -193,18 +187,30 @@ ohos_shared_library("appkit_native") { "i18n:preferred_language", "init:libbegetutil", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", "resource_management:global_resmgr", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] + public_external_deps = [ "ability_base:configuration" ] + + if (cj_frontend) { + sources += [ + "${ability_runtime_native_path}/appkit/ability_runtime/app/cj_ability_stage.cpp", + "${ability_runtime_native_path}/appkit/ability_runtime/app/cj_ability_stage_object.cpp", + ] + + include_dirs += + [ "${ability_runtime_path}/cj_environment/interfaces/inner_api" ] + } if (ability_runtime_graphics) { - deps += [ "//third_party/icu/icu4c:shared_icuuc" ] external_deps += [ "ace_engine:ace_forward_compatibility", "graphic_2d:librender_service_client", "i18n:intl_util", + "icu:shared_icuuc", "window_manager:libwm", ] } @@ -238,7 +244,6 @@ ohos_shared_library("appkit_native") { # build so ohos_shared_library("app_context") { include_dirs = [ - "${ability_base_kits_path}/extractortool/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", @@ -263,6 +268,7 @@ ohos_shared_library("app_context") { } deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_innerkits_path}/runtime:runtime", @@ -270,7 +276,7 @@ ohos_shared_library("app_context") { ] external_deps = [ - "ability_base:configuration", + "ability_base:extractortool", "ability_base:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", @@ -280,14 +286,18 @@ ohos_shared_library("app_context") { "hitrace:hitrace_meter", "init:libbegetutil", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", "resource_management:global_resmgr", "samgr:samgr_proxy", ] + public_external_deps = [ "ability_base:configuration" ] if (ability_runtime_graphics) { - deps += [ "//third_party/icu/icu4c:shared_icuuc" ] - external_deps += [ "i18n:intl_util" ] + external_deps += [ + "i18n:intl_util", + "icu:shared_icuuc", + ] } innerapi_tags = [ "platformsdk" ] @@ -318,6 +328,7 @@ ohos_shared_library("app_context_utils") { } deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/error_utils:ability_runtime_error_util", "${ability_runtime_innerkits_path}/runtime:runtime", @@ -337,14 +348,17 @@ ohos_shared_library("app_context_utils") { "hilog:libhilog", "hitrace:hitrace_meter", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", "resource_management:global_resmgr", "resource_management:resmgr_napi_core", ] - + public_external_deps = [ "ability_base:configuration" ] if (ability_runtime_graphics) { - deps += [ "//third_party/icu/icu4c:shared_icuuc" ] - external_deps += [ "i18n:intl_util" ] + external_deps += [ + "i18n:intl_util", + "icu:shared_icuuc", + ] } innerapi_tags = [ "platformsdk" ] @@ -388,6 +402,7 @@ ohos_shared_library("appkit_delegator") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_native_path}/appkit:app_context", "${ability_runtime_native_path}/appkit:delegator_mgmt", @@ -401,11 +416,19 @@ ohos_shared_library("appkit_delegator") { "eventhandler:libeventhandler", "hilog:libhilog", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", ] + public_external_deps = [ "ability_base:configuration" ] + if (cj_frontend) { + sources += [ + "${ability_runtime_native_path}/appkit/ability_delegator/runner_runtime/cj_test_runner.cpp", + "${ability_runtime_native_path}/appkit/ability_delegator/runner_runtime/cj_test_runner_object.cpp", + ] + } if (ability_runtime_graphics) { - deps += [ "//third_party/icu/icu4c:shared_icuuc" ] + external_deps += [ "icu:shared_icuuc" ] } innerapi_tags = [ "platformsdk" ] @@ -425,6 +448,7 @@ ohos_shared_library("appkit_manager_helper") { "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", "${ability_runtime_services_path}/common/include", "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_utils_path}/global/constant", ] configs = [ ":appkit_config" ] @@ -447,11 +471,12 @@ ohos_shared_library("appkit_manager_helper") { "hilog:libhilog", "hitrace:hitrace_meter", "ipc:ipc_core", + "json:nlohmann_json_static", "samgr:samgr_proxy", ] if (ability_runtime_graphics) { - deps += [ "//third_party/icu/icu4c:shared_icuuc" ] + external_deps += [ "icu:shared_icuuc" ] } innerapi_tags = [ "platformsdk" ] diff --git a/frameworks/native/appkit/ability_bundle_manager_helper/bundle_mgr_helper.cpp b/frameworks/native/appkit/ability_bundle_manager_helper/bundle_mgr_helper.cpp index 732169263b..515fd24eb3 100644 --- a/frameworks/native/appkit/ability_bundle_manager_helper/bundle_mgr_helper.cpp +++ b/frameworks/native/appkit/ability_bundle_manager_helper/bundle_mgr_helper.cpp @@ -16,6 +16,7 @@ #include "bundle_mgr_helper.h" #include "bundle_mgr_service_death_recipient.h" +#include "global_constant.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" #include "hitrace_meter.h" @@ -81,7 +82,7 @@ ErrCode BundleMgrHelper::InstallSandboxApp(const std::string &bundleName, int32_ ErrCode BundleMgrHelper::UninstallSandboxApp(const std::string &bundleName, int32_t appIndex, int32_t userId) { TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); - if (bundleName.empty() || appIndex <= Constants::INITIAL_APP_INDEX) { + if (bundleName.empty() || appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "The params are invalid."); return ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR; } @@ -112,7 +113,7 @@ ErrCode BundleMgrHelper::GetSandboxBundleInfo( const std::string &bundleName, int32_t appIndex, int32_t userId, BundleInfo &info) { TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); - if (bundleName.empty() || appIndex <= Constants::INITIAL_APP_INDEX) { + if (bundleName.empty() || appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "The params are invalid."); return ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR; } @@ -130,7 +131,7 @@ ErrCode BundleMgrHelper::GetSandboxAbilityInfo(const Want &want, int32_t appInde AbilityInfo &abilityInfo) { TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); - if (appIndex <= Constants::INITIAL_APP_INDEX || appIndex > Constants::MAX_APP_INDEX) { + if (appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "The params are invalid."); return ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR; } @@ -151,7 +152,7 @@ ErrCode BundleMgrHelper::GetSandboxExtAbilityInfos(const Want &want, int32_t app int32_t userId, std::vector &extensionInfos) { TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); - if (appIndex <= Constants::INITIAL_APP_INDEX || appIndex > Constants::MAX_APP_INDEX) { + if (appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "The params are invalid."); return ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR; } @@ -169,7 +170,7 @@ ErrCode BundleMgrHelper::GetSandboxHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) { TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); - if (appIndex <= Constants::INITIAL_APP_INDEX || appIndex > Constants::MAX_APP_INDEX) { + if (appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "The params are invalid."); return ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR; } @@ -797,5 +798,31 @@ ErrCode BundleMgrHelper::GetLaunchWantForBundle(const std::string &bundleName, W return bundleMgr->GetLaunchWantForBundle(bundleName, want, userId); } +ErrCode BundleMgrHelper::QueryCloneAbilityInfo(const ElementName &element, int32_t flags, int32_t appCloneIndex, + AbilityInfo &abilityInfo, int32_t userId) +{ + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + auto bundleMgr = Connect(); + if (bundleMgr == nullptr) { + TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); + return ERR_APPEXECFWK_SERVICE_INTERNAL_ERROR; + } + + return bundleMgr->QueryCloneAbilityInfo(element, flags, appCloneIndex, abilityInfo, userId); +} + +ErrCode BundleMgrHelper::GetCloneBundleInfo(const std::string &bundleName, int32_t flags, int32_t appCloneIndex, + BundleInfo &bundleInfo, int32_t userId) +{ + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + auto bundleMgr = Connect(); + if (bundleMgr == nullptr) { + TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); + return ERR_APPEXECFWK_SERVICE_INTERNAL_ERROR; + } + + return bundleMgr->GetCloneBundleInfo(bundleName, flags, appCloneIndex, bundleInfo, userId); +} + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/appkit/ability_delegator/runner_runtime/cj_test_runner.cpp b/frameworks/native/appkit/ability_delegator/runner_runtime/cj_test_runner.cpp new file mode 100644 index 0000000000..dd9216fb24 --- /dev/null +++ b/frameworks/native/appkit/ability_delegator/runner_runtime/cj_test_runner.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2024 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 "runner_runtime/cj_test_runner.h" + +#include + +#include "ability_delegator_registry.h" +#include "hilog_wrapper.h" +#include "runner_runtime/cj_test_runner_object.h" + +namespace OHOS { +namespace RunnerRuntime { + +std::unique_ptr CJTestRunner::Create(const std::unique_ptr &runtime, + const std::shared_ptr &args, const AppExecFwk::BundleInfo &bundleInfo) +{ + HILOG_INFO("CJTestRunner::Create start."); + if (!runtime) { + HILOG_ERROR("Invalid runtime"); + return nullptr; + } + + auto cjRuntime = static_cast(runtime.get()); + if (cjRuntime->IsAppLibLoaded()) { + HILOG_ERROR("CJTestRunner: AppLib Not Loaded"); + return nullptr; + } + + if (!args) { + HILOG_ERROR("Invalid ability delegator args"); + return nullptr; + } + + auto pTestRunner = new (std::nothrow) CJTestRunner(*cjRuntime, args, bundleInfo); + if (!pTestRunner) { + HILOG_ERROR("Failed to create test runner"); + return nullptr; + } + + return std::unique_ptr(pTestRunner); +} + +CJTestRunner::CJTestRunner(CJRuntime &cjRuntime, const std::shared_ptr &args, + const AppExecFwk::BundleInfo &bundleInfo) : cjRuntime_(cjRuntime) +{ + std::string moduleName = args->GetTestRunnerClassName(); + cjTestRunnerObj_ = CJTestRunnerObject::LoadModule(moduleName); +} + +CJTestRunner::~CJTestRunner() = default; + +bool CJTestRunner::Initialize() +{ + if (!cjRuntime_.IsAppLibLoaded()) { + HILOG_ERROR("CJTestRunner: AppLib Not Loaded"); + return false; + } + if (!cjTestRunnerObj_) { + HILOG_ERROR("CJTestRunnerObj does not exist, Initialize failed."); + return false; + } + return true; +} + +void CJTestRunner::Prepare() +{ + HILOG_INFO("Enter"); + TestRunner::Prepare(); + if (!cjTestRunnerObj_) { + HILOG_ERROR("CJTestRunnerObj does not exist, Prepare failed."); + return; + } + cjTestRunnerObj_->OnPrepare(); + HILOG_INFO("End"); +} + +void CJTestRunner::Run() +{ + HILOG_INFO("Enter"); + TestRunner::Run(); + if (!cjTestRunnerObj_) { + HILOG_ERROR("CJTestRunnerObj does not exist, OnRun failed."); + return; + } + cjTestRunnerObj_->OnRun(); + HILOG_INFO("End"); +} + +void CJTestRunner::ReportFinished(const std::string &msg) +{ + HILOG_INFO("Enter"); + auto delegator = AbilityDelegatorRegistry::GetAbilityDelegator(); + if (!delegator) { + HILOG_ERROR("delegator is null."); + return; + } + + delegator->FinishUserTest(msg, -1); +} + +void CJTestRunner::ReportStatus(const std::string &msg) +{ + HILOG_INFO("Enter"); + auto delegator = AbilityDelegatorRegistry::GetAbilityDelegator(); + if (!delegator) { + HILOG_ERROR("delegator is null."); + return; + } + + delegator->Print(msg); +} +} // namespace RunnerRuntime +} // namespace OHOS diff --git a/frameworks/native/appkit/ability_delegator/runner_runtime/cj_test_runner_object.cpp b/frameworks/native/appkit/ability_delegator/runner_runtime/cj_test_runner_object.cpp new file mode 100644 index 0000000000..68ea89ca09 --- /dev/null +++ b/frameworks/native/appkit/ability_delegator/runner_runtime/cj_test_runner_object.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2024 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 "runner_runtime/cj_test_runner_object.h" + +#include + +#include "hilog_wrapper.h" + +namespace { +// g_cjTestRunnerFuncs is used to save cj functions. +// It is assigned by the global variable REGISTER_ABILITY on the cj side which invokes RegisterCJTestRunnerFuncs. +// And it is never released. +CJTestRunnerFuncs* g_cjTestRunnerFuncs = nullptr; +} // namespace + +void RegisterCJTestRunnerFuncs(void (*registerFunc)(CJTestRunnerFuncs*)) +{ + HILOG_INFO("RegisterCJTestRunnerFuncs start."); + if (g_cjTestRunnerFuncs != nullptr) { + HILOG_ERROR("Repeated registration for cj functions of CJTestRunner."); + return; + } + + if (registerFunc == nullptr) { + HILOG_ERROR("RegisterCJTestRunnerFuncs failed, registerFunc is nullptr."); + return; + } + + g_cjTestRunnerFuncs = new CJTestRunnerFuncs(); + registerFunc(g_cjTestRunnerFuncs); + HILOG_INFO("RegisterCJTestRunnerFuncs end."); +} + +namespace OHOS { +namespace RunnerRuntime { +std::shared_ptr CJTestRunnerObject::LoadModule(const std::string& name) +{ + if (g_cjTestRunnerFuncs == nullptr) { + HILOG_ERROR("cj functions for CJTestRunner are not registered"); + return nullptr; + } + auto id = g_cjTestRunnerFuncs->cjTestRunnerCreate(name.c_str()); + if (id == 0) { + HILOG_ERROR( + "Failed to invoke CJTestRunnerObject::LoadModule. Ability: %{public}s is not registered.", name.c_str()); + return nullptr; + } + return std::make_shared(id); +} + +CJTestRunnerObject::~CJTestRunnerObject() +{ + g_cjTestRunnerFuncs->cjTestRunnerRelease(id_); + id_ = 0; +} + +void CJTestRunnerObject::OnRun() const +{ + if (g_cjTestRunnerFuncs == nullptr) { + HILOG_ERROR("cj functions for CJTestRunner are not registered"); + return; + } + g_cjTestRunnerFuncs->cjTestRunnerOnRun(id_); +} + +void CJTestRunnerObject::OnPrepare() const +{ + if (g_cjTestRunnerFuncs == nullptr) { + HILOG_ERROR("cj functions for CJTestRunner are not registered"); + return; + } + g_cjTestRunnerFuncs->cjTestRunnerOnPrepare(id_); +} +} // namespace RunnerRuntime +} // namespace OHOS diff --git a/frameworks/native/appkit/ability_delegator/test_runner.cpp b/frameworks/native/appkit/ability_delegator/test_runner.cpp index c12c9a66dd..69f641a69a 100644 --- a/frameworks/native/appkit/ability_delegator/test_runner.cpp +++ b/frameworks/native/appkit/ability_delegator/test_runner.cpp @@ -17,6 +17,7 @@ #include "bundle_mgr_helper.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" +#include "runner_runtime/cj_test_runner.h" #include "runner_runtime/js_test_runner.h" #include "runtime.h" #include "sys_mgr_client.h" @@ -58,6 +59,8 @@ std::unique_ptr TestRunner::Create(const std::unique_ptrGetLanguage()) { case AbilityRuntime::Runtime::Language::JS: return RunnerRuntime::JsTestRunner::Create(runtime, args, bundleInfo, isFaJsModel); + case AbilityRuntime::Runtime::Language::CJ: + return RunnerRuntime::CJTestRunner::Create(runtime, args, bundleInfo); default: return std::make_unique(); } diff --git a/frameworks/native/appkit/ability_runtime/app/ability_stage.cpp b/frameworks/native/appkit/ability_runtime/app/ability_stage.cpp index 1e23dc2f2e..59e91cb145 100644 --- a/frameworks/native/appkit/ability_runtime/app/ability_stage.cpp +++ b/frameworks/native/appkit/ability_runtime/app/ability_stage.cpp @@ -19,6 +19,7 @@ #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" #include "hitrace_meter.h" +#include "cj_ability_stage.h" #include "js_ability_stage.h" #include "runtime.h" @@ -35,7 +36,8 @@ std::shared_ptr AbilityStage::Create( switch (runtime->GetLanguage()) { case Runtime::Language::JS: return JsAbilityStage::Create(runtime, hapModuleInfo); - + case Runtime::Language::CJ: + return CJAbilityStage::Create(runtime, hapModuleInfo); default: return std::make_shared(); } @@ -115,7 +117,8 @@ void AbilityStage::OnMemoryLevel(int level) TAG_LOGD(AAFwkTag::APPKIT, "%{public}s called.", __func__); } -int32_t AbilityStage::RunAutoStartupTask(const std::function &callback, bool &isAsyncCallback) +int32_t AbilityStage::RunAutoStartupTask(const std::function &callback, bool &isAsyncCallback, + const std::shared_ptr &stageContext) { TAG_LOGD(AAFwkTag::APPKIT, "called"); isAsyncCallback = false; diff --git a/frameworks/native/appkit/ability_runtime/app/cj_ability_stage.cpp b/frameworks/native/appkit/ability_runtime/app/cj_ability_stage.cpp new file mode 100644 index 0000000000..5a6b60581a --- /dev/null +++ b/frameworks/native/appkit/ability_runtime/app/cj_ability_stage.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2024 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 "cj_ability_stage.h" + +#include "cj_runtime.h" +#include "context_impl.h" +#include "hilog_wrapper.h" + +using namespace OHOS::AbilityRuntime; + +std::shared_ptr CJAbilityStage::Create( + const std::unique_ptr& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo) +{ + if (!runtime) { + HILOG_ERROR("Runtime does not exist."); + return nullptr; + } + auto& cjRuntime = static_cast(*runtime); + // Load cj app library. + if (!cjRuntime.IsAppLibLoaded()) { + HILOG_ERROR("Failed to create CJAbilityStage, applib not loaded."); + return nullptr; + } + + auto cjAbilityStageObject = CJAbilityStageObject::LoadModule(hapModuleInfo.moduleName); + if (cjAbilityStageObject == nullptr) { + cjRuntime.UnLoadCJAppLibrary(); + HILOG_ERROR("Failed to create CJAbilityStage."); + return nullptr; + } + + return std::make_shared(cjAbilityStageObject); +} + +void CJAbilityStage::OnCreate(const AAFwk::Want& want) const +{ + AbilityStage::OnCreate(want); + if (!cjAbilityStageObject_) { + HILOG_ERROR("CJAbilityStage is not loaded."); + return; + } + HILOG_DEBUG("CJAbilityStage::OnCreate"); + cjAbilityStageObject_->OnCreate(); +} + +std::string CJAbilityStage::OnAcceptWant(const AAFwk::Want& want) +{ + AbilityStage::OnAcceptWant(want); + if (!cjAbilityStageObject_) { + HILOG_ERROR("CJAbilityStage is not loaded."); + return ""; + } + return cjAbilityStageObject_->OnAcceptWant(want); +} + +void CJAbilityStage::OnConfigurationUpdated(const AppExecFwk::Configuration& configuration) +{ + AbilityStage::OnConfigurationUpdated(configuration); + auto fullConfig = GetContext()->GetConfiguration(); + if (!fullConfig) { + HILOG_ERROR("configuration is nullptr."); + return; + } + + if (!cjAbilityStageObject_) { + HILOG_ERROR("CJAbilityStage is not loaded."); + return; + } + cjAbilityStageObject_->OnConfigurationUpdated(fullConfig); +} + +void CJAbilityStage::OnMemoryLevel(int level) +{ + AbilityStage::OnMemoryLevel(level); + if (!cjAbilityStageObject_) { + HILOG_ERROR("CJAbilityStage is not loaded."); + return; + } + cjAbilityStageObject_->OnMemoryLevel(level); +} diff --git a/frameworks/native/appkit/ability_runtime/app/cj_ability_stage_object.cpp b/frameworks/native/appkit/ability_runtime/app/cj_ability_stage_object.cpp new file mode 100644 index 0000000000..3f931baa83 --- /dev/null +++ b/frameworks/native/appkit/ability_runtime/app/cj_ability_stage_object.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2024 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 "cj_ability_stage_object.h" + +#include "hilog_wrapper.h" + +using namespace OHOS::AbilityRuntime; + +namespace { +// g_cjAbilityStageFuncs is used to save cj functions. +// It is assigned by the global variable REGISTER_ABILITY_STAGE on the cj side which invokes +// RegisterCJAbilityStageFuncs. And it is never released. +CJAbilityStageFuncs* g_cjAbilityStageFuncs = nullptr; +} // namespace + +void RegisterCJAbilityStageFuncs(void (*registerFunc)(CJAbilityStageFuncs* result)) +{ + if (g_cjAbilityStageFuncs != nullptr) { + HILOG_ERROR("Repeated registration for cj functions of CJAbilityStage."); + return; + } + + if (registerFunc == nullptr) { + HILOG_ERROR("RegisterCJAbilityStageFuncs failed, registerFunc is nullptr."); + return; + } + + g_cjAbilityStageFuncs = new CJAbilityStageFuncs(); + registerFunc(g_cjAbilityStageFuncs); +} + +std::shared_ptr CJAbilityStageObject::LoadModule(const std::string& moduleName) +{ + if (g_cjAbilityStageFuncs == nullptr) { + HILOG_ERROR("cj functions for CJAbilityStage are not registered"); + return nullptr; + } + + HILOG_DEBUG("CJAbilityStageObject::LoadModule"); + auto handle = g_cjAbilityStageFuncs->LoadAbilityStage(moduleName.c_str()); + if (!handle) { + HILOG_ERROR("Failed to invoke CJAbilityStageObject::LoadModule. AbilityStage is not registered: %{public}s.", + moduleName.c_str()); + return nullptr; + } + + return std::make_shared(handle); +} + +CJAbilityStageObject::~CJAbilityStageObject() +{ + g_cjAbilityStageFuncs->ReleaseAbilityStage(id_); + id_ = 0; +} + +void CJAbilityStageObject::OnCreate() const +{ + if (g_cjAbilityStageFuncs == nullptr) { + HILOG_ERROR("cj functions for CJAbilityStage are not registered"); + return; + } + g_cjAbilityStageFuncs->AbilityStageOnCreate(id_); +} + +std::string CJAbilityStageObject::OnAcceptWant(const AAFwk::Want& want) const +{ + if (g_cjAbilityStageFuncs == nullptr) { + HILOG_ERROR("cj functions for CJAbilityStage are not registered"); + return ""; + } + + auto wantHandle = const_cast(&want); + auto unsafeStr = g_cjAbilityStageFuncs->AbilityStageOnAcceptWant(id_, wantHandle); + std::string result = unsafeStr == nullptr ? "" : unsafeStr; + if (unsafeStr != nullptr) { + free(static_cast(unsafeStr)); + } + return result; +} + +void CJAbilityStageObject::OnConfigurationUpdated(const std::shared_ptr& configuration) const +{ + if (g_cjAbilityStageFuncs == nullptr) { + HILOG_ERROR("cj functions for CJAbilityStage are not registered"); + return; + } +} + +void CJAbilityStageObject::OnMemoryLevel(int32_t level) const +{ + if (g_cjAbilityStageFuncs == nullptr) { + HILOG_ERROR("cj functions for CJAbilityStage are not registered"); + return; + } + g_cjAbilityStageFuncs->AbilityStageOnMemoryLevel(id_, level); +} diff --git a/frameworks/native/appkit/ability_runtime/app/js_ability_stage.cpp b/frameworks/native/appkit/ability_runtime/app/js_ability_stage.cpp index 099fa9b80d..f9b4fb504a 100644 --- a/frameworks/native/appkit/ability_runtime/app/js_ability_stage.cpp +++ b/frameworks/native/appkit/ability_runtime/app/js_ability_stage.cpp @@ -49,7 +49,7 @@ constexpr const char* RUN_ON_THREAD = "runOnThread"; constexpr const char* WAIT_ON_MAIN_THREAD = "waitOnMainThread"; constexpr const char* CONFIG_ENTRY = "configEntry"; constexpr const char *MAIN_THREAD = "mainThread"; -constexpr const char *TASKPOOL = "taskpool"; +constexpr const char *TASKPOOL = "taskPool"; napi_value AttachAbilityStageContext(napi_env env, void *value, void *) { @@ -169,39 +169,8 @@ void JsAbilityStage::Init(const std::shared_ptr &context, TAG_LOGE(AAFwkTag::APPKIT, "stage is nullptr"); return; } - - HandleScope handleScope(jsRuntime_); - auto env = jsRuntime_.GetNapiEnv(); - - napi_value obj = jsAbilityStageObj_->GetNapiValue(); - if (!CheckTypeForNapiValue(env, obj, napi_object)) { - TAG_LOGE(AAFwkTag::APPKIT, "Failed to get AbilityStage object"); - return; - } - - napi_value contextObj = CreateJsAbilityStageContext(env, context, nullptr, nullptr); - shellContextRef_ = JsRuntime::LoadSystemModuleByEngine(env, "application.AbilityStageContext", &contextObj, 1); - if (shellContextRef_ == nullptr) { - TAG_LOGE(AAFwkTag::APPKIT, "Failed to get LoadSystemModuleByEngine"); - return; - } - contextObj = shellContextRef_->GetNapiValue(); - if (!CheckTypeForNapiValue(env, contextObj, napi_object)) { - TAG_LOGE(AAFwkTag::APPKIT, "Failed to get context native object"); - return; - } - auto workContext = new (std::nothrow) std::weak_ptr(context); - napi_coerce_to_native_binding_object( - env, contextObj, DetachCallbackFunc, AttachAbilityStageContext, workContext, nullptr); - context->Bind(jsRuntime_, shellContextRef_.get()); - napi_set_named_property(env, obj, "context", contextObj); - TAG_LOGD(AAFwkTag::APPKIT, "Set ability stage context"); - napi_wrap(env, contextObj, workContext, - [](napi_env, void* data, void*) { - TAG_LOGD(AAFwkTag::APPKIT, "Finalizer for weak_ptr ability stage context is called"); - delete static_cast*>(data); - }, - nullptr, nullptr); + + SetJsAbilityStage(context); } void JsAbilityStage::OnCreate(const AAFwk::Want &want) const @@ -383,7 +352,8 @@ void JsAbilityStage::OnMemoryLevel(int32_t level) TAG_LOGD(AAFwkTag::APPKIT, "end"); } -int32_t JsAbilityStage::RunAutoStartupTask(const std::function &callback, bool &isAsyncCallback) +int32_t JsAbilityStage::RunAutoStartupTask(const std::function &callback, bool &isAsyncCallback, + const std::shared_ptr &stageContext) { TAG_LOGD(AAFwkTag::APPKIT, "called"); isAsyncCallback = false; @@ -397,12 +367,13 @@ int32_t JsAbilityStage::RunAutoStartupTask(const std::function &callback TAG_LOGE(AAFwkTag::APPKIT, "hapModuleInfo invalid."); return ERR_INVALID_VALUE; } - if (hapModuleInfo->moduleType != AppExecFwk::ModuleType::ENTRY || - hapModuleInfo->appStartup.empty()) { + if (hapModuleInfo->moduleType != AppExecFwk::ModuleType::ENTRY || hapModuleInfo->appStartup.empty()) { TAG_LOGD(AAFwkTag::APPKIT, "not entry module or appStartup not exist."); return ERR_INVALID_VALUE; } - + if (!shellContextRef_) { + SetJsAbilityStage(stageContext); + } std::vector jsStartupTasks; int32_t result = RegisterStartupTaskFromProfile(jsStartupTasks); if (result != ERR_OK) { @@ -803,5 +774,52 @@ bool JsAbilityStage::GetResFromResMgr( profileInfo.emplace_back(profile); return true; } + +void JsAbilityStage::SetJsAbilityStage(const std::shared_ptr &context) +{ + if (!context) { + TAG_LOGE(AAFwkTag::APPKIT, "context is nullptr"); + return; + } + + HandleScope handleScope(jsRuntime_); + auto env = jsRuntime_.GetNapiEnv(); + + napi_value obj = nullptr; + if (jsAbilityStageObj_) { + obj = jsAbilityStageObj_->GetNapiValue(); + if (!CheckTypeForNapiValue(env, obj, napi_object)) { + TAG_LOGE(AAFwkTag::APPKIT, "Failed to get AbilityStage object"); + return; + } + } + + napi_value contextObj = CreateJsAbilityStageContext(env, context, nullptr, nullptr); + shellContextRef_ = JsRuntime::LoadSystemModuleByEngine(env, "application.AbilityStageContext", &contextObj, 1); + if (shellContextRef_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Failed to get LoadSystemModuleByEngine"); + return; + } + contextObj = shellContextRef_->GetNapiValue(); + if (!CheckTypeForNapiValue(env, contextObj, napi_object)) { + TAG_LOGE(AAFwkTag::APPKIT, "Failed to get context native object"); + return; + } + auto workContext = new (std::nothrow) std::weak_ptr(context); + napi_coerce_to_native_binding_object( + env, contextObj, DetachCallbackFunc, AttachAbilityStageContext, workContext, nullptr); + context->Bind(jsRuntime_, shellContextRef_.get()); + + if (obj != nullptr) { + napi_set_named_property(env, obj, "context", contextObj); + } + TAG_LOGD(AAFwkTag::APPKIT, "Set ability stage context"); + napi_wrap(env, contextObj, workContext, + [](napi_env, void* data, void*) { + TAG_LOGD(AAFwkTag::APPKIT, "Finalizer for weak_ptr ability stage context is called"); + delete static_cast*>(data); + }, + nullptr, nullptr); +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/appkit/ability_runtime/context/application_context.cpp b/frameworks/native/appkit/ability_runtime/context/application_context.cpp index 29980816e1..c87c71944c 100644 --- a/frameworks/native/appkit/ability_runtime/context/application_context.cpp +++ b/frameworks/native/appkit/ability_runtime/context/application_context.cpp @@ -544,6 +544,19 @@ std::string ApplicationContext::GetAppRunningUniqueId() const return appRunningUniqueId_; } +int32_t ApplicationContext::GetCurrentAppCloneIndex() +{ + TAG_LOGD(AAFwkTag::APPKIT, "getCurrentAppCloneIndex is %{public}d.", appIndex_); + return appIndex_; +} + +int32_t ApplicationContext::GetCurrentAppMode() +{ + TAG_LOGD(AAFwkTag::APPKIT, "getCurrentMode is %{public}d.", appMode_); + return appMode_; +} + + void ApplicationContext::SetAppRunningUniqueId(const std::string &appRunningUniqueId) { TAG_LOGD(AAFwkTag::APPKIT, "SetAppRunningUniqueId is %{public}s.", appRunningUniqueId.c_str()); @@ -558,5 +571,17 @@ int32_t ApplicationContext::SetSupportedProcessCacheSelf(bool isSupport) TAG_LOGE(AAFwkTag::APPKIT, "contextImpl_ is nullptr."); return ERR_INVALID_VALUE; } + +void ApplicationContext::SetCurrentAppCloneIndex(int32_t appIndex) +{ + TAG_LOGD(AAFwkTag::APPKIT, "setCurrentAppCloneIndex is %{public}d.", appIndex); + appIndex_ = appIndex; +} + +void ApplicationContext::SetCurrentAppMode(int32_t appMode) +{ + TAG_LOGD(AAFwkTag::APPKIT, "setCurrentAppMode is %{public}d.", appMode); + appMode_ = appMode; +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/appkit/ability_runtime/context/context_impl.cpp b/frameworks/native/appkit/ability_runtime/context/context_impl.cpp index 269fc95aa6..afd034f204 100644 --- a/frameworks/native/appkit/ability_runtime/context/context_impl.cpp +++ b/frameworks/native/appkit/ability_runtime/context/context_impl.cpp @@ -59,8 +59,7 @@ const std::string ContextImpl::CONTEXT_BUNDLE("/bundle/"); const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE("/mnt/hmdfs/"); const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE("/device_view/local/data/"); const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES("distributedfiles"); -const std::string ContextImpl::CONTEXT_CLOUDFILE_DIR_BASE_BEFORE("/data/service/el2/"); -const std::string ContextImpl::CONTEXT_CLOUDFILE_DIR_BASE_MIDDLE("/hmdfs/cloud/data/"); +const std::string ContextImpl::CONTEXT_CLOUDFILE("cloud"); const std::string ContextImpl::CONTEXT_FILE_SEPARATOR("/"); const std::string ContextImpl::CONTEXT_DATA("/data/"); const std::string ContextImpl::CONTEXT_DATA_STORAGE("/data/storage/"); @@ -343,8 +342,7 @@ std::string ContextImpl::GetDistributedFilesDir() std::string ContextImpl::GetCloudFileDir() { - std::string dir = CONTEXT_CLOUDFILE_DIR_BASE_BEFORE + std::to_string(GetCurrentAccountId()) + - CONTEXT_CLOUDFILE_DIR_BASE_MIDDLE + GetBundleName(); + std::string dir = CONTEXT_DATA_STORAGE + CONTEXT_ELS[1] + CONTEXT_FILE_SEPARATOR + CONTEXT_CLOUDFILE; CreateDirIfNotExist(dir, MODE); return dir; } diff --git a/frameworks/native/appkit/ability_runtime/context/js_application_context_utils.cpp b/frameworks/native/appkit/ability_runtime/context/js_application_context_utils.cpp index 308199d540..c18df7372d 100644 --- a/frameworks/native/appkit/ability_runtime/context/js_application_context_utils.cpp +++ b/frameworks/native/appkit/ability_runtime/context/js_application_context_utils.cpp @@ -22,6 +22,7 @@ #include "ability_manager_interface.h" #include "ability_runtime_error_util.h" #include "application_context.h" +#include "application_info.h" #include "application_context_manager.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" @@ -690,13 +691,13 @@ napi_value JsApplicationContextUtils::OnPreloadUIExtensionAbility(napi_env env, auto innerErrCode = std::make_shared(ERR_OK); NapiAsyncTask::ExecuteCallback execute = [applicationContext = applicationContext_, want, innerErrCode]() { auto context = applicationContext.lock(); - auto hostBundleName = context->GetBundleName(); - TAG_LOGD(AAFwkTag::APPKIT, "HostBundleName is %{public}s.", hostBundleName.c_str()); if (!context) { TAG_LOGE(AAFwkTag::APPKIT, "context is released"); *innerErrCode = static_cast(AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT); return; } + auto hostBundleName = context->GetBundleName(); + TAG_LOGD(AAFwkTag::APPKIT, "HostBundleName is %{public}s.", hostBundleName.c_str()); *innerErrCode = AAFwk::AbilityManagerClient::GetInstance()->PreloadUIExtensionAbility(want, hostBundleName); }; NapiAsyncTask::CompleteCallback complete = [innerErrCode](napi_env env, NapiAsyncTask& task, int32_t status) { @@ -801,6 +802,29 @@ napi_value JsApplicationContextUtils::OnGetRunningProcessInformation(napi_env en return result; } +napi_value JsApplicationContextUtils::GetCurrentAppCloneIndex(napi_env env, napi_callback_info info) +{ + GET_NAPI_INFO_WITH_NAME_AND_CALL(env, info, JsApplicationContextUtils, + OnGetCurrentAppCloneIndex, APPLICATION_CONTEXT_NAME); +} + +napi_value JsApplicationContextUtils::OnGetCurrentAppCloneIndex(napi_env env, NapiCallbackInfo& info) +{ + TAG_LOGD(AAFwkTag::APPKIT, "Get App Index"); + auto context = applicationContext_.lock(); + if (context == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "context is nullptr."); + ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT); + return CreateJsUndefined(env); + } + if (context->GetCurrentAppMode() != static_cast(AppExecFwk::MultiAppModeType::APP_CLONE)) { + ThrowError(env, AbilityErrorCode::ERROR_NOT_APP_CLONE); + return CreateJsUndefined(env); + } + int32_t appIndex = context->GetCurrentAppCloneIndex(); + return CreateJsValue(env, appIndex); +} + void JsApplicationContextUtils::Finalizer(napi_env env, void *data, void *hint) { TAG_LOGD(AAFwkTag::APPKIT, "called"); @@ -1492,6 +1516,8 @@ void JsApplicationContextUtils::BindNativeApplicationContext(napi_env env, napi_ JsApplicationContextUtils::GetRunningProcessInformation); BindNativeFunction(env, object, "getRunningProcessInformation", MD_NAME, JsApplicationContextUtils::GetRunningProcessInformation); + BindNativeFunction(env, object, "getCurrentAppCloneIndex", MD_NAME, + JsApplicationContextUtils::GetCurrentAppCloneIndex); BindNativeFunction(env, object, "getGroupDir", MD_NAME, JsApplicationContextUtils::GetGroupDir); BindNativeFunction(env, object, "restartApp", MD_NAME, diff --git a/frameworks/native/appkit/ability_runtime/service_extension_context.cpp b/frameworks/native/appkit/ability_runtime/service_extension_context.cpp index 7f4d2de6ee..e3649d0694 100644 --- a/frameworks/native/appkit/ability_runtime/service_extension_context.cpp +++ b/frameworks/native/appkit/ability_runtime/service_extension_context.cpp @@ -125,8 +125,12 @@ ErrCode ServiceExtensionContext::ConnectAbility( ErrCode ServiceExtensionContext::StartAbilityWithAccount(const AAFwk::Want &want, int32_t accountId) const { - TAG_LOGD(AAFwkTag::APPKIT, "%{public}s begin.", __func__); - TAG_LOGI(AAFwkTag::APPKIT, "%{public}d accountId:", accountId); + std::string callerName = ""; + if (GetAbilityInfo() != nullptr) { + callerName = GetAbilityInfo()->name; + } + TAG_LOGI(AAFwkTag::APPKIT, "accountId: %{public}d, ability: %{public}s, caller: %{public}s", + accountId, want.GetElement().GetURI().c_str(), callerName.c_str()); (const_cast(want)).SetParam(START_ABILITY_TYPE, true); ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility( want, token_, ILLEGAL_REQUEST_CODE, accountId); diff --git a/frameworks/native/appkit/app/child_main_thread.cpp b/frameworks/native/appkit/app/child_main_thread.cpp index 004d0cca2b..a6030e6d93 100644 --- a/frameworks/native/appkit/app/child_main_thread.cpp +++ b/frameworks/native/appkit/app/child_main_thread.cpp @@ -14,7 +14,7 @@ */ #include "child_main_thread.h" - +#include #include "bundle_mgr_proxy.h" #include "child_process_manager.h" #include "constants.h" @@ -172,7 +172,12 @@ void ChildMainThread::InitNativeLib(const BundleInfo &bundleInfo) GetNativeLibPath(bundleInfo, appLibPaths); bool isSystemApp = bundleInfo.applicationInfo.isSystemApp; TAG_LOGD(AAFwkTag::APPKIT, "the application isSystemApp: %{public}d", isSystemApp); - AbilityRuntime::JsRuntime::SetAppLibPath(appLibPaths, isSystemApp); + + if (processInfo_->processType != CHILD_PROCESS_TYPE_NATIVE) { + AbilityRuntime::JsRuntime::SetAppLibPath(appLibPaths, isSystemApp); + } else { + UpdateNativeChildLibPath(appLibPaths); + } } void ChildMainThread::ExitProcessSafely() @@ -222,6 +227,67 @@ void ChildMainThread::HandleExitProcessSafely() } } +bool ChildMainThread::ScheduleRunNativeProc(const sptr &mainProcessCb) +{ + TAG_LOGD(AAFwkTag::APPKIT, "ScheduleRunNativeProc"); + if (mainProcessCb == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Main process callback is null"); + return false; + } + + if (mainHandler_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "mainHandler_ is null"); + return false; + } + + auto task = [weak = wptr(this), callback = sptr(mainProcessCb)]() { + auto childMainThread = weak.promote(); + if (childMainThread == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "childMainThread is nullptr, ScheduleRunNativeProc failed."); + return; + } + childMainThread->HandleRunNativeProc(callback); + }; + if (!mainHandler_->PostTask(task, "ChildMainThread::HandleRunNativeProc")) { + TAG_LOGE(AAFwkTag::APPKIT, "HandleRunNativeProc PostTask task failed."); + return false; + } + return true; +} + +void ChildMainThread::HandleRunNativeProc(const sptr &mainProcessCb) +{ + TAG_LOGD(AAFwkTag::APPKIT, "HandleRunNativeProc called start."); + if (!processInfo_) { + TAG_LOGE(AAFwkTag::APPKIT, "processInfo is null."); + return; + } + + ChildProcessManager &childProcessMgr = ChildProcessManager::GetInstance(); + childProcessMgr.LoadNativeLib(processInfo_->srcEntry, mainProcessCb); + TAG_LOGD(AAFwkTag::APPKIT, "HandleRunNativeProc end."); + ExitProcessSafely(); +} + +void ChildMainThread::UpdateNativeChildLibPath(const AppLibPathMap &appLibPaths) +{ + std::string nativeLibPath; + for (const auto &libPathPair : appLibPaths) { + for (const auto &libDir : libPathPair.second) { + nativeLibPath = libDir; + if (!nativeLibPath.empty() && nativeLibPath.back() != '/') { + nativeLibPath += '/'; + } + + nativeLibPath += processInfo_->srcEntry; + if (access(nativeLibPath.c_str(), F_OK) == 0) { + processInfo_->srcEntry = nativeLibPath; + break; + } + } + } +} + void ChildMainThread::GetNativeLibPath(const BundleInfo &bundleInfo, AppLibPathMap &appLibPaths) { std::string nativeLibraryPath = bundleInfo.applicationInfo.nativeLibraryPath; diff --git a/frameworks/native/appkit/app/dump_ffrt_helper.cpp b/frameworks/native/appkit/app/dump_ffrt_helper.cpp new file mode 100644 index 0000000000..ee589fa8aa --- /dev/null +++ b/frameworks/native/appkit/app/dump_ffrt_helper.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 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 "dump_ffrt_helper.h" + +#include +#include +#include "ffrt_inner.h" + +namespace OHOS { +namespace AppExecFwk { +constexpr const uint32_t MAX_BUF_SIZE = (1U << 19); +int DumpFfrtHelper::DumpFfrt(std::string& result) +{ + result.resize(MAX_BUF_SIZE); + + int printNum = ffrt_dump(ffrt_dump_cmd_t::DUMP_INFO_ALL, &result[0], MAX_BUF_SIZE); + if (printNum > 0) { + result.resize(printNum); + return 0; + } + result.resize(0); + return -1; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/native/appkit/app/dump_ipc_helper.cpp b/frameworks/native/appkit/app/dump_ipc_helper.cpp index 3f2fdcc652..040a9bd8e2 100644 --- a/frameworks/native/appkit/app/dump_ipc_helper.cpp +++ b/frameworks/native/appkit/app/dump_ipc_helper.cpp @@ -19,8 +19,8 @@ #include #include -#include "string_ex.h" #include "ipc_payload_statistics.h" +#include "string_ex.h" namespace OHOS { namespace AppExecFwk { @@ -29,7 +29,7 @@ const std::string DUMP_IPC_CMD_FAIL = "fail"; void DumpIpcHelper::DumpIpcStart(std::string& result) { - result += "StartIpcStatistics pid: " + std::to_string(getpid()) + "\t"; + result += "StartIpcStatistics pid: " + std::to_string(getprocpid()) + "\t"; if (IPCPayloadStatistics::StartStatistics()) { result += DUMP_IPC_CMD_SUCCESS; return; @@ -39,7 +39,7 @@ void DumpIpcHelper::DumpIpcStart(std::string& result) void DumpIpcHelper::DumpIpcStop(std::string& result) { - result += "StopIpcStatistics pid: " + std::to_string(getpid()) + "\t"; + result += "StopIpcStatistics pid: " + std::to_string(getprocpid()) + "\t"; if (IPCPayloadStatistics::StopStatistics()) { result += DUMP_IPC_CMD_SUCCESS; return; @@ -51,7 +51,7 @@ void DumpIpcHelper::DumpIpcStat(std::string& result) { result += "********************************GlobalStatisticsInfo********************************"; result += "\nCurrentPid:"; - result += std::to_string(getpid()); + result += std::to_string(getprocpid()); result += "\nTotalCount:"; result += std::to_string(IPCPayloadStatistics::GetTotalCount()); result += "\nTotalTimeCost:"; diff --git a/frameworks/native/appkit/app/main_thread.cpp b/frameworks/native/appkit/app/main_thread.cpp index beeaae14cb..361b620986 100644 --- a/frameworks/native/appkit/app/main_thread.cpp +++ b/frameworks/native/appkit/app/main_thread.cpp @@ -42,8 +42,11 @@ #include "child_process_manager.h" #include "configuration_convertor.h" #include "common_event_manager.h" +#include "global_constant.h" #include "context_deal.h" #include "context_impl.h" +#include "dump_ffrt_helper.h" +#include "dump_ipc_helper.h" #include "exit_reason.h" #include "extension_ability_info.h" #include "extension_module_loader.h" @@ -81,7 +84,6 @@ #include "js_runtime_utils.h" #include "context/application_context.h" #include "os_account_manager_wrapper.h" -#include "dump_ipc_helper.h" #if defined(NWEB) #include @@ -638,7 +640,16 @@ void MainThread::ScheduleJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info) return; } if (info.needSnapshot == true) { - runtime->DumpHeapSnapshot(info.tid, info.needGc); + std::vector fdVec; + for (auto &fd : info.fdVec) { + uint32_t newFd = dup(fd); + if (newFd == -1) { + TAG_LOGE(AAFwkTag::APPKIT, "dup failed."); + return; + } + fdVec.push_back(newFd); + } + runtime->DumpHeapSnapshot(info.tid, info.needGc, fdVec, info.tidVec); } else { if (info.needGc == true) { runtime->ForceFullGC(info.tid); @@ -1169,6 +1180,7 @@ bool IsNeedLoadLibrary(const std::string &bundleName) std::vector needLoadLibraryBundleNames{ "com.ohos.contactsdataability", "com.ohos.medialibrary.medialibrarydata", + "com.ohos.ringtonelibrary.ringtonelibrarydata", "com.ohos.telephonydataability", "com.ohos.FusionSearch", "com.ohos.formrenderservice" @@ -1186,7 +1198,7 @@ bool GetBundleForLaunchApplication(std::shared_ptr bundleMgrHel int32_t appIndex, BundleInfo &bundleInfo) { bool queryResult; - if (appIndex != 0) { + if (appIndex > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { TAG_LOGD(AAFwkTag::APPKIT, "The bundleName = %{public}s.", bundleName.c_str()); queryResult = (bundleMgrHelper->GetSandboxBundleInfo(bundleName, appIndex, UNSPECIFIED_USERID, bundleInfo) == 0); @@ -1316,6 +1328,9 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con contextImpl->SetApplicationInfo(std::make_shared(appInfo)); std::shared_ptr applicationContext = AbilityRuntime::ApplicationContext::GetInstance(); + int32_t appIndex = appLaunchData.GetAppIndex(); + applicationContext->SetCurrentAppCloneIndex(appIndex); + applicationContext->SetCurrentAppMode(static_cast(appInfo.multiAppMode.multiAppModeType)); applicationContext->AttachContextImpl(contextImpl); auto appRunningId = appLaunchData.GetAppRunningUniqueId(); applicationContext->SetAppRunningUniqueId(appRunningId); @@ -2417,7 +2432,7 @@ void MainThread::ForceFullGC() void MainThread::Start() { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); - TAG_LOGI(AAFwkTag::APPKIT, "App main thread create, pid:%{public}d.", getpid()); + TAG_LOGI(AAFwkTag::APPKIT, "App main thread create, pid:%{public}d.", getprocpid()); if (AAFwk::AppUtils::GetInstance().IsMultiProcessModel()) { ChildProcessInfo info; @@ -3113,12 +3128,22 @@ void MainThread::AssertFaultPauseMainThreadDetection() { TAG_LOGD(AAFwkTag::APPKIT, "Called."); SetAppDebug(AbilityRuntime::AppFreezeState::AppFreezeFlag::ASSERT_DEBUG_MODE, true); + if (appMgr_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "appMgr is nullptr."); + return; + } + appMgr_->SetAppAssertionPauseState(true); } void MainThread::AssertFaultResumeMainThreadDetection() { TAG_LOGD(AAFwkTag::APPKIT, "Called."); SetAppDebug(AbilityRuntime::AppFreezeState::AppFreezeFlag::ASSERT_DEBUG_MODE, false); + if (appMgr_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "appMgr is nullptr."); + return; + } + appMgr_->SetAppAssertionPauseState(false); } void MainThread::HandleInitAssertFaultTask(bool isDebugModule, bool isDebugApp) @@ -3175,23 +3200,29 @@ void MainThread::HandleCancelAssertFaultTask() int32_t MainThread::ScheduleDumpIpcStart(std::string& result) { - TAG_LOGD(AAFwkTag::APPKIT, "MainThread::ScheduleDumpIpcStart::pid:%{public}d", getpid()); + TAG_LOGD(AAFwkTag::APPKIT, "MainThread::ScheduleDumpIpcStart::pid:%{public}d", getprocpid()); DumpIpcHelper::DumpIpcStart(result); return ERR_OK; } int32_t MainThread::ScheduleDumpIpcStop(std::string& result) { - TAG_LOGD(AAFwkTag::APPKIT, "MainThread::ScheduleDumpIpcStop::pid:%{public}d", getpid()); + TAG_LOGD(AAFwkTag::APPKIT, "MainThread::ScheduleDumpIpcStop::pid:%{public}d", getprocpid()); DumpIpcHelper::DumpIpcStop(result); return ERR_OK; } int32_t MainThread::ScheduleDumpIpcStat(std::string& result) { - TAG_LOGD(AAFwkTag::APPKIT, "MainThread::ScheduleDumpIpcStat::pid:%{public}d", getpid()); + TAG_LOGD(AAFwkTag::APPKIT, "MainThread::ScheduleDumpIpcStat::pid:%{public}d", getprocpid()); DumpIpcHelper::DumpIpcStat(result); return ERR_OK; } + +int32_t MainThread::ScheduleDumpFfrt(std::string& result) +{ + TAG_LOGD(AAFwkTag::APPKIT, "MainThread::ScheduleDumpFfrt::pid:%{public}d", getprocpid()); + return DumpFfrtHelper::DumpFfrt(result); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/native/appkit/app/ohos_application.cpp b/frameworks/native/appkit/app/ohos_application.cpp index 77d7dce47e..262301b742 100644 --- a/frameworks/native/appkit/app/ohos_application.cpp +++ b/frameworks/native/appkit/app/ohos_application.cpp @@ -676,7 +676,7 @@ std::shared_ptr OHOSApplication::AddAbilityStage( ohosApplication->AutoStartupDone(abilityRecord, abilityStage, moduleName); callback(abilityStage->GetContext()); }; - abilityStage->RunAutoStartupTask(autoStartupCallback, isAsyncCallback); + abilityStage->RunAutoStartupTask(autoStartupCallback, isAsyncCallback, stageContext); if (isAsyncCallback) { TAG_LOGI(AAFwkTag::APPKIT, "waiting for startup"); return nullptr; diff --git a/frameworks/native/appkit/app_startup/js_startup_task.cpp b/frameworks/native/appkit/app_startup/js_startup_task.cpp index fbad92d8d5..c0dfdd5876 100644 --- a/frameworks/native/appkit/app_startup/js_startup_task.cpp +++ b/frameworks/native/appkit/app_startup/js_startup_task.cpp @@ -20,8 +20,9 @@ #include "js_runtime_utils.h" namespace { -constexpr size_t ARGC_ONE = 1; +constexpr size_t ARGC_TWO = 2; constexpr int32_t INDEX_ZERO = 0; +constexpr int32_t INDEX_ONE = 1; } namespace OHOS { namespace AbilityRuntime { @@ -119,14 +120,13 @@ void JsStartupTask::LoadJsAsyncTaskCallback() JsRuntime::LoadSystemModuleByEngine(env, "app.appstartup.AsyncTaskCallback", &asyncTaskCallbackClass, 1); } -void JsStartupTask::OnAsyncTaskCompleted() +void JsStartupTask::OnAsyncTaskCompleted(const std::shared_ptr &result) { TAG_LOGD(AAFwkTag::STARTUP, "Called."); if (startupTaskResultCallback_ == nullptr) { TAG_LOGE(AAFwkTag::STARTUP, "Startup task result callback object is nullptr."); return; } - std::shared_ptr result = std::make_shared(nullptr); startupTaskResultCallback_->Call(result); } @@ -189,8 +189,8 @@ napi_value JsStartupTask::GetDependencyResult(napi_env env, const std::string &d napi_value AsyncTaskCallBack::AsyncTaskCompleted(napi_env env, napi_callback_info info) { TAG_LOGD(AAFwkTag::STARTUP, "Called."); - size_t argc = ARGC_ONE; - napi_value argv[ARGC_ONE] = { nullptr }; + size_t argc = ARGC_TWO; + napi_value argv[ARGC_TWO] = { nullptr }; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); @@ -200,6 +200,12 @@ napi_value AsyncTaskCallBack::AsyncTaskCompleted(napi_env env, napi_callback_inf return CreateJsUndefined(env); } + napi_value resultJs = argv[INDEX_ONE]; + napi_ref resultRef = nullptr; + napi_create_reference(env, resultJs, INDEX_ONE, &resultRef); + std::shared_ptr result(reinterpret_cast(resultRef)); + std::shared_ptr callbackResult = std::make_shared(result); + std::shared_ptr startupTask; for (auto iter : AsyncTaskCallBack::jsStartupTaskObjects_) { if (iter.first == startupName) { @@ -208,7 +214,7 @@ napi_value AsyncTaskCallBack::AsyncTaskCompleted(napi_env env, napi_callback_inf } if (startupTask != nullptr) { - startupTask->OnAsyncTaskCompleted(); + startupTask->OnAsyncTaskCompleted(callbackResult); AsyncTaskCallBack::jsStartupTaskObjects_.erase(startupName); } diff --git a/frameworks/native/appkit/app_startup/js_startup_task_executor.cpp b/frameworks/native/appkit/app_startup/js_startup_task_executor.cpp index 8ea932fc5a..e4bb365e22 100644 --- a/frameworks/native/appkit/app_startup/js_startup_task_executor.cpp +++ b/frameworks/native/appkit/app_startup/js_startup_task_executor.cpp @@ -182,6 +182,7 @@ void JsStartupTaskExecutor::ReplyFailed(StartupTaskResultCallback *callback, std::shared_ptr result = std::make_shared(resultCode, resultMessage); callback->Call(result); delete callback; + callback = nullptr; } void JsStartupTaskExecutor::ReplyFailed(std::unique_ptr callback, @@ -205,6 +206,7 @@ void JsStartupTaskExecutor::ReplySucceeded(StartupTaskResultCallback *callback, std::shared_ptr result = std::make_shared(resultRef); callback->Call(result); delete callback; + callback = nullptr; } } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/appkit/app_startup/js_startup_task_result.cpp b/frameworks/native/appkit/app_startup/js_startup_task_result.cpp index cdacf747ad..113f5d37e6 100644 --- a/frameworks/native/appkit/app_startup/js_startup_task_result.cpp +++ b/frameworks/native/appkit/app_startup/js_startup_task_result.cpp @@ -35,7 +35,7 @@ StartupTaskResult::ResultType JsStartupTaskResult::GetResultType() const return ResultType::JS; } -std::shared_ptr JsStartupTaskResult::GetJsStartupResultRef() const +const std::shared_ptr& JsStartupTaskResult::GetJsStartupResultRef() const { return jsStartupResultRef_; } diff --git a/frameworks/native/appkit/app_startup/startup_config.cpp b/frameworks/native/appkit/app_startup/startup_config.cpp index a77d6560e6..3e0dffed88 100644 --- a/frameworks/native/appkit/app_startup/startup_config.cpp +++ b/frameworks/native/appkit/app_startup/startup_config.cpp @@ -36,12 +36,11 @@ int32_t StartupConfig::GetAwaitTimeoutMs() const return awaitTimeoutMs_; } -int32_t StartupConfig::ListenerOnCompleted(const std::shared_ptr &result) +void StartupConfig::ListenerOnCompleted(const std::shared_ptr &result) { if (listener_ != nullptr) { listener_->OnCompleted(result); } - return ERR_OK; } } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/appkit/app_startup/startup_manager.cpp b/frameworks/native/appkit/app_startup/startup_manager.cpp index d64aeab7fd..3cc7f822ca 100644 --- a/frameworks/native/appkit/app_startup/startup_manager.cpp +++ b/frameworks/native/appkit/app_startup/startup_manager.cpp @@ -128,7 +128,7 @@ void StartupManager::SetDefaultConfig(const std::shared_ptr &conf defaultConfig_ = config; } -std::shared_ptr StartupManager::GetDefaultConfig() const +const std::shared_ptr& StartupManager::GetDefaultConfig() const { return defaultConfig_; } diff --git a/frameworks/native/appkit/app_startup/startup_task.cpp b/frameworks/native/appkit/app_startup/startup_task.cpp index 4ce4529368..00203dcc5a 100644 --- a/frameworks/native/appkit/app_startup/startup_task.cpp +++ b/frameworks/native/appkit/app_startup/startup_task.cpp @@ -13,22 +13,18 @@ * limitations under the License. */ - #include "startup_task.h" - #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { -StartupTask::StartupTask(const std::string &name) : name_(name) -{ - state_ = State::CREATED; -} +StartupTask::StartupTask(const std::string &name) : name_(name), state_(State::CREATED) +{} StartupTask::~StartupTask() = default; -std::string StartupTask::GetName() const +const std::string& StartupTask::GetName() const { return name_; } @@ -100,7 +96,7 @@ int32_t StartupTask::RemoveResult() return ERR_OK; } -std::shared_ptr StartupTask::GetResult() const +const std::shared_ptr& StartupTask::GetResult() const { return result_; } @@ -117,7 +113,7 @@ std::string StartupTask::DumpDependencies() const } bool isFirst = true; std::string dumpResult; - for (auto &iter : dependencies_) { + for (const auto &iter : dependencies_) { if (isFirst) { dumpResult = iter; isFirst = false; diff --git a/frameworks/native/appkit/app_startup/startup_task_manager.cpp b/frameworks/native/appkit/app_startup/startup_task_manager.cpp index 05ee16c31f..b7b3203ef7 100644 --- a/frameworks/native/appkit/app_startup/startup_task_manager.cpp +++ b/frameworks/native/appkit/app_startup/startup_task_manager.cpp @@ -47,10 +47,9 @@ int32_t StartupTaskManager::AddTask(const std::shared_ptr &task) return ERR_OK; } -int32_t StartupTaskManager::SetConfig(const std::shared_ptr &config) +void StartupTaskManager::SetConfig(const std::shared_ptr &config) { config_ = config; - return ERR_OK; } int32_t StartupTaskManager::Prepare() diff --git a/frameworks/native/appkit/app_startup/startup_task_result.cpp b/frameworks/native/appkit/app_startup/startup_task_result.cpp index e9b0cebc5e..a378faf843 100644 --- a/frameworks/native/appkit/app_startup/startup_task_result.cpp +++ b/frameworks/native/appkit/app_startup/startup_task_result.cpp @@ -44,7 +44,7 @@ int32_t StartupTaskResult::GetResultCode() const return resultCode_; } -std::string StartupTaskResult::GetResultMessage() const +const std::string& StartupTaskResult::GetResultMessage() const { return resultMessage_; } diff --git a/frameworks/native/appkit/dfr/appfreeze_inner.cpp b/frameworks/native/appkit/dfr/appfreeze_inner.cpp index 96f50b67bc..743ad2b067 100644 --- a/frameworks/native/appkit/dfr/appfreeze_inner.cpp +++ b/frameworks/native/appkit/dfr/appfreeze_inner.cpp @@ -18,6 +18,7 @@ #include "ability_manager_client.h" #include "ability_state.h" +#include "appfreeze_manager.h" #include "app_recovery.h" #include "exit_reason.h" #include "ffrt.h" diff --git a/frameworks/native/child_process/BUILD.gn b/frameworks/native/child_process/BUILD.gn new file mode 100644 index 0000000000..4d5fe5006a --- /dev/null +++ b/frameworks/native/child_process/BUILD.gn @@ -0,0 +1,66 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +config("child_process_ndk_config") { + include_dirs = + [ "${ability_runtime_ndk_path}/ability/ability_runtime/child_process" ] + + if (target_cpu == "arm") { + cflags = [ "-DBINDER_IPC_32BIT" ] + } +} + +ohos_shared_library("child_process") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + cfi_vcall_icall_only = true + debug = false + } + branch_protector_ret = "pac_ret" + + include_dirs = [ "include" ] + + configs = [ "${ability_runtime_services_path}/common:common_config" ] + public_configs = [ ":child_process_ndk_config" ] + + sources = [ + "${ability_runtime_native_path}/child_process/src/native_child_callback.cpp", + "${ability_runtime_native_path}/child_process/src/native_child_process.cpp", + ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_innerkits_path}/child_process_manager:child_process_manager", + "${ability_runtime_native_path}/ability/native:ability_business_error", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_capi", + "ipc:ipc_core", + ] + + output_extension = "so" + innerapi_tags = [ "ndk" ] + install_images = [ "system" ] + subsystem_name = "ability" + part_name = "ability_runtime" +} diff --git a/frameworks/native/child_process/include/native_child_callback.h b/frameworks/native/child_process/include/native_child_callback.h new file mode 100644 index 0000000000..b0be67b876 --- /dev/null +++ b/frameworks/native/child_process/include/native_child_callback.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_NATIVE_CHILD_CALLBACK_H +#define OHOS_ABILITY_RUNTIME_NATIVE_CHILD_CALLBACK_H + +#include "native_child_notify_stub.h" +#include "native_child_process.h" + +namespace OHOS { +namespace AbilityRuntime { + +class NativeChildCallback : public OHOS::AppExecFwk::NativeChildNotifyStub { +public: + explicit NativeChildCallback(OH_Ability_OnNativeChildProcessStarted cb); + ~NativeChildCallback() = default; + + void OnNativeChildStarted(const sptr &nativeChild) override; + void OnError(int32_t errCode) override; + +private: + OH_Ability_OnNativeChildProcessStarted callback_ = nullptr; +}; + +} // namespace AbilityRuntime +} // namespace OHOS + +#endif // OHOS_ABILITY_RUNTIME_NATIVE_CHILD_CALLBACK_H diff --git a/frameworks/native/child_process/src/native_child_callback.cpp b/frameworks/native/child_process/src/native_child_callback.cpp new file mode 100644 index 0000000000..1102c8b3fb --- /dev/null +++ b/frameworks/native/child_process/src/native_child_callback.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_child_callback.h" +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" +#include "ipc_inner_object.h" +#include "child_process_manager_error_utils.h" + +namespace OHOS { +namespace AbilityRuntime { + +NativeChildCallback::NativeChildCallback(OH_Ability_OnNativeChildProcessStarted cb) + : NativeChildNotifyStub(), callback_(cb) +{ +} + +void NativeChildCallback::OnNativeChildStarted(const sptr &nativeChild) +{ + if (callback_ == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Native child process started, but callback is null?"); + return; + } + + if (!nativeChild) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Native child process ipc object is null"); + return; + } + + TAG_LOGI(AAFwkTag::PROCESSMGR, "Native child process started"); + sptr ipcRemote = nativeChild; + OHIPCRemoteProxy *ipcProxy = CreateIPCRemoteProxy(ipcRemote); + if (ipcProxy == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Convert inner ipc object to OHIPCRemoteProxy point failed"); + callback_(NCP_ERR_INTERNAL, nullptr); + return; + } + + callback_(static_cast(ChildProcessManagerErrorCode::ERR_OK), ipcProxy); +} + +void NativeChildCallback::OnError(int32_t errCode) +{ + if (callback_ == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Native child process start failed, but callback is null?"); + return; + } + + TAG_LOGI(AAFwkTag::PROCESSMGR, "Native child process start failed, err %{public}d", errCode); + callback_(errCode, nullptr); +} + +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/frameworks/native/child_process/src/native_child_process.cpp b/frameworks/native/child_process/src/native_child_process.cpp new file mode 100644 index 0000000000..f87e4a8562 --- /dev/null +++ b/frameworks/native/child_process/src/native_child_process.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_child_process.h" +#include +#include +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" +#include "native_child_callback.h" +#include "child_process_manager.h" + +using namespace OHOS; +using namespace OHOS::AbilityRuntime; + +namespace { + +std::mutex g_mutexCallBackObj; +sptr g_CallbackStub; +OH_Ability_OnNativeChildProcessStarted g_Callback = nullptr; + +const std::map CPM_ERRCODE_MAP = { + { ChildProcessManagerErrorCode::ERR_OK, NCP_NO_ERROR }, + { ChildProcessManagerErrorCode::ERR_MULTI_PROCESS_MODEL_DISABLED, NCP_ERR_MULTI_PROCESS_DISABLED }, + { ChildProcessManagerErrorCode::ERR_ALREADY_IN_CHILD_PROCESS, NCP_ERR_ALREADY_IN_CHILD }, + { ChildProcessManagerErrorCode::ERR_GET_APP_MGR_FAILED, NCP_ERR_SERVICE_ERROR }, + { ChildProcessManagerErrorCode::ERR_GET_APP_MGR_START_PROCESS_FAILED, NCP_ERR_SERVICE_ERROR }, + { ChildProcessManagerErrorCode::ERR_UNSUPPORT_NATIVE_CHILD_PROCESS, NCP_ERR_NOT_SUPPORTED }, + { ChildProcessManagerErrorCode::ERR_MAX_NATIVE_CHILD_PROCESSES, NCP_ERR_MAX_CHILD_PROCESSES_REACHED }, + { ChildProcessManagerErrorCode::ERR_LIB_LOADING_FAILED, NCP_ERR_LIB_LOADING_FAILED }, + { ChildProcessManagerErrorCode::ERR_CONNECTION_FAILED, NCP_ERR_CONNECTION_FAILED }, +}; + +int CvtChildProcessManagerErrCode(ChildProcessManagerErrorCode cpmErr) +{ + auto it = CPM_ERRCODE_MAP.find(cpmErr); + if (it == CPM_ERRCODE_MAP.end()) { + return NCP_ERR_INTERNAL; + } + + return it->second; +} + +void OnNativeChildProcessStartedWapper(int errCode, OHIPCRemoteProxy *ipcProxy) +{ + std::unique_lock autoLock(g_mutexCallBackObj); + if (g_Callback != nullptr) { + g_Callback(CvtChildProcessManagerErrCode(static_cast(errCode)), ipcProxy); + g_Callback = nullptr; + } else { + TAG_LOGW(AAFwkTag::PROCESSMGR, "Remote call twice?"); + } + + g_CallbackStub.clear(); +} + +} // Anonymous namespace + +int OH_Ability_CreateNativeChildProcess(const char* libName, OH_Ability_OnNativeChildProcessStarted onProcessStarted) +{ + if (libName == nullptr || *libName == '\0' || onProcessStarted == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Invalid libname or callback"); + return NCP_ERR_INVALID_PARAM; + } + + std::string strLibName(libName); + if (strLibName.find("../") != std::string::npos) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Do not allow use relative path"); + return NCP_ERR_INVALID_PARAM; + } + + std::unique_lock autoLock(g_mutexCallBackObj); + if (g_Callback != nullptr || g_CallbackStub != nullptr) { + TAG_LOGW(AAFwkTag::PROCESSMGR, "Another native process process starting, try again later"); + return NCP_ERR_BUSY; + } + + sptr callbackStub(new (std::nothrow) NativeChildCallback(OnNativeChildProcessStartedWapper)); + if (!callbackStub) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Alloc callback ipc stub object faild."); + return NCP_ERR_INTERNAL; + } + + ChildProcessManager &mgr = ChildProcessManager::GetInstance(); + auto cpmErr = mgr.StartNativeChildProcessByAppSpawnFork(strLibName, callbackStub); + if (cpmErr != ChildProcessManagerErrorCode::ERR_OK) { + return CvtChildProcessManagerErrCode(cpmErr); + } + + g_Callback = onProcessStarted; + g_CallbackStub = callbackStub; + return NCP_NO_ERROR; +} diff --git a/frameworks/native/insight_intent/insight_intent_context/BUILD.gn b/frameworks/native/insight_intent/insight_intent_context/BUILD.gn index 66264511ed..1f51aad0e6 100644 --- a/frameworks/native/insight_intent/insight_intent_context/BUILD.gn +++ b/frameworks/native/insight_intent/insight_intent_context/BUILD.gn @@ -34,6 +34,7 @@ ohos_shared_library("insightintentcontext") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/ability/native:ability_business_error", diff --git a/frameworks/native/runtime/cj_runtime.cpp b/frameworks/native/runtime/cj_runtime.cpp new file mode 100644 index 0000000000..588daf9a4f --- /dev/null +++ b/frameworks/native/runtime/cj_runtime.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2024 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 "cj_runtime.h" + +#include +#include +#include + +#include "cj_environment.h" +#include "hilog_wrapper.h" +#include "hdc_register.h" +#include "connect_server_manager.h" + +using namespace OHOS::AbilityRuntime; + +namespace { +const std::string DEBUGGER = "@Debugger"; +const std::string SANDBOX_LIB_PATH = "/data/storage/el1/bundle/libs/arm64"; +const std::string CJ_RT_PATH = SANDBOX_LIB_PATH + "/runtime"; +const std::string CJ_LIB_PATH = SANDBOX_LIB_PATH + "/ohos"; +const std::string CJ_SYSLIB_PATH = "/system/lib64:/system/lib64/platformsdk:/system/lib64/module:/system/lib64/ndk"; +const std::string CJ_CHIPSDK_PATH = "/system/lib64/chipset-pub-sdk"; +} // namespace + +AppLibPathVec CJRuntime::appLibPaths_; + +std::unique_ptr CJRuntime::Create(const Options& options) +{ + auto instance = std::make_unique(); + if (!instance || !instance->Initialize(options)) { + return nullptr; + } + return instance; +} + +void CJRuntime::SetAppLibPath(const AppLibPathMap& appLibPaths) +{ + std::string appPath = ""; + for (const auto& kv : appLibPaths) { + for (const auto& libPath : kv.second) { + HILOG_INFO("SetCJAppLibPath: %{public}s.", libPath.c_str()); + CJRuntime::appLibPaths_.emplace_back(libPath); + appPath += appPath.empty() ? libPath : ":" + libPath; + } + } + CJEnvironment::GetInstance()->InitCJAppNS(appPath); + CJEnvironment::GetInstance()->InitCJSDKNS(CJ_RT_PATH + ":" + CJ_LIB_PATH); + CJEnvironment::GetInstance()->InitCJSysNS(CJ_SYSLIB_PATH); + CJEnvironment::GetInstance()->InitCJChipSDKNS(CJ_CHIPSDK_PATH); +} + +bool CJRuntime::Initialize(const Options& options) +{ + if (options.lang != GetLanguage()) { + HILOG_ERROR("CJRuntime Initialize fail, language mismatch"); + return false; + } + if (!OHOS::CJEnvironment::GetInstance()->StartRuntime()) { + HILOG_ERROR("start cj runtime failed"); + return false; + } + if (!OHOS::CJEnvironment::GetInstance()->StartUIScheduler()) { + HILOG_ERROR("start cj ui context failed"); + return false; + } + if (!LoadCJAppLibrary(CJRuntime::appLibPaths_)) { + HILOG_ERROR("CJRuntime::Initialize fail, load app library fail."); + return false; + } + bundleName_ = options.bundleName; + instanceId_ = static_cast(getproctid()); + return true; +} + +void CJRuntime::RegisterUncaughtExceptionHandler(const CJUncaughtExceptionInfo& uncaughtExceptionInfo) +{ + HILOG_INFO("RegisterUncaughtExceptionHandler not support yet"); +} + +bool CJRuntime::LoadCJAppLibrary(const AppLibPathVec& appLibPaths) +{ + void* handle = nullptr; + for (const auto& libPath : appLibPaths) { + for (auto& itor : std::filesystem::directory_iterator(libPath)) { + // According to the convention, the names of Cangjie generated products must contain the following keywords + if (itor.path().string().find("ohos_app_cangjie") == std::string::npos) { + continue; + } + handle = OHOS::CJEnvironment::GetInstance()->LoadCJLibrary(itor.path().c_str()); + if (handle == nullptr) { + char* errMsg = dlerror(); + HILOG_ERROR( + "Failed to load %{public}s : reason: %{public}s.", itor.path().c_str(), errMsg ? errMsg : "null"); + return false; + } + } + } + appLibLoaded_ = true; + return true; +} + +void CJRuntime::StartDebugMode(const DebugOption dOption) +{ + if (debugModel_) { + HILOG_INFO("Already in debug mode"); + return; + } + + bool isStartWithDebug = dOption.isStartWithDebug; + bool isDebugApp = dOption.isDebugApp; + const std::string bundleName = bundleName_; + uint32_t instanceId = instanceId_; + std::string inputProcessName = bundleName_ != dOption.processName ? dOption.processName : ""; + + HILOG_INFO("StartDebugMode %{public}s", bundleName_.c_str()); + + HdcRegister::Get().StartHdcRegister(bundleName_, inputProcessName, isDebugApp, + [bundleName, isStartWithDebug, isDebugApp](int socketFd, std::string option) { + HILOG_INFO("HdcRegister callback is call, socket fd is %{public}d, option is %{public}s.", + socketFd, option.c_str()); + if (option.find(DEBUGGER) == std::string::npos) { + if (!isDebugApp) { + ConnectServerManager::Get().StopConnectServer(false); + } + ConnectServerManager::Get().SendDebuggerInfo(isStartWithDebug, isDebugApp); + ConnectServerManager::Get().StartConnectServer(bundleName, socketFd, false); + } else { + HILOG_ERROR("debugger service unexpected option: %{public}s", option.c_str()); + } + }); + if (isDebugApp) { + ConnectServerManager::Get().StartConnectServer(bundleName_, -1, true); + } + ConnectServerManager::Get().AddInstance(instanceId_, instanceId_); + + debugModel_ = StartDebugger(); +} + +bool CJRuntime::StartDebugger() +{ + return CJEnvironment::GetInstance()->StartDebugger(); +} + +void CJRuntime::UnLoadCJAppLibrary() +{ + HILOG_INFO("UnLoadCJAppLibrary not support yet"); +} diff --git a/frameworks/native/runtime/connect_server_manager.cpp b/frameworks/native/runtime/connect_server_manager.cpp index c9c641a9c1..df32a44c68 100644 --- a/frameworks/native/runtime/connect_server_manager.cpp +++ b/frameworks/native/runtime/connect_server_manager.cpp @@ -171,9 +171,9 @@ void ConnectServerManager::SendDebuggerInfo(bool needBreakPoint, bool isDebugApp auto instanceName = instance.second.first; auto tid = instance.second.second; - panda::EcmaVM* vm = reinterpret_cast(g_debuggerInfo[instanceId].first); + panda::EcmaVM* vm = reinterpret_cast(g_debuggerInfo[tid].first); std::lock_guard lock(g_debuggerMutex); - const auto &debuggerPoskTask = g_debuggerInfo[instanceId].second; + const auto &debuggerPoskTask = g_debuggerInfo[tid].second; if (!debuggerPoskTask) { continue; } @@ -407,4 +407,13 @@ void ConnectServerManager::SendArkUIStateProfilerMessage(const std::string &mess sendProfilerMessage(message); } +DebuggerPostTask ConnectServerManager::GetDebuggerPostTask(int32_t tid) +{ + auto it = g_debuggerInfo.find(tid); + if (it == g_debuggerInfo.end()) { + TAG_LOGW(AAFwkTag::JSRUNTIME, "ConnectServerManager::GetDebuggerPostTask tid %{public}d is not found: ", tid); + return nullptr; + } + return it->second.second; +} } // namespace OHOS::AbilityRuntime \ No newline at end of file diff --git a/frameworks/native/runtime/connect_server_manager.h b/frameworks/native/runtime/connect_server_manager.h index 0c98c613b4..a4dd6a9a4d 100644 --- a/frameworks/native/runtime/connect_server_manager.h +++ b/frameworks/native/runtime/connect_server_manager.h @@ -52,6 +52,7 @@ public: bool SendInstanceMessage(int32_t tid, int32_t instanceId, const std::string& instanceName); void SendDebuggerInfo(bool needBreakPoint, bool isDebugApp); void LoadConnectServerDebuggerSo(); + DebuggerPostTask GetDebuggerPostTask(int32_t tid); private: ConnectServerManager() = default; diff --git a/frameworks/native/runtime/js_error_utils.cpp b/frameworks/native/runtime/js_error_utils.cpp index 32be7a3044..b9993ef2d7 100755 --- a/frameworks/native/runtime/js_error_utils.cpp +++ b/frameworks/native/runtime/js_error_utils.cpp @@ -36,7 +36,7 @@ void ThrowError(napi_env env, const AbilityErrorCode& err) napi_throw(env, CreateJsError(env, static_cast(err), GetErrorMsg(err))); } -void ThrowInvaildCallerError(napi_env env) +void ThrowInvalidCallerError(napi_env env) { napi_throw(env, CreateJsError(env, static_cast(AbilityErrorCode::ERROR_CODE_INVALID_CALLER), diff --git a/frameworks/native/runtime/js_runtime.cpp b/frameworks/native/runtime/js_runtime.cpp index bc2439fa66..30ce8611ea 100644 --- a/frameworks/native/runtime/js_runtime.cpp +++ b/frameworks/native/runtime/js_runtime.cpp @@ -282,7 +282,9 @@ void JsRuntime::StartDebugMode(const DebugOption dOption) if (isDebugApp) { weak->StopDebugger(option); } - weak->StartDebugger(option, ARK_DEBUGGER_LIB_PATH, socketFd, isStartWithDebug, instanceId); + int32_t tid = weak->ParseHdcRegisterOption(option); + const auto &debuggerPostTask = ConnectServerManager::Get().GetDebuggerPostTask(tid); + weak->StartDebugger(option, socketFd, isDebugApp, debuggerPostTask); } }); if (isDebugApp) { @@ -293,7 +295,7 @@ void JsRuntime::StartDebugMode(const DebugOption dOption) EcmaVM* vm = GetEcmaVm(); auto dTask = jsEnv_->GetDebuggerPostTask(); panda::JSNApi::DebugOption option = {ARK_DEBUGGER_LIB_PATH, isDebugApp ? isStartWithDebug : false}; - ConnectServerManager::Get().StoreDebuggerInfo(instanceId_, reinterpret_cast(vm), option, dTask, isDebugApp); + ConnectServerManager::Get().StoreDebuggerInfo(getproctid(), reinterpret_cast(vm), option, dTask, isDebugApp); jsEnv_->NotifyDebugMode(getproctid(), ARK_DEBUGGER_LIB_PATH, instanceId_, isDebugApp, isStartWithDebug); } @@ -408,7 +410,9 @@ void JsRuntime::StartProfiler(const DebugOption dOption) if (isDebugApp) { weak->StopDebugger(option); } - weak->StartDebugger(option, ARK_DEBUGGER_LIB_PATH, socketFd, isStartWithDebug, instanceId); + int32_t tid = weak->ParseHdcRegisterOption(option); + const auto &debuggerPostTask = ConnectServerManager::Get().GetDebuggerPostTask(tid); + weak->StartDebugger(option, socketFd, isDebugApp, debuggerPostTask); } }); if (isDebugApp) { @@ -425,7 +429,7 @@ void JsRuntime::StartProfiler(const DebugOption dOption) EcmaVM* vm = GetEcmaVm(); auto dTask = jsEnv_->GetDebuggerPostTask(); panda::JSNApi::DebugOption option = {ARK_DEBUGGER_LIB_PATH, isDebugApp ? isStartWithDebug : false}; - ConnectServerManager::Get().StoreDebuggerInfo(instanceId_, reinterpret_cast(vm), option, dTask, isDebugApp); + ConnectServerManager::Get().StoreDebuggerInfo(getproctid(), reinterpret_cast(vm), option, dTask, isDebugApp); TAG_LOGD(AAFwkTag::JSRUNTIME, "profiler:%{public}d interval:%{public}d.", profiler, interval); jsEnv_->StartProfiler(ARK_DEBUGGER_LIB_PATH, instanceId_, profiler, interval, getproctid(), isDebugApp); } @@ -622,7 +626,6 @@ void JsRuntime::FinishPreload() auto vm = GetEcmaVm(); CHECK_POINTER(vm); panda::JSNApi::PreFork(vm); - jsEnv_->StopMonitorJSHeapUsage(); } void JsRuntime::PostPreload(const Options& options) @@ -683,8 +686,6 @@ bool JsRuntime::Initialize(const Options& options) } NativeCreateEnv::RegCreateNapiEnvCallback(CreateNapiEnv); NativeCreateEnv::RegDestroyNapiEnvCallback(DestroyNapiEnv); - } else { - jsEnv_->StartMonitorJSHeapUsage(); } apiTargetVersion_ = options.apiTargetVersion; TAG_LOGD(AAFwkTag::JSRUNTIME, "Initialize: %{public}d.", apiTargetVersion_); @@ -1191,11 +1192,12 @@ void JsRuntime::DumpHeapSnapshot(bool isPrivate) nativeEngine->DumpHeapSnapshot(true, DumpFormat::JSON, isPrivate, false); } -void JsRuntime::DumpHeapSnapshot(uint32_t tid, bool isFullGC) +void JsRuntime::DumpHeapSnapshot(uint32_t tid, bool isFullGC, std::vector fdVec, + std::vector tidVec) { auto vm = GetEcmaVm(); CHECK_POINTER(vm); - DFXJSNApi::DumpHeapSnapshot(vm, 0, true, false, false, isFullGC, tid); + DFXJSNApi::DumpHeapSnapshot(vm, 0, true, false, false, isFullGC, tid, fdVec, tidVec); } void JsRuntime::ForceFullGC(uint32_t tid) diff --git a/frameworks/native/runtime/native_runtime_impl.cpp b/frameworks/native/runtime/native_runtime_impl.cpp index 98bf9d55dc..1eccd3c66c 100644 --- a/frameworks/native/runtime/native_runtime_impl.cpp +++ b/frameworks/native/runtime/native_runtime_impl.cpp @@ -147,9 +147,6 @@ napi_status NativeRuntimeImpl::Init(const Options& options, napi_env env) } if (!options.preload) { - auto operatorObj = std::make_shared(options.bundleName, isModular, - options.isDebugVersion); - InitSourceMap(operatorObj, jsEnv); if (!options.isUnique) { InitTimerModule(jsEnv); } @@ -248,16 +245,6 @@ void NativeRuntimeImpl::InitConsoleModule(const std::shared_ptrInitConsoleModule(); } -void NativeRuntimeImpl::InitSourceMap(const std::shared_ptr operatorObj, - const std::shared_ptr& jsEnv) -{ - if (jsEnv == nullptr) { - TAG_LOGE(AAFwkTag::JSRUNTIME, "jsEnv is nullptr."); - return; - } - jsEnv->InitSourceMap(operatorObj); -} - void NativeRuntimeImpl::InitTimerModule(const std::shared_ptr& jsEnv) { if (jsEnv == nullptr) { diff --git a/frameworks/native/runtime/runtime.cpp b/frameworks/native/runtime/runtime.cpp index e9c31dc120..f2c51a6bd2 100644 --- a/frameworks/native/runtime/runtime.cpp +++ b/frameworks/native/runtime/runtime.cpp @@ -15,6 +15,7 @@ #include "runtime.h" +#include "cj_runtime.h" #include "js_runtime.h" namespace OHOS { @@ -28,7 +29,8 @@ std::unique_ptr Runtime::Create(const Runtime::Options& options) switch (options.lang) { case Runtime::Language::JS: return JsRuntime::Create(options); - + case Runtime::Language::CJ: + return CJRuntime::Create(options); default: return std::unique_ptr(); } diff --git a/frameworks/simulator/ability_simulator/BUILD.gn b/frameworks/simulator/ability_simulator/BUILD.gn index 2107c1f990..0671f9f18f 100644 --- a/frameworks/simulator/ability_simulator/BUILD.gn +++ b/frameworks/simulator/ability_simulator/BUILD.gn @@ -105,10 +105,7 @@ ohos_shared_library("ability_simulator_inner") { configs = [ "${windowmanager_path}/previewer:previewer_window_config" ] - deps = [ - ":gen_obj_src_js_mock_abc", - "//third_party/jsoncpp:jsoncpp_static", - ] + deps = [ ":gen_obj_src_js_mock_abc" ] external_deps = [ "ability_base:string_utils", @@ -116,6 +113,7 @@ ohos_shared_library("ability_simulator_inner") { "ets_utils:console", "ets_utils:timer", "hilog:libhilog", + "jsoncpp:jsoncpp_static", "napi:ace_napi", ] diff --git a/frameworks/simulator/ability_simulator/src/js_runtime_utils.cpp b/frameworks/simulator/ability_simulator/src/js_runtime_utils.cpp index 998bd24579..df9e345c84 100644 --- a/frameworks/simulator/ability_simulator/src/js_runtime_utils.cpp +++ b/frameworks/simulator/ability_simulator/src/js_runtime_utils.cpp @@ -299,21 +299,21 @@ std::unique_ptr CreateAsyncTaskWithLastParam(napi_env env, napi_v } std::unique_ptr CreateAsyncTaskWithLastParam(napi_env env, napi_value lastParam, - NapiAsyncTask::ExecuteCallback &&execute, nullptr_t, napi_value *result) + NapiAsyncTask::ExecuteCallback &&execute, std::nullptr_t, napi_value *result) { return CreateAsyncTaskWithLastParam( env, lastParam, std::make_unique(std::move(execute)), nullptr, result); } std::unique_ptr CreateAsyncTaskWithLastParam(napi_env env, napi_value lastParam, - nullptr_t, NapiAsyncTask::CompleteCallback &&complete, napi_value *result) + std::nullptr_t, NapiAsyncTask::CompleteCallback &&complete, napi_value *result) { return CreateAsyncTaskWithLastParam( env, lastParam, nullptr, std::make_unique(std::move(complete)), result); } std::unique_ptr CreateAsyncTaskWithLastParam(napi_env env, napi_value lastParam, - nullptr_t, nullptr_t, napi_value *result) + std::nullptr_t, std::nullptr_t, napi_value *result) { return CreateAsyncTaskWithLastParam(env, lastParam, std::unique_ptr(), std::unique_ptr(), result); diff --git a/frameworks/simulator/ability_simulator/src/simulator.cpp b/frameworks/simulator/ability_simulator/src/simulator.cpp index cd20910a0b..19c438535e 100644 --- a/frameworks/simulator/ability_simulator/src/simulator.cpp +++ b/frameworks/simulator/ability_simulator/src/simulator.cpp @@ -56,6 +56,13 @@ constexpr size_t DEFAULT_GC_THREAD_NUM = 7; constexpr size_t DEFAULT_LONG_PAUSE_TIME = 40; constexpr char BUNDLE_INSTALL_PATH[] = "/data/storage/el1/bundle/"; +const std::string PACKAGE_NAME = "packageName"; +const std::string BUNDLE_NAME = "bundleName"; +const std::string MODULE_NAME = "moduleName"; +const std::string VERSION = "version"; +const std::string ENTRY_PATH = "entryPath"; +const std::string IS_SO = "isSO"; +const std::string DEPENDENCY_ALIAS = "dependencyAlias"; #if defined(WINDOWS_PLATFORM) constexpr char ARK_DEBUGGER_LIB_PATH[] = "libark_debugger.dll"; @@ -140,6 +147,11 @@ private: std::shared_ptr moduleInfo_; std::shared_ptr abilityInfo_; CallbackTypePostTask postTask_ = nullptr; + void GetPkgContextInfoListMap(const std::map &contextInfoMap, + std::map>> &pkgContextInfoMap, + std::map &pkgAliasMap); + void GetPkgContextInfoListInner(nlohmann::json &itemObject, std::vector &items, + std::map &pkgAliasMap, std::string &pkgName); }; void DebuggerTask::HandleTask(const uv_async_t *req) @@ -719,6 +731,12 @@ bool SimulatorImpl::OnInit() panda::JSNApi::SetBundleName(vm_, options_.bundleName); panda::JSNApi::SetModuleName(vm_, options_.moduleName); panda::JSNApi::SetAssetPath(vm_, options_.modulePath); + std::map>> pkgContextInfoMap; + std::map pkgAliasMap; + GetPkgContextInfoListMap(options_.pkgContextInfoJsonStringMap, pkgContextInfoMap, pkgAliasMap); + panda::JSNApi::SetpkgContextInfoList(vm_, pkgContextInfoMap); + panda::JSNApi::SetPkgAliasList(vm_, pkgAliasMap); + panda::JSNApi::SetPkgNameList(vm_, options_.packageNameList); nativeEngine_ = env; return true; @@ -834,5 +852,87 @@ void SimulatorImpl::SetHostResolveBufferTracker(ResolveBufferTrackerCallback cb) } panda::JSNApi::SetHostResolveBufferTracker(vm_, cb); } + +void SimulatorImpl::GetPkgContextInfoListMap(const std::map &contextInfoMap, + std::map>> &pkgContextInfoMap, + std::map &pkgAliasMap) +{ + for (auto it = contextInfoMap.begin(); it != contextInfoMap.end(); it++) { + std::vector> pkgContextInfoList; + auto jsonObject = nlohmann::json::parse(it->second); + if (jsonObject.is_discarded()) { + TAG_LOGE(AAFwkTag::JSRUNTIME, "moduleName: %{public}s parse json error", it->first.c_str()); + continue; + } + for (nlohmann::json::iterator jsonIt = jsonObject.begin(); jsonIt != jsonObject.end(); jsonIt++) { + std::vector items; + items.emplace_back(jsonIt.key()); + nlohmann::json itemObject = jsonIt.value(); + std::string pkgName = ""; + items.emplace_back(PACKAGE_NAME); + if (itemObject[PACKAGE_NAME].is_null() || !itemObject[PACKAGE_NAME].is_string()) { + items.emplace_back(pkgName); + } else { + pkgName = itemObject[PACKAGE_NAME].get(); + items.emplace_back(pkgName); + } + + items.emplace_back(BUNDLE_NAME); + if (itemObject[BUNDLE_NAME].is_null() || !itemObject[BUNDLE_NAME].is_string()) { + items.emplace_back(""); + } else { + items.emplace_back(itemObject[BUNDLE_NAME].get()); + } + + items.emplace_back(MODULE_NAME); + if (itemObject[MODULE_NAME].is_null() || !itemObject[MODULE_NAME].is_string()) { + items.emplace_back(""); + } else { + items.emplace_back(itemObject[MODULE_NAME].get()); + } + + GetPkgContextInfoListInner(itemObject, items, pkgAliasMap, pkgName); + pkgContextInfoList.emplace_back(items); + } + TAG_LOGI(AAFwkTag::JSRUNTIME, "moduleName: %{public}s parse json success", it->first.c_str()); + pkgContextInfoMap[it->first] = pkgContextInfoList; + } +} + +void SimulatorImpl::GetPkgContextInfoListInner(nlohmann::json &itemObject, std::vector &items, + std::map &pkgAliasMap, std::string &pkgName) +{ + items.emplace_back(VERSION); + if (itemObject[VERSION].is_null() || !itemObject[VERSION].is_string()) { + items.emplace_back(""); + } else { + items.emplace_back(itemObject[VERSION].get()); + } + + items.emplace_back(ENTRY_PATH); + if (itemObject[ENTRY_PATH].is_null() || !itemObject[ENTRY_PATH].is_string()) { + items.emplace_back(""); + } else { + items.emplace_back(itemObject[ENTRY_PATH].get()); + } + + items.emplace_back(IS_SO); + if (itemObject[IS_SO].is_null() || !itemObject[IS_SO].is_boolean()) { + items.emplace_back("false"); + } else { + bool isSo = itemObject[IS_SO].get(); + if (isSo) { + items.emplace_back("true"); + } else { + items.emplace_back("false"); + } + } + if (!itemObject[DEPENDENCY_ALIAS].is_null() && itemObject[DEPENDENCY_ALIAS].is_string()) { + std::string pkgAlias = itemObject[DEPENDENCY_ALIAS].get(); + if (!pkgAlias.empty()) { + pkgAliasMap[pkgAlias] = pkgName; + } + } +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/simulator/common/include/configuration.h b/frameworks/simulator/common/include/configuration.h index 01b651a318..d4e38e088c 100644 --- a/frameworks/simulator/common/include/configuration.h +++ b/frameworks/simulator/common/include/configuration.h @@ -44,20 +44,6 @@ constexpr const char* APPLICATION_DIRECTION = "ohos.application.direction"; constexpr const char* APPLICATION_DENSITYDPI = "ohos.application.densitydpi"; constexpr const char* APPLICATION_DISPLAYID = "ohos.application.displayid"; -/* - * This must be synchronized with the value in GlobalConfigurationKey - */ -const std::vector SystemConfigurationKeyStore { - OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE, - OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_HOUR, - OHOS::AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, - OHOS::AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, - OHOS::AAFwk::GlobalConfigurationKey::DEVICE_TYPE, - OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DIRECTION, - OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DENSITYDPI, - OHOS::AppExecFwk::ConfigurationInner::APPLICATION_DISPLAYID, -}; - constexpr const char* COLOR_MODE_LIGHT = "light"; constexpr const char* COLOR_MODE_DARK = "dark"; constexpr const char* DEVICE_TYPE_DEFAULT = "default"; diff --git a/frameworks/simulator/common/include/options.h b/frameworks/simulator/common/include/options.h index 0f7952e156..eb4180fb9d 100644 --- a/frameworks/simulator/common/include/options.h +++ b/frameworks/simulator/common/include/options.h @@ -102,6 +102,8 @@ struct Options { std::shared_ptr configuration; std::vector moduleJsonBuffer; CallbackTypePostTask postTask; + std::map pkgContextInfoJsonStringMap; + std::map packageNameList; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/hisysevent.yaml b/hisysevent.yaml index 7ee5356092..2779d3226e 100644 --- a/hisysevent.yaml +++ b/hisysevent.yaml @@ -352,3 +352,15 @@ START_STANDARD_ABILITIES: BUNDLE_NAME: {type: STRING, desc: bundle name} MODULE_NAME: {type: STRING, desc: module name} ABILITY_NAME: {type: STRING, desc: ability name} + +PREVENT_START_ABILITY: + __BASE: {type: BEHAVIOR, level: MINOR, desc: Process start control, preserve: true} + CALLER_UID: {type: INT32, desc: caller uid} + CALLER_PID: {type: INT32, desc: caller pid} + CALLER_PROCESS_NAME: {type: STRING, desc: caller process name} + CALLER_BUNDLE_NAME: {type: STRING, desc: caller bundle name} + CALLEE_BUNDLE_NAME: {type: STRING, desc: callee bundle name} + CALLEE_PROCESS_NAME: {type: STRING, desc: callee process name} + EXTENSION_ABILITY_TYPE: {type: INT32, desc: extension ability type} + ABILITY_NAME: {type: STRING, desc: caller ability name} + \ No newline at end of file diff --git a/interfaces/inner_api/ability_manager/BUILD.gn b/interfaces/inner_api/ability_manager/BUILD.gn index 645b4100e0..c81443611c 100644 --- a/interfaces/inner_api/ability_manager/BUILD.gn +++ b/interfaces/inner_api/ability_manager/BUILD.gn @@ -26,11 +26,9 @@ config("ability_manager_public_config") { include_dirs = [ "include/", "include/status_bar_delegate", - "${eventhandler_path}/interfaces/inner_api", - "${ability_base_kits_path}/configuration/include", - "${ability_base_kits_path}/uri/include", - "${ability_base_kits_path}/want/include", "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/kits", + "${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/distributed", "${bundlefwk_inner_api_path}/appexecfwk_base/include", "${ability_runtime_innerkits_path}/ability_manager/include", "${ability_runtime_innerkits_path}/app_manager/include/appmgr", @@ -38,7 +36,6 @@ config("ability_manager_public_config") { "${ability_runtime_path}/interfaces/kits/native/appkit/dfr", "${ability_runtime_path}/interfaces/kits/native/appkit", "${ability_runtime_innerkits_path}/dataobs_manager/include", - "//third_party/jsoncpp/include", ] defines = [] @@ -71,11 +68,8 @@ ohos_shared_library("ability_manager") { "${ability_runtime_native_path}/ability/native/task_handler_client.cpp", "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_client.cpp", "${ability_runtime_services_path}/abilitymgr/src/ability_manager_client.cpp", - "${ability_runtime_services_path}/abilitymgr/src/ability_manager_collaborator_proxy.cpp", "${ability_runtime_services_path}/abilitymgr/src/ability_manager_proxy.cpp", - "${ability_runtime_services_path}/abilitymgr/src/ability_manager_stub.cpp", "${ability_runtime_services_path}/abilitymgr/src/ability_running_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/ability_scheduler_proxy.cpp", "${ability_runtime_services_path}/abilitymgr/src/ability_scheduler_stub.cpp", "${ability_runtime_services_path}/abilitymgr/src/acquire_share_data_callback_proxy.cpp", "${ability_runtime_services_path}/abilitymgr/src/acquire_share_data_callback_stub.cpp", @@ -90,17 +84,14 @@ ohos_shared_library("ability_manager") { "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_result.cpp", "${ability_runtime_services_path}/abilitymgr/src/launch_param.cpp", "${ability_runtime_services_path}/abilitymgr/src/lifecycle_state_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/mission_listener_proxy.cpp", "${ability_runtime_services_path}/abilitymgr/src/mission_listener_stub.cpp", "${ability_runtime_services_path}/abilitymgr/src/open_link/open_link_options.cpp", "${ability_runtime_services_path}/abilitymgr/src/prepare_terminate_callback_proxy.cpp", "${ability_runtime_services_path}/abilitymgr/src/prepare_terminate_callback_stub.cpp", - "${ability_runtime_services_path}/abilitymgr/src/remote_mission_listener_proxy.cpp", "${ability_runtime_services_path}/abilitymgr/src/remote_mission_listener_stub.cpp", "${ability_runtime_services_path}/abilitymgr/src/remote_on_listener_proxy.cpp", "${ability_runtime_services_path}/abilitymgr/src/remote_on_listener_stub.cpp", "${ability_runtime_services_path}/abilitymgr/src/sender_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/start_options.cpp", "${ability_runtime_services_path}/abilitymgr/src/system_ability_token_callback_stub.cpp", "${ability_runtime_services_path}/abilitymgr/src/ui_extension_ability_connect_info.cpp", "${ability_runtime_services_path}/abilitymgr/src/ui_extension_host_info.cpp", @@ -111,7 +102,6 @@ ohos_shared_library("ability_manager") { "${ability_runtime_services_path}/abilitymgr/src/want_sender_proxy.cpp", "${ability_runtime_services_path}/abilitymgr/src/want_sender_stub.cpp", "${ability_runtime_services_path}/abilitymgr/src/wants_info.cpp", - "${ability_runtime_services_path}/common/src/ability_manager_radar.cpp", "src/status_bar_delegate/status_bar_delegate_proxy.cpp", "src/status_bar_delegate/status_bar_delegate_stub.cpp", "src/window_manager_service_handler_proxy.cpp", @@ -134,20 +124,16 @@ ohos_shared_library("ability_manager") { public_deps = [ ":ability_connect_callback_stub" ] deps = [ + ":ability_start_options", ":ability_start_setting", ":mission_info", ":process_options", "${ability_runtime_innerkits_path}/app_manager:app_manager", - "//third_party/jsoncpp:jsoncpp", ] external_deps = [ "ability_base:base", - "ability_base:configuration", - "ability_base:want", - "ability_base:zuri", "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", "bundle_framework:libappexecfwk_common", "c_utils:utils", "common_event_service:cesfwk_innerkits", @@ -161,7 +147,13 @@ ohos_shared_library("ability_manager") { "samgr:samgr_proxy", ] - public_external_deps = [ "bundle_framework:appexecfwk_core" ] + public_external_deps = [ + "ability_base:configuration", + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_core", + "jsoncpp:jsoncpp", + ] if (ability_runtime_graphics) { deps += [] @@ -188,6 +180,44 @@ ohos_shared_library("ability_manager") { part_name = "ability_runtime" } +ohos_shared_library("ability_start_options") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + cfi_vcall_icall_only = true + debug = false + } + branch_protector_ret = "pac_ret" + + include_dirs = [ + "include/", + "${ability_runtime_services_path}/common/include", + ] + + sources = + [ "${ability_runtime_services_path}/abilitymgr/src/start_options.cpp" ] + + deps = [ ":process_options" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + ] + + cflags_cc = [] + innerapi_tags = [ + "platformsdk", + "sasdk", + ] + subsystem_name = "ability" + part_name = "ability_runtime" +} + ohos_shared_library("mission_info") { sources = [ "${ability_runtime_services_path}/abilitymgr/src/mission_info.cpp", @@ -197,11 +227,16 @@ ohos_shared_library("mission_info") { public_configs = [ ":ability_manager_public_config" ] external_deps = [ - "ability_base:want", "c_utils:utils", "ipc:ipc_core", ] - + public_external_deps = [ + "ability_base:configuration", + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_core", + "jsoncpp:jsoncpp", + ] if (ability_runtime_graphics) { external_deps += [ "image_framework:image_native" ] } @@ -232,7 +267,13 @@ ohos_shared_library("ability_start_setting") { public_configs = [ ":ability_manager_public_config" ] external_deps = [ "c_utils:utils" ] - + public_external_deps = [ + "ability_base:configuration", + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_core", + "jsoncpp:jsoncpp", + ] cflags_cc = [] innerapi_tags = [ "platformsdk" ] subsystem_name = "ability" @@ -285,12 +326,17 @@ ohos_shared_library("ability_connect_callback_stub") { public_configs = [ ":ability_manager_public_config" ] external_deps = [ - "ability_base:want", - "ability_base:zuri", "c_utils:utils", "hilog:libhilog", "ipc:ipc_core", ] + public_external_deps = [ + "ability_base:configuration", + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_core", + "jsoncpp:jsoncpp", + ] cflags_cc = [] innerapi_tags = [ diff --git a/interfaces/inner_api/ability_manager/include/ability_manager_client.h b/interfaces/inner_api/ability_manager/include/ability_manager_client.h index 505bd3ba93..67b4163983 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_client.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_client.h @@ -335,9 +335,10 @@ public: * Start ui ability with want, send want to ability manager service. * * @param sessionInfo the session info of the ability to start. + * @param isColdStart the session info of the ability is or not cold start. * @return Returns ERR_OK on success, others on failure. */ - ErrCode StartUIAbilityBySCB(sptr sessionInfo); + ErrCode StartUIAbilityBySCB(sptr sessionInfo, bool &isColdStart); /** * Stop extension ability with want, send want to ability manager service. @@ -1478,6 +1479,17 @@ public: */ int32_t GetAbilityStateByPersistentId(int32_t persistentId, bool &state); + /** + * Transfer resultCode & want to abms. + * + * @param callerToken caller ability token. + * @param requestCode the resultCode of the ability to start. + * @param want Indicates the ability to start. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t TransferAbilityResultForExtension(const sptr &callerToken, int32_t resultCode, + const Want &want); + private: AbilityManagerClient(); DISALLOW_COPY_AND_MOVE(AbilityManagerClient); diff --git a/interfaces/inner_api/ability_manager/include/ability_manager_errors.h b/interfaces/inner_api/ability_manager/include/ability_manager_errors.h index 9e9a725637..71badbb21f 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_errors.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_errors.h @@ -504,6 +504,16 @@ enum { * Native error(2097249) no resident process permissions set. */ ERR_NO_RESIDENT_PERMISSION, + + /** + * Result(2097250) for app clone index does not exist. + */ + ERR_APP_CLONE_INDEX_INVALID, + + /** + * Result(2097251) not support twin. + */ + ERR_MULTI_APP_NOT_SUPPORTED, }; enum { diff --git a/interfaces/inner_api/ability_manager/include/ability_manager_interface.h b/interfaces/inner_api/ability_manager/include/ability_manager_interface.h index 15212da991..32d8cf430c 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_interface.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_interface.h @@ -380,9 +380,10 @@ public: * Start ui ability with want, send want to ability manager service. * * @param sessionInfo the session info of the ability to start. + * @param isColdStart the session info of the ability is or not cold start. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartUIAbilityBySCB(sptr sessionInfo) + virtual int StartUIAbilityBySCB(sptr sessionInfo, bool &isColdStart) { return 0; } @@ -1591,6 +1592,19 @@ public: { return 0; } + + /** + * Transfer resultCode & want to ability manager service. + * + * @param resultCode, the resultCode of the ability to terminate. + * @param resultWant, the Want of the ability to return. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t TransferAbilityResultForExtension(const sptr &callerToken, int32_t resultCode, + const Want &want) + { + return 0; + } }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/ability_manager/include/ability_manager_ipc_interface_code.h b/interfaces/inner_api/ability_manager/include/ability_manager_ipc_interface_code.h index 9dbbf3df41..d9de07455d 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_ipc_interface_code.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_ipc_interface_code.h @@ -439,6 +439,7 @@ enum class AbilityManagerInterfaceCode { UNREGISTER_ABILITY_FIRST_FRAME_STATE_OBSERVER = 1127, // ipc for get ability state by persistent id GET_ABILITY_STATE_BY_PERSISTENT_ID = 1128, + TRANSFER_ABILITY_RESULT = 1129, // ipc id 2001-3000 for tools // ipc id for dumping state (2001) diff --git a/interfaces/inner_api/ability_manager/include/assert_fault_proxy.h b/interfaces/inner_api/ability_manager/include/assert_fault_proxy.h index eb98199c33..e2900cb419 100644 --- a/interfaces/inner_api/ability_manager/include/assert_fault_proxy.h +++ b/interfaces/inner_api/ability_manager/include/assert_fault_proxy.h @@ -16,6 +16,8 @@ #ifndef OHOS_ABILITY_RUNTIME_ASSERT_FAULT_PROXY_H #define OHOS_ABILITY_RUNTIME_ASSERT_FAULT_PROXY_H +#include +#include #include #include "iremote_broker.h" @@ -23,6 +25,7 @@ #include "iremote_proxy.h" #include "ability_connect_callback_stub.h" #include "assert_fault_interface.h" +#include "singleton.h" namespace OHOS { namespace AbilityRuntime { @@ -52,34 +55,39 @@ private: RemoteDiedHandler handler_; }; -class ModalSystemAssertUIExtension : public std::enable_shared_from_this { +class ModalSystemAssertUIExtension { public: + static ModalSystemAssertUIExtension &GetInstance(); ModalSystemAssertUIExtension() = default; virtual ~ModalSystemAssertUIExtension(); bool CreateModalUIExtension(const AAFwk::Want &want); + friend class AssertFaultProxy; + private: class AssertDialogConnection : public OHOS::AAFwk::AbilityConnectionStub { public: AssertDialogConnection() = default; - virtual ~AssertDialogConnection(); - - bool RequestShowDialog(const AAFwk::Want &want); - void CleanUp(); + virtual ~AssertDialogConnection() = default; + void SetReqeustAssertDialogWant(const AAFwk::Want &want); void OnAbilityConnectDone(const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; private: - std::mutex mutex_; - std::atomic_bool isDialogShow_ = false; - std::queue consumptionList_; - sptr remoteObject_; - sptr deathRecipient_; + AAFwk::Want want_; }; +private: + bool DisconnectSystemUI(); + void TryNotifyOneWaitingThread(); + void TryNotifyOneWaitingThreadInner(); + + std::mutex assertResultMutex_; + std::condition_variable assertResultCV_; + int32_t reqeustCount_ = 0; sptr GetConnection(); std::mutex dialogConnectionMutex_; sptr dialogConnectionCallback_; diff --git a/interfaces/inner_api/ability_manager/include/dialog_session_info.h b/interfaces/inner_api/ability_manager/include/dialog_session_info.h index dcf0970434..fc6f550944 100644 --- a/interfaces/inner_api/ability_manager/include/dialog_session_info.h +++ b/interfaces/inner_api/ability_manager/include/dialog_session_info.h @@ -34,6 +34,7 @@ struct DialogAbilityInfo { int32_t bundleLabelId = 0; int32_t abilityIconId = 0; int32_t abilityLabelId = 0; + bool visible = true; std::string GetURI() const; bool ParseURI(const std::string &uri); diff --git a/interfaces/inner_api/ability_manager/include/open_link_options.h b/interfaces/inner_api/ability_manager/include/open_link_options.h index fb066fdcfc..f01875662f 100644 --- a/interfaces/inner_api/ability_manager/include/open_link_options.h +++ b/interfaces/inner_api/ability_manager/include/open_link_options.h @@ -23,7 +23,7 @@ #include "want.h" namespace OHOS { namespace AAFwk { -class OpenLinkOptions final : public Parcelable, public std::enable_shared_from_this { +class OpenLinkOptions final : public Parcelable { public: OpenLinkOptions() = default; virtual ~OpenLinkOptions() = default; diff --git a/interfaces/inner_api/ability_manager/include/process_options.h b/interfaces/inner_api/ability_manager/include/process_options.h index e0f3f45621..17a26e7c9f 100644 --- a/interfaces/inner_api/ability_manager/include/process_options.h +++ b/interfaces/inner_api/ability_manager/include/process_options.h @@ -24,6 +24,7 @@ enum class ProcessMode { UNSPECIFIED = 0, NEW_PROCESS_ATTACH_TO_PARENT = 1, NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM = 2, + ATTACH_TO_STATUS_BAR_ITEM = 3, END }; @@ -46,9 +47,12 @@ public: static ProcessMode ConvertInt32ToProcessMode(int32_t value); static StartupVisibility ConvertInt32ToStartupVisibility(int32_t value); static bool IsNewProcessMode(ProcessMode value); + static bool IsAttachToStatusBarMode(ProcessMode value); + static bool IsValidProcessMode(ProcessMode value); ProcessMode processMode = ProcessMode::UNSPECIFIED; StartupVisibility startupVisibility = StartupVisibility::UNSPECIFIED; + std::string processName; }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/BUILD.gn b/interfaces/inner_api/app_manager/BUILD.gn index 6e3e3d772c..bd61cba560 100644 --- a/interfaces/inner_api/app_manager/BUILD.gn +++ b/interfaces/inner_api/app_manager/BUILD.gn @@ -12,18 +12,14 @@ # limitations under the License. import("//build/ohos.gni") -import("//foundation/ability/ability_base/ability_base.gni") import("//foundation/ability/ability_runtime/ability_runtime.gni") config("appmgr_sdk_config") { include_dirs = [ "include/appmgr", - "${ability_base_innerapi_path}/log/include", "${ability_base_kits_path}/configuration/include", - "${ability_base_kits_path}/want/include", "${ability_runtime_path}/interfaces/kits/native/ability/native", "${ability_runtime_innerkits_path}/ability_manager/include", - "${bundlefwk_inner_api_path}/appexecfwk_base/include", ] defines = [] if (ability_command_for_test) { @@ -92,6 +88,8 @@ ohos_shared_library("app_manager") { "src/appmgr/configuration_observer_stub.cpp", "src/appmgr/fault_data.cpp", "src/appmgr/memory_level_info.cpp", + "src/appmgr/native_child_notify_proxy.cpp", + "src/appmgr/native_child_notify_stub.cpp", "src/appmgr/page_state_data.cpp", "src/appmgr/priority_object.cpp", "src/appmgr/process_data.cpp", @@ -105,6 +103,7 @@ ohos_shared_library("app_manager") { "src/appmgr/render_state_data.cpp", "src/appmgr/render_state_observer_proxy.cpp", "src/appmgr/render_state_observer_stub.cpp", + "src/appmgr/running_multi_info.cpp", "src/appmgr/running_process_info.cpp", "src/appmgr/start_specified_ability_response_proxy.cpp", "src/appmgr/start_specified_ability_response_stub.cpp", @@ -126,8 +125,6 @@ ohos_shared_library("app_manager") { external_deps = [ "ability_base:configuration", - "ability_base:want", - "bundle_framework:appexecfwk_base", "c_utils:utils", "faultloggerd:libdfx_dumpcatcher", "faultloggerd:libfaultloggerd", @@ -139,6 +136,10 @@ ohos_shared_library("app_manager") { "ipc:ipc_core", "samgr:samgr_proxy", ] + public_external_deps = [ + "ability_base:want", + "bundle_framework:appexecfwk_base", + ] if (background_task_mgr_continuous_task_enable) { defines += [ "BGTASKMGR_CONTINUOUS_TASK_ENABLE" ] diff --git a/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_interface.h b/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_interface.h index 19ffa2c25a..9b9281eb1c 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_interface.h +++ b/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_interface.h @@ -172,18 +172,27 @@ public: virtual void GetRunningProcessInfoByToken( const sptr &token, OHOS::AppExecFwk::RunningProcessInfo &info) = 0; - virtual void GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) = 0; - virtual void SetAbilityForegroundingFlagToAppRecord(const pid_t pid) = 0; - virtual void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) = 0; + virtual void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId = 0) = 0; virtual void RegisterStartSpecifiedAbilityResponse(const sptr &response) = 0; - virtual void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) = 0; + virtual void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId = 0) = 0; virtual int GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application, bool &debug) = 0; + /** + * Record process exit reason to appRunningRecord + * @param pid pid + * @param reason reason enum + * @param exitMsg exitMsg + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg) = 0; + /** * Set the current userId of appMgr. * @@ -277,14 +286,6 @@ public: */ virtual bool IsAttachDebug(const std::string &bundleName) = 0; - /** - * Set application assertion pause state. - * - * @param pid App process pid. - * @param flag assertion pause state. - */ - virtual void SetAppAssertionPauseState(int32_t pid, bool flag) {} - /** * @brief Set resident process enable status. * @param bundleName The application bundle name. @@ -326,7 +327,6 @@ public: GET_CONFIGURATION, GET_APPLICATION_INFO_BY_PROCESS_ID, KILL_APPLICATION_SELF, - GET_RUNNING_PROCESS_INFO_BY_PID, UPDATE_APPLICATION_INFO_INSTALLED, SET_CURRENT_USER_ID, Get_BUNDLE_NAME_BY_PID, @@ -343,13 +343,13 @@ public: REGISTER_ABILITY_DEBUG_RESPONSE, IS_ATTACH_DEBUG, START_SPECIFIED_PROCESS, - SET_APP_ASSERT_PAUSE_STATE, CLEAR_PROCESS_BY_TOKEN, REGISTER_ABILITY_MS_DELEGATE, KILL_PROCESSES_BY_PIDS, ATTACH_PID_TO_PARENT, IS_MEMORY_SIZE_SUFFICIENT, SET_KEEP_ALIVE_ENABLE_STATE, + NOTIFY_APP_MGR_RECORD_EXIT_REASON, }; }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_proxy.h b/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_proxy.h index cbd091bdf0..20ef1a58af 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_proxy.h +++ b/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_proxy.h @@ -153,14 +153,14 @@ public: virtual int GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application, bool &debug) override; + virtual int32_t NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg) override; + virtual void AbilityAttachTimeOut(const sptr &token) override; virtual void PrepareTerminate(const sptr &token) override; void GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info) override; - void GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) override; - /** * Set AbilityForegroundingFlag of an app-record to true. * @@ -170,11 +170,12 @@ public: void SetAbilityForegroundingFlagToAppRecord(const pid_t pid) override; virtual void StartSpecifiedAbility( - const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) override; + const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, int32_t requestId = 0) override; virtual void RegisterStartSpecifiedAbilityResponse(const sptr &response) override; - virtual void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) override; + virtual void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId = 0) override; virtual void SetCurrentUserId(const int32_t userId) override; @@ -254,14 +255,6 @@ public: */ bool IsAttachDebug(const std::string &bundleName) override; - /** - * Set application assertion pause state. - * - * @param pid App process pid. - * @param flag assertion pause state. - */ - void SetAppAssertionPauseState(int32_t pid, bool flag) override; - /** * @brief Set resident process enable status. * @param bundleName The application bundle name. diff --git a/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_stub.h b/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_stub.h index cde52456cd..ae986f45b6 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/ams_mgr_stub.h @@ -61,11 +61,11 @@ private: int32_t HandleKillApplicationByUid(MessageParcel &data, MessageParcel &reply); int32_t HandleKillApplicationSelf(MessageParcel &data, MessageParcel &reply); int32_t HandleGetRunningProcessInfoByToken(MessageParcel &data, MessageParcel &reply); - int32_t HandleGetRunningProcessInfoByPid(MessageParcel &data, MessageParcel &reply); int32_t HandleSetAbilityForegroundingFlagToAppRecord(MessageParcel &data, MessageParcel &reply); int32_t HandleStartSpecifiedAbility(MessageParcel &data, MessageParcel &reply); int32_t HandleRegisterStartSpecifiedAbilityResponse(MessageParcel &data, MessageParcel &reply); int32_t HandleGetApplicationInfoByProcessID(MessageParcel &data, MessageParcel &reply); + int32_t HandleNotifyAppMgrRecordExitReason(MessageParcel &data, MessageParcel &reply); int32_t HandleUpdateApplicationInfoInstalled(MessageParcel &data, MessageParcel &reply); int32_t HandleSetCurrentUserId(MessageParcel &data, MessageParcel &reply); int32_t HandleGetBundleNameByPid(MessageParcel &data, MessageParcel &reply); @@ -80,7 +80,6 @@ private: int32_t HandleClearNonPersistWaitingDebugFlag(MessageParcel &data, MessageParcel &reply); int32_t HandleRegisterAbilityDebugResponse(MessageParcel &data, MessageParcel &reply); int32_t HandleIsAttachDebug(MessageParcel &data, MessageParcel &reply); - int32_t HandleSetAppAssertionPauseState(MessageParcel &data, MessageParcel &reply); int32_t HandleClearProcessByToken(MessageParcel &data, MessageParcel &reply); int32_t HandleIsMemorySizeSufficent(MessageParcel &data, MessageParcel &reply); int32_t HandleSetKeepAliveEnableState(MessageParcel &data, MessageParcel &reply); diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_jsheap_mem_info.h b/interfaces/inner_api/app_manager/include/appmgr/app_jsheap_mem_info.h index e720f38282..6791cf79fb 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_jsheap_mem_info.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_jsheap_mem_info.h @@ -16,16 +16,21 @@ #ifndef OHOS_ABILITY_RUNTIME_APP_JSHEAP_MEM_INFO_H #define OHOS_ABILITY_RUNTIME_APP_JSHEAP_MEM_INFO_H +#include #include "parcel.h" #include "iremote_object.h" namespace OHOS { namespace AppExecFwk { struct JsHeapDumpInfo : public Parcelable { + ~JsHeapDumpInfo(); uint32_t pid; uint32_t tid; bool needGc; bool needSnapshot; + std::vector fdVec; + std::vector tidVec; + bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; static JsHeapDumpInfo *Unmarshalling(Parcel &parcel); }; diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_client.h b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_client.h index f18c6ef7ca..9b0d9f7a8b 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_client.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_client.h @@ -305,10 +305,11 @@ public: /** * Get running process information by pid. * - * @param token Process id. - * @param info Running process info. + * @param pid process id. + * @param info Output parameters, return runningProcessInfo. + * @return Returns ERR_OK on success, others on failure. */ - virtual void GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const; + virtual int32_t GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const; /** * Notify that the ability stage has been updated @@ -385,7 +386,8 @@ public: * @param want Want contains information wish to start. * @param abilityInfo Ability information. */ - virtual void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo); + virtual void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId = 0); /** * Register response of start specified ability. @@ -400,16 +402,8 @@ public: * @param want Want contains information wish to start. * @param abilityInfo Ability information. */ - virtual void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo); - - /** - * Schedule new process request done. - * - * @param recordId Application record. - * @param want Want. - * @param flag flag get from OnNewProcessRequest. - */ - virtual void ScheduleNewProcessRequest(const int32_t recordId, const AAFwk::Want &want, const std::string &flag); + virtual void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId = 0); /** * Schedule accept want done. @@ -448,7 +442,7 @@ public: */ virtual int StartRenderProcess(const std::string &renderParam, int32_t ipcFd, int32_t sharedFd, - int32_t crashFd, pid_t &renderPid); + int32_t crashFd, pid_t &renderPid, bool isGPU = false); /** * Render process call this to attach app manager service. @@ -484,7 +478,7 @@ public: * @param debug Whether IsDebugApp. * @return Returns ERR_OK on success, others on failure. */ - int32_t StartNativeProcessForDebugger(const AAFwk::Want &want) const; + int32_t StartNativeProcessForDebugger(const AAFwk::Want &want); /** * Set the current userId of appMgr. @@ -619,14 +613,6 @@ public: */ void SetKeepAliveEnableState(const std::string &bundleName, bool enable); - /** - * Set application assertion pause state. - * - * @param pid App process pid. - * @param flag assertion pause state. - */ - void SetAppAssertionPauseState(int32_t pid, bool flag); - /** * Register application or process state observer. * @param observer, ability token. @@ -728,6 +714,15 @@ public: */ bool IsMemorySizeSufficent() const; + /** + * Record process exit reason to appRunningRecord + * @param pid pid + * @param reason reason enum + * @param exitMsg exitMsg + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg); + /** * Preload application. * @@ -741,6 +736,8 @@ public: AppExecFwk::PreloadMode preloadMode, int32_t appIndex = 0); int32_t SetSupportedProcessCacheSelf(bool isSupport); + + void SaveBrowserChannel(sptr browser); private: void SetServiceManager(std::unique_ptr serviceMgr); /** diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_constants.h b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_constants.h index af3dba052c..0eed09018a 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_constants.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_constants.h @@ -19,7 +19,7 @@ namespace OHOS { namespace AppExecFwk { namespace Constants { -const std::string APP_MGR_SERVICE_NAME = "AppMgrService"; +constexpr const char* APP_MGR_SERVICE_NAME = "AppMgrService"; } // namespace Constants enum class ApplicationState { @@ -78,6 +78,7 @@ enum class ProcessType { NORMAL = 0, EXTENSION, RENDER, + GPU, }; enum class AppStartType { diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_interface.h b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_interface.h index 723d2a714b..3881e8e41c 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_interface.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_interface.h @@ -41,6 +41,7 @@ #include "system_memory_attr.h" #include "want.h" #include "app_jsheap_mem_info.h" +#include "running_multi_info.h" namespace OHOS { namespace AppExecFwk { @@ -143,6 +144,17 @@ public: */ virtual int GetAllRunningProcesses(std::vector &info) = 0; + /** + * GetRunningMultiAppInfoByBundleName, call GetRunningMultiAppInfoByBundleName() through proxy project. + * Obtains information about multiapp that are running on the device. + * + * @param bundlename, bundle name in Application record. + * @param info, output multiapp information. + * @return ERR_OK ,return back success,others fail. + */ + virtual int32_t GetRunningMultiAppInfoByBundleName(const std::string &bundleName, + RunningMultiAppInfo &info) = 0; + /** * GetRunningProcessesByBundleType, call GetRunningProcessesByBundleType() through proxy project. * Obtains information about application processes by bundle type that are running on the device. @@ -334,11 +346,12 @@ public: * @param sharedFd, shared memory file descriptior. * @param crashFd, crash signal file descriptior. * @param renderPid, created render pid. + * @param isGPU, is or not gpu process * @return Returns ERR_OK on success, others on failure. */ virtual int StartRenderProcess(const std::string &renderParam, int32_t ipcFd, int32_t sharedFd, - int32_t crashFd, pid_t &renderPid) = 0; + int32_t crashFd, pid_t &renderPid, bool isGPU = false) = 0; /** * Render process call this to attach app manager service. @@ -452,6 +465,18 @@ public: */ virtual int32_t GetBundleNameByPid(const int pid, std::string &bundleName, int32_t &uid) = 0; + /** + * Get running process information by pid. + * + * @param pid process id. + * @param info Output parameters, return runningProcessInfo. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) + { + return 0; + } + /** * get memorySize by pid. * @@ -652,6 +677,25 @@ public: } virtual int32_t SetSupportedProcessCacheSelf(bool isSupport) = 0; + + /** + * Set application assertion pause state. + * + * @param flag assertion pause state. + */ + virtual void SetAppAssertionPauseState(bool flag) {} + + /** + * Start native child process, callde by ChildProcessManager. + * @param libName lib file name to be load in child process + * @param childProcessCount current started child process count + * @param callback callback for notify start result + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t StartNativeChildProcess(const std::string &libName, int32_t childProcessCount, + const sptr &callback) = 0; + + virtual void SaveBrowserChannel(sptr browser) = 0; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_ipc_interface_code.h b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_ipc_interface_code.h index abc01de315..8f93a117b1 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_ipc_interface_code.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_ipc_interface_code.h @@ -99,7 +99,12 @@ enum class AppMgrInterfaceCode { PRELOAD_APPLICATION = 73, SET_SUPPORTED_PROCESS_CACHE_SELF = 74, APP_GET_RUNNING_PROCESSES_BY_BUNDLE_TYPE = 75, + START_NATIVE_CHILD_PROCESS = 76, + SAVE_BROWSER_CHANNEL = 77, + GET_RUNNING_MULTIAPP_INFO_BY_BUNDLENAME = 78, + SET_APP_ASSERT_PAUSE_STATE_SELF = 79, + GET_RUNNING_PROCESS_INFO_BY_PID = 80, }; } // AppExecFwk } // OHOS -#endif // OHOS_ABILITY_RUNTIME_APP_MGR_IPC_INTERFACE_CODE_H \ No newline at end of file +#endif // OHOS_ABILITY_RUNTIME_APP_MGR_IPC_INTERFACE_CODE_H diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_proxy.h b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_proxy.h index 3b5c4feebc..b7caa84e6e 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_proxy.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_proxy.h @@ -16,13 +16,14 @@ #ifndef OHOS_ABILITY_RUNTIME_APP_MGR_PROXY_H #define OHOS_ABILITY_RUNTIME_APP_MGR_PROXY_H +#include "app_jsheap_mem_info.h" #include "app_malloc_info.h" #include "app_mgr_interface.h" #include "bundle_info.h" #include "iremote_proxy.h" #include "memory_level_info.h" +#include "running_process_info.h" #include "want.h" -#include "app_jsheap_mem_info.h" namespace OHOS { namespace AppExecFwk { @@ -122,6 +123,16 @@ public: */ virtual int32_t GetAllRunningProcesses(std::vector &info) override; + /** + * GetALLRunningMultiAppInfo, call GetALLRunningMultiAppInfo() through proxy project. + * Obtains information about multiapp that are running on the device. + * + * @param info, app name in multiappinfo. + * @return ERR_OK ,return back success,others fail. + */ + virtual int32_t GetRunningMultiAppInfoByBundleName(const std::string &bundleName, + RunningMultiAppInfo &info) override; + /** * GetRunningProcessesByBundleType, call GetRunningProcessesByBundleType() through proxy project. * Obtains information about application processes by bundle type that are running on the device. @@ -306,11 +317,12 @@ public: * @param sharedFd, shared memory file descriptior. * @param crashFd, crash signal file descriptior. * @param renderPid, created render pid. + * @param isGPU, is or not GPU process * @return Returns ERR_OK on success, others on failure. */ virtual int StartRenderProcess(const std::string &renderParam, int32_t ipcFd, int32_t sharedFd, - int32_t crashFd, pid_t &renderPid) override; + int32_t crashFd, pid_t &renderPid, bool isGPU = false) override; /** * Render process call this to attach app manager service. @@ -396,6 +408,15 @@ public: */ virtual int32_t GetBundleNameByPid(const int pid, std::string &bundleName, int32_t &uid) override; + /** + * Get running process information by pid. + * + * @param pid process id. + * @param info Output parameters, return runningProcessInfo. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) override; + /** * get memorySize by pid. * @@ -568,6 +589,26 @@ public: virtual int32_t NotifyMemorySizeStateChanged(bool isMemorySizeSufficent) override; int32_t SetSupportedProcessCacheSelf(bool isSupport) override; + + /** + * Set application assertion pause state. + * + * @param flag assertion pause state. + */ + void SetAppAssertionPauseState(bool flag) override; + + /** + * Start native child process, callde by ChildProcessManager. + * @param libName lib file name to be load in child process + * @param childProcessCount current started child process count + * @param callback callback for notify start result + * @return Returns ERR_OK on success, others on failure. + */ + int32_t StartNativeChildProcess(const std::string &libName, int32_t childProcessCount, + const sptr &callback) override; + + virtual void SaveBrowserChannel(sptr browser) override; + private: bool SendTransactCmd(AppMgrInterfaceCode code, MessageParcel &data, MessageParcel &reply); bool WriteInterfaceToken(MessageParcel &data); diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_stub.h b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_stub.h index 51de220229..feada9236c 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_mgr_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_mgr_stub.h @@ -94,6 +94,7 @@ private: int32_t HandleUnregisterConfigurationObserver(MessageParcel &data, MessageParcel &reply); int32_t HandleDumpHeapMemory(MessageParcel &data, MessageParcel &reply); int32_t HandleDumpJsHeapMemory(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetRunningMultiAppInfoByBundleName(MessageParcel &data, MessageParcel &reply); #ifdef ABILITY_COMMAND_FOR_TEST int32_t HandleBlockAppServiceDone(MessageParcel &data, MessageParcel &reply); #endif @@ -110,6 +111,7 @@ private: int32_t HandleNotifyFaultBySA(MessageParcel &data, MessageParcel &reply); int32_t HandleJudgeSandboxByPid(MessageParcel &data, MessageParcel &reply); int32_t HandleGetBundleNameByPid(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetRunningProcessInfoByPid(MessageParcel &data, MessageParcel &reply); int32_t HandleGetProcessMemoryByPid(MessageParcel &data, MessageParcel &reply); int32_t HandleGetRunningProcessInformation(MessageParcel &data, MessageParcel &reply); int32_t HandleChangeAppGcState(MessageParcel &data, MessageParcel &reply); @@ -135,7 +137,9 @@ private: int32_t HandleGetAllUIExtensionProviderPid(MessageParcel &data, MessageParcel &reply); int32_t HandleNotifyMemorySizeStateChanged(MessageParcel &data, MessageParcel &reply); int32_t HandleSetSupportedProcessCacheSelf(MessageParcel &data, MessageParcel &reply); - + int32_t HandleSetAppAssertionPauseState(MessageParcel &data, MessageParcel &reply); + int32_t HandleStartNativeChildProcess(MessageParcel &data, MessageParcel &reply); + int32_t HandleSaveBrowserChannel(MessageParcel &data, MessageParcel &reply); using AppMgrFunc = int32_t (AppMgrStub::*)(MessageParcel &data, MessageParcel &reply); std::map memberFuncMap_; diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_const.h b/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_const.h index 3a12f94a9b..ed5edc95dd 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_const.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_const.h @@ -16,15 +16,18 @@ #ifndef OHOS_ABILITY_RUNTIME_APP_SCHEDULER_CONST_H #define OHOS_ABILITY_RUNTIME_APP_SCHEDULER_CONST_H -#include +#include +#include namespace OHOS { namespace AppExecFwk { -const std::string MSG_DUMP_IPC_START_STAT = "StartIpcStatistics\t"; -const std::string MSG_DUMP_IPC_STOP_STAT = "StopIpcStatistics\t"; -const std::string MSG_DUMP_IPC_STAT = "IpcStatistics\t"; -const std::string MSG_DUMP_IPC_FAIL = "fail\n"; -const std::string MSG_DUMP_IPC_FAIL_REASON_INTERNAL = "internal error.\n"; +constexpr const size_t MAX_CAPACITY = (1U << 20); + +constexpr const char* MSG_DUMP_IPC_START_STAT = "StartIpcStatistics\t"; +constexpr const char* MSG_DUMP_IPC_STOP_STAT = "StopIpcStatistics\t"; +constexpr const char* MSG_DUMP_IPC_STAT = "IpcStatistics\t"; +constexpr const char* MSG_DUMP_FAIL = "fail\n"; +constexpr const char* MSG_DUMP_FAIL_REASON_INTERNAL = "internal error.\n"; enum DumpErrorCode { // success diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_host.h b/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_host.h index eb513363cb..d0722996dc 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_host.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_host.h @@ -63,6 +63,7 @@ private: int32_t HandleScheduleDumpIpcStart(MessageParcel &data, MessageParcel &reply); int32_t HandleScheduleDumpIpcStop(MessageParcel &data, MessageParcel &reply); int32_t HandleScheduleDumpIpcStat(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleDumpFfrt(MessageParcel &data, MessageParcel &reply); using AppSchedulerFunc = int32_t (AppSchedulerHost::*)(MessageParcel &data, MessageParcel &reply); std::map memberFuncMap_; diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_interface.h b/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_interface.h index 4c80f3f1dd..2b04eb7678 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_interface.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_interface.h @@ -262,6 +262,16 @@ public: */ virtual int32_t ScheduleDumpIpcStat(std::string& result) = 0; + /** + * ScheduleDumpFfrt, call ScheduleDumpFfrt(std::string& result) through proxy project, + * Start querying the application's ffrt usage. + * + * @param result, ffrt dump result output. + * + * @return Returns 0 on success, error code on failure. + */ + virtual int32_t ScheduleDumpFfrt(std::string& result) = 0; + enum class Message { SCHEDULE_FOREGROUND_APPLICATION_TRANSACTION = 0, SCHEDULE_BACKGROUND_APPLICATION_TRANSACTION, @@ -291,6 +301,7 @@ public: SCHEDULE_DUMP_IPC_START, SCHEDULE_DUMP_IPC_STOP, SCHEDULE_DUMP_IPC_STAT, + SCHEDULE_DUMP_FFRT, }; }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_proxy.h b/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_proxy.h index 56c3ffd6ce..72197fc710 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_proxy.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_scheduler_proxy.h @@ -222,6 +222,16 @@ public: */ virtual int32_t ScheduleDumpIpcStat(std::string& result) override; + /** + * ScheduleDumpFfrt, call ScheduleDumpFfrt(std::string& result) through proxy project, + * Start querying the application's ffrt usage. + * + * @param result, ffrt dump result output. + * + * @return Returns 0 on success, error code on failure. + */ + virtual int32_t ScheduleDumpFfrt(std::string& result) override; + private: bool WriteInterfaceToken(MessageParcel &data); void ScheduleMemoryCommon(const int32_t level, const uint32_t operation); diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_host.h b/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_host.h index 64d8e70eae..b80157a978 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_host.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_host.h @@ -62,12 +62,19 @@ public: * @param bundleInfos resident process bundle infos. */ virtual void NotifyStartResidentProcess(std::vector &bundleInfos) override; + + /** + * @brief Notify abilityms app process OnRemoteDied + * @param abilityTokens abilities in died process. + */ + virtual void OnAppRemoteDied(const std::vector> &abilityTokens) override; private: int32_t HandleOnAppStateChanged(MessageParcel &data, MessageParcel &reply); int32_t HandleOnAbilityRequestDone(MessageParcel &data, MessageParcel &reply); int32_t HandleNotifyConfigurationChange(MessageParcel &data, MessageParcel &reply); int32_t HandleNotifyStartResidentProcess(MessageParcel &data, MessageParcel &reply); + int32_t HandleOnAppRemoteDied(MessageParcel &data, MessageParcel &reply); using AppStateCallbackFunc = int32_t (AppStateCallbackHost::*)(MessageParcel &data, MessageParcel &reply); std::map memberFuncMap_; diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_proxy.h b/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_proxy.h index b464a65a54..1995ea5668 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_proxy.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_state_callback_proxy.h @@ -57,6 +57,12 @@ public: */ virtual void NotifyStartResidentProcess(std::vector &bundleInfos) override; + /** + * @brief Notify abilityms app process OnRemoteDied + * @param abilityTokens abilities in died process. + */ + virtual void OnAppRemoteDied(const std::vector> &abilityTokens) override; + private: bool WriteInterfaceToken(MessageParcel &data); static inline BrokerDelegator delegator_; diff --git a/interfaces/inner_api/app_manager/include/appmgr/child_process_info.h b/interfaces/inner_api/app_manager/include/appmgr/child_process_info.h index 89b4706190..cb5352d12e 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/child_process_info.h +++ b/interfaces/inner_api/app_manager/include/appmgr/child_process_info.h @@ -22,10 +22,15 @@ namespace OHOS { namespace AppExecFwk { + +constexpr int32_t CHILD_PROCESS_TYPE_JS = 0; +constexpr int32_t CHILD_PROCESS_TYPE_NATIVE = 1; + struct ChildProcessInfo : public Parcelable { std::int32_t pid; std::int32_t hostPid; std::int32_t uid; + std::int32_t processType; std::string bundleName; std::string processName; std::string srcEntry; diff --git a/interfaces/inner_api/app_manager/include/appmgr/child_scheduler_interface.h b/interfaces/inner_api/app_manager/include/appmgr/child_scheduler_interface.h index beaa93d6a9..89fbfc623f 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/child_scheduler_interface.h +++ b/interfaces/inner_api/app_manager/include/appmgr/child_scheduler_interface.h @@ -34,9 +34,16 @@ public: */ virtual bool ScheduleExitProcessSafely() = 0; + /** + * Notify child process run main proc from shared lib. + * @param mainProcessCb Main process callback ipc object + */ + virtual bool ScheduleRunNativeProc(const sptr &mainProcessCb) = 0; + enum class Message { SCHEDULE_LOAD_JS = 0, SCHEDULE_EXIT_PROCESS_SAFELY = 1, + SCHEDULE_RUN_NATIVE_PROC = 2, }; }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/child_scheduler_proxy.h b/interfaces/inner_api/app_manager/include/appmgr/child_scheduler_proxy.h index 355dd1398a..f5cd00d0f1 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/child_scheduler_proxy.h +++ b/interfaces/inner_api/app_manager/include/appmgr/child_scheduler_proxy.h @@ -29,6 +29,7 @@ public: bool ScheduleLoadJs() override; bool ScheduleExitProcessSafely() override; + bool ScheduleRunNativeProc(const sptr &mainProcessCb) override; private: bool WriteInterfaceToken(MessageParcel &data); diff --git a/interfaces/inner_api/app_manager/include/appmgr/child_scheduler_stub.h b/interfaces/inner_api/app_manager/include/appmgr/child_scheduler_stub.h index 6a73ccbf03..a6ecf59dce 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/child_scheduler_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/child_scheduler_stub.h @@ -36,6 +36,7 @@ public: private: int32_t HandleScheduleLoadJs(MessageParcel &data, MessageParcel &reply); int32_t HandleScheduleExitProcessSafely(MessageParcel &data, MessageParcel &reply); + int32_t HandleScheduleRunNativeProc(MessageParcel &data, MessageParcel &reply); using ChildSchedulerFunc = int32_t (ChildSchedulerStub::*)(MessageParcel &data, MessageParcel &reply); std::map memberFuncMap_; diff --git a/interfaces/inner_api/app_manager/include/appmgr/iapp_state_callback.h b/interfaces/inner_api/app_manager/include/appmgr/iapp_state_callback.h index 938104b90f..767fd95b98 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/iapp_state_callback.h +++ b/interfaces/inner_api/app_manager/include/appmgr/iapp_state_callback.h @@ -63,11 +63,18 @@ public: */ virtual void NotifyStartResidentProcess(std::vector &bundleInfos) {} + /** + * @brief Notify abilityms app process OnRemoteDied + * @param abilityTokens abilities in died process. + */ + virtual void OnAppRemoteDied(const std::vector> &abilityTokens) {} + enum class Message { TRANSACT_ON_APP_STATE_CHANGED = 0, TRANSACT_ON_ABILITY_REQUEST_DONE, TRANSACT_ON_NOTIFY_CONFIG_CHANGE, - TRANSACT_ON_NOTIFY_START_RESIDENT_PROCESS + TRANSACT_ON_NOTIFY_START_RESIDENT_PROCESS, + TRANSACT_ON_APP_REMOTE_DIED }; }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/irender_scheduler.h b/interfaces/inner_api/app_manager/include/appmgr/irender_scheduler.h index 22d9f891dc..35c114587a 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/irender_scheduler.h +++ b/interfaces/inner_api/app_manager/include/appmgr/irender_scheduler.h @@ -36,7 +36,7 @@ public: * @param crashFd, crash signal file descriptior. */ virtual void NotifyBrowserFd(int32_t ipcFd, int32_t sharedFd, - int32_t crashFd) = 0; + int32_t crashFd, sptr browser) = 0; enum class Message { NOTIFY_BROWSER_FD = 1, diff --git a/interfaces/inner_api/app_manager/include/appmgr/istart_specified_ability_response.h b/interfaces/inner_api/app_manager/include/appmgr/istart_specified_ability_response.h index a7f2fc87ed..a8327e41f4 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/istart_specified_ability_response.h +++ b/interfaces/inner_api/app_manager/include/appmgr/istart_specified_ability_response.h @@ -26,13 +26,14 @@ class IStartSpecifiedAbilityResponse : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.startSpecifiedAbilityResponse"); - virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag) = 0; + virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag, int32_t requestId) = 0; - virtual void OnTimeoutResponse(const AAFwk::Want &want) = 0; + virtual void OnTimeoutResponse(const AAFwk::Want &want, int32_t requestId) = 0; - virtual void OnNewProcessRequestResponse(const AAFwk::Want &want, const std::string &flag) = 0; + virtual void OnNewProcessRequestResponse(const AAFwk::Want &want, const std::string &flag, + int32_t requestId) = 0; - virtual void OnNewProcessRequestTimeoutResponse(const AAFwk::Want &want) = 0; + virtual void OnNewProcessRequestTimeoutResponse(const AAFwk::Want &want, int32_t requestId) = 0; enum class Message { ON_ACCEPT_WANT_RESPONSE = 0, diff --git a/interfaces/inner_api/app_manager/include/appmgr/native_child_notify_interface.h b/interfaces/inner_api/app_manager/include/appmgr/native_child_notify_interface.h new file mode 100644 index 0000000000..b901b6c107 --- /dev/null +++ b/interfaces/inner_api/app_manager/include/appmgr/native_child_notify_interface.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_NATIVE_CHILD_NOTIFY_INTERFACE_H +#define OHOS_ABILITY_RUNTIME_NATIVE_CHILD_NOTIFY_INTERFACE_H + +#include "iremote_broker.h" + +namespace OHOS { +namespace AppExecFwk { + +class INativeChildNotify : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.NativeChildNotify"); + + /** + * Notify native child process started. + * + * @param nativeChild child process ipc object + */ + virtual void OnNativeChildStarted(const sptr &nativeChild) = 0; + + /** + * Notify native child process start failed. + * + * @param errCode failed error code + */ + virtual void OnError(int32_t errCode) = 0; + +protected: + static constexpr uint32_t IPC_ID_ON_NATIVE_CHILD_STARTED = 0; + static constexpr uint32_t IPC_ID_ON_ERROR = 1; +}; + +} // OHOS +} // AppExecFwk + +#endif // OHOS_ABILITY_RUNTIME_NATIVE_CHILD_NOTIFY_INTERFACE_H \ No newline at end of file diff --git a/interfaces/inner_api/app_manager/include/appmgr/native_child_notify_proxy.h b/interfaces/inner_api/app_manager/include/appmgr/native_child_notify_proxy.h new file mode 100644 index 0000000000..fabd51a855 --- /dev/null +++ b/interfaces/inner_api/app_manager/include/appmgr/native_child_notify_proxy.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_NATIVE_CHILD_NOTIFY_PROXY_H +#define OHOS_ABILITY_RUNTIME_NATIVE_CHILD_NOTIFY_PROXY_H + +#include "native_child_notify_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { + +class NativeChildNotifyProxy : public IRemoteProxy { +public: + explicit NativeChildNotifyProxy(const sptr &impl); + virtual ~NativeChildNotifyProxy() = default; + + void OnNativeChildStarted(const sptr &nativeChild) override; + void OnError(int32_t errCode) override; + +private: + bool WriteInterfaceToken(MessageParcel &data); + int32_t SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption& option); + + static inline BrokerDelegator delegator_; +}; + +} // OHOS +} // AppExecFwk + +#endif // OHOS_ABILITY_RUNTIME_NATIVE_CHILD_NOTIFY_PROXY_H \ No newline at end of file diff --git a/interfaces/inner_api/app_manager/include/appmgr/native_child_notify_stub.h b/interfaces/inner_api/app_manager/include/appmgr/native_child_notify_stub.h new file mode 100644 index 0000000000..a77580f3a0 --- /dev/null +++ b/interfaces/inner_api/app_manager/include/appmgr/native_child_notify_stub.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_NATIVE_CHILD_NOTIFY_STUB_H +#define OHOS_ABILITY_RUNTIME_NATIVE_CHILD_NOTIFY_STUB_H + +#include "native_child_notify_interface.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace AppExecFwk { + +class NativeChildNotifyStub : public IRemoteStub { +public: + NativeChildNotifyStub() = default; + virtual ~NativeChildNotifyStub() = default; + + int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + int32_t HandleOnNativeChildStarted(MessageParcel &data, MessageParcel &reply); + int32_t HandleOnError(MessageParcel &data, MessageParcel &reply); +}; + +} // OHOS +} // AppExecFwk + +#endif // OHOS_ABILITY_RUNTIME_NATIVE_CHILD_NOTIFY_STUB_H \ No newline at end of file diff --git a/interfaces/inner_api/app_manager/include/appmgr/process_data.h b/interfaces/inner_api/app_manager/include/appmgr/process_data.h index d9c3882228..0181f217b0 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/process_data.h +++ b/interfaces/inner_api/app_manager/include/appmgr/process_data.h @@ -49,7 +49,9 @@ struct ProcessData : public Parcelable { std::string bundleName; int32_t pid = 0; - int32_t uid = 0; + int32_t uid = 0; // host uid + int32_t hostPid = 0; + int32_t gpuPid = 0; int32_t renderUid = -1; AppProcessState state; bool isContinuousTask = false; @@ -62,6 +64,8 @@ struct ProcessData : public Parcelable { ExtensionAbilityType extensionType = ExtensionAbilityType::UNSPECIFIED; uint32_t accessTokenId = 0; bool isTestMode = false; // Indicates whether the process is started by aa test + int32_t exitReason = 0; + std::string exitMsg = ""; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/include/appmgr/render_scheduler_proxy.h b/interfaces/inner_api/app_manager/include/appmgr/render_scheduler_proxy.h index c529f55548..5465ad97b8 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/render_scheduler_proxy.h +++ b/interfaces/inner_api/app_manager/include/appmgr/render_scheduler_proxy.h @@ -40,7 +40,7 @@ public: * @param crashFd, crash signal file descriptior. */ virtual void NotifyBrowserFd(int32_t ipcFd, int32_t sharedFd, - int32_t crashFd) override; + int32_t crashFd, sptr browser) override; private: bool WriteInterfaceToken(MessageParcel &data); diff --git a/interfaces/inner_api/app_manager/include/appmgr/running_multi_info.h b/interfaces/inner_api/app_manager/include/appmgr/running_multi_info.h new file mode 100644 index 0000000000..954c4cd109 --- /dev/null +++ b/interfaces/inner_api/app_manager/include/appmgr/running_multi_info.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_RUNNING_MULTI_INFO_H +#define OHOS_ABILITY_RUNTIME_RUNNING_MULTI_INFO_H + +#include +#include + +#include "ability_info.h" +#include "app_mgr_constants.h" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +const int32_t MAX_CLONE_APP_NUM = 128; +struct RunningAppClone { + int32_t appCloneIndex; + int32_t uid; + std::vector pids; +}; + +struct RunningMultiAppInfo : public Parcelable { + std::string bundleName; + int32_t mode; + std::vector runningAppClones; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static RunningMultiAppInfo *Unmarshalling(Parcel &parcel); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // OHOS_ABILITY_RUNTIME_RUNNING_MULTI_INFO_H \ No newline at end of file diff --git a/interfaces/inner_api/app_manager/include/appmgr/start_specified_ability_response_proxy.h b/interfaces/inner_api/app_manager/include/appmgr/start_specified_ability_response_proxy.h index 4f94d57f5d..c9b72bfe99 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/start_specified_ability_response_proxy.h +++ b/interfaces/inner_api/app_manager/include/appmgr/start_specified_ability_response_proxy.h @@ -25,13 +25,15 @@ public: explicit StartSpecifiedAbilityResponseProxy(const sptr &impl); virtual ~StartSpecifiedAbilityResponseProxy() = default; - virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag) override; + virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag, + int32_t requestId) override; - virtual void OnTimeoutResponse(const AAFwk::Want &want) override; + virtual void OnTimeoutResponse(const AAFwk::Want &want, int32_t requestId) override; - virtual void OnNewProcessRequestResponse(const AAFwk::Want &want, const std::string &flag) override; - - virtual void OnNewProcessRequestTimeoutResponse(const AAFwk::Want &want) override; + virtual void OnNewProcessRequestResponse(const AAFwk::Want &want, const std::string &flag, + int32_t requestId = 0) override; + + virtual void OnNewProcessRequestTimeoutResponse(const AAFwk::Want &want, int32_t requestId) override; private: bool WriteInterfaceToken(MessageParcel &data); diff --git a/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_proxy.cpp index 6fc6a49476..87c443fb7f 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_proxy.cpp @@ -534,37 +534,6 @@ void AmsMgrProxy::GetRunningProcessInfoByToken( info = *processInfo; } -void AmsMgrProxy::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) -{ - TAG_LOGD(AAFwkTag::APPMGR, "start"); - MessageParcel data; - MessageParcel reply; - MessageOption option(MessageOption::TF_SYNC); - if (!WriteInterfaceToken(data)) { - return; - } - - if (!data.WriteInt32(static_cast(pid))) { - TAG_LOGE(AAFwkTag::APPMGR, "parcel WriteInt32 failed."); - return; - } - - auto ret = SendTransactCmd( - static_cast(IAmsMgr::Message::GET_RUNNING_PROCESS_INFO_BY_PID), data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - return; - } - - std::unique_ptr processInfo(reply.ReadParcelable()); - if (processInfo == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "recv process info failded"); - return; - } - - info = *processInfo; -} - void AmsMgrProxy::SetAbilityForegroundingFlagToAppRecord(const pid_t pid) { TAG_LOGD(AAFwkTag::APPMGR, "calling"); @@ -587,8 +556,8 @@ void AmsMgrProxy::SetAbilityForegroundingFlagToAppRecord(const pid_t pid) } } -void AmsMgrProxy::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) - +void AmsMgrProxy::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId) { MessageParcel data; MessageParcel reply; @@ -597,7 +566,8 @@ void AmsMgrProxy::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFw return; } - if (!data.WriteParcelable(&want) || !data.WriteParcelable(&abilityInfo)) { + if (!data.WriteParcelable(&want) || !data.WriteParcelable(&abilityInfo) || + !data.WriteInt32(requestId)) { TAG_LOGE(AAFwkTag::APPMGR, "Write data failed."); return; } @@ -609,7 +579,8 @@ void AmsMgrProxy::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFw } } -void AmsMgrProxy::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +void AmsMgrProxy::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId) { MessageParcel data; @@ -620,7 +591,8 @@ void AmsMgrProxy::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFw return; } - if (!data.WriteParcelable(&want) || !data.WriteParcelable(&abilityInfo)) { + if (!data.WriteParcelable(&want) || !data.WriteParcelable(&abilityInfo) || + data.WriteInt32(requestId)) { TAG_LOGE(AAFwkTag::APPMGR, "Write data failed."); return; } @@ -695,6 +667,37 @@ int AmsMgrProxy::GetApplicationInfoByProcessID(const int pid, AppExecFwk::Applic return NO_ERROR; } +int32_t AmsMgrProxy::NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg) +{ + TAG_LOGD(AAFwkTag::APPMGR, "NotifyAppMgrRecordExitReason called."); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "token write error."); + return IPC_PROXY_ERR; + } + if (!data.WriteInt32(pid)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write pid failed."); + return IPC_PROXY_ERR; + } + if (!data.WriteInt32(reason)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write reason failed."); + return IPC_PROXY_ERR; + } + if (!data.WriteString16(Str8ToStr16(exitMsg))) { + TAG_LOGE(AAFwkTag::APPMGR, "Write exitMsg failed."); + return IPC_PROXY_ERR; + } + int32_t ret = SendTransactCmd( + static_cast(IAmsMgr::Message::NOTIFY_APP_MGR_RECORD_EXIT_REASON), data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGE(AAFwkTag::APPMGR, "NotifyAppMgrRecordExitReason send request fail."); + return ret; + } + return reply.ReadInt32(); +} + void AmsMgrProxy::SetCurrentUserId(const int32_t userId) { TAG_LOGD(AAFwkTag::APPMGR, "start"); @@ -1042,34 +1045,6 @@ bool AmsMgrProxy::IsAttachDebug(const std::string &bundleName) return reply.ReadBool(); } -void AmsMgrProxy::SetAppAssertionPauseState(int32_t pid, bool flag) -{ - TAG_LOGD(AAFwkTag::APPMGR, "Called."); - MessageParcel data; - if (!WriteInterfaceToken(data)) { - TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); - return; - } - - if (!data.WriteInt32(pid)) { - TAG_LOGE(AAFwkTag::APPMGR, "Write pid fail."); - return; - } - - if (!data.WriteBool(flag)) { - TAG_LOGE(AAFwkTag::APPMGR, "Write flag fail."); - return; - } - - MessageParcel reply; - MessageOption option; - auto ret = SendTransactCmd(static_cast(IAmsMgr::Message::SET_APP_ASSERT_PAUSE_STATE), - data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request failed, err: %{public}d", ret); - } -} - void AmsMgrProxy::ClearProcessByToken(sptr token) { MessageParcel data; diff --git a/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_stub.cpp index 864ea07e3d..059d77a11f 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ams_mgr_stub.cpp @@ -27,6 +27,7 @@ #include "ipc_skeleton.h" #include "ipc_types.h" #include "iremote_object.h" +#include "string_ex.h" namespace OHOS { namespace AppExecFwk { @@ -64,8 +65,6 @@ AmsMgrStub::AmsMgrStub() &AmsMgrStub::HandleKillApplicationSelf; memberFuncMap_[static_cast(IAmsMgr::Message::GET_RUNNING_PROCESS_INFO_BY_TOKEN)] = &AmsMgrStub::HandleGetRunningProcessInfoByToken; - memberFuncMap_[static_cast(IAmsMgr::Message::GET_RUNNING_PROCESS_INFO_BY_PID)] = - &AmsMgrStub::HandleGetRunningProcessInfoByPid; memberFuncMap_[static_cast(IAmsMgr::Message::SET_ABILITY_FOREGROUNDING_FLAG)] = &AmsMgrStub::HandleSetAbilityForegroundingFlagToAppRecord; memberFuncMap_[static_cast(IAmsMgr::Message::START_SPECIFIED_ABILITY)] = @@ -74,6 +73,8 @@ AmsMgrStub::AmsMgrStub() &AmsMgrStub::HandleRegisterStartSpecifiedAbilityResponse; memberFuncMap_[static_cast(IAmsMgr::Message::GET_APPLICATION_INFO_BY_PROCESS_ID)] = &AmsMgrStub::HandleGetApplicationInfoByProcessID; + memberFuncMap_[static_cast(IAmsMgr::Message::NOTIFY_APP_MGR_RECORD_EXIT_REASON)] = + &AmsMgrStub::HandleNotifyAppMgrRecordExitReason; memberFuncMap_[static_cast(IAmsMgr::Message::UPDATE_APPLICATION_INFO_INSTALLED)] = &AmsMgrStub::HandleUpdateApplicationInfoInstalled; memberFuncMap_[static_cast(IAmsMgr::Message::SET_CURRENT_USER_ID)] = @@ -112,8 +113,6 @@ void AmsMgrStub::CreateMemberFuncMap() &AmsMgrStub::HandleRegisterAbilityDebugResponse; memberFuncMap_[static_cast(IAmsMgr::Message::IS_ATTACH_DEBUG)] = &AmsMgrStub::HandleIsAttachDebug; - memberFuncMap_[static_cast(IAmsMgr::Message::SET_APP_ASSERT_PAUSE_STATE)] = - &AmsMgrStub::HandleSetAppAssertionPauseState; memberFuncMap_[static_cast(IAmsMgr::Message::CLEAR_PROCESS_BY_TOKEN)] = &AmsMgrStub::HandleClearProcessByToken; memberFuncMap_[static_cast(IAmsMgr::Message::KILL_PROCESSES_BY_PIDS)] = @@ -360,18 +359,6 @@ int32_t AmsMgrStub::HandleGetRunningProcessInfoByToken(MessageParcel &data, Mess return NO_ERROR; } -int32_t AmsMgrStub::HandleGetRunningProcessInfoByPid(MessageParcel &data, MessageParcel &reply) -{ - RunningProcessInfo processInfo; - auto pid = static_cast(data.ReadInt32()); - GetRunningProcessInfoByPid(pid, processInfo); - if (reply.WriteParcelable(&processInfo)) { - TAG_LOGE(AAFwkTag::APPMGR, "process info write failed."); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - int32_t AmsMgrStub::HandleSetAbilityForegroundingFlagToAppRecord(MessageParcel &data, MessageParcel &reply) { RunningProcessInfo processInfo; @@ -394,7 +381,7 @@ int32_t AmsMgrStub::HandleStartSpecifiedAbility(MessageParcel &data, MessageParc delete want; return ERR_INVALID_VALUE; } - StartSpecifiedAbility(*want, *abilityInfo); + StartSpecifiedAbility(*want, *abilityInfo, data.ReadInt32()); delete want; delete abilityInfo; return NO_ERROR; @@ -430,6 +417,20 @@ int32_t AmsMgrStub::HandleGetApplicationInfoByProcessID(MessageParcel &data, Mes return NO_ERROR; } +int32_t AmsMgrStub::HandleNotifyAppMgrRecordExitReason(MessageParcel &data, MessageParcel &reply) +{ + TAG_LOGD(AAFwkTag::APPMGR, "HandleNotifyAppMgrRecordExitReason called."); + int32_t pid = data.ReadInt32(); + int32_t reason = data.ReadInt32(); + std::string exitMsg = Str16ToStr8(data.ReadString16()); + int32_t result = NotifyAppMgrRecordExitReason(pid, reason, exitMsg); + if (!reply.WriteInt32(result)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write result failed."); + return IPC_PROXY_ERR; + } + return NO_ERROR; +} + int32_t AmsMgrStub::HandleUpdateApplicationInfoInstalled(MessageParcel &data, MessageParcel &reply) { HITRACE_METER(HITRACE_TAG_APP); @@ -650,15 +651,6 @@ int32_t AmsMgrStub::HandleIsAttachDebug(MessageParcel &data, MessageParcel &repl return NO_ERROR; } -int32_t AmsMgrStub::HandleSetAppAssertionPauseState(MessageParcel &data, MessageParcel &reply) -{ - TAG_LOGD(AAFwkTag::APPMGR, "Called."); - auto pid = data.ReadInt32(); - auto flag = data.ReadBool(); - SetAppAssertionPauseState(pid, flag); - return NO_ERROR; -} - int32_t AmsMgrStub::HandleClearProcessByToken(MessageParcel &data, MessageParcel &reply) { HITRACE_METER(HITRACE_TAG_APP); diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_jsheap_mem_info.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_jsheap_mem_info.cpp index 02b4333129..619f615ccb 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_jsheap_mem_info.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_jsheap_mem_info.cpp @@ -19,10 +19,61 @@ namespace OHOS { namespace AppExecFwk { +namespace { +constexpr int32_t MAX_TID_COUNT = 40; +} + +JsHeapDumpInfo::~JsHeapDumpInfo() +{ + TAG_LOGI(AAFwkTag::APPMGR, "~JsHeapDumpInfo start"); + for (auto &fd : fdVec) { + close(fd); + } + fdVec.clear(); + tidVec.clear(); +} + bool JsHeapDumpInfo::Marshalling(Parcel &parcel) const { - return (parcel.WriteUint32(pid) && parcel.WriteUint32(tid) - && parcel.WriteBool(needGc) && parcel.WriteBool(needSnapshot)); + bool res = (parcel.WriteUint32(pid) && parcel.WriteUint32(tid) + && parcel.WriteBool(needGc) && parcel.WriteBool(needSnapshot) + && parcel.WriteUInt32Vector(fdVec) && parcel.WriteUInt32Vector(tidVec)); + + auto msgParcel = static_cast(&parcel); + if (msgParcel == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "Dump Marshalling msgParcel==nullptr"); + return false; + } + for (auto &fd : fdVec) { + msgParcel->WriteFileDescriptor(fd); + } + return res; +} + +bool JsHeapDumpInfo::ReadFromParcel(Parcel &parcel) +{ + pid = parcel.ReadUint32(); + tid = parcel.ReadUint32(); + needGc = parcel.ReadBool(); + needSnapshot = parcel.ReadBool(); + if (fdVec.size() > MAX_TID_COUNT || tidVec.size() > MAX_TID_COUNT) { + TAG_LOGE(AAFwkTag::APPMGR, "fdVec or tidVec size more than 40."); + return false; + } + parcel.ReadUInt32Vector(&fdVec); + parcel.ReadUInt32Vector(&tidVec); + + auto msgParcel = static_cast(&parcel); + if (msgParcel == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "ReadFromParcel failed."); + return false; + } + fdVec.clear(); + for (auto &tid : tidVec) { + uint32_t parcelFd = static_cast(msgParcel->ReadFileDescriptor()); + fdVec.push_back(parcelFd); + } + return true; } JsHeapDumpInfo *JsHeapDumpInfo::Unmarshalling(Parcel &parcel) @@ -32,10 +83,11 @@ JsHeapDumpInfo *JsHeapDumpInfo::Unmarshalling(Parcel &parcel) TAG_LOGE(AAFwkTag::APPMGR, "info nullptr"); return nullptr; } - info->pid = parcel.ReadUint32(); - info->tid = parcel.ReadUint32(); - info->needGc = parcel.ReadBool(); - info->needSnapshot = parcel.ReadBool(); + if (info && !info->ReadFromParcel(parcel)) { + TAG_LOGE(AAFwkTag::APPMGR, "JsHeapDumpInfo failed, because ReadFromParcel failed"); + delete info; + info = nullptr; + } return info; } } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_mgr_client.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_mgr_client.cpp index 8a65c60534..41a97ea17c 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_mgr_client.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_mgr_client.cpp @@ -519,15 +519,14 @@ void AppMgrClient::GetRunningProcessInfoByToken(const sptr &token } } -void AppMgrClient::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const +int32_t AppMgrClient::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const { sptr service = iface_cast(mgrHolder_->GetRemoteObject()); - if (service != nullptr) { - sptr amsService = service->GetAmsMgr(); - if (amsService != nullptr) { - amsService->GetRunningProcessInfoByPid(pid, info); - } + if (service == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "Service is nullptr."); + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; } + return service->GetRunningProcessInfoByPid(pid, info); } void AppMgrClient::SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const @@ -584,7 +583,8 @@ int AppMgrClient::FinishUserTest(const std::string &msg, const int64_t &resultCo return service->FinishUserTest(msg, resultCode, bundleName); } -void AppMgrClient::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +void AppMgrClient::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId) { sptr service = iface_cast(mgrHolder_->GetRemoteObject()); if (service == nullptr) { @@ -594,7 +594,7 @@ void AppMgrClient::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecF if (amsService == nullptr) { return; } - amsService->StartSpecifiedAbility(want, abilityInfo); + amsService->StartSpecifiedAbility(want, abilityInfo, requestId); } void AppMgrClient::SetKeepAliveEnableState(const std::string &bundleName, bool enable) @@ -605,7 +605,8 @@ void AppMgrClient::SetKeepAliveEnableState(const std::string &bundleName, bool e amsService_->SetKeepAliveEnableState(bundleName, enable); } -void AppMgrClient::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +void AppMgrClient::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId) { TAG_LOGD(AAFwkTag::APPMGR, "call."); sptr service = iface_cast(mgrHolder_->GetRemoteObject()); @@ -616,7 +617,7 @@ void AppMgrClient::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecF if (amsService == nullptr) { return; } - amsService->StartSpecifiedProcess(want, abilityInfo); + amsService->StartSpecifiedProcess(want, abilityInfo, requestId); } void AppMgrClient::RegisterStartSpecifiedAbilityResponse(const sptr &response) @@ -643,17 +644,6 @@ void AppMgrClient::ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::W service->ScheduleAcceptWantDone(recordId, want, flag); } -void AppMgrClient::ScheduleNewProcessRequest(const int32_t recordId, const AAFwk::Want &want, const std::string &flag) -{ - sptr service = iface_cast(mgrHolder_->GetRemoteObject()); - if (service == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "service is nullptr"); - return; - } - - service->ScheduleNewProcessRequestDone(recordId, want, flag); -} - AppMgrResultCode AppMgrClient::UpdateConfiguration(const Configuration &config) { sptr service = iface_cast(mgrHolder_->GetRemoteObject()); @@ -729,7 +719,22 @@ int AppMgrClient::GetApplicationInfoByProcessID(const int pid, AppExecFwk::Appli return amsService->GetApplicationInfoByProcessID(pid, application, debug); } -int32_t AppMgrClient::StartNativeProcessForDebugger(const AAFwk::Want &want) const +int32_t AppMgrClient::NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg) +{ + sptr service = iface_cast(mgrHolder_->GetRemoteObject()); + if (service == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "service is nullptr"); + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; + } + sptr amsService = service->GetAmsMgr(); + if (amsService == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "amsService is nullptr"); + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; + } + return amsService->NotifyAppMgrRecordExitReason(pid, reason, exitMsg); +} + +int32_t AppMgrClient::StartNativeProcessForDebugger(const AAFwk::Want &want) { sptr service = iface_cast(mgrHolder_->GetRemoteObject()); if (service == nullptr) { @@ -752,12 +757,12 @@ int AppMgrClient::PreStartNWebSpawnProcess() int AppMgrClient::StartRenderProcess(const std::string &renderParam, int32_t ipcFd, int32_t sharedFd, - int32_t crashFd, pid_t &renderPid) + int32_t crashFd, pid_t &renderPid, bool isGPU) { sptr service = iface_cast(mgrHolder_->GetRemoteObject()); if (service != nullptr) { return service->StartRenderProcess(renderParam, ipcFd, sharedFd, crashFd, - renderPid); + renderPid, isGPU); } return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; } @@ -953,14 +958,6 @@ bool AppMgrClient::IsAttachDebug(const std::string &bundleName) return amsService_->IsAttachDebug(bundleName); } -void AppMgrClient::SetAppAssertionPauseState(int32_t pid, bool flag) -{ - if (!IsAmsServiceReady()) { - return; - } - amsService_->SetAppAssertionPauseState(pid, flag); -} - bool AppMgrClient::IsAmsServiceReady() { if (mgrHolder_ == nullptr) { @@ -1176,5 +1173,15 @@ int32_t AppMgrClient::SetSupportedProcessCacheSelf(bool isSupport) } return service->SetSupportedProcessCacheSelf(isSupport); } + +void AppMgrClient::SaveBrowserChannel(sptr browser) +{ + sptr service = iface_cast(mgrHolder_->GetRemoteObject()); + if (service == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "Service is nullptr."); + return; + } + service->SaveBrowserChannel(browser); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_mgr_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_mgr_proxy.cpp index aec1f49eb8..f89bd7eb08 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_mgr_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_mgr_proxy.cpp @@ -237,6 +237,30 @@ int32_t AppMgrProxy::GetAllRunningProcesses(std::vector &inf return result; } +int32_t AppMgrProxy::GetRunningMultiAppInfoByBundleName(const std::string &bundleName, + RunningMultiAppInfo &info) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return ERR_FLATTEN_OBJECT; + } + if (!data.WriteString(bundleName)) { + TAG_LOGE(AAFwkTag::APPMGR, "bundleName write failed."); + return ERR_INVALID_VALUE; + } + int32_t ret = SendRequest(AppMgrInterfaceCode::GET_RUNNING_MULTIAPP_INFO_BY_BUNDLENAME, data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); + return ret; + } + std::unique_ptr infoReply(reply.ReadParcelable()); + info = *infoReply; + int result = reply.ReadInt32(); + return result; +} + int32_t AppMgrProxy::GetRunningProcessesByBundleType(const BundleType bundleType, std::vector &info) { @@ -808,7 +832,7 @@ int AppMgrProxy::PreStartNWebSpawnProcess() int AppMgrProxy::StartRenderProcess(const std::string &renderParam, int32_t ipcFd, int32_t sharedFd, - int32_t crashFd, pid_t &renderPid) + int32_t crashFd, pid_t &renderPid, bool isGPU) { if (renderParam.empty() || ipcFd <= 0 || sharedFd <= 0 || crashFd <= 0) { TAG_LOGE(AAFwkTag::APPMGR, "Invalid params, renderParam:%{private}s, ipcFd:%{public}d, " @@ -836,6 +860,11 @@ int AppMgrProxy::StartRenderProcess(const std::string &renderParam, return -1; } + if (!data.WriteBool(isGPU)) { + TAG_LOGE(AAFwkTag::APPMGR, "want processType failed."); + return -1; + } + int32_t ret = SendRequest(AppMgrInterfaceCode::START_RENDER_PROCESS, data, reply, option); if (ret != NO_ERROR) { @@ -877,6 +906,27 @@ void AppMgrProxy::AttachRenderProcess(const sptr &renderScheduler } } +void AppMgrProxy::SaveBrowserChannel(sptr browser) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "WriteInterfaceToken failed"); + return; + } + + if (!data.WriteRemoteObject(browser)) { + TAG_LOGE(AAFwkTag::APPMGR, "browser write failed."); + return; + } + + if (!SendTransactCmd(AppMgrInterfaceCode::SAVE_BROWSER_CHANNEL, data, reply)) { + TAG_LOGE(AAFwkTag::APPMGR, "SendTransactCmd SAVE_BROWSER_CHANNEL failed"); + return; + } +} + int AppMgrProxy::GetRenderProcessTerminationStatus(pid_t renderPid, int &status) { MessageParcel data; @@ -1283,6 +1333,36 @@ int32_t AppMgrProxy::GetBundleNameByPid(const int pid, std::string &bundleName, return ERR_NONE; } +int32_t AppMgrProxy::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) +{ + TAG_LOGD(AAFwkTag::APPMGR, "start"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return ERR_INVALID_DATA; + } + + if (!data.WriteInt32(static_cast(pid))) { + TAG_LOGE(AAFwkTag::APPMGR, "parcel WriteInt32 failed."); + return ERR_INVALID_DATA; + } + + auto ret = SendRequest(AppMgrInterfaceCode::GET_RUNNING_PROCESS_INFO_BY_PID, data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); + return ret; + } + + std::unique_ptr processInfo(reply.ReadParcelable()); + if (processInfo == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "recv process info failded"); + return ERR_INVALID_DATA; + } + info = *processInfo; + return reply.ReadInt32(); +} + int32_t AppMgrProxy::NotifyAppFault(const FaultData &faultData) { TAG_LOGD(AAFwkTag::APPMGR, "called."); @@ -1989,5 +2069,68 @@ int32_t AppMgrProxy::SetSupportedProcessCacheSelf(bool isSupport) } return reply.ReadInt32(); } + +void AppMgrProxy::SetAppAssertionPauseState(bool flag) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called."); + MessageParcel data; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); + return; + } + if (!data.WriteBool(flag)) { + TAG_LOGE(AAFwkTag::APPMGR, "flag write failed."); + return; + } + + MessageParcel reply; + MessageOption option; + auto error = SendRequest(AppMgrInterfaceCode::SET_APP_ASSERT_PAUSE_STATE_SELF, data, reply, option); + if (error != NO_ERROR) { + TAG_LOGE(AAFwkTag::APPMGR, "Send request error: %{public}d", error); + return; + } +} + +int32_t AppMgrProxy::StartNativeChildProcess(const std::string &libName, int32_t childProcessCount, + const sptr &callback) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called."); + if (libName.empty() || !callback) { + TAG_LOGE(AAFwkTag::APPMGR, "Invalid params, libName:%{private}s", libName.c_str()); + return ERR_INVALID_VALUE; + } + + MessageParcel data; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); + return IPC_PROXY_ERR; + } + + if (!data.WriteString(libName)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write lib name failed."); + return IPC_PROXY_ERR; + } + + if (!data.WriteInt32(childProcessCount)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write param childProcessCount failed."); + return IPC_PROXY_ERR; + } + + if (!data.WriteRemoteObject(callback)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write call back ipc object failed."); + return IPC_PROXY_ERR; + } + + MessageParcel reply; + MessageOption option; + auto error = SendRequest(AppMgrInterfaceCode::START_NATIVE_CHILD_PROCESS, data, reply, option); + if (error != NO_ERROR) { + TAG_LOGE(AAFwkTag::APPMGR, "Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_mgr_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_mgr_stub.cpp index b1c3946e05..c18811cdc3 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_mgr_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_mgr_stub.cpp @@ -16,6 +16,7 @@ #include "app_mgr_stub.h" #include "ability_info.h" +#include "app_jsheap_mem_info.h" #include "app_malloc_info.h" #include "app_mgr_proxy.h" #include "app_scheduler_interface.h" @@ -29,8 +30,8 @@ #include "ipc_types.h" #include "iremote_object.h" #include "memory_level_info.h" +#include "running_process_info.h" #include "want.h" -#include "app_jsheap_mem_info.h" namespace OHOS { namespace AppExecFwk { @@ -102,6 +103,8 @@ AppMgrStub::AppMgrStub() &AppMgrStub::HandleDumpHeapMemory; memberFuncMap_[static_cast(AppMgrInterfaceCode::DUMP_JSHEAP_MEMORY_PROCESS)] = &AppMgrStub::HandleDumpJsHeapMemory; + memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_RUNNING_MULTIAPP_INFO_BY_BUNDLENAME)] = + &AppMgrStub::HandleGetRunningMultiAppInfoByBundleName; #ifdef ABILITY_COMMAND_FOR_TEST memberFuncMap_[static_cast(AppMgrInterfaceCode::BLOCK_APP_SERVICE)] = &AppMgrStub::HandleBlockAppServiceDone; @@ -130,6 +133,8 @@ AppMgrStub::AppMgrStub() &AppMgrStub::HandleJudgeSandboxByPid; memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_BUNDLE_NAME_BY_PID)] = &AppMgrStub::HandleGetBundleNameByPid; + memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_RUNNING_PROCESS_INFO_BY_PID)] = + &AppMgrStub::HandleGetRunningProcessInfoByPid; memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_GET_ALL_RENDER_PROCESSES)] = &AppMgrStub::HandleGetAllRenderProcesses; memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_PROCESS_MEMORY_BY_PID)] = @@ -190,6 +195,12 @@ AppMgrStub::AppMgrStub() &AppMgrStub::HandleSetSupportedProcessCacheSelf; memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_GET_RUNNING_PROCESSES_BY_BUNDLE_TYPE)] = &AppMgrStub::HandleGetRunningProcessesByBundleType; + memberFuncMap_[static_cast(AppMgrInterfaceCode::SET_APP_ASSERT_PAUSE_STATE_SELF)] = + &AppMgrStub::HandleSetAppAssertionPauseState; + memberFuncMap_[static_cast(AppMgrInterfaceCode::START_NATIVE_CHILD_PROCESS)] = + &AppMgrStub::HandleStartNativeChildProcess; + memberFuncMap_[static_cast(AppMgrInterfaceCode::SAVE_BROWSER_CHANNEL)] = + &AppMgrStub::HandleSaveBrowserChannel; } AppMgrStub::~AppMgrStub() @@ -326,6 +337,21 @@ int32_t AppMgrStub::HandleGetAllRunningProcesses(MessageParcel &data, MessagePar return NO_ERROR; } +int32_t AppMgrStub::HandleGetRunningMultiAppInfoByBundleName(MessageParcel &data, MessageParcel &reply) +{ + std::string bundleName = data.ReadString(); + RunningMultiAppInfo info; + int32_t result = GetRunningMultiAppInfoByBundleName(bundleName, info); + if (!reply.WriteParcelable(&info)) { + return ERR_INVALID_VALUE; + } + if (!reply.WriteInt32(result)) { + TAG_LOGE(AAFwkTag::APPMGR, "fail to write result."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + int32_t AppMgrStub::HandleGetRunningProcessesByBundleType(MessageParcel &data, MessageParcel &reply) { HITRACE_METER(HITRACE_TAG_APP); @@ -674,8 +700,9 @@ int32_t AppMgrStub::HandleStartRenderProcess(MessageParcel &data, MessageParcel int32_t sharedFd = data.ReadFileDescriptor(); int32_t crashFd = data.ReadFileDescriptor(); int32_t renderPid = 0; + bool isGPU = data.ReadBool(); int32_t result = - StartRenderProcess(renderParam, ipcFd, sharedFd, crashFd, renderPid); + StartRenderProcess(renderParam, ipcFd, sharedFd, crashFd, renderPid, isGPU); if (!reply.WriteInt32(result)) { TAG_LOGE(AAFwkTag::APPMGR, "write result error."); return ERR_INVALID_VALUE; @@ -694,6 +721,13 @@ int32_t AppMgrStub::HandleAttachRenderProcess(MessageParcel &data, MessageParcel return NO_ERROR; } +int32_t AppMgrStub::HandleSaveBrowserChannel(MessageParcel &data, MessageParcel &reply) +{ + sptr browser = data.ReadRemoteObject(); + SaveBrowserChannel(browser); + return NO_ERROR; +} + int32_t AppMgrStub::HandleGetRenderProcessTerminationStatus(MessageParcel &data, MessageParcel &reply) { int32_t renderPid = data.ReadInt32(); @@ -923,6 +957,22 @@ int32_t AppMgrStub::HandleGetBundleNameByPid(MessageParcel &data, MessageParcel return NO_ERROR; } +int32_t AppMgrStub::HandleGetRunningProcessInfoByPid(MessageParcel &data, MessageParcel &reply) +{ + RunningProcessInfo processInfo; + auto pid = static_cast(data.ReadInt32()); + auto result = GetRunningProcessInfoByPid(pid, processInfo); + if (reply.WriteParcelable(&processInfo)) { + TAG_LOGE(AAFwkTag::APPMGR, "process info write failed."); + return ERR_INVALID_VALUE; + } + if (!reply.WriteInt32(result)) { + TAG_LOGE(AAFwkTag::APPMGR, "fail to write result."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + int32_t AppMgrStub::HandleNotifyFault(MessageParcel &data, MessageParcel &reply) { std::unique_ptr faultData(data.ReadParcelable()); @@ -1312,5 +1362,29 @@ int32_t AppMgrStub::HandleSetSupportedProcessCacheSelf(MessageParcel &data, Mess } return NO_ERROR; } + +int32_t AppMgrStub::HandleSetAppAssertionPauseState(MessageParcel &data, MessageParcel &reply) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called."); + bool flag = data.ReadBool(); + SetAppAssertionPauseState(flag); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleStartNativeChildProcess(MessageParcel &data, MessageParcel &reply) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called."); + std::string libName = data.ReadString(); + int32_t childCount = data.ReadInt32(); + sptr callback = data.ReadRemoteObject(); + int32_t result = StartNativeChildProcess(libName, childCount, callback); + if (!reply.WriteInt32(result)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write ret error."); + return IPC_STUB_ERR; + } + + return NO_ERROR; +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_scheduler_host.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_scheduler_host.cpp index 6672d3cf82..84aa6e86f6 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_scheduler_host.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_scheduler_host.cpp @@ -86,6 +86,8 @@ void AppSchedulerHost::InitMemberFuncMap() &AppSchedulerHost::HandleScheduleDumpIpcStop; memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_DUMP_IPC_STAT)] = &AppSchedulerHost::HandleScheduleDumpIpcStat; + memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_DUMP_FFRT)] = + &AppSchedulerHost::HandleScheduleDumpFfrt; } AppSchedulerHost::~AppSchedulerHost() @@ -433,5 +435,17 @@ int32_t AppSchedulerHost::HandleScheduleDumpIpcStat(MessageParcel &data, Message } return NO_ERROR; } + +int32_t AppSchedulerHost::HandleScheduleDumpFfrt(MessageParcel &data, MessageParcel &reply) +{ + HITRACE_METER(HITRACE_TAG_APP); + std::string result; + ScheduleDumpFfrt(result); + if (!reply.WriteString(result)) { + TAG_LOGE(AAFwkTag::APPMGR, "Fail to write string of ScheduleDumpFfrt result"); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_scheduler_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_scheduler_proxy.cpp index c86db0c84e..6172932d56 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_scheduler_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_scheduler_proxy.cpp @@ -615,24 +615,24 @@ int32_t AppSchedulerProxy::ScheduleDumpIpcStart(std::string& result) MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); if (!WriteInterfaceToken(data)) { - result.append(MSG_DUMP_IPC_START_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "AppSchedulerProxy !WriteInterfaceToken."); return DumpErrorCode::ERR_INTERNAL_ERROR; } int32_t ret = SendTransactCmd(operation, data, reply, option); if (ret != NO_ERROR) { - result.append(MSG_DUMP_IPC_START_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); return DumpErrorCode::ERR_INTERNAL_ERROR; } if (!reply.ReadString(result)) { - result.append(MSG_DUMP_IPC_START_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "Fail to read string of ScheduleDumpIpcStart result"); return DumpErrorCode::ERR_INTERNAL_ERROR; } @@ -647,24 +647,24 @@ int32_t AppSchedulerProxy::ScheduleDumpIpcStop(std::string& result) MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); if (!WriteInterfaceToken(data)) { - result.append(MSG_DUMP_IPC_STOP_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "AppSchedulerProxy !WriteInterfaceToken."); return DumpErrorCode::ERR_INTERNAL_ERROR; } int32_t ret = SendTransactCmd(operation, data, reply, option); if (ret != NO_ERROR) { - result.append(MSG_DUMP_IPC_STOP_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); return DumpErrorCode::ERR_INTERNAL_ERROR; } if (!reply.ReadString(result)) { - result.append(MSG_DUMP_IPC_STOP_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "Fail to read string of ScheduleDumpIpcStop result"); return DumpErrorCode::ERR_INTERNAL_ERROR; } @@ -679,30 +679,60 @@ int32_t AppSchedulerProxy::ScheduleDumpIpcStat(std::string& result) MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); if (!WriteInterfaceToken(data)) { - result.append(MSG_DUMP_IPC_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "AppSchedulerProxy !WriteInterfaceToken."); return DumpErrorCode::ERR_INTERNAL_ERROR; } int32_t ret = SendTransactCmd(operation, data, reply, option); if (ret != NO_ERROR) { - result.append(MSG_DUMP_IPC_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); return DumpErrorCode::ERR_INTERNAL_ERROR; } if (!reply.ReadString(result)) { - result.append(MSG_DUMP_IPC_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "Fail to read string of ScheduleDumpIpcStat result"); return DumpErrorCode::ERR_INTERNAL_ERROR; } return DumpErrorCode::ERR_OK; } +int32_t AppSchedulerProxy::ScheduleDumpFfrt(std::string& result) +{ + TAG_LOGD(AAFwkTag::APPMGR, "AppSchedulerProxy::ScheduleDumpFfrt start"); + uint32_t operation = static_cast(IAppScheduler::Message::SCHEDULE_DUMP_FFRT); + MessageParcel data; + MessageParcel reply; + reply.SetMaxCapacity(MAX_CAPACITY); + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); + TAG_LOGE(AAFwkTag::APPMGR, "AppSchedulerProxy !WriteInterfaceToken."); + return DumpErrorCode::ERR_INTERNAL_ERROR; + } + int32_t ret = SendTransactCmd(operation, data, reply, option); + if (ret != NO_ERROR) { + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); + TAG_LOGE(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); + return DumpErrorCode::ERR_INTERNAL_ERROR; + } + if (!reply.ReadString(result)) { + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); + TAG_LOGE(AAFwkTag::APPMGR, "Fail to read string of ScheduleDumpFfrt result"); + return DumpErrorCode::ERR_INTERNAL_ERROR; + } + return DumpErrorCode::ERR_OK; +} + int32_t AppSchedulerProxy::SendTransactCmd(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_host.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_host.cpp index 42779c87e0..e71dbf28c5 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_host.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_host.cpp @@ -38,6 +38,8 @@ AppStateCallbackHost::AppStateCallbackHost() &AppStateCallbackHost::HandleNotifyConfigurationChange; memberFuncMap_[static_cast(IAppStateCallback::Message::TRANSACT_ON_NOTIFY_START_RESIDENT_PROCESS)] = &AppStateCallbackHost::HandleNotifyStartResidentProcess; + memberFuncMap_[static_cast(IAppStateCallback::Message::TRANSACT_ON_APP_REMOTE_DIED)] = + &AppStateCallbackHost::HandleOnAppRemoteDied; } AppStateCallbackHost::~AppStateCallbackHost() @@ -87,6 +89,11 @@ void AppStateCallbackHost::NotifyStartResidentProcess(std::vector> &abilityTokens) +{ + TAG_LOGD(AAFwkTag::APPMGR, "called"); +} + int32_t AppStateCallbackHost::HandleOnAppStateChanged(MessageParcel &data, MessageParcel &reply) { HITRACE_METER(HITRACE_TAG_APP); @@ -143,5 +150,25 @@ int32_t AppStateCallbackHost::HandleNotifyStartResidentProcess(MessageParcel &da NotifyStartResidentProcess(bundleInfos); return NO_ERROR; } + +int32_t AppStateCallbackHost::HandleOnAppRemoteDied(MessageParcel &data, MessageParcel &reply) +{ + std::vector> abilityTokens; + int32_t infoSize = data.ReadInt32(); + if (infoSize > CYCLE_LIMIT) { + TAG_LOGE(AAFwkTag::APPMGR, "infoSize is too large"); + return ERR_INVALID_VALUE; + } + for (int32_t i = 0; i < infoSize; i++) { + sptr obj = data.ReadRemoteObject(); + if (!obj) { + TAG_LOGE(AAFwkTag::APPMGR, "Read token failed."); + return ERR_INVALID_VALUE; + } + abilityTokens.emplace_back(obj); + } + OnAppRemoteDied(abilityTokens); + return NO_ERROR; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_proxy.cpp index 25f37a9e6d..1636c1c45e 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_state_callback_proxy.cpp @@ -138,6 +138,35 @@ void AppStateCallbackProxy::NotifyStartResidentProcess(std::vector> &abilityTokens) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "WriteInterfaceToken failed"); + return; + } + + if (!data.WriteInt32(abilityTokens.size())) { + TAG_LOGE(AAFwkTag::APPMGR, "write token size failed."); + return; + } + + for (auto &token : abilityTokens) { + if (!data.WriteRemoteObject(token.GetRefPtr())) { + TAG_LOGE(AAFwkTag::APPMGR, "write token failed"); + return; + } + } + auto ret = SendTransactCmd( + static_cast(IAppStateCallback::Message::TRANSACT_ON_APP_REMOTE_DIED), + data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); + } +} + int32_t AppStateCallbackProxy::SendTransactCmd(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { diff --git a/interfaces/inner_api/app_manager/src/appmgr/child_process_info.cpp b/interfaces/inner_api/app_manager/src/appmgr/child_process_info.cpp index 490bbe820b..9790eeba07 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/child_process_info.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/child_process_info.cpp @@ -37,6 +37,8 @@ bool ChildProcessInfo::ReadFromParcel(Parcel &parcel) READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, uidData); uid = static_cast(uidData); + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, processType); + bundleName = Str16ToStr8(parcel.ReadString16()); processName = Str16ToStr8(parcel.ReadString16()); srcEntry = Str16ToStr8(parcel.ReadString16()); @@ -64,6 +66,7 @@ bool ChildProcessInfo::Marshalling(Parcel &parcel) const WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(pid)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(hostPid)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(uid)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(processType)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(bundleName)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(processName)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(srcEntry)); diff --git a/interfaces/inner_api/app_manager/src/appmgr/child_scheduler_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/child_scheduler_proxy.cpp index edf650c809..e14eaa5e71 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/child_scheduler_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/child_scheduler_proxy.cpp @@ -84,5 +84,39 @@ bool ChildSchedulerProxy::ScheduleExitProcessSafely() TAG_LOGD(AAFwkTag::APPMGR, "ScheduleExitProcessSafely end."); return true; } + +bool ChildSchedulerProxy::ScheduleRunNativeProc(const sptr &mainProcessCb) +{ + TAG_LOGD(AAFwkTag::APPMGR, "ScheduleRunNativeProc start."); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); + return false; + } + + if (!data.WriteRemoteObject(mainProcessCb)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write main process callback ipc object failed."); + return false; + } + + sptr remote = Remote(); + if (remote == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "Remote() is null."); + return false; + } + + int32_t ret = remote->SendRequest( + static_cast(IChildScheduler::Message::SCHEDULE_RUN_NATIVE_PROC), data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGE(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d.", ret); + return false; + } + + TAG_LOGD(AAFwkTag::APPMGR, "ScheduleRunNativeProc end."); + return true; +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/src/appmgr/child_scheduler_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/child_scheduler_stub.cpp index 1fda7ab84c..b434032513 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/child_scheduler_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/child_scheduler_stub.cpp @@ -27,6 +27,8 @@ ChildSchedulerStub::ChildSchedulerStub() &ChildSchedulerStub::HandleScheduleLoadJs; memberFuncMap_[static_cast(IChildScheduler::Message::SCHEDULE_EXIT_PROCESS_SAFELY)] = &ChildSchedulerStub::HandleScheduleExitProcessSafely; + memberFuncMap_[static_cast(IChildScheduler::Message::SCHEDULE_RUN_NATIVE_PROC)] = + &ChildSchedulerStub::HandleScheduleRunNativeProc; } ChildSchedulerStub::~ChildSchedulerStub() @@ -68,5 +70,13 @@ int32_t ChildSchedulerStub::HandleScheduleExitProcessSafely(MessageParcel &data, ScheduleExitProcessSafely(); return ERR_NONE; } + +int32_t ChildSchedulerStub::HandleScheduleRunNativeProc(MessageParcel &data, MessageParcel &reply) +{ + sptr cb = data.ReadRemoteObject(); + ScheduleRunNativeProc(cb); + return ERR_NONE; +} + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_api/app_manager/src/appmgr/native_child_notify_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/native_child_notify_proxy.cpp new file mode 100644 index 0000000000..e97ec17658 --- /dev/null +++ b/interfaces/inner_api/app_manager/src/appmgr/native_child_notify_proxy.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_child_notify_proxy.h" +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" +#include "ipc_types.h" + +namespace OHOS { +namespace AppExecFwk { + +NativeChildNotifyProxy::NativeChildNotifyProxy(const sptr &impl) + : IRemoteProxy(impl) +{ +} + +bool NativeChildNotifyProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(NativeChildNotifyProxy::GetDescriptor())) { + TAG_LOGE(AAFwkTag::APPMGR, "NativeChildNotifyProxy write interface token failed"); + return false; + } + + return true; +} + +int32_t NativeChildNotifyProxy::SendRequest(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption& option) +{ + sptr remote = Remote(); + if (!remote) { + TAG_LOGE(AAFwkTag::APPMGR, "NativeChildNotifyProxy get remote object failed"); + return ERR_NULL_OBJECT; + } + + int32_t ret = remote->SendRequest(code, data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGE(AAFwkTag::APPMGR, "NativeChildNotifyProxy SendRequest failed(%{public}d)", ret); + return ret; + } + + return NO_ERROR; +} + +void NativeChildNotifyProxy::OnNativeChildStarted(const sptr &nativeChild) +{ + TAG_LOGD(AAFwkTag::APPMGR, "NativeChildNotifyProxy OnNativeChildStarted"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + + if (!data.WriteRemoteObject(nativeChild)) { + TAG_LOGE(AAFwkTag::APPMGR, "NativeChildNotifyProxy write native child ipc object failed."); + return; + } + + SendRequest(INativeChildNotify::IPC_ID_ON_NATIVE_CHILD_STARTED, data, reply, option); +} + +void NativeChildNotifyProxy::OnError(int32_t errCode) +{ + TAG_LOGD(AAFwkTag::APPMGR, "NativeChildNotifyProxy OnError(%{public}d)", errCode); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + + if (!data.WriteInt32(errCode)) { + TAG_LOGE(AAFwkTag::APPMGR, "NativeChildNotifyProxy write error code failed."); + return; + } + + SendRequest(INativeChildNotify::IPC_ID_ON_ERROR, data, reply, option); +} + +} // OHOS +} // AppExecFwk \ No newline at end of file diff --git a/interfaces/inner_api/app_manager/src/appmgr/native_child_notify_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/native_child_notify_stub.cpp new file mode 100644 index 0000000000..63ad1fb4e2 --- /dev/null +++ b/interfaces/inner_api/app_manager/src/appmgr/native_child_notify_stub.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_child_notify_stub.h" +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" +#include "ipc_types.h" + +namespace OHOS { +namespace AppExecFwk { + +int NativeChildNotifyStub::OnRemoteRequest(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + TAG_LOGD(AAFwkTag::APPMGR, "NativeChildNotifyStub::OnRemoteRequest, code=%{public}u, flags=%{public}d.", + code, option.GetFlags()); + std::u16string descriptor = NativeChildNotifyStub::GetDescriptor(); + std::u16string remoteDesc = data.ReadInterfaceToken(); + if (descriptor != remoteDesc) { + TAG_LOGE(AAFwkTag::APPMGR, "A local descriptor is not equivalent to a remote"); + return ERR_INVALID_STATE; + } + + int32_t ret; + switch (code) { + case INativeChildNotify::IPC_ID_ON_NATIVE_CHILD_STARTED: + ret = HandleOnNativeChildStarted(data, reply); + break; + + case INativeChildNotify::IPC_ID_ON_ERROR: + ret = HandleOnError(data, reply); + break; + + default: + TAG_LOGW(AAFwkTag::APPMGR, "NativeChildNotifyStub Unknow ipc call(%{public}u)", code); + ret = IPCObjectStub::OnRemoteRequest(code, data, reply, option); + break; + } + + TAG_LOGD(AAFwkTag::APPMGR, "NativeChildNotifyStub::OnRemoteRequest end"); + return ret; +} + +int32_t NativeChildNotifyStub::HandleOnNativeChildStarted(MessageParcel &data, MessageParcel &reply) +{ + sptr cb = data.ReadRemoteObject(); + OnNativeChildStarted(cb); + return ERR_NONE; +} + +int32_t NativeChildNotifyStub::HandleOnError(MessageParcel &data, MessageParcel &reply) +{ + int32_t err = data.ReadInt32(); + OnError(err); + return ERR_NONE; +} + +} // OHOS +} // AppExecFwk diff --git a/interfaces/inner_api/app_manager/src/appmgr/process_data.cpp b/interfaces/inner_api/app_manager/src/appmgr/process_data.cpp index cff7d93a37..3e1759f9ec 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/process_data.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/process_data.cpp @@ -18,18 +18,20 @@ #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" #include "parcel_macro_base.h" +#include "string_ex.h" namespace OHOS { namespace AppExecFwk { bool ProcessData::Marshalling(Parcel &parcel) const { - return (parcel.WriteString(bundleName) && parcel.WriteInt32(pid) && parcel.WriteInt32(uid) && + return (parcel.WriteString(bundleName) && parcel.WriteInt32(pid) && + parcel.WriteInt32(uid) && parcel.WriteInt32(hostPid) && parcel.WriteInt32(gpuPid) && parcel.WriteInt32(static_cast(state)) && parcel.WriteBool(isContinuousTask) && parcel.WriteBool(isKeepAlive) && parcel.WriteBool(isFocused) && parcel.WriteInt32(requestProcCode) && parcel.WriteInt32(processChangeReason) && parcel.WriteString(processName) && parcel.WriteInt32(static_cast(processType)) && parcel.WriteInt32(static_cast(extensionType)) && parcel.WriteInt32(renderUid) && parcel.WriteUint32(accessTokenId) && - parcel.WriteBool(isTestMode)); + parcel.WriteBool(isTestMode) && parcel.WriteInt32(exitReason) && parcel.WriteString16(Str8ToStr16(exitMsg))); } bool ProcessData::ReadFromParcel(Parcel &parcel) @@ -37,6 +39,8 @@ bool ProcessData::ReadFromParcel(Parcel &parcel) bundleName = parcel.ReadString(); pid = parcel.ReadInt32(); uid = parcel.ReadInt32(); + hostPid = parcel.ReadInt32(); + gpuPid = parcel.ReadInt32(); state = static_cast(parcel.ReadInt32()); isContinuousTask = parcel.ReadBool(); isKeepAlive = parcel.ReadBool(); @@ -49,6 +53,8 @@ bool ProcessData::ReadFromParcel(Parcel &parcel) renderUid = parcel.ReadInt32(); accessTokenId = parcel.ReadUint32(); isTestMode = parcel.ReadBool(); + exitReason = parcel.ReadInt32(); + exitMsg = Str16ToStr8(parcel.ReadString16()); return true; } diff --git a/interfaces/inner_api/app_manager/src/appmgr/render_scheduler_host.cpp b/interfaces/inner_api/app_manager/src/appmgr/render_scheduler_host.cpp index 8fef51a28d..059e9b6b72 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/render_scheduler_host.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/render_scheduler_host.cpp @@ -60,7 +60,8 @@ int RenderSchedulerHost::HandleNotifyBrowserFd(MessageParcel &data, MessageParce int32_t ipcFd = data.ReadFileDescriptor(); int32_t sharedFd = data.ReadFileDescriptor(); int32_t crashFd = data.ReadFileDescriptor(); - NotifyBrowserFd(ipcFd, sharedFd, crashFd); + sptr browser = data.ReadRemoteObject(); + NotifyBrowserFd(ipcFd, sharedFd, crashFd, browser); return 0; } } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/src/appmgr/render_scheduler_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/render_scheduler_proxy.cpp index 3f0073bb88..9f670bedfb 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/render_scheduler_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/render_scheduler_proxy.cpp @@ -36,7 +36,7 @@ bool RenderSchedulerProxy::WriteInterfaceToken(MessageParcel &data) } void RenderSchedulerProxy::NotifyBrowserFd(int32_t ipcFd, int32_t sharedFd, - int32_t crashFd) + int32_t crashFd, sptr browser) { TAG_LOGD(AAFwkTag::APPMGR, "NotifyBrowserFd start"); MessageParcel data; @@ -53,6 +53,10 @@ void RenderSchedulerProxy::NotifyBrowserFd(int32_t ipcFd, int32_t sharedFd, return; } + if (!data.WriteRemoteObject(browser)) { + TAG_LOGE(AAFwkTag::APPMGR, "write browser failed!"); + } + sptr remote = Remote(); if (remote == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Remote() is NULL"); diff --git a/interfaces/inner_api/app_manager/src/appmgr/running_multi_info.cpp b/interfaces/inner_api/app_manager/src/appmgr/running_multi_info.cpp new file mode 100644 index 0000000000..104963d4c1 --- /dev/null +++ b/interfaces/inner_api/app_manager/src/appmgr/running_multi_info.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2024 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 "running_multi_info.h" + +#include "nlohmann/json.hpp" +#include "string_ex.h" + +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" +#include "parcel_macro_base.h" + +namespace OHOS { +namespace AppExecFwk { +bool RunningMultiAppInfo::ReadFromParcel(Parcel &parcel) +{ + bundleName = Str16ToStr8(parcel.ReadString16()); + mode = parcel.ReadInt32(); + int32_t runningAppClonesSize; + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, runningAppClonesSize); + if (runningAppClonesSize > MAX_CLONE_APP_NUM) { + return false; + } + for (auto i = 0; i < runningAppClonesSize; i++) { + RunningAppClone clone; + clone.appCloneIndex = parcel.ReadInt32(); + clone.uid = parcel.ReadInt32(); + parcel.ReadInt32Vector(&clone.pids); + runningAppClones.emplace_back(clone); + } + return true; +} + +RunningMultiAppInfo *RunningMultiAppInfo::Unmarshalling(Parcel &parcel) +{ + RunningMultiAppInfo *info = new (std::nothrow) RunningMultiAppInfo(); + if (info && !info->ReadFromParcel(parcel)) { + TAG_LOGW(AAFwkTag::APPMGR, "read from parcel failed"); + delete info; + info = nullptr; + } + return info; +} + +bool RunningMultiAppInfo::Marshalling(Parcel &parcel) const +{ + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(bundleName)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, mode); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, runningAppClones.size()); + if (runningAppClones.size() > MAX_CLONE_APP_NUM) { + return false; + } + for (auto &clone : runningAppClones) { + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, clone.appCloneIndex); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, clone.uid); + if (!parcel.WriteInt32Vector(clone.pids)) { + TAG_LOGE(AAFwkTag::APPMGR, "write runningAppClones failed."); + return false; + } + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_api/app_manager/src/appmgr/start_specified_ability_response_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/start_specified_ability_response_proxy.cpp index 595ae4a485..c54bc1faee 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/start_specified_ability_response_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/start_specified_ability_response_proxy.cpp @@ -34,7 +34,7 @@ bool StartSpecifiedAbilityResponseProxy::WriteInterfaceToken(MessageParcel &data } void StartSpecifiedAbilityResponseProxy::OnAcceptWantResponse( - const AAFwk::Want &want, const std::string &flag) + const AAFwk::Want &want, const std::string &flag, int32_t requestId) { TAG_LOGD(AAFwkTag::APPMGR, "On accept want by proxy."); MessageParcel data; @@ -43,7 +43,8 @@ void StartSpecifiedAbilityResponseProxy::OnAcceptWantResponse( if (!WriteInterfaceToken(data)) { return; } - if (!data.WriteParcelable(&want) || !data.WriteString(flag)) { + if (!data.WriteParcelable(&want) || !data.WriteString(flag) || + !data.WriteInt32(requestId)) { TAG_LOGE(AAFwkTag::APPMGR, "Write data failed."); return; } @@ -55,7 +56,7 @@ void StartSpecifiedAbilityResponseProxy::OnAcceptWantResponse( } } -void StartSpecifiedAbilityResponseProxy::OnTimeoutResponse(const AAFwk::Want &want) +void StartSpecifiedAbilityResponseProxy::OnTimeoutResponse(const AAFwk::Want &want, int32_t requestId) { TAG_LOGD(AAFwkTag::APPMGR, "On timeout response by proxy."); MessageParcel data; @@ -64,7 +65,7 @@ void StartSpecifiedAbilityResponseProxy::OnTimeoutResponse(const AAFwk::Want &wa if (!WriteInterfaceToken(data)) { return; } - if (!data.WriteParcelable(&want)) { + if (!data.WriteParcelable(&want) || !data.WriteInt32(requestId)) { TAG_LOGE(AAFwkTag::APPMGR, "Write data failed."); return; } @@ -88,7 +89,8 @@ int32_t StartSpecifiedAbilityResponseProxy::SendTransactCmd(uint32_t code, Messa return remote->SendRequest(code, data, reply, option); } -void StartSpecifiedAbilityResponseProxy::OnNewProcessRequestResponse(const AAFwk::Want &want, const std::string &flag) +void StartSpecifiedAbilityResponseProxy::OnNewProcessRequestResponse(const AAFwk::Want &want, const std::string &flag, + int32_t requestId) { TAG_LOGD(AAFwkTag::APPMGR, "On satrt specified process response by proxy."); MessageParcel data; @@ -97,7 +99,8 @@ void StartSpecifiedAbilityResponseProxy::OnNewProcessRequestResponse(const AAFwk if (!WriteInterfaceToken(data)) { return; } - if (!data.WriteParcelable(&want) || !data.WriteString(flag)) { + if (!data.WriteParcelable(&want) || !data.WriteString(flag) || + !data.WriteInt32(requestId)) { TAG_LOGE(AAFwkTag::APPMGR, "Write data failed."); return; } @@ -115,7 +118,8 @@ void StartSpecifiedAbilityResponseProxy::OnNewProcessRequestResponse(const AAFwk } } -void StartSpecifiedAbilityResponseProxy::OnNewProcessRequestTimeoutResponse(const AAFwk::Want &want) +void StartSpecifiedAbilityResponseProxy::OnNewProcessRequestTimeoutResponse(const AAFwk::Want &want, + int32_t requestId) { TAG_LOGD(AAFwkTag::APPMGR, "On start specified process timeout response by proxy."); MessageParcel data; @@ -124,7 +128,7 @@ void StartSpecifiedAbilityResponseProxy::OnNewProcessRequestTimeoutResponse(cons if (!WriteInterfaceToken(data)) { return; } - if (!data.WriteParcelable(&want)) { + if (!data.WriteParcelable(&want) || data.WriteInt32(requestId)) { TAG_LOGE(AAFwkTag::APPMGR, "Write data failed."); return; } diff --git a/interfaces/inner_api/app_manager/src/appmgr/start_specified_ability_response_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/start_specified_ability_response_stub.cpp index 4b618c56e9..677aed718f 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/start_specified_ability_response_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/start_specified_ability_response_stub.cpp @@ -64,7 +64,7 @@ int32_t StartSpecifiedAbilityResponseStub::HandleOnAcceptWantResponse(MessagePar } auto flag = Str16ToStr8(data.ReadString16()); - OnAcceptWantResponse(*want, flag); + OnAcceptWantResponse(*want, flag, data.ReadInt32()); delete want; return NO_ERROR; } @@ -77,7 +77,7 @@ int32_t StartSpecifiedAbilityResponseStub::HandleOnTimeoutResponse(MessageParcel return ERR_INVALID_VALUE; } - OnTimeoutResponse(*want); + OnTimeoutResponse(*want, data.ReadInt32()); delete want; return NO_ERROR; } @@ -91,7 +91,7 @@ int32_t StartSpecifiedAbilityResponseStub::HandleOnNewProcessRequestResponse(Mes } auto flag = Str16ToStr8(data.ReadString16()); - OnNewProcessRequestResponse(*want, flag); + OnNewProcessRequestResponse(*want, flag, data.ReadInt32()); delete want; return NO_ERROR; } @@ -105,7 +105,7 @@ int32_t StartSpecifiedAbilityResponseStub::HandleOnNewProcessRequestTimeoutRespo return ERR_INVALID_VALUE; } - OnNewProcessRequestTimeoutResponse(*want); + OnNewProcessRequestTimeoutResponse(*want, data.ReadInt32()); delete want; return NO_ERROR; } diff --git a/interfaces/inner_api/auto_fill_manager/include/auto_fill_error.h b/interfaces/inner_api/auto_fill_manager/include/auto_fill_error.h index 7cc4d9a31b..f1fee33281 100644 --- a/interfaces/inner_api/auto_fill_manager/include/auto_fill_error.h +++ b/interfaces/inner_api/auto_fill_manager/include/auto_fill_error.h @@ -29,7 +29,8 @@ enum { AUTO_FILL_OBJECT_IS_NULL, AUTO_FILL_CREATE_MODULE_UI_EXTENSION_FAILED, AUTO_FILL_REQUEST_TIME_OUT, - AUTO_FILL_TYPE_INVALID + AUTO_FILL_TYPE_INVALID, + AUTO_FILL_PREVIOUS_REQUEST_NOT_FINISHED }; } // namespace AutoFill } // namespace AbilityRuntime diff --git a/interfaces/inner_api/auto_fill_manager/include/auto_fill_extension_callback.h b/interfaces/inner_api/auto_fill_manager/include/auto_fill_extension_callback.h index b6c9f7ea97..3c849a601a 100644 --- a/interfaces/inner_api/auto_fill_manager/include/auto_fill_extension_callback.h +++ b/interfaces/inner_api/auto_fill_manager/include/auto_fill_extension_callback.h @@ -47,6 +47,7 @@ public: void SetSessionId(int32_t sessionId); void SetUIContent(Ace::UIContent *uiContent); + Ace::UIContent *GetUIContent(); void SetEventId(uint32_t eventId); void SetWindowType(const AutoFill::AutoFillWindowType &autoFillWindowType); void SetExtensionType(bool isSmartAutoFill); diff --git a/interfaces/inner_api/auto_fill_manager/include/auto_fill_manager.h b/interfaces/inner_api/auto_fill_manager/include/auto_fill_manager.h index 7547a53759..134bf2089d 100644 --- a/interfaces/inner_api/auto_fill_manager/include/auto_fill_manager.h +++ b/interfaces/inner_api/auto_fill_manager/include/auto_fill_manager.h @@ -106,6 +106,7 @@ private: void SetTimeOutEvent(uint32_t eventId); AutoFill::AutoFillWindowType ConvertAutoFillWindowType(const AutoFill::AutoFillRequest &request, bool &isSmartAutoFill); + bool IsPreviousRequestFinished(Ace::UIContent *uiContent); std::mutex extensionCallbacksMutex_; std::mutex modalProxyMapMutex_; diff --git a/interfaces/inner_api/auto_fill_manager/src/auto_fill_extension_callback.cpp b/interfaces/inner_api/auto_fill_manager/src/auto_fill_extension_callback.cpp index abe2d0609e..eedcc1a0db 100644 --- a/interfaces/inner_api/auto_fill_manager/src/auto_fill_extension_callback.cpp +++ b/interfaces/inner_api/auto_fill_manager/src/auto_fill_extension_callback.cpp @@ -198,6 +198,11 @@ void AutoFillExtensionCallback::SetUIContent(Ace::UIContent *uiContent) uiContent_ = uiContent; } +Ace::UIContent *AutoFillExtensionCallback::GetUIContent() +{ + return uiContent_; +} + void AutoFillExtensionCallback::SetEventId(uint32_t eventId) { eventId_ = eventId; @@ -276,12 +281,12 @@ void AutoFillExtensionCallback::CloseModalUIExtension() return; } - AutoFillManager::GetInstance().RemoveAutoFillExtensionProxy(uiContent_); if (autoFillWindowType_ == AutoFill::AutoFillWindowType::POPUP_WINDOW) { uiContent_->DestroyCustomPopupUIExtension(sessionId_); } else if (autoFillWindowType_ == AutoFill::AutoFillWindowType::MODAL_WINDOW) { uiContent_->CloseModalUIExtension(sessionId_); } + AutoFillManager::GetInstance().RemoveAutoFillExtensionProxy(uiContent_); uiContent_ = nullptr; } } // namespace AbilityRuntime diff --git a/interfaces/inner_api/auto_fill_manager/src/auto_fill_manager.cpp b/interfaces/inner_api/auto_fill_manager/src/auto_fill_manager.cpp index e3be0d5374..0d9f9100f7 100644 --- a/interfaces/inner_api/auto_fill_manager/src/auto_fill_manager.cpp +++ b/interfaces/inner_api/auto_fill_manager/src/auto_fill_manager.cpp @@ -96,6 +96,10 @@ int32_t AutoFillManager::HandleRequestExecuteInner( TAG_LOGE(AAFwkTag::AUTOFILLMGR, "UIContent or fillCallback&saveCallback is nullptr."); return AutoFill::AUTO_FILL_OBJECT_IS_NULL; } + if (!IsPreviousRequestFinished(uiContent)) { + TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Previous request is not finished."); + return AutoFill::AUTO_FILL_PREVIOUS_REQUEST_NOT_FINISHED; + } { std::lock_guard lock(extensionCallbacksMutex_); SetTimeOutEvent(++eventId_); @@ -371,5 +375,20 @@ void AutoFillManager::HandleTimeOut(uint32_t eventId) extensionCallback->HandleTimeOut(); extensionCallbacks_.erase(ret); } + +bool AutoFillManager::IsPreviousRequestFinished(Ace::UIContent *uiContent) +{ + std::lock_guard lock(extensionCallbacksMutex_); + for (auto& item: extensionCallbacks_) { + auto extensionCallback = item.second.lock(); + if (extensionCallback == nullptr) { + continue; + } + if (extensionCallback->GetUIContent() == uiContent) { + return false; + } + } + return true; +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/interfaces/inner_api/child_process_manager/BUILD.gn b/interfaces/inner_api/child_process_manager/BUILD.gn index e9bd88528e..bbd9caaebe 100644 --- a/interfaces/inner_api/child_process_manager/BUILD.gn +++ b/interfaces/inner_api/child_process_manager/BUILD.gn @@ -32,6 +32,7 @@ ohos_shared_library("child_process_manager") { "${ability_runtime_native_path}/ability/native/child_process_manager/child_process_manager.cpp", "${ability_runtime_native_path}/ability/native/child_process_manager/child_process_manager_error_utils.cpp", "${ability_runtime_native_path}/ability/native/child_process_manager/js_child_process.cpp", + "${ability_runtime_native_path}/ability/native/child_process_manager/native_child_ipc_process.cpp", ] deps = [ @@ -50,6 +51,7 @@ ohos_shared_library("child_process_manager") { "eventhandler:libeventhandler", "hilog:libhilog", "init:libbegetutil", + "ipc:ipc_capi", "ipc:ipc_core", "napi:ace_napi", "samgr:samgr_proxy", diff --git a/interfaces/inner_api/child_process_manager/include/child_process_manager.h b/interfaces/inner_api/child_process_manager/include/child_process_manager.h index 3bf2137fe4..f9fbf3c654 100644 --- a/interfaces/inner_api/child_process_manager/include/child_process_manager.h +++ b/interfaces/inner_api/child_process_manager/include/child_process_manager.h @@ -25,6 +25,7 @@ #include "child_process_manager_error_utils.h" #include "hap_module_info.h" #include "runtime.h" +#include "iremote_object.h" namespace OHOS { namespace AbilityRuntime { @@ -41,12 +42,15 @@ public: bool IsChildProcess(); ChildProcessManagerErrorCode StartChildProcessBySelfFork(const std::string &srcEntry, pid_t &pid); ChildProcessManagerErrorCode StartChildProcessByAppSpawnFork(const std::string &srcEntry, pid_t &pid); + ChildProcessManagerErrorCode StartNativeChildProcessByAppSpawnFork( + const std::string &libName, const sptr &callbackStub); bool GetBundleInfo(AppExecFwk::BundleInfo &bundleInfo); bool GetHapModuleInfo(const AppExecFwk::BundleInfo &bundleInfo, AppExecFwk::HapModuleInfo &hapModuleInfo); std::unique_ptr CreateRuntime(const AppExecFwk::BundleInfo &bundleInfo, const AppExecFwk::HapModuleInfo &hapModuleInfo, const bool fromAppSpawn, const bool jitEnabled); bool LoadJsFile(const std::string &srcEntry, const AppExecFwk::HapModuleInfo &hapModuleInfo, std::unique_ptr &runtime); + bool LoadNativeLib(const std::string &libPath, const sptr &mainProcessCb); void SetForkProcessJITEnabled(bool jitEnabled); void SetForkProcessDebugOption(const std::string bundleName, const bool isStartWithDebug, const bool isDebugApp, const bool isStartWithNative); @@ -55,6 +59,7 @@ private: ChildProcessManager(); ChildProcessManagerErrorCode PreCheck(); + ChildProcessManagerErrorCode PreCheckNativeProcess(); void RegisterSignal(); void HandleChildProcessBySelfFork(const std::string &srcEntry, const AppExecFwk::BundleInfo &bundleInfo); bool hasChildProcessRecord(); diff --git a/interfaces/inner_api/child_process_manager/include/child_process_manager_error_utils.h b/interfaces/inner_api/child_process_manager/include/child_process_manager_error_utils.h index 3bd4893d87..93e28ccfdf 100644 --- a/interfaces/inner_api/child_process_manager/include/child_process_manager_error_utils.h +++ b/interfaces/inner_api/child_process_manager/include/child_process_manager_error_utils.h @@ -31,6 +31,10 @@ enum class ChildProcessManagerErrorCode { ERR_GET_BUNDLE_INFO_FAILED = 5, ERR_GET_APP_MGR_FAILED = 6, ERR_GET_APP_MGR_START_PROCESS_FAILED = 7, + ERR_UNSUPPORT_NATIVE_CHILD_PROCESS = 8, + ERR_MAX_NATIVE_CHILD_PROCESSES = 9, + ERR_LIB_LOADING_FAILED = 10, + ERR_CONNECTION_FAILED = 11, }; const std::map INTERNAL_ERR_CODE_MAP = { diff --git a/interfaces/inner_api/child_process_manager/include/child_process_start_info.h b/interfaces/inner_api/child_process_manager/include/child_process_start_info.h index 75cbfabd60..07828eae1b 100644 --- a/interfaces/inner_api/child_process_manager/include/child_process_start_info.h +++ b/interfaces/inner_api/child_process_manager/include/child_process_start_info.h @@ -17,6 +17,7 @@ #define OHOS_ABILITY_RUNTIME_CHILD_PROCESS_START_INFO_H #include +#include "iremote_object.h" namespace OHOS { namespace AbilityRuntime { @@ -26,6 +27,7 @@ struct ChildProcessStartInfo { std::string srcEntry; std::string hapPath; bool isEsModule = true; + sptr ipcObj; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/interfaces/inner_api/child_process_manager/include/native_child_ipc_process.h b/interfaces/inner_api/child_process_manager/include/native_child_ipc_process.h new file mode 100644 index 0000000000..5a007069e8 --- /dev/null +++ b/interfaces/inner_api/child_process_manager/include/native_child_ipc_process.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_NATIVE_CHILD_IPC_PROCESS_H +#define OHOS_ABILITY_RUNTIME_NATIVE_CHILD_IPC_PROCESS_H + +#include +#include "child_process.h" +#include "native_child_notify_interface.h" +#include "ipc_inner_object.h" + +namespace OHOS { +namespace AbilityRuntime { + +class NativeChildIpcProcess : public ChildProcess { +public: + NativeChildIpcProcess() = default; + ~NativeChildIpcProcess(); + + static std::shared_ptr Create(); + + bool Init(const std::shared_ptr &info) override; + void OnStart() override; + +private: + bool LoadNativeLib(const std::shared_ptr &info); + void UnloadNativeLib(); + + typedef OHIPCRemoteStub* (*NativeChildProcess_OnConnect)(); + typedef void (*NativeChildProcess_MainProc)(); + + sptr mainProcessCb_; + void *nativeLibHandle_ = nullptr; + NativeChildProcess_OnConnect funcNativeLibOnConnect_ = nullptr; + NativeChildProcess_MainProc funcNativeLibMainProc_ = nullptr; +}; + +} // namespace AbilityRuntime +} // namespace OHOS + +#endif // OHOS_ABILITY_RUNTIME_NATIVE_CHILD_IPC_PROCESS_H \ No newline at end of file diff --git a/interfaces/inner_api/connectionobs_manager/BUILD.gn b/interfaces/inner_api/connectionobs_manager/BUILD.gn index c6ade90376..1933838380 100644 --- a/interfaces/inner_api/connectionobs_manager/BUILD.gn +++ b/interfaces/inner_api/connectionobs_manager/BUILD.gn @@ -23,8 +23,6 @@ config("connection_obs_manager_public_config") { include_dirs = [ "include", "${ability_runtime_services_path}/common/include", - "${safwk_path}/native/include", - "${bundlefwk_inner_api_path}/appexecfwk_base/include", ] cflags = [] if (target_cpu == "arm") { @@ -56,7 +54,7 @@ ohos_shared_library("connection_obs_manager") { "ipc:ipc_core", "samgr:samgr_proxy", ] - + public_external_deps = [ "bundle_framework:appexecfwk_base" ] innerapi_tags = [ "platformsdk" ] subsystem_name = "ability" part_name = "ability_runtime" diff --git a/interfaces/inner_api/dataobs_manager/BUILD.gn b/interfaces/inner_api/dataobs_manager/BUILD.gn index 3527f7d787..cabea243fe 100644 --- a/interfaces/inner_api/dataobs_manager/BUILD.gn +++ b/interfaces/inner_api/dataobs_manager/BUILD.gn @@ -18,10 +18,8 @@ config("dataobs_manager_public_config") { visibility = [ ":*" ] include_dirs = [ "include/", - "${safwk_path}/native/include", "${ability_runtime_path}/interfaces/kits/native/ability/native", "${ability_runtime_services_path}/dataobsmgr/include", - "${ability_base_kits_path}/uri/include", ] cflags = [] if (target_cpu == "arm") { @@ -46,13 +44,12 @@ ohos_shared_library("dataobs_manager") { deps = [] external_deps = [ - "ability_base:zuri", "c_utils:utils", "hilog:libhilog", "ipc:ipc_core", "samgr:samgr_proxy", ] - + public_external_deps = [ "ability_base:zuri" ] innerapi_tags = [ "platformsdk", "sasdk", diff --git a/interfaces/inner_api/error_utils/include/ability_runtime_error_util.h b/interfaces/inner_api/error_utils/include/ability_runtime_error_util.h index c3de0b5c47..1c621573e5 100644 --- a/interfaces/inner_api/error_utils/include/ability_runtime_error_util.h +++ b/interfaces/inner_api/error_utils/include/ability_runtime_error_util.h @@ -55,11 +55,11 @@ enum { ERR_ABILITY_RUNTIME_CHILD_PROCESS_NUMBER_EXCEEDS_UPPER_BOUND = 16000062, ERR_ABILITY_RUNTIME_RESTART_APP_INCORRECT_ABILITY = 16000063, ERR_ABILITY_RUNTIME_RESTART_APP_FREQUENT = 16000064, - ERR_ABILITY_RUNTIME_SET_SUPPORTED_PROCESS_CACHE_AGAIN = 16000068, ERR_ABILITY_RUNTIME_EXTERNAL_EXECUTE_SHELL_COMMAND_FAILED = 16000101, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_WANTAGENT = 16000151, ERR_ABILITY_RUNTIME_EXTERNAL_WANTAGENT_NOT_FOUND = 16000152, ERR_ABILITY_RUNTIME_EXTERNAL_WANTAGENT_CANCELED = 16000153, + ERR_ABILITY_RUNTIME_SET_SUPPORTED_PROCESS_CACHE_AGAIN = 16000200, ERR_ABILITY_RUNTIME_EXTERNAL_NO_SUCH_URI_ABILITY = 16100001, ERR_ABILITY_RUNTIME_EXTERNAL_FA_NOT_SUPPORT_OPERATION = 16100002, diff --git a/interfaces/inner_api/napi_base_context/BUILD.gn b/interfaces/inner_api/napi_base_context/BUILD.gn index a3bc3d2821..def1216d0c 100644 --- a/interfaces/inner_api/napi_base_context/BUILD.gn +++ b/interfaces/inner_api/napi_base_context/BUILD.gn @@ -27,6 +27,12 @@ ohos_shared_library("napi_base_context") { external_deps = [ "napi:ace_napi" ] + public_external_deps = [ + "form_fwk:form_manager", + "window_manager:libdm", + "window_manager:libwm", + ] + innerapi_tags = [ "platformsdk" ] subsystem_name = "ability" part_name = "ability_runtime" diff --git a/interfaces/inner_api/runtime/BUILD.gn b/interfaces/inner_api/runtime/BUILD.gn index a9d85e7fea..b0d5637eb9 100644 --- a/interfaces/inner_api/runtime/BUILD.gn +++ b/interfaces/inner_api/runtime/BUILD.gn @@ -53,6 +53,7 @@ ohos_shared_library("runtime") { "${ability_runtime_path}/services/abilitymgr/include", "${bundlefwk_path}/interfaces/kits/js/common", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_utils_path}/global/constant", ] sources = [ @@ -87,8 +88,6 @@ ohos_shared_library("runtime") { "${ability_runtime_native_path}/ability/native:ability_business_error", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_path}/js_environment/frameworks/js_environment:js_environment", - "${third_party_path}/jsoncpp:jsoncpp", - "${third_party_path}/zlib:shared_libz", ] external_deps = [ @@ -112,11 +111,22 @@ ohos_shared_library("runtime") { "hilog:libhilog", "hitrace:hitrace_meter", "ipc:ipc_core", + "jsoncpp:jsoncpp", "napi:ace_napi", "resource_management:global_resmgr", "samgr:samgr_proxy", + "zlib:shared_libz", ] + if (cj_frontend) { + sources += [ "${ability_runtime_native_path}/runtime/cj_runtime.cpp" ] + + include_dirs += + [ "${ability_runtime_path}/cj_environment/interfaces/inner_api" ] + + deps += [ "${ability_runtime_path}/cj_environment/frameworks/cj_environment:cj_environment" ] + } + defines = [] if (is_standard_system) { defines += [ "ENABLE_HITRACE" ] diff --git a/interfaces/inner_api/runtime/include/cj_runtime.h b/interfaces/inner_api/runtime/include/cj_runtime.h new file mode 100644 index 0000000000..b2ecbf80df --- /dev/null +++ b/interfaces/inner_api/runtime/include/cj_runtime.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_CJ_RUNTIME_H +#define OHOS_ABILITY_RUNTIME_CJ_RUNTIME_H + +#include +#include +#include + +#include "runtime.h" + +using AppLibPathMap = std::map>; +using AppLibPathVec = std::vector; + +namespace OHOS { +struct CJUncaughtExceptionInfo; +namespace AbilityRuntime { + +class CJRuntime : public Runtime { +public: + static std::unique_ptr Create(const Options& options); + static void SetAppLibPath(const AppLibPathMap& appLibPaths); + ~CJRuntime() override = default; + + Language GetLanguage() const override + { + return Language::CJ; + } + + void StartDebugMode(const DebugOption debugOption) override; + bool BuildJsStackInfoList(uint32_t tid, std::vector& jsFrames) override { return false; }; + void DumpHeapSnapshot(bool isPrivate) override {} + void NotifyApplicationState(bool isBackground) override {} + bool SuspendVM(uint32_t tid) override { return false; } + void ResumeVM(uint32_t tid) override {} + void PreloadSystemModule(const std::string& moduleName) override {} + void FinishPreload() override {} + bool LoadRepairPatch(const std::string& patchFile, const std::string& baseFile) override { return false; } + bool NotifyHotReloadPage() override { return false; } + bool UnLoadRepairPatch(const std::string& patchFile) override { return false; } + void RegisterQuickFixQueryFunc(const std::map& moduleAndPath) override {}; + void StartProfiler(const DebugOption debugOption) override {}; + void DoCleanWorkAfterStageCleaned() override {}; + void SetModuleLoadChecker(const std::shared_ptr& moduleCheckerDelegate) const override {} + void SetDeviceDisconnectCallback(const std::function &cb) override {}; + bool IsAppLibLoaded() const { return appLibLoaded_; } + void UnLoadCJAppLibrary(); + void DestroyHeapProfiler() override {}; + void ForceFullGC() override {}; + void ForceFullGC(uint32_t tid) override {}; + void DumpHeapSnapshot(uint32_t tid, bool isFullGC, std::vector fdVec, + std::vector tidVec) override {}; + void DumpCpuProfile(bool isPrivate) override {}; + void AllowCrossThreadExecution() override {}; + void GetHeapPrepare() override {}; + void RegisterUncaughtExceptionHandler(const CJUncaughtExceptionInfo& uncaughtExceptionInfo); +private: + bool StartDebugger(); + bool LoadCJAppLibrary(const AppLibPathVec& appLibPaths); + bool Initialize(const Options& options); + std::string cjAppLibPath_; + bool appLibLoaded_ = false; + bool debugModel_ = false; + std::string bundleName_; + int instanceId_ {0}; + static AppLibPathVec appLibPaths_; +}; +} // namespace AbilityRuntime +} // namespace OHOS + +#endif // OHOS_ABILITY_RUNTIME_CJ_RUNTIME_H diff --git a/interfaces/inner_api/runtime/include/js_error_utils.h b/interfaces/inner_api/runtime/include/js_error_utils.h index 9388851313..731f18a59b 100755 --- a/interfaces/inner_api/runtime/include/js_error_utils.h +++ b/interfaces/inner_api/runtime/include/js_error_utils.h @@ -24,7 +24,7 @@ namespace AbilityRuntime { void ThrowError(napi_env env, int32_t errCode, const std::string& errorMsg = ""); void ThrowError(napi_env env, const AbilityErrorCode& err); -void ThrowInvaildCallerError(napi_env env); +void ThrowInvalidCallerError(napi_env env); void ThrowTooFewParametersError(napi_env env); void ThrowInvalidNumParametersError(napi_env env); void ThrowNoPermissionError(napi_env env, const std::string& permission); diff --git a/interfaces/inner_api/runtime/include/js_runtime.h b/interfaces/inner_api/runtime/include/js_runtime.h index 6a34c6f6c0..268607ff1c 100644 --- a/interfaces/inner_api/runtime/include/js_runtime.h +++ b/interfaces/inner_api/runtime/include/js_runtime.h @@ -85,7 +85,8 @@ public: void DestroyHeapProfiler() override; void ForceFullGC() override; void ForceFullGC(uint32_t tid) override; - void DumpHeapSnapshot(uint32_t tid, bool isFullGC) override; + void DumpHeapSnapshot(uint32_t tid, bool isFullGC, std::vector fdVec, + std::vector tidVec) override; void AllowCrossThreadExecution() override; void GetHeapPrepare() override; bool BuildJsStackInfoList(uint32_t tid, std::vector& jsFrames) override; diff --git a/interfaces/inner_api/runtime/include/js_runtime_utils.h b/interfaces/inner_api/runtime/include/js_runtime_utils.h index be8fb80f30..e586f1bff0 100644 --- a/interfaces/inner_api/runtime/include/js_runtime_utils.h +++ b/interfaces/inner_api/runtime/include/js_runtime_utils.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-2024 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 @@ -295,13 +295,13 @@ std::unique_ptr CreateAsyncTaskWithLastParam(napi_env env, napi_v NapiAsyncTask::ExecuteCallback&& execute, NapiAsyncTask::CompleteCallback&& complete, napi_value* result); std::unique_ptr CreateAsyncTaskWithLastParam(napi_env env, napi_value lastParam, - NapiAsyncTask::ExecuteCallback&& execute, nullptr_t, napi_value* result); + NapiAsyncTask::ExecuteCallback&& execute, std::nullptr_t, napi_value* result); std::unique_ptr CreateAsyncTaskWithLastParam(napi_env env, napi_value lastParam, - nullptr_t, NapiAsyncTask::CompleteCallback&& complete, napi_value* result); + std::nullptr_t, NapiAsyncTask::CompleteCallback&& complete, napi_value* result); std::unique_ptr CreateAsyncTaskWithLastParam(napi_env env, napi_value lastParam, - nullptr_t, nullptr_t, napi_value* result); + std::nullptr_t, std::nullptr_t, napi_value* result); } // namespace AbilityRuntime } // namespace OHOS #endif // OHOS_ABILITY_RUNTIME_JS_RUNTIME_UTILS_H diff --git a/interfaces/inner_api/runtime/include/native_runtime_impl.h b/interfaces/inner_api/runtime/include/native_runtime_impl.h index c1ecb6703f..3b64a145f8 100644 --- a/interfaces/inner_api/runtime/include/native_runtime_impl.h +++ b/interfaces/inner_api/runtime/include/native_runtime_impl.h @@ -45,8 +45,6 @@ private: std::shared_ptr GetJsEnv(napi_env env); void LoadAotFile(const Options& options, const std::shared_ptr& jsEnv); void InitConsoleModule(const std::shared_ptr& jsEnv); - void InitSourceMap(const std::shared_ptr operatorObj, - const std::shared_ptr& jsEnv); void InitTimerModule(const std::shared_ptr& jsEnv); void SetModuleLoadChecker(const std::shared_ptr& moduleCheckerDelegate, const std::shared_ptr& jsEnv); diff --git a/interfaces/inner_api/runtime/include/runtime.h b/interfaces/inner_api/runtime/include/runtime.h index 9282b92cfd..b894d4c835 100644 --- a/interfaces/inner_api/runtime/include/runtime.h +++ b/interfaces/inner_api/runtime/include/runtime.h @@ -38,6 +38,7 @@ class Runtime { public: enum class Language { JS = 0, + CJ }; struct Options { @@ -96,7 +97,8 @@ public: virtual void DestroyHeapProfiler() = 0; virtual void ForceFullGC() = 0; virtual void ForceFullGC(uint32_t tid) = 0; - virtual void DumpHeapSnapshot(uint32_t tid, bool isFullGC) = 0; + virtual void DumpHeapSnapshot(uint32_t tid, bool isFullGC, std::vector fdVec, + std::vector tidVec) = 0; virtual void AllowCrossThreadExecution() = 0; virtual void GetHeapPrepare() = 0; virtual void NotifyApplicationState(bool isBackground) = 0; diff --git a/interfaces/inner_api/uri_permission/include/uri_permission_manager_client.h b/interfaces/inner_api/uri_permission/include/uri_permission_manager_client.h index 2628922647..9cf107fa4a 100644 --- a/interfaces/inner_api/uri_permission/include/uri_permission_manager_client.h +++ b/interfaces/inner_api/uri_permission/include/uri_permission_manager_client.h @@ -37,7 +37,7 @@ public: * @param targetBundleName The user of uri. */ int GrantUriPermission(const Uri &uri, unsigned int flag, const std::string targetBundleName, int32_t appIndex = 0, - uint32_t initiatorTokenId = 0); + uint32_t initiatorTokenId = 0, int32_t abilityId = -1); /** * @brief Authorize the uri permission of to targetBundleName. @@ -46,8 +46,8 @@ public: * @param flag Want::FLAG_AUTH_READ_URI_PERMISSION or Want::FLAG_AUTH_WRITE_URI_PERMISSION. * @param targetBundleName The user of uri. */ - int GrantUriPermission(const std::vector &uriVec, unsigned int flag, - const std::string targetBundleName, int32_t appIndex = 0, uint32_t initiatorTokenId = 0); + int GrantUriPermission(const std::vector &uriVec, unsigned int flag, const std::string targetBundleName, + int32_t appIndex = 0, uint32_t initiatorTokenId = 0, int32_t abilityId = -1); /** * @brief Authorize the uri permission to targetBundleName. @@ -61,32 +61,20 @@ public: int32_t GrantUriPermissionPrivileged(const std::vector &uriVec, uint32_t flag, const std::string &targetBundleName, int32_t appIndex = 0); - /** - * @brief Authorize the uri permission to targetBundleName for 2in1, only supports AbilityManagerService calls. - * - * @param uriVec The file urilist. - * @param flag Want::FLAG_AUTH_READ_URI_PERMISSION or Want::FLAG_AUTH_WRITE_URI_PERMISSION. - * @param targetBundleName The user of uri. - * @param appIndex The index of application in sandbox. - * @param isSystemAppCall The flag of system application called. - * @return Returns true if the authorization is successful, otherwise returns false. - */ - int GrantUriPermissionFor2In1(const std::vector &uriVec, unsigned int flag, - const std::string &targetBundleName, int32_t appIndex = 0, bool isSystemAppCall = false); - /** * @brief Clear user's uri authorization record with auto remove flag. * * @param tokenId A tokenId of an application. + * @param abilityId The abilityId of an ability record. */ - void RevokeUriPermission(const Security::AccessToken::AccessTokenID tokenId); + void RevokeUriPermission(const uint32_t tokenId, int32_t abilityId = -1); /** * @brief Clear user's all uri authorization record with auto remove flag. * * @param tokenId A tokenId of an application. */ - int RevokeAllUriPermissions(const Security::AccessToken::AccessTokenID tokenId); + int RevokeAllUriPermissions(const uint32_t tokenId); /** * @brief Clear user's uri authorization record. @@ -114,8 +102,6 @@ public: */ std::vector CheckUriAuthorization(const std::vector &uriVec, uint32_t flag, uint32_t tokenId); - bool IsAuthorizationUriAllowed(uint32_t fromTokenId); - void OnLoadSystemAbilitySuccess(const sptr &remoteObject); void OnLoadSystemAbilityFail(); private: diff --git a/interfaces/inner_api/uri_permission/include/uri_permission_manager_interface.h b/interfaces/inner_api/uri_permission/include/uri_permission_manager_interface.h index e7bf0af07e..160d98abc9 100644 --- a/interfaces/inner_api/uri_permission/include/uri_permission_manager_interface.h +++ b/interfaces/inner_api/uri_permission/include/uri_permission_manager_interface.h @@ -34,8 +34,8 @@ public: * @param targetBundleName The user of uri. * @return Returns true if the authorization is successful, otherwise returns false. */ - virtual int GrantUriPermission(const Uri &uri, unsigned int flag, - const std::string targetBundleName, int32_t appIndex = 0, uint32_t initiatorTokenId = 0) = 0; + virtual int GrantUriPermission(const Uri &uri, unsigned int flag, const std::string targetBundleName, + int32_t appIndex = 0, uint32_t initiatorTokenId = 0, int32_t abilityId = -1) = 0; /** * @brief Authorize the uri permission to targetBundleName. @@ -46,7 +46,8 @@ public: * @return Returns true if the authorization is successful, otherwise returns false. */ virtual int GrantUriPermission(const std::vector &uriVec, unsigned int flag, - const std::string targetBundleName, int32_t appIndex = 0, uint32_t initiatorTokenId = 0) = 0; + const std::string targetBundleName, int32_t appIndex = 0, uint32_t initiatorTokenId = 0, + int32_t abilityId = -1) = 0; /** * @brief Authorize the uri permission to targetBundleName. @@ -60,26 +61,14 @@ public: virtual int32_t GrantUriPermissionPrivileged(const std::vector &uriVec, uint32_t flag, const std::string &targetBundleName, int32_t appIndex = 0) = 0; - /** - * @brief Authorize the uri permission to targetBundleName for 2in1, only supports foundation process calls. - * - * @param uriVec The file urilist. - * @param flag Want::FLAG_AUTH_READ_URI_PERMISSION or Want::FLAG_AUTH_WRITE_URI_PERMISSION. - * @param targetBundleName The user of uri. - * @param appIndex The index of application in sandbox. - * @param isSystemAppCall The flag of system application called. - * @return Returns true if the authorization is successful, otherwise returns false. - */ - virtual int GrantUriPermissionFor2In1(const std::vector &uriVec, unsigned int flag, - const std::string &targetBundleName, int32_t appIndex = 0, bool isSystemAppCall = false) = 0; - /** * @brief Clear user's uri authorization record with autoremove flag. * * @param tokenId A tokenId of an application. + * @param abilityId The abilityId of an ability record. * @return Returns true if the remove is successful, otherwise returns false. */ - virtual void RevokeUriPermission(const Security::AccessToken::AccessTokenID tokenId) = 0; + virtual void RevokeUriPermission(const uint32_t tokenId, int32_t abilityId = -1) = 0; /** * @brief Clear user's all uri authorization record with autoremove flag. @@ -87,7 +76,7 @@ public: * @param tokenId A tokenId of an application. * @return Returns true if the remove is successful, otherwise returns false. */ - virtual int RevokeAllUriPermissions(const Security::AccessToken::AccessTokenID tokenId) = 0; + virtual int RevokeAllUriPermissions(const uint32_t tokenId) = 0; /** * @brief Clear user's uri authorization record. @@ -117,8 +106,6 @@ public: virtual std::vector CheckUriAuthorization(const std::vector &uriVec, uint32_t flag, uint32_t tokenId) = 0; - virtual bool IsAuthorizationUriAllowed(uint32_t fromTokenId) = 0; - enum UriPermMgrCmd { // ipc id for GrantUriPermission ON_GRANT_URI_PERMISSION = 0, @@ -137,12 +124,6 @@ public: // ipc id for BatchGrantUriPermission ON_BATCH_GRANT_URI_PERMISSION, - // ipc id for BatchGrantUriPermissionFor2In1 - ON_BATCH_GRANT_URI_PERMISSION_FOR_2_IN_1, - - //ipc id for IsAuthorizationUriAllowed - ON_IS_Authorization_URI_ALLOWED, - //ipc id for GrantUriPermissionPrivileged ON_GRANT_URI_PERMISSION_PRIVILEGED, diff --git a/interfaces/inner_api/uri_permission/include/uri_permission_manager_proxy.h b/interfaces/inner_api/uri_permission/include/uri_permission_manager_proxy.h index d9726d74d7..30d38da80e 100644 --- a/interfaces/inner_api/uri_permission/include/uri_permission_manager_proxy.h +++ b/interfaces/inner_api/uri_permission/include/uri_permission_manager_proxy.h @@ -28,23 +28,21 @@ public: virtual ~UriPermissionManagerProxy() = default; virtual int GrantUriPermission(const Uri &uri, unsigned int flag, - const std::string targetBundleName, int32_t appIndex = 0, uint32_t initiatorTokenId = 0) override; + const std::string targetBundleName, int32_t appIndex = 0, uint32_t initiatorTokenId = 0, + int32_t abilityId = -1) override; virtual int GrantUriPermission(const std::vector &uriVec, unsigned int flag, - const std::string targetBundleName, int32_t appIndex = 0, uint32_t initiatorTokenId = 0) override; + const std::string targetBundleName, int32_t appIndex = 0, uint32_t initiatorTokenId = 0, + int32_t abilityId = -1) override; virtual int32_t GrantUriPermissionPrivileged(const std::vector &uriVec, uint32_t flag, const std::string &targetBundleName, int32_t appIndex = 0) override; - - virtual int GrantUriPermissionFor2In1(const std::vector &uriVec, unsigned int flag, - const std::string &targetBundleName, int32_t appIndex = 0, bool isSystemAppCall = false) override; - virtual void RevokeUriPermission(const Security::AccessToken::AccessTokenID tokenId) override; - virtual int RevokeAllUriPermissions(const Security::AccessToken::AccessTokenID tokenId) override; + virtual void RevokeUriPermission(const uint32_t tokenId, int32_t abilityId) override; + virtual int RevokeAllUriPermissions(const uint32_t tokenId) override; virtual int RevokeUriPermissionManually(const Uri &uri, const std::string bundleName) override; virtual bool VerifyUriPermission(const Uri &uri, uint32_t flag, uint32_t tokenId) override; virtual std::vector CheckUriAuthorization(const std::vector &uriVec, uint32_t flag, uint32_t tokenId) override; - virtual bool IsAuthorizationUriAllowed(uint32_t fromTokenId) override; private: static inline BrokerDelegator delegator_; diff --git a/interfaces/inner_api/uri_permission/include/uri_permission_manager_stub.h b/interfaces/inner_api/uri_permission/include/uri_permission_manager_stub.h index a5f6099407..7be88d3af1 100644 --- a/interfaces/inner_api/uri_permission/include/uri_permission_manager_stub.h +++ b/interfaces/inner_api/uri_permission/include/uri_permission_manager_stub.h @@ -40,11 +40,9 @@ private: int HandleGrantUriPermission(MessageParcel &data, MessageParcel &reply); int32_t HandleGrantUriPermissionPrivileged(MessageParcel &data, MessageParcel &reply); int32_t HandleCheckUriAuthorization(MessageParcel &data, MessageParcel &reply); - int HandleBatchGrantUriPermissionFor2In1(MessageParcel &data, MessageParcel &reply); int HandleBatchGrantUriPermission(MessageParcel &data, MessageParcel &reply); int HandleRevokeUriPermissionManually(MessageParcel &data, MessageParcel &reply); int HandleVerifyUriPermission(MessageParcel &data, MessageParcel &reply); - int HandleIsAuthorizationUriAllowed(MessageParcel &data, MessageParcel &reply); }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/uri_permission/src/uri_permission_manager_client.cpp b/interfaces/inner_api/uri_permission/src/uri_permission_manager_client.cpp index 80e2a80ab9..6bca59b5ad 100644 --- a/interfaces/inner_api/uri_permission/src/uri_permission_manager_client.cpp +++ b/interfaces/inner_api/uri_permission/src/uri_permission_manager_client.cpp @@ -36,18 +36,18 @@ UriPermissionManagerClient& UriPermissionManagerClient::GetInstance() } int UriPermissionManagerClient::GrantUriPermission(const Uri &uri, unsigned int flag, - const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId) + const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId, int32_t abilityId) { TAG_LOGD(AAFwkTag::URIPERMMGR, "targetBundleName :%{public}s", targetBundleName.c_str()); auto uriPermMgr = ConnectUriPermService(); if (uriPermMgr) { - return uriPermMgr->GrantUriPermission(uri, flag, targetBundleName, appIndex, initiatorTokenId); + return uriPermMgr->GrantUriPermission(uri, flag, targetBundleName, appIndex, initiatorTokenId, abilityId); } return INNER_ERR; } int UriPermissionManagerClient::GrantUriPermission(const std::vector &uriVec, unsigned int flag, - const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId) + const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId, int32_t abilityId) { TAG_LOGD(AAFwkTag::URIPERMMGR, "targetBundleName: %{public}s, uriVec size: %{public}zu", targetBundleName.c_str(), uriVec.size()); @@ -57,7 +57,7 @@ int UriPermissionManagerClient::GrantUriPermission(const std::vector &uriVe } auto uriPermMgr = ConnectUriPermService(); if (uriPermMgr) { - return uriPermMgr->GrantUriPermission(uriVec, flag, targetBundleName, appIndex, initiatorTokenId); + return uriPermMgr->GrantUriPermission(uriVec, flag, targetBundleName, appIndex, initiatorTokenId, abilityId); } return INNER_ERR; } @@ -78,32 +78,17 @@ int32_t UriPermissionManagerClient::GrantUriPermissionPrivileged(const std::vect return INNER_ERR; } -int UriPermissionManagerClient::GrantUriPermissionFor2In1(const std::vector &uriVec, unsigned int flag, - const std::string &targetBundleName, int32_t appIndex, bool isSystemAppCall) -{ - TAG_LOGD(AAFwkTag::URIPERMMGR, "targetBundleName: %{public}s, uriVec size: %{public}zu", targetBundleName.c_str(), - uriVec.size()); - if (uriVec.empty() || uriVec.size() > MAX_URI_COUNT) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "uriVec is empty or exceed maximum size %{public}d.", MAX_URI_COUNT); - return ERR_URI_LIST_OUT_OF_RANGE; - } - auto uriPermMgr = ConnectUriPermService(); - if (uriPermMgr != nullptr) { - return uriPermMgr->GrantUriPermissionFor2In1(uriVec, flag, targetBundleName, appIndex, isSystemAppCall); - } - return INNER_ERR; -} -void UriPermissionManagerClient::RevokeUriPermission(const Security::AccessToken::AccessTokenID tokenId) +void UriPermissionManagerClient::RevokeUriPermission(const uint32_t tokenId, int32_t abilityId) { TAG_LOGD(AAFwkTag::URIPERMMGR, "UriPermissionManagerClient::RevokeUriPermission is called."); auto uriPermMgr = ConnectUriPermService(); if (uriPermMgr) { - return uriPermMgr->RevokeUriPermission(tokenId); + return uriPermMgr->RevokeUriPermission(tokenId, abilityId); } } -int UriPermissionManagerClient::RevokeAllUriPermissions(const Security::AccessToken::AccessTokenID tokenId) +int UriPermissionManagerClient::RevokeAllUriPermissions(const uint32_t tokenId) { TAG_LOGD(AAFwkTag::URIPERMMGR, "UriPermissionManagerClient::RevokeAllUriPermissions is called."); auto uriPermMgr = ConnectUriPermService(); @@ -149,15 +134,6 @@ std::vector UriPermissionManagerClient::CheckUriAuthorization(const std::v return errorRes; } -bool UriPermissionManagerClient::IsAuthorizationUriAllowed(uint32_t fromTokenId) -{ - auto uriPermMgr = ConnectUriPermService(); - if (uriPermMgr) { - return uriPermMgr->IsAuthorizationUriAllowed(fromTokenId); - } - return false; -} - sptr UriPermissionManagerClient::ConnectUriPermService() { TAG_LOGD(AAFwkTag::URIPERMMGR, "UriPermissionManagerClient::ConnectUriPermService is called."); diff --git a/interfaces/inner_api/uri_permission/src/uri_permission_manager_proxy.cpp b/interfaces/inner_api/uri_permission/src/uri_permission_manager_proxy.cpp index 1954a726c8..1dd6e83ef1 100644 --- a/interfaces/inner_api/uri_permission/src/uri_permission_manager_proxy.cpp +++ b/interfaces/inner_api/uri_permission/src/uri_permission_manager_proxy.cpp @@ -29,7 +29,7 @@ UriPermissionManagerProxy::UriPermissionManagerProxy(const sptr & : IRemoteProxy(impl) {} int UriPermissionManagerProxy::GrantUriPermission(const Uri &uri, unsigned int flag, - const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId) + const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId, int32_t abilityId) { TAG_LOGD(AAFwkTag::URIPERMMGR, "UriPermissionManagerProxy::GrantUriPermission is called."); MessageParcel data; @@ -57,6 +57,10 @@ int UriPermissionManagerProxy::GrantUriPermission(const Uri &uri, unsigned int f TAG_LOGE(AAFwkTag::URIPERMMGR, "Write initiatorTokenId failed."); return INNER_ERR; } + if (!data.WriteInt32(abilityId)) { + TAG_LOGE(AAFwkTag::URIPERMMGR, "Write abilityId failed."); + return INNER_ERR; + } MessageParcel reply; MessageOption option; int error = SendTransactCmd(UriPermMgrCmd::ON_GRANT_URI_PERMISSION, data, reply, option); @@ -68,7 +72,7 @@ int UriPermissionManagerProxy::GrantUriPermission(const Uri &uri, unsigned int f } int UriPermissionManagerProxy::GrantUriPermission(const std::vector &uriVec, unsigned int flag, - const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId) + const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId, int32_t abilityId) { TAG_LOGD(AAFwkTag::URIPERMMGR, "UriPermissionManagerProxy::GrantUriPermission is called."); if (uriVec.empty() || uriVec.size() > MAX_URI_COUNT) { @@ -106,6 +110,10 @@ int UriPermissionManagerProxy::GrantUriPermission(const std::vector &uriVec TAG_LOGE(AAFwkTag::URIPERMMGR, "Write initiatorTokenId failed."); return INNER_ERR; } + if (!data.WriteInt32(abilityId)) { + TAG_LOGE(AAFwkTag::URIPERMMGR, "Write abilityId failed."); + return INNER_ERR; + } MessageParcel reply; MessageOption option; int error = SendTransactCmd(UriPermMgrCmd::ON_BATCH_GRANT_URI_PERMISSION, data, reply, option); @@ -161,56 +169,7 @@ int32_t UriPermissionManagerProxy::GrantUriPermissionPrivileged(const std::vecto return reply.ReadInt32(); } -int UriPermissionManagerProxy::GrantUriPermissionFor2In1(const std::vector &uriVec, unsigned int flag, - const std::string &targetBundleName, int32_t appIndex, bool isSystemAppCall) -{ - TAG_LOGD(AAFwkTag::URIPERMMGR, "Called."); - if (uriVec.empty() || uriVec.size() > MAX_URI_COUNT) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "uriVec is empty or exceed maximum size %{public}d.", MAX_URI_COUNT); - return ERR_URI_LIST_OUT_OF_RANGE; - } - MessageParcel data; - if (!data.WriteInterfaceToken(IUriPermissionManager::GetDescriptor())) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Write interface token failed."); - return INNER_ERR; - } - if (!data.WriteUint32(uriVec.size())) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Write size of uriVec failed."); - return INNER_ERR; - } - for (const auto &uri : uriVec) { - if (!data.WriteParcelable(&uri)) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Write uri failed."); - return INNER_ERR; - } - } - if (!data.WriteUint32(flag)) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Write flag failed."); - return INNER_ERR; - } - if (!data.WriteString(targetBundleName)) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Write targetBundleName failed."); - return INNER_ERR; - } - if (!data.WriteInt32(appIndex)) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Write appIndex failed."); - return INNER_ERR; - } - if (!data.WriteBool(isSystemAppCall)) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Write isSystemAppCall failed."); - return INNER_ERR; - } - MessageParcel reply; - MessageOption option; - int error = SendTransactCmd(UriPermMgrCmd::ON_BATCH_GRANT_URI_PERMISSION_FOR_2_IN_1, data, reply, option); - if (error != ERR_OK) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "SendRequest fial, error: %{public}d", error); - return INNER_ERR; - } - return reply.ReadInt32(); -} - -void UriPermissionManagerProxy::RevokeUriPermission(const Security::AccessToken::AccessTokenID tokenId) +void UriPermissionManagerProxy::RevokeUriPermission(const uint32_t tokenId, int32_t abilityId) { TAG_LOGD(AAFwkTag::URIPERMMGR, "UriPermissionManagerProxy::RevokeUriPermission is called."); MessageParcel data; @@ -222,6 +181,10 @@ void UriPermissionManagerProxy::RevokeUriPermission(const Security::AccessToken: TAG_LOGE(AAFwkTag::URIPERMMGR, "Write AccessTokenID failed."); return; } + if (!data.WriteInt32(abilityId)) { + TAG_LOGE(AAFwkTag::URIPERMMGR, "Write AccessTokenID failed."); + return; + } MessageParcel reply; MessageOption option; int error = SendTransactCmd(UriPermMgrCmd::ON_REVOKE_URI_PERMISSION, data, reply, option); @@ -230,7 +193,7 @@ void UriPermissionManagerProxy::RevokeUriPermission(const Security::AccessToken: } } -int UriPermissionManagerProxy::RevokeAllUriPermissions(const Security::AccessToken::AccessTokenID tokenId) +int UriPermissionManagerProxy::RevokeAllUriPermissions(const uint32_t tokenId) { TAG_LOGD(AAFwkTag::URIPERMMGR, "UriPermissionManagerProxy::RevokeAllUriPermissions is called."); MessageParcel data; @@ -348,34 +311,12 @@ std::vector UriPermissionManagerProxy::CheckUriAuthorization(const std::ve return result; } auto size = reply.ReadUint32(); - for (auto i = 0; i < size; i++) { + for (auto i = 0; i < static_cast(size); i++) { result[i] = reply.ReadBool(); } return result; } -bool UriPermissionManagerProxy::IsAuthorizationUriAllowed(uint32_t fromTokenId) -{ - TAG_LOGD(AAFwkTag::URIPERMMGR, "UriPermissionManagerProxy::IsAuthorizationUriAllowed is called."); - MessageParcel data; - if (!data.WriteInterfaceToken(IUriPermissionManager::GetDescriptor())) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Write interface token failed."); - return false; - } - if (!data.WriteUint32(fromTokenId)) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Write fromTokenId failed."); - return false; - } - MessageParcel reply; - MessageOption option; - int error = SendTransactCmd(UriPermMgrCmd::ON_IS_Authorization_URI_ALLOWED, data, reply, option); - if (error != ERR_OK) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "SendRequest fail, error: %{public}d", error); - return false; - } - return reply.ReadBool(); -} - int32_t UriPermissionManagerProxy::SendTransactCmd(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { diff --git a/interfaces/inner_api/uri_permission/src/uri_permission_manager_stub.cpp b/interfaces/inner_api/uri_permission/src/uri_permission_manager_stub.cpp index 2e097c6736..2021ee5ff4 100644 --- a/interfaces/inner_api/uri_permission/src/uri_permission_manager_stub.cpp +++ b/interfaces/inner_api/uri_permission/src/uri_permission_manager_stub.cpp @@ -54,15 +54,9 @@ int UriPermissionManagerStub::OnRemoteRequest( case UriPermMgrCmd::ON_VERIFY_URI_PERMISSION : { return HandleVerifyUriPermission(data, reply); } - case UriPermMgrCmd::ON_BATCH_GRANT_URI_PERMISSION_FOR_2_IN_1 : { - return HandleBatchGrantUriPermissionFor2In1(data, reply); - } case UriPermMgrCmd::ON_CHECK_URI_AUTHORIZATION : { return HandleCheckUriAuthorization(data, reply); } - case UriPermMgrCmd::ON_IS_Authorization_URI_ALLOWED : { - return HandleIsAuthorizationUriAllowed(data, reply); - } default: return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } @@ -72,7 +66,8 @@ int UriPermissionManagerStub::OnRemoteRequest( int UriPermissionManagerStub::HandleRevokeUriPermission(MessageParcel &data, MessageParcel &reply) { auto tokenId = data.ReadUint32(); - RevokeUriPermission(tokenId); + auto abilityId = data.ReadInt32(); + RevokeUriPermission(tokenId, abilityId); return ERR_OK; } @@ -95,7 +90,8 @@ int UriPermissionManagerStub::HandleGrantUriPermission(MessageParcel &data, Mess auto targetBundleName = data.ReadString(); auto appIndex = data.ReadInt32(); auto initiatorTokenId = data.ReadUint32(); - int result = GrantUriPermission(*uri, flag, targetBundleName, appIndex, initiatorTokenId); + auto abilityId = data.ReadInt32(); + int result = GrantUriPermission(*uri, flag, targetBundleName, appIndex, initiatorTokenId, abilityId); reply.WriteInt32(result); return ERR_OK; } @@ -120,7 +116,8 @@ int UriPermissionManagerStub::HandleBatchGrantUriPermission(MessageParcel &data, auto targetBundleName = data.ReadString(); auto appIndex = data.ReadInt32(); auto initiatorTokenId = data.ReadUint32(); - int result = GrantUriPermission(uriVec, flag, targetBundleName, appIndex, initiatorTokenId); + auto abilityId = data.ReadInt32(); + int result = GrantUriPermission(uriVec, flag, targetBundleName, appIndex, initiatorTokenId, abilityId); reply.WriteInt32(result); return ERR_OK; } @@ -176,31 +173,6 @@ int UriPermissionManagerStub::HandleVerifyUriPermission(MessageParcel &data, Mes return ERR_OK; } -int UriPermissionManagerStub::HandleBatchGrantUriPermissionFor2In1(MessageParcel &data, MessageParcel &reply) -{ - auto size = data.ReadUint32(); - if (size == 0 || size > MAX_URI_COUNT) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "size is invalid."); - return ERR_DEAD_OBJECT; - } - std::vector uriVec; - for (uint32_t i = 0; i < size; i++) { - std::unique_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "To read uri failed."); - return ERR_DEAD_OBJECT; - } - uriVec.emplace_back(*uri); - } - auto flag = data.ReadUint32(); - auto targetBundleName = data.ReadString(); - auto appIndex = data.ReadInt32(); - auto isSystemAppCall = data.ReadBool(); - int result = GrantUriPermissionFor2In1(uriVec, flag, targetBundleName, appIndex, isSystemAppCall); - reply.WriteInt32(result); - return ERR_OK; -} - int32_t UriPermissionManagerStub::HandleCheckUriAuthorization(MessageParcel &data, MessageParcel &reply) { auto size = data.ReadUint32(); @@ -228,13 +200,5 @@ int32_t UriPermissionManagerStub::HandleCheckUriAuthorization(MessageParcel &dat } return ERR_OK; } - -int UriPermissionManagerStub::HandleIsAuthorizationUriAllowed(MessageParcel &data, MessageParcel &reply) -{ - auto fromTokenId = data.ReadUint32(); - bool result = IsAuthorizationUriAllowed(fromTokenId); - reply.WriteBool(result); - return ERR_OK; -} } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/wantagent/BUILD.gn b/interfaces/inner_api/wantagent/BUILD.gn index e42236abf9..bcc4d00546 100644 --- a/interfaces/inner_api/wantagent/BUILD.gn +++ b/interfaces/inner_api/wantagent/BUILD.gn @@ -30,24 +30,24 @@ config("wantagent_innerkits_public_config") { ] include_dirs = [ - "${eventhandler_path}/interfaces/inner_api", "${ability_base_kits_path}/configuration/include", - "${global_path}/resource_management/interfaces/inner_api/include", "${ability_runtime_path}/interfaces/kits/native/ability/native", "${ability_runtime_innerkits_path}/ability_manager/include", "${ability_runtime_innerkits_path}/wantagent/include", "${ability_runtime_services_path}/abilitymgr/include", "${ability_runtime_innerkits_path}/app_manager/include/appmgr", - "${bundlefwk_inner_api_path}/appexecfwk_base/include", "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_path}/interfaces/kits/native/appkit", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime", - "//third_party/icu/icu4c/source/common", ] } ohos_shared_library("wantagent_innerkits") { - include_dirs = [ "${ability_runtime_services_path}/common/include" ] + include_dirs = [ + "${ability_runtime_services_path}/common/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_path}/interfaces/inner_api/deps_wrapper/include", + ] sources = [ "${ability_runtime_services_path}/abilitymgr/src/sender_info.cpp", @@ -71,11 +71,12 @@ ohos_shared_library("wantagent_innerkits") { public_configs = [ ":wantagent_innerkits_public_config" ] deps = [ - "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/error_utils:ability_runtime_error_util", ] external_deps = [ + "ability_base:session_info", "ability_base:want", "bundle_framework:appexecfwk_core", "c_utils:utils", @@ -86,7 +87,14 @@ ohos_shared_library("wantagent_innerkits") { "samgr:samgr_proxy", ] - public_external_deps = [ "bundle_framework:appexecfwk_core" ] + public_external_deps = [ + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "eventhandler:libeventhandler", + "icu:shared_icuuc", + "image_framework:image_native", + "resource_management:global_resmgr", + ] if (is_double_framework) { cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] diff --git a/interfaces/kits/c/ability/ability_runtime/child_process/native_child_process.h b/interfaces/kits/c/ability/ability_runtime/child_process/native_child_process.h new file mode 100644 index 0000000000..60ab59bc0f --- /dev/null +++ b/interfaces/kits/c/ability/ability_runtime/child_process/native_child_process.h @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_C_NATIVE_CHILD_PROCESS_H +#define OHOS_ABILITY_RUNTIME_C_NATIVE_CHILD_PROCESS_H + +#include "ipc_cparcel.h" + +/** + * @addtogroup ChildProcess + * @{ + * + * @brief Provides the APIs to manage child processes. + * + * @syscap SystemCapability.Ability.AbilityRuntime.Core + * @since 12 + */ + +/** + * @file native_child_process.h + * + * @brief Declares the APIs used to create a native child process and establish an IPC channel between the parent and + * child processes. + * + * @library libchild_process.so + * @syscap SystemCapability.Ability.AbilityRuntime.Core + * @since 12 + */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Enumerates the error codes used by the native child process module. + * @since 12 + */ +typedef enum Ability_NativeChildProcess_ErrCode { + /** + * @error Operation successful. + */ + NCP_NO_ERROR = 0, + + /** + * @error Invalid parameter. + */ + NCP_ERR_INVALID_PARAM = 401, + + /** + * @error Creating a native child process is not supported. + */ + NCP_ERR_NOT_SUPPORTED = 801, + + /** + * @error Internal error. + */ + NCP_ERR_INTERNAL = 16000050, + + /** + * @error A new child process cannot be created during the startup of another native child process. + * You can try again after the child process is started. + */ + NCP_ERR_BUSY = 16010001, + + /** + * @error Starting the native child process times out. + */ + NCP_ERR_TIMEOUT = 16010002, + + /** + * @error Server error. + */ + NCP_ERR_SERVICE_ERROR = 16010003, + + /** + * @error The multi-process mode is disabled. A child process cannot be started. + */ + NCP_ERR_MULTI_PROCESS_DISABLED = 16010004, + + /** + * @error A process cannot be created in a child process. + */ + NCP_ERR_ALREADY_IN_CHILD = 16010005, + + /** + * @error The number of native child processes reaches the maximum. + */ + NCP_ERR_MAX_CHILD_PROCESSES_REACHED = 16010006, + + /** + * @error The child process fails to load the dynamic library because the file does not exist + * or the corresponding method is not implemented or exported. + */ + NCP_ERR_LIB_LOADING_FAILED = 16010007, + + /** + * @error The child process fails to call the OnConnect method of the dynamic library. + * An invalid IPC object pointer may be returned. + */ + NCP_ERR_CONNECTION_FAILED = 16010008, +} Ability_NativeChildProcess_ErrCode; + + +/** + * @brief Defines a callback function for notifying the child process startup result. + * + * @param errCode Error code corresponding to the callback function. The following values are available: + * {@link NCP_NO_ERROR} if the child process is created successfully.\n + * {@link NCP_ERR_LIB_LOADING_FAILED} if loading the dynamic library file fails or the necessary export function + * is not implemented in the dynamic library.\n + * {@link NCP_ERR_CONNECTION_FAILED} if the OnConnect method implemented in the dynamic library does not return + * a valid IPC stub pointer.\n + * For details, see {@link Ability_NativeChildProcess_ErrCode}. + * @param remoteProxy Pointer to the IPC object of the child process. If an exception occurs, the value may be nullptr. + * The object must be released by calling {@link OH_IPCRemoteProxy_Destory} when it is no longer needed. + * @see OH_Ability_CreateNativeChildProcess + * @see OH_IPCRemoteProxy_Destory + * @since 12 + */ +typedef void (*OH_Ability_OnNativeChildProcessStarted)(int errCode, OHIPCRemoteProxy *remoteProxy); + +/** + * @brief Creates a child process, loads the specified dynamic library file, and returns the startup result + * asynchronously through a callback parameter. + * The callback notification is an independent thread. When implementing the callback function, + * pay attention to thread synchronization and do not perform time-consuming operations to avoid long-time blocking. + * + * The dynamic library specified must implement and export the following functions:\n + * 1. OHIPCRemoteStub* NativeChildProcess_OnConnect()\n + * 2. void NativeChildProcess_MainProc()\n + * + * The processing logic sequence is shown in the following pseudocode: \n + * Main process: \n + * 1. OH_Ability_CreateNativeChildProcess(libName, onProcessStartedCallback)\n + * Child process: \n + * 2. dlopen(libName)\n + * 3. dlsym("NativeChildProcess_OnConnect")\n + * 4. dlsym("NativeChildProcess_MainProc")\n + * 5. ipcRemote = NativeChildProcess_OnConnect()\n + * 6. NativeChildProcess_MainProc()\n + * Main process: \n + * 7. onProcessStartedCallback(ipcRemote, errCode)\n + * Child process: \n + * 8. The child process exits after the NativeChildProcess_MainProc() function is returned. \n + * + * @param libName Name of the dynamic library file loaded in the child process. The value cannot be nullptr. + * @param onProcessStarted Pointer to the callback function for notifying the child process startup result. + * The value cannot be nullptr. For details, see {@link OH_Ability_OnNativeChildProcessStarted}. + * @return Returns {@link NCP_NO_ERROR} if the call is successful, but the actual startup result is notified by the + * callback function.\n + * Returns {@link NCP_ERR_INVALID_PARAM} if the dynamic library name or callback function pointer is invalid.\n + * Returns {@link NCP_ERR_NOT_SUPPORTED} if the device does not support the creation of native child processes.\n + * Returns {@link NCP_ERR_MULTI_PROCESS_DISABLED} if the multi-process mode is disabled on the device.\n + * Returns {@link NCP_ERR_ALREADY_IN_CHILD} if it is not allowed to create another child process in the child process.\n + * Returns {@link NCP_ERR_MAX_CHILD_PROCESSES_REACHED} if the maximum number of native child processes is reached.\n + * For details, see {@link Ability_NativeChildProcess_ErrCode}. + * @see OH_Ability_OnNativeChildProcessStarted + * @since 12 + */ +int OH_Ability_CreateNativeChildProcess(const char* libName, + OH_Ability_OnNativeChildProcessStarted onProcessStarted); + + +#ifdef __cplusplus +} // extern "C" +#endif + +/** @} */ +#endif // OHOS_ABILITY_RUNTIME_C_NATIVE_CHILD_PROCESS_H diff --git a/interfaces/kits/native/ability/native/ability.h b/interfaces/kits/native/ability/native/ability.h index c877512cb5..1c462cade9 100644 --- a/interfaces/kits/native/ability/native/ability.h +++ b/interfaces/kits/native/ability/native/ability.h @@ -1295,7 +1295,6 @@ protected: std::shared_ptr setting_ = nullptr; std::shared_ptr abilityInfo_ = nullptr; LaunchParam launchParam_; - int32_t appIndex_ = 0; bool securityFlag_ = false; private: diff --git a/interfaces/kits/native/ability/native/ability_business_error/ability_business_error.h b/interfaces/kits/native/ability/native/ability_business_error/ability_business_error.h index 6182bbde15..e27ac14d0e 100644 --- a/interfaces/kits/native/ability/native/ability_business_error/ability_business_error.h +++ b/interfaces/kits/native/ability/native/ability_business_error/ability_business_error.h @@ -141,6 +141,15 @@ enum class AbilityErrorCode { // Ability already running. ERROR_ABILITY_ALREADY_RUNNING = 16000068, + // not support Clone app. + ERROR_CODE_MULTI_APP_NOT_SUPPORTED = 16000072, + + // app is not Clone. + ERROR_NOT_APP_CLONE = 16000071, + + // app clone index does not exist. + ERROR_APP_CLONE_INDEX_INVALID = 16000073, + // invalid caller. ERROR_CODE_INVALID_CALLER = 16200001, diff --git a/interfaces/kits/native/ability/native/js_service_extension.h b/interfaces/kits/native/ability/native/js_service_extension.h index 7f75ec8225..7cbed03673 100644 --- a/interfaces/kits/native/ability/native/js_service_extension.h +++ b/interfaces/kits/native/ability/native/js_service_extension.h @@ -23,6 +23,7 @@ #ifdef SUPPORT_GRAPHICS #include "display_manager.h" #include "system_ability_status_change_stub.h" +#include "window_manager.h" #endif #include "service_extension.h" @@ -125,7 +126,7 @@ public: * value of startId is 6. */ virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; - + /** * @brief Called back when Service is started by intent driver. * @@ -178,7 +179,7 @@ private: bool CallPromise(napi_value result, AppExecFwk::AbilityTransactionCallbackInfo<> *callbackInfo); void ListenWMS(); - + bool GetInsightIntentExecutorInfo(const Want &want, const std::shared_ptr &executeParam, InsightIntentExecutorInfo &executorInfo); @@ -192,36 +193,21 @@ private: #ifdef SUPPORT_GRAPHICS protected: - class JsServiceExtensionDisplayListener : public Rosen::DisplayManager::IDisplayListener { + class JsServiceExtensionDisplayListener : public Rosen::IDisplayInfoChangedListener { public: explicit JsServiceExtensionDisplayListener(const std::weak_ptr& jsServiceExtension) { jsServiceExtension_ = jsServiceExtension; } - void OnCreate(Rosen::DisplayId displayId) override - { - auto sptr = jsServiceExtension_.lock(); - if (sptr != nullptr) { - sptr->OnCreate(displayId); + void OnDisplayInfoChange(const sptr& token, Rosen::DisplayId displayId, float density, + Rosen::DisplayOrientation orientation) override + { + auto sptr = jsServiceExtension_.lock(); + if (sptr != nullptr) { + sptr->OnDisplayInfoChange(token, displayId, density, orientation); + } } - } - - void OnDestroy(Rosen::DisplayId displayId) override - { - auto sptr = jsServiceExtension_.lock(); - if (sptr != nullptr) { - sptr->OnDestroy(displayId); - } - } - - void OnChange(Rosen::DisplayId displayId) override - { - auto sptr = jsServiceExtension_.lock(); - if (sptr != nullptr) { - sptr->OnChange(displayId); - } - } private: std::weak_ptr jsServiceExtension_; @@ -230,17 +216,20 @@ protected: void OnCreate(Rosen::DisplayId displayId); void OnDestroy(Rosen::DisplayId displayId); void OnChange(Rosen::DisplayId displayId); + void OnDisplayInfoChange(const sptr& token, Rosen::DisplayId displayId, float density, + Rosen::DisplayOrientation orientation); private: class SystemAbilityStatusChangeListener : public OHOS::SystemAbilityStatusChangeStub { public: - SystemAbilityStatusChangeListener(sptr displayListener) - : tmpDisplayListener_(displayListener) {}; + SystemAbilityStatusChangeListener(sptr displayListener, + const sptr & token): tmpDisplayListener_(displayListener), token_(token) {}; virtual void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; virtual void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override {} private: sptr tmpDisplayListener_ = nullptr; + sptr token_ = nullptr; }; sptr displayListener_ = nullptr; diff --git a/interfaces/kits/native/ability/native/ui_ability.h b/interfaces/kits/native/ability/native/ui_ability.h index 8e5184641f..5319a9c1e3 100644 --- a/interfaces/kits/native/ability/native/ui_ability.h +++ b/interfaces/kits/native/ability/native/ui_ability.h @@ -32,6 +32,7 @@ #include "display_manager.h" #include "session_info.h" #include "window_scene.h" +#include "window_manager.h" #endif namespace OHOS { @@ -331,7 +332,6 @@ protected: std::shared_ptr abilityRecovery_ = nullptr; std::shared_ptr abilityInfo_ = nullptr; AAFwk::LaunchParam launchParam_; - int32_t appIndex_ = 0; bool securityFlag_ = false; private: @@ -536,37 +536,25 @@ public: void EraseUIExtension(int32_t sessionId) override; + void SetIdentityToken(const std::string &identityToken); + std::string GetIdentityToken() const; + protected: - class UIAbilityDisplayListener : public OHOS::Rosen::DisplayManager::IDisplayListener { + class UIAbilityDisplayListener : public OHOS::Rosen::IDisplayInfoChangedListener { public: explicit UIAbilityDisplayListener(const std::weak_ptr &ability) { ability_ = ability; } - void OnCreate(Rosen::DisplayId displayId) override - { - auto sptr = ability_.lock(); - if (sptr != nullptr) { - sptr->OnCreate(displayId); + void OnDisplayInfoChange(const sptr& token, Rosen::DisplayId displayId, float density, + Rosen::DisplayOrientation orientation) override + { + auto sptr = ability_.lock(); + if (sptr != nullptr) { + sptr->OnDisplayInfoChange(token, displayId, density, orientation); + } } - } - - void OnDestroy(Rosen::DisplayId displayId) override - { - auto sptr = ability_.lock(); - if (sptr != nullptr) { - sptr->OnDestroy(displayId); - } - } - - void OnChange(Rosen::DisplayId displayId) override - { - auto sptr = ability_.lock(); - if (sptr != nullptr) { - sptr->OnChange(displayId); - } - } private: std::weak_ptr ability_; @@ -575,6 +563,8 @@ protected: void OnCreate(Rosen::DisplayId displayId); void OnDestroy(Rosen::DisplayId displayId); void OnChange(Rosen::DisplayId displayId); + void OnDisplayInfoChange(const sptr& token, Rosen::DisplayId displayId, float density, + Rosen::DisplayOrientation orientation); class AbilityDisplayMoveListener : public OHOS::Rosen::IDisplayMoveListener { public: @@ -606,6 +596,7 @@ private: void OnChangeForUpdateConfiguration(const AppExecFwk::Configuration &newConfig); void SetSessionToken(sptr sessionToken); + std::string identityToken_; bool showOnLockScreen_ = false; #endif }; diff --git a/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_content_session.h b/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_content_session.h index 8260ebdfd3..bf112df27d 100644 --- a/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_content_session.h +++ b/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_content_session.h @@ -117,6 +117,8 @@ protected: napi_env env, NapiCallbackInfo& info, std::shared_ptr &innerErrorCode); void StartAbilityForResultRuntimeTask(napi_env env, AAFwk::Want &want, std::shared_ptr asyncTask, size_t& unwrapArgc, AAFwk::StartOptions startOptions); + void SetCallbackForTerminateWithResult(int32_t resultCode, AAFwk::Want& want, + NapiAsyncTask::CompleteCallback& complete); bool CheckStartAbilityByTypeParam(napi_env env, NapiCallbackInfo& info, std::string& type, AAFwk::WantParams& wantParam); diff --git a/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_context.h b/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_context.h index a541015e50..85b45fddce 100755 --- a/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_context.h +++ b/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_context.h @@ -54,6 +54,8 @@ protected: virtual napi_value OnDisconnectAbility(napi_env env, NapiCallbackInfo& info); virtual napi_value OnReportDrawnCompleted(napi_env env, NapiCallbackInfo& info); virtual napi_value OnOpenAtomicService(napi_env env, NapiCallbackInfo& info); + void SetCallbackForTerminateWithResult(int32_t resultCode, AAFwk::Want& want, + NapiAsyncTask::CompleteCallback& complete); protected: std::weak_ptr context_; diff --git a/interfaces/kits/native/appkit/ability_bundle_manager_helper/bundle_mgr_helper.h b/interfaces/kits/native/appkit/ability_bundle_manager_helper/bundle_mgr_helper.h index 85e41577d3..33834ac6d0 100644 --- a/interfaces/kits/native/appkit/ability_bundle_manager_helper/bundle_mgr_helper.h +++ b/interfaces/kits/native/appkit/ability_bundle_manager_helper/bundle_mgr_helper.h @@ -91,6 +91,10 @@ public: const uint32_t flag, const int32_t userId, std::vector &extensionInfos); sptr GetDefaultAppProxy(); ErrCode GetLaunchWantForBundle(const std::string &bundleName, Want &want, int32_t userId); + ErrCode QueryCloneAbilityInfo(const ElementName &element, int32_t flags, int32_t appCloneIndex, + AbilityInfo &abilityInfo, int32_t userId); + ErrCode GetCloneBundleInfo(const std::string &bundleName, int32_t flags, int32_t appCloneIndex, + BundleInfo &bundleInfo, int32_t userId); private: sptr Connect(); diff --git a/interfaces/kits/native/appkit/ability_delegator/runner_runtime/cj_test_runner.h b/interfaces/kits/native/appkit/ability_delegator/runner_runtime/cj_test_runner.h new file mode 100644 index 0000000000..e725d2908a --- /dev/null +++ b/interfaces/kits/native/appkit/ability_delegator/runner_runtime/cj_test_runner.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_CJ_TEST_RUNNER_H +#define OHOS_ABILITY_RUNTIME_CJ_TEST_RUNNER_H + +#include "bundle_info.h" +#include "cj_runtime.h" +#include "test_runner.h" + +namespace OHOS { +namespace RunnerRuntime { +using namespace AppExecFwk; +using namespace AbilityRuntime; + +class CJTestRunnerObject; + +class CJTestRunner : public TestRunner { +public: + /** + * Creates a TestRunner instance with the input parameter passed. + * + * @param runtime Indicates the ability runtime. + * @param args Indicates the AbilityDelegatorArgs object. + * @param bundleInfo Indicates the bundle info. + * @return the TestRunner object if TestRunner object is created successfully; returns null otherwise. + */ + static std::unique_ptr Create(const std::unique_ptr &runtime, + const std::shared_ptr &args, const AppExecFwk::BundleInfo &bundleInfo); + + /** + * Default deconstructor used to deconstruct. + */ + ~CJTestRunner() override; + + /** + * Prepares the testing environment for running test code. + */ + void Prepare() override; + + /** + * Runs all test code. + */ + void Run() override; + + bool Initialize() override; + +private: + CJTestRunner(CJRuntime &cjRuntime, + const std::shared_ptr &args, const AppExecFwk::BundleInfo &bundleInfo); + + void ReportFinished(const std::string &msg); + void ReportStatus(const std::string &msg); + + CJRuntime &cjRuntime_; + std::shared_ptr cjTestRunnerObj_; +}; +} // namespace RunnerRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_CJ_TEST_RUNNER_H \ No newline at end of file diff --git a/interfaces/kits/native/appkit/ability_delegator/runner_runtime/cj_test_runner_object.h b/interfaces/kits/native/appkit/ability_delegator/runner_runtime/cj_test_runner_object.h new file mode 100644 index 0000000000..72dad87953 --- /dev/null +++ b/interfaces/kits/native/appkit/ability_delegator/runner_runtime/cj_test_runner_object.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_CJ_TEST_RUNNER_OBJECT_H +#define OHOS_ABILITY_RUNTIME_CJ_TEST_RUNNER_OBJECT_H + +#include + +#ifdef WINDOWS_PLATFORM +#define CJ_EXPORT __declspec(dllexport) +#else +#define CJ_EXPORT __attribute__((visibility("default"))) +#endif + +extern "C" { +struct CJTestRunnerFuncs { + int64_t (*cjTestRunnerCreate)(const char* name); + void (*cjTestRunnerRelease)(int64_t id); + void (*cjTestRunnerOnRun)(int64_t id); + void (*cjTestRunnerOnPrepare)(int64_t id); +}; + +CJ_EXPORT void RegisterCJTestRunnerFuncs(void (*registerFunc)(CJTestRunnerFuncs*)); +} + +namespace OHOS { +namespace RunnerRuntime { +class CJTestRunnerObject { +public: + static std::shared_ptr LoadModule(const std::string& name); + explicit CJTestRunnerObject(int64_t id) : id_(id) {} + ~CJTestRunnerObject(); + void OnRun() const; + void OnPrepare() const; +private: + int64_t id_ = -1; +}; +} // namespace RunnerRuntime +} // namespace OHOS + +#endif // OHOS_ABILITY_RUNTIME_CJ_TEST_RUNNER_OBJECT_H diff --git a/interfaces/kits/native/appkit/ability_runtime/app/ability_stage.h b/interfaces/kits/native/appkit/ability_runtime/app/ability_stage.h index b45048e785..2f09864779 100644 --- a/interfaces/kits/native/appkit/ability_runtime/app/ability_stage.h +++ b/interfaces/kits/native/appkit/ability_runtime/app/ability_stage.h @@ -59,7 +59,8 @@ public: bool ContainsAbility() const; virtual void OnConfigurationUpdated(const AppExecFwk::Configuration& configuration); virtual void OnMemoryLevel(int level); - virtual int32_t RunAutoStartupTask(const std::function &callback, bool &isAsyncCallback); + virtual int32_t RunAutoStartupTask(const std::function &callback, bool &isAsyncCallback, + const std::shared_ptr &stageContext); private: friend class JsAbilityStage; diff --git a/interfaces/kits/native/appkit/ability_runtime/app/cj_ability_stage.h b/interfaces/kits/native/appkit/ability_runtime/app/cj_ability_stage.h new file mode 100644 index 0000000000..386d3c5239 --- /dev/null +++ b/interfaces/kits/native/appkit/ability_runtime/app/cj_ability_stage.h @@ -0,0 +1,45 @@ +/* + * 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 OHOS_ABILITY_RUNTIME_CJ_ABILITY_STAGE_H +#define OHOS_ABILITY_RUNTIME_CJ_ABILITY_STAGE_H + +#include + +#include "ability_stage.h" +#include "cj_ability_stage_object.h" + +namespace OHOS { +namespace AbilityRuntime { +class CJAbilityStage : public AbilityStage { +public: + static std::shared_ptr Create( + const std::unique_ptr& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo); + explicit CJAbilityStage( + std::shared_ptr cjStage) : cjAbilityStageObject_(std::move(cjStage)) {} + ~CJAbilityStage() override = default; + + void OnCreate(const AAFwk::Want& want) const override; + std::string OnAcceptWant(const AAFwk::Want& want) override; + void OnConfigurationUpdated(const AppExecFwk::Configuration& configuration) override; + void OnMemoryLevel(int level) override; + +private: + std::shared_ptr cjAbilityStageObject_; +}; +} // namespace AbilityRuntime +} // namespace OHOS + +#endif // OHOS_ABILITY_RUNTIME_CJ_ABILITY_STAGE_H diff --git a/interfaces/kits/native/appkit/ability_runtime/app/cj_ability_stage_object.h b/interfaces/kits/native/appkit/ability_runtime/app/cj_ability_stage_object.h new file mode 100644 index 0000000000..55cde5e87f --- /dev/null +++ b/interfaces/kits/native/appkit/ability_runtime/app/cj_ability_stage_object.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_CJ_ABILITY_STAGE_OBJECT_H +#define OHOS_ABILITY_RUNTIME_CJ_ABILITY_STAGE_OBJECT_H + +#include + +#include "configuration.h" +#include "want.h" + +#ifdef WINDOWS_PLATFORM +#define CJ_EXPORT __declspec(dllexport) +#else +#define CJ_EXPORT __attribute__((visibility("default"))) +#endif + +extern "C" { +struct CJConfiguration { + int32_t colorMode; + int32_t direction; + int32_t displayId; + int32_t screenDensity; + bool isValid; + const char* language; +}; + +struct CJAbilityStageFuncs { + int64_t (*LoadAbilityStage)(const char* moduleName); + void (*ReleaseAbilityStage)(int64_t handle); + void (*AbilityStageOnCreate)(int64_t handle); + char* (*AbilityStageOnAcceptWant)(int64_t handle, OHOS::AAFwk::Want* want); + void (*AbilityStageOnConfigurationUpdated)(int64_t id, CJConfiguration configuration); + void (*AbilityStageOnMemoryLevel)(int64_t id, int32_t level); +}; + +CJ_EXPORT void RegisterCJAbilityStageFuncs(void (*registerFunc)(CJAbilityStageFuncs* result)); +} + +namespace OHOS { +namespace AbilityRuntime { +class CJAbilityStageObject { +public: + static std::shared_ptr LoadModule(const std::string& moduleName); + + explicit CJAbilityStageObject(int64_t id) : id_(id) {} + ~CJAbilityStageObject(); + + void OnCreate() const; + std::string OnAcceptWant(const AAFwk::Want& want) const; + void OnConfigurationUpdated(const std::shared_ptr& configuration) const; + void OnMemoryLevel(int32_t level) const; + +private: + int64_t id_; +}; +} // namespace AbilityRuntime +} // namespace OHOS + +#endif // OHOS_ABILITY_RUNTIME_CJ_ABILITY_STAGE_OBJECT_H diff --git a/interfaces/kits/native/appkit/ability_runtime/app/js_ability_stage.h b/interfaces/kits/native/appkit/ability_runtime/app/js_ability_stage.h index 60f20dba49..7dd7860dfe 100644 --- a/interfaces/kits/native/appkit/ability_runtime/app/js_ability_stage.h +++ b/interfaces/kits/native/appkit/ability_runtime/app/js_ability_stage.h @@ -56,7 +56,8 @@ public: void OnMemoryLevel(int32_t level) override; - int32_t RunAutoStartupTask(const std::function &callback, bool &isAsyncCallback) override; + int32_t RunAutoStartupTask(const std::function &callback, bool &isAsyncCallback, + const std::shared_ptr &stageContext) override; private: napi_value CallObjectMethod(const char* name, napi_value const * argv = nullptr, size_t argc = 0); @@ -87,6 +88,8 @@ private: bool IsFileExisted(const std::string &filePath); bool TransformFileToJsonString(const std::string &resPath, std::string &profile); + + void SetJsAbilityStage(const std::shared_ptr &context); JsRuntime& jsRuntime_; std::shared_ptr jsAbilityStageObj_; diff --git a/interfaces/kits/native/appkit/ability_runtime/context/application_context.h b/interfaces/kits/native/appkit/ability_runtime/context/application_context.h index 42ed96ce9f..e7dd14c9cb 100644 --- a/interfaces/kits/native/appkit/ability_runtime/context/application_context.h +++ b/interfaces/kits/native/appkit/ability_runtime/context/application_context.h @@ -114,6 +114,10 @@ public: std::string GetAppRunningUniqueId() const; void SetAppRunningUniqueId(const std::string &appRunningUniqueId); int32_t SetSupportedProcessCacheSelf(bool isSupport); + int32_t GetCurrentAppCloneIndex(); + void SetCurrentAppCloneIndex(int32_t appIndex); + int32_t GetCurrentAppMode(); + void SetCurrentAppMode(int32_t appIndex); private: std::shared_ptr contextImpl_; static std::vector> callbacks_; @@ -125,6 +129,8 @@ private: bool applicationInfoUpdateFlag_ = false; AppConfigUpdateCallback appConfigChangeCallback_ = nullptr; std::string appRunningUniqueId_; + int32_t appIndex_ = 0; + int32_t appMode_ = 0; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/interfaces/kits/native/appkit/ability_runtime/context/context_impl.h b/interfaces/kits/native/appkit/ability_runtime/context/context_impl.h index 647401b713..cea4d75680 100644 --- a/interfaces/kits/native/appkit/ability_runtime/context/context_impl.h +++ b/interfaces/kits/native/appkit/ability_runtime/context/context_impl.h @@ -369,8 +369,7 @@ private: static const std::string CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE; static const std::string CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE; static const std::string CONTEXT_DISTRIBUTEDFILES; - static const std::string CONTEXT_CLOUDFILE_DIR_BASE_BEFORE; - static const std::string CONTEXT_CLOUDFILE_DIR_BASE_MIDDLE; + static const std::string CONTEXT_CLOUDFILE; static const std::string CONTEXT_FILE_SEPARATOR; static const std::string CONTEXT_DATA; static const std::string CONTEXT_DATA_STORAGE; diff --git a/interfaces/kits/native/appkit/ability_runtime/context/js_application_context_utils.h b/interfaces/kits/native/appkit/ability_runtime/context/js_application_context_utils.h index f62cd7a7af..ca3bcd046d 100644 --- a/interfaces/kits/native/appkit/ability_runtime/context/js_application_context_utils.h +++ b/interfaces/kits/native/appkit/ability_runtime/context/js_application_context_utils.h @@ -98,6 +98,7 @@ public: napi_value OnRestartApp(napi_env env, NapiCallbackInfo& info); napi_value OnSetSupportedProcessCacheSelf(napi_env env, NapiCallbackInfo& info); napi_value OnPreloadUIExtensionAbility(napi_env env, NapiCallbackInfo& info); + napi_value OnGetCurrentAppCloneIndex(napi_env env, NapiCallbackInfo& info); static napi_value GetCacheDir(napi_env env, napi_callback_info info); static napi_value GetTempDir(napi_env env, napi_callback_info info); @@ -119,6 +120,7 @@ public: static napi_value RestartApp(napi_env env, napi_callback_info info); static napi_value SetSupportedProcessCacheSelf(napi_env env, napi_callback_info info); static napi_value PreloadUIExtensionAbility(napi_env env, napi_callback_info info); + static napi_value GetCurrentAppCloneIndex(napi_env env, napi_callback_info info); protected: std::weak_ptr applicationContext_; diff --git a/interfaces/kits/native/appkit/app/child_main_thread.h b/interfaces/kits/native/appkit/app/child_main_thread.h index ca6d337866..73a1abf9de 100644 --- a/interfaces/kits/native/appkit/app/child_main_thread.h +++ b/interfaces/kits/native/appkit/app/child_main_thread.h @@ -39,6 +39,7 @@ public: static void Start(const ChildProcessInfo &processInfo); bool ScheduleLoadJs() override; bool ScheduleExitProcessSafely() override; + bool ScheduleRunNativeProc(const sptr &mainProcessCb) override; private: bool Init(const std::shared_ptr &runner, const ChildProcessInfo &processInfo); @@ -49,6 +50,8 @@ private: void ExitProcessSafely(); void GetNativeLibPath(const BundleInfo &bundleInfo, AppLibPathMap &appLibPaths); void GetHapSoPath(const HapModuleInfo &hapInfo, AppLibPathMap &appLibPaths, bool isPreInstallApp); + void HandleRunNativeProc(const sptr &mainProcessCb); + void UpdateNativeChildLibPath(const AppLibPathMap &appLibPaths); std::string GetLibPath(const std::string &hapPath, bool isPreInstallApp); sptr appMgr_ = nullptr; diff --git a/interfaces/kits/native/appkit/app/dump_ffrt_helper.h b/interfaces/kits/native/appkit/app/dump_ffrt_helper.h new file mode 100644 index 0000000000..96f20cbcf9 --- /dev/null +++ b/interfaces/kits/native/appkit/app/dump_ffrt_helper.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_DUMP_FFRT_HELPER_H +#define OHOS_ABILITY_RUNTIME_DUMP_FFRT_HELPER_H + +#include + +namespace OHOS { +namespace AppExecFwk { + +class DumpFfrtHelper { +public: + DumpFfrtHelper(); + ~DumpFfrtHelper(); + + static int DumpFfrt(std::string& result); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_DUMP_FFRT_HELPER_H diff --git a/interfaces/kits/native/appkit/app/main_thread.h b/interfaces/kits/native/appkit/app/main_thread.h index 1a7b93a33e..751c0044cf 100644 --- a/interfaces/kits/native/appkit/app/main_thread.h +++ b/interfaces/kits/native/appkit/app/main_thread.h @@ -329,6 +329,16 @@ public: */ int32_t ScheduleDumpIpcStat(std::string& result) override; + /** + * ScheduleDumpFfrt, call ScheduleDumpFfrt(std::string& result) through proxy project, + * Start querying the application's ffrt usage. + * + * @param result, ffrt dump result output. + * + * @return Returns 0 on success, error code on failure. + */ + int32_t ScheduleDumpFfrt(std::string& result) override; + private: /** * diff --git a/interfaces/kits/native/appkit/app_startup/js_startup_task.h b/interfaces/kits/native/appkit/app_startup/js_startup_task.h index 592b056432..c69b67ccb0 100644 --- a/interfaces/kits/native/appkit/app_startup/js_startup_task.h +++ b/interfaces/kits/native/appkit/app_startup/js_startup_task.h @@ -53,7 +53,7 @@ public: void LoadJsAsyncTaskCallback(); - void OnAsyncTaskCompleted() override; + void OnAsyncTaskCompleted(const std::shared_ptr &result) override; private: JsRuntime &jsRuntime_; diff --git a/interfaces/kits/native/appkit/app_startup/js_startup_task_result.h b/interfaces/kits/native/appkit/app_startup/js_startup_task_result.h index a64af705a2..9f67decc8c 100644 --- a/interfaces/kits/native/appkit/app_startup/js_startup_task_result.h +++ b/interfaces/kits/native/appkit/app_startup/js_startup_task_result.h @@ -33,7 +33,7 @@ public: ResultType GetResultType() const override; - std::shared_ptr GetJsStartupResultRef() const; + const std::shared_ptr& GetJsStartupResultRef() const; private: std::shared_ptr jsStartupResultRef_; diff --git a/interfaces/kits/native/appkit/app_startup/startup_config.h b/interfaces/kits/native/appkit/app_startup/startup_config.h index c180beae8c..c76bb163d9 100644 --- a/interfaces/kits/native/appkit/app_startup/startup_config.h +++ b/interfaces/kits/native/appkit/app_startup/startup_config.h @@ -34,11 +34,11 @@ public: explicit StartupConfig(const std::shared_ptr &listener); - explicit StartupConfig(int32_t awaitTimeoutMs, const std::shared_ptr &listener); + StartupConfig(int32_t awaitTimeoutMs, const std::shared_ptr &listener); int32_t GetAwaitTimeoutMs() const; - int32_t ListenerOnCompleted(const std::shared_ptr &result); + void ListenerOnCompleted(const std::shared_ptr &result); static constexpr int32_t DEFAULT_AWAIT_TIMEOUT_MS = 10000; // 10s diff --git a/interfaces/kits/native/appkit/app_startup/startup_manager.h b/interfaces/kits/native/appkit/app_startup/startup_manager.h index 5cfe561aa2..6420be5acd 100644 --- a/interfaces/kits/native/appkit/app_startup/startup_manager.h +++ b/interfaces/kits/native/appkit/app_startup/startup_manager.h @@ -43,7 +43,7 @@ public: void SetDefaultConfig(const std::shared_ptr &config); - std::shared_ptr GetDefaultConfig() const; + const std::shared_ptr& GetDefaultConfig() const; int32_t RemoveAllResult(); diff --git a/interfaces/kits/native/appkit/app_startup/startup_task.h b/interfaces/kits/native/appkit/app_startup/startup_task.h index dbc881571a..37f0bb9fe6 100644 --- a/interfaces/kits/native/appkit/app_startup/startup_task.h +++ b/interfaces/kits/native/appkit/app_startup/startup_task.h @@ -38,7 +38,7 @@ public: virtual ~StartupTask(); - std::string GetName() const; + const std::string& GetName() const; std::vector GetDependencies() const; @@ -62,7 +62,7 @@ public: int32_t RemoveResult(); - std::shared_ptr GetResult() const; + const std::shared_ptr& GetResult() const; virtual int32_t RunTaskInit(std::unique_ptr callback) = 0; @@ -75,7 +75,7 @@ public: void CallExtraCallback(const std::shared_ptr &result); - virtual void OnAsyncTaskCompleted() = 0; + virtual void OnAsyncTaskCompleted(const std::shared_ptr &result) = 0; protected: std::string name_; diff --git a/interfaces/kits/native/appkit/app_startup/startup_task_manager.h b/interfaces/kits/native/appkit/app_startup/startup_task_manager.h index 73119ecd2d..7985e2021a 100644 --- a/interfaces/kits/native/appkit/app_startup/startup_task_manager.h +++ b/interfaces/kits/native/appkit/app_startup/startup_task_manager.h @@ -37,7 +37,7 @@ public: int32_t AddTask(const std::shared_ptr &task); - int32_t SetConfig(const std::shared_ptr &config); + void SetConfig(const std::shared_ptr &config); int32_t Prepare(); diff --git a/interfaces/kits/native/appkit/app_startup/startup_task_result.h b/interfaces/kits/native/appkit/app_startup/startup_task_result.h index 247f88e37c..8dc820eca5 100644 --- a/interfaces/kits/native/appkit/app_startup/startup_task_result.h +++ b/interfaces/kits/native/appkit/app_startup/startup_task_result.h @@ -42,7 +42,7 @@ public: int32_t GetResultCode() const; - std::string GetResultMessage() const; + const std::string& GetResultMessage() const; virtual ResultType GetResultType() const; diff --git a/js_environment/frameworks/js_environment/src/js_environment.cpp b/js_environment/frameworks/js_environment/src/js_environment.cpp index 343ad34af7..c5326be1e5 100644 --- a/js_environment/frameworks/js_environment/src/js_environment.cpp +++ b/js_environment/frameworks/js_environment/src/js_environment.cpp @@ -181,7 +181,7 @@ bool JsEnvironment::LoadScript(const std::string& path, std::vector* bu } bool JsEnvironment::StartDebugger( - std::string& option, const char* libraryPath, uint32_t socketFd, bool needBreakPoint, uint32_t instanceId) + std::string& option, uint32_t socketFd, bool isDebugApp, const DebuggerPostTask &debuggerPostTask) { JSENV_LOG_D("call."); if (vm_ == nullptr) { @@ -193,7 +193,18 @@ bool JsEnvironment::StartDebugger( JSENV_LOG_E("Abnormal parsing of tid results."); return false; } - debugMode_ = panda::JSNApi::StartDebuggerForSocketPair(identifierId, socketFd); + if (isDebugApp) { + debugMode_ = panda::JSNApi::StartDebuggerForSocketPair(identifierId, socketFd); + } else { + if (debuggerPostTask == nullptr) { + JSENV_LOG_E("debuggerPostTask is nullptr."); + return false; + } + auto startDebuggerForSocketPairTask = [identifierId, socketFd, this]() { + debugMode_ = panda::JSNApi::StartDebuggerForSocketPair(identifierId, socketFd); + }; + debuggerPostTask(startDebuggerForSocketPairTask); + } return debugMode_; } @@ -338,24 +349,6 @@ void JsEnvironment::SetDeviceDisconnectCallback(const std::function &cb) panda::JSNApi::SetDeviceDisconnectCallback(vm_, std::move(cb)); } -void JsEnvironment::StartMonitorJSHeapUsage() -{ - if (engine_ == nullptr) { - JSENV_LOG_E("Invalid native engine."); - return; - } - engine_->StartMonitorJSHeapUsage(); -} - -void JsEnvironment::StopMonitorJSHeapUsage() -{ - if (engine_ == nullptr) { - JSENV_LOG_E("Invalid native engine."); - return; - } - engine_->StopMonitorJSHeapUsage(); -} - DebuggerPostTask JsEnvironment::GetDebuggerPostTask() { auto debuggerPostTask = [weak = weak_from_this()](std::function&& task) { diff --git a/js_environment/interfaces/inner_api/js_environment.h b/js_environment/interfaces/inner_api/js_environment.h index af19c00695..587655c4e3 100644 --- a/js_environment/interfaces/inner_api/js_environment.h +++ b/js_environment/interfaces/inner_api/js_environment.h @@ -77,7 +77,7 @@ public: bool LoadScript(const std::string& path, std::vector* buffer = nullptr, bool isBundle = false); bool StartDebugger( - std::string& option, const char* libraryPath, uint32_t socketFd, bool needBreakPoint, uint32_t instanceId); + std::string& option, uint32_t socketFd, bool isDebugApp, const DebuggerPostTask &debuggerPostTask); void StopDebugger(); @@ -108,10 +108,6 @@ public: void SetDeviceDisconnectCallback(const std::function &cb); - void StartMonitorJSHeapUsage(); - - void StopMonitorJSHeapUsage(); - void NotifyDebugMode(int tid, const char* libraryPath, uint32_t instanceId, bool isDebugApp, bool debugMode); bool GetDebugMode() const; diff --git a/js_environment/test/unittest/BUILD.gn b/js_environment/test/unittest/BUILD.gn index 68d637e8a9..04a5773ea1 100644 --- a/js_environment/test/unittest/BUILD.gn +++ b/js_environment/test/unittest/BUILD.gn @@ -21,5 +21,6 @@ group("unittest") { "js_env_log_unit_test:unittest", "js_environment_test:unittest", "source_map_test:unittest", + "uncaught_exception_callback_test:unittest", ] } diff --git a/js_environment/test/unittest/js_environment_test/js_environment_test.cpp b/js_environment/test/unittest/js_environment_test/js_environment_test.cpp index 362294ac36..ce7445f884 100644 --- a/js_environment/test/unittest/js_environment_test/js_environment_test.cpp +++ b/js_environment/test/unittest/js_environment_test/js_environment_test.cpp @@ -237,12 +237,31 @@ HWTEST_F(JsEnvironmentTest, StartDebugger_0100, TestSize.Level0) ASSERT_NE(jsEnv, nullptr); std::string option = "ark:1234@Debugger"; - const char* libraryPath = "LIBRARYPATH"; uint32_t socketFd = 10; - bool needBreakPoint = true; - uint32_t instanceId = 10; - bool result = jsEnv->StartDebugger(option, libraryPath, socketFd, needBreakPoint, instanceId); - EXPECT_EQ(result, false); + bool isDebugApp = true; + bool result = jsEnv->StartDebugger(option, socketFd, isDebugApp, jsEnv->GetDebuggerPostTask()); + ASSERT_EQ(result, false); +} + +/** + * @tc.name: StartDebugger_0200 + * @tc.desc: StartDebugger + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(JsEnvironmentTest, StartDebugger_0200, TestSize.Level0) +{ + auto jsEnv = std::make_shared(std::make_unique()); + ASSERT_NE(jsEnv, nullptr); + panda::RuntimeOption pandaOption; + auto ret = jsEnv->Initialize(pandaOption, static_cast(this)); + ASSERT_EQ(ret, true); + + std::string option = "ark:1234@Debugger"; + uint32_t socketFd = 10; + bool isDebugApp = true; + bool result = jsEnv->StartDebugger(option, socketFd, isDebugApp, jsEnv->GetDebuggerPostTask()); + ASSERT_EQ(result, false); } /** @@ -479,6 +498,21 @@ HWTEST_F(JsEnvironmentTest, GetDebuggerPostTask_0100, TestSize.Level0) ASSERT_NE(jsEnv, nullptr); } +/** + * @tc.name: GetDebuggerPostTask_0200 + * @tc.desc: Js environment GetDebuggerPostTask. + * @tc.type: FUNC + */ +HWTEST_F(JsEnvironmentTest, GetDebuggerPostTask_0200, TestSize.Level0) +{ + auto jsEnv = std::make_shared(std::make_unique()); + auto poster = jsEnv->GetDebuggerPostTask(); + ASSERT_NE(jsEnv, nullptr); + poster([]() { + std::string temp; + }); +} + /** * @tc.name: GetHeapPrepare_0100 * @tc.desc: Js environment GetHeapPrepare. @@ -504,57 +538,5 @@ HWTEST_F(JsEnvironmentTest, GetHeapPrepare_0200, TestSize.Level0) jsEnv->GetHeapPrepare(); ASSERT_NE(jsEnv, nullptr); } - -/** - * @tc.name: StartMonitorJSHeapUsage_0100 - * @tc.desc: Js environment StartMonitorJSHeapUsage. - * @tc.type: FUNC - */ -HWTEST_F(JsEnvironmentTest, StartMonitorJSHeapUsage_0100, TestSize.Level0) -{ - auto jsEnv = std::make_shared(std::make_unique()); - jsEnv->StartMonitorJSHeapUsage(); - ASSERT_NE(jsEnv, nullptr); -} - -/** - * @tc.name: StartMonitorJSHeapUsage_0200 - * @tc.desc: Js environment StartMonitorJSHeapUsage. - * @tc.type: FUNC - */ -HWTEST_F(JsEnvironmentTest, StartMonitorJSHeapUsage_0200, TestSize.Level0) -{ - auto jsEnv = std::make_shared(std::make_unique()); - panda::RuntimeOption pandaOption; - jsEnv->Initialize(pandaOption, static_cast(this)); - jsEnv->StartMonitorJSHeapUsage(); - ASSERT_NE(jsEnv, nullptr); -} - -/** - * @tc.name: StopMonitorJSHeapUsage_0100 - * @tc.desc: Js environment StopMonitorJSHeapUsage. - * @tc.type: FUNC - */ -HWTEST_F(JsEnvironmentTest, StopMonitorJSHeapUsage_0100, TestSize.Level0) -{ - auto jsEnv = std::make_shared(std::make_unique()); - jsEnv->StopMonitorJSHeapUsage(); - ASSERT_NE(jsEnv, nullptr); -} - -/** - * @tc.name: StopMonitorJSHeapUsage_0200 - * @tc.desc: Js environment StopMonitorJSHeapUsage. - * @tc.type: FUNC - */ -HWTEST_F(JsEnvironmentTest, StopMonitorJSHeapUsage_0200, TestSize.Level0) -{ - auto jsEnv = std::make_shared(std::make_unique()); - panda::RuntimeOption pandaOption; - jsEnv->Initialize(pandaOption, static_cast(this)); - jsEnv->StopMonitorJSHeapUsage(); - ASSERT_NE(jsEnv, nullptr); -} } // namespace JsEnv } // namespace OHOS diff --git a/js_environment/test/unittest/source_map_test/source_map_test.cpp b/js_environment/test/unittest/source_map_test/source_map_test.cpp index 5afeb8341a..9504f20d34 100644 --- a/js_environment/test/unittest/source_map_test/source_map_test.cpp +++ b/js_environment/test/unittest/source_map_test/source_map_test.cpp @@ -193,6 +193,35 @@ HWTEST_F(SourceMapTest, JsEnv_SourceMap_0900, Function | MediumTest | Level1) GTEST_LOG_(INFO) << "JsEnv_SourceMap_0900 end"; } +/** + * @tc.number: JsEnv_SourceMap_1000 + * @tc.name: Find + * @tc.desc: Verifying Find succeeded. + * @tc.require: #I6T4K1 + */ +HWTEST_F(SourceMapTest, JsEnv_SourceMap_1000, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "JsEnv_SourceMap_1000 start"; + auto modSourceMap = std::make_shared(); + int32_t row = 2; + int32_t col = 3; + SourceMapData targetMap; + targetMap.sources_.emplace_back("sources"); + for (int32_t i = 0; i < 10; i++) { + for (int32_t j = 0; j < 5; j++) { + SourceMapInfo mapInfo; + mapInfo.beforeRow = 0; + mapInfo.beforeColumn = 0; + mapInfo.afterRow = i; + mapInfo.afterColumn = j; + targetMap.afterPos_.emplace_back(mapInfo); + } + } + auto info = modSourceMap->Find(row, col, targetMap); + EXPECT_STREQ(info.sources.c_str(), "sources"); + GTEST_LOG_(INFO) << "JsEnv_SourceMap_1000 end"; +} + /** * @tc.number: JsEnv_SourceMap_1300 * @tc.name: GetPosInfo diff --git a/js_environment/test/unittest/uncaught_exception_callback_test/uncaught_exception_callback_test.cpp b/js_environment/test/unittest/uncaught_exception_callback_test/uncaught_exception_callback_test.cpp index 76646c9331..4231ab8db3 100644 --- a/js_environment/test/unittest/uncaught_exception_callback_test/uncaught_exception_callback_test.cpp +++ b/js_environment/test/unittest/uncaught_exception_callback_test/uncaught_exception_callback_test.cpp @@ -94,6 +94,36 @@ HWTEST_F(NapiUncaughtExceptionCallbackTest, NapiUncaughtExceptionCallbackTest_01 ASSERT_EQ(callback3.GetNativeStrFromJsTaggedObj(object, "stack"), errorStack); } +/** + * @tc.name: NapiUncaughtExceptionCallbackTest_0101 + * @tc.type: FUNC + * @tc.desc: Test NapiNapiUncaughtExceptionCallback GetNativeStrFromJsTaggedObj. + * @tc.require: #I6T4K1 + */ +HWTEST_F(NapiUncaughtExceptionCallbackTest, NapiUncaughtExceptionCallbackTest_0101, TestSize.Level1) +{ + AbilityRuntime::Runtime::Options options; + options.preload = false; + auto jsRuntime = AbilityRuntime::JsRuntime::Create(options); + ASSERT_NE(jsRuntime, nullptr); + auto env = jsRuntime->GetNapiEnv(); + EXPECT_NE(env, nullptr); + + // Test with null object + auto task = [](std::string summary, const JsEnv::ErrorObject errorObj) { + summary += "test"; + }; + + // Test with invalid object + napi_value object = nullptr; + napi_create_object(env, &object); + napi_value valueUint32 = nullptr; + napi_create_uint32(env, 0x11, &valueUint32); + napi_set_named_property(env, object, "key", valueUint32); + NapiUncaughtExceptionCallback callback(task, nullptr, env); + ASSERT_EQ(callback.GetNativeStrFromJsTaggedObj(object, "key"), ""); +} + /** * @tc.name: NapiUncaughtExceptionCallbackTest_0200 * @tc.type: FUNC diff --git a/service_router_framework/interfaces/kits/js/serviceroutermgr/BUILD.gn b/service_router_framework/interfaces/kits/js/serviceroutermgr/BUILD.gn index 59ff9fd5fb..ab2448d98d 100755 --- a/service_router_framework/interfaces/kits/js/serviceroutermgr/BUILD.gn +++ b/service_router_framework/interfaces/kits/js/serviceroutermgr/BUILD.gn @@ -37,6 +37,7 @@ ohos_shared_library("businessabilityrouter") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${srms_inner_api_path}:srms_fwk", ] diff --git a/service_router_framework/services/srms/BUILD.gn b/service_router_framework/services/srms/BUILD.gn index b358dfc2ec..fc4ed26a2e 100755 --- a/service_router_framework/services/srms/BUILD.gn +++ b/service_router_framework/services/srms/BUILD.gn @@ -27,6 +27,12 @@ config("srms_config") { } ohos_shared_library("libsrms") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" sources = [ "src/inner_service_info.cpp", "src/service_router_data_mgr.cpp", @@ -40,6 +46,7 @@ ohos_shared_library("libsrms") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${srms_inner_api_path}:srms_fwk", ] diff --git a/service_router_framework/services/srms/test/unittest/service_router_mgr_interface_test/BUILD.gn b/service_router_framework/services/srms/test/unittest/service_router_mgr_interface_test/BUILD.gn index 0e96c19afc..c53934f6f8 100755 --- a/service_router_framework/services/srms/test/unittest/service_router_mgr_interface_test/BUILD.gn +++ b/service_router_framework/services/srms/test/unittest/service_router_mgr_interface_test/BUILD.gn @@ -23,10 +23,12 @@ ohos_unittest("ServiceRouterMgrInterfaceTest") { sources = [ "${srms_services_path}/src/inner_service_info.cpp", "${srms_services_path}/src/service_router_data_mgr.cpp", + "${srms_services_path}/src/sr_samgr_helper.cpp", "srms_interface_test.cpp", ] deps = [ + "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${bundlefwk_common_path}:libappexecfwk_common", "${srms_inner_api_path}:srms_fwk", ] diff --git a/service_router_framework/services/srms/test/unittest/service_router_mgr_interface_test/srms_interface_test.cpp b/service_router_framework/services/srms/test/unittest/service_router_mgr_interface_test/srms_interface_test.cpp index ee661879ce..dd8c61d50a 100755 --- a/service_router_framework/services/srms/test/unittest/service_router_mgr_interface_test/srms_interface_test.cpp +++ b/service_router_framework/services/srms/test/unittest/service_router_mgr_interface_test/srms_interface_test.cpp @@ -391,6 +391,116 @@ HWTEST_F(ServiceRouterMgrInterfaceTest, ServiceRouterMgrInterfaceTest_0019, Func EXPECT_TRUE(ret); } +/** + * @tc.number: ServiceRouterMgrInterfaceTest + * @tc.name: test LoadAllBundleInfos + * @tc.desc: test LoadAllBundleInfos function + */ +HWTEST_F(ServiceRouterMgrInterfaceTest, ServiceRouterMgrInterfaceTest_0020, Function | SmallTest | Level0) +{ + auto serviceRouterMgr = std::make_shared(); + EXPECT_NE(serviceRouterMgr, nullptr); + if (serviceRouterMgr != nullptr) { + auto ret = serviceRouterMgr->LoadAllBundleInfos(); + EXPECT_EQ(ret, true); + } +} + +/** + * @tc.number: ServiceRouterMgrInterfaceTest + * @tc.name: test LoadBundleInfo + * @tc.desc: test LoadBundleInfo function + */ +HWTEST_F(ServiceRouterMgrInterfaceTest, ServiceRouterMgrInterfaceTest_0021, Function | SmallTest | Level0) +{ + auto serviceRouterMgr = std::make_shared(); + EXPECT_NE(serviceRouterMgr, nullptr); + if (serviceRouterMgr != nullptr) { + std::string bundleName = BUNDLE_NAME; + auto ret = serviceRouterMgr->LoadBundleInfo(bundleName); + EXPECT_EQ(ret, false); + } +} + +/** + * @tc.number: ServiceRouterMgrInterfaceTest + * @tc.name: test UpdateBundleInfoLocked + * @tc.desc: test UpdateBundleInfoLocked function + */ +HWTEST_F(ServiceRouterMgrInterfaceTest, ServiceRouterMgrInterfaceTest_0022, Function | SmallTest | Level0) +{ + auto serviceRouterMgr = std::make_shared(); + EXPECT_NE(serviceRouterMgr, nullptr); + if (serviceRouterMgr != nullptr) { + BundleInfo bundleInfo; + serviceRouterMgr->UpdateBundleInfoLocked(bundleInfo); + } +} + +/** + * @tc.number: ServiceRouterMgrInterfaceTest + * @tc.name: test DeleteBundleInfo + * @tc.desc: test DeleteBundleInfo function + */ +HWTEST_F(ServiceRouterMgrInterfaceTest, ServiceRouterMgrInterfaceTest_0023, Function | SmallTest | Level0) +{ + auto serviceRouterMgr = std::make_shared(); + EXPECT_NE(serviceRouterMgr, nullptr); + if (serviceRouterMgr != nullptr) { + std::string bundleName = BUNDLE_NAME; + serviceRouterMgr->DeleteBundleInfo(bundleName); + } +} + +/** + * @tc.number: ServiceRouterMgrInterfaceTest + * @tc.name: test GetBusinessType + * @tc.desc: test GetBusinessType function 1 + */ +HWTEST_F(ServiceRouterMgrInterfaceTest, ServiceRouterMgrInterfaceTest_0024, Function | SmallTest | Level0) +{ + auto serviceRouterMgr = std::make_shared(); + EXPECT_NE(serviceRouterMgr, nullptr); + if (serviceRouterMgr != nullptr) { + BusinessAbilityFilter filter; + filter.businessType = BusinessType::SHARE; + auto ret = serviceRouterMgr->GetBusinessType(filter); + EXPECT_EQ(ret, BusinessType::SHARE); + } +} + +/** + * @tc.number: ServiceRouterMgrInterfaceTest + * @tc.name: test GetBusinessType + * @tc.desc: test GetBusinessType function 2 + */ +HWTEST_F(ServiceRouterMgrInterfaceTest, ServiceRouterMgrInterfaceTest_0025, Function | SmallTest | Level0) +{ + auto serviceRouterMgr = std::make_shared(); + EXPECT_NE(serviceRouterMgr, nullptr); + if (serviceRouterMgr != nullptr) { + BusinessAbilityFilter filter; + filter.businessType = BusinessType::UNSPECIFIED; + filter.uri = ""; + auto ret = serviceRouterMgr->GetBusinessType(filter); + EXPECT_EQ(ret, BusinessType::UNSPECIFIED); + } +} + +/** + * @tc.number: ServiceRouterMgrInterfaceTest + * @tc.name: test ClearAllBundleInfos + * @tc.desc: test ClearAllBundleInfos function + */ +HWTEST_F(ServiceRouterMgrInterfaceTest, ServiceRouterMgrInterfaceTest_0026, Function | SmallTest | Level0) +{ + auto serviceRouterMgr = std::make_shared(); + EXPECT_NE(serviceRouterMgr, nullptr); + if (serviceRouterMgr != nullptr) { + serviceRouterMgr->ClearAllBundleInfos(); + } +} + /** * @tc.number: serviceRouterMgrProxy * @tc.name: test QueryBusinessAbilityInfos diff --git a/services/abilitymgr/BUILD.gn b/services/abilitymgr/BUILD.gn index e3000ef609..33681ed8cc 100644 --- a/services/abilitymgr/BUILD.gn +++ b/services/abilitymgr/BUILD.gn @@ -11,13 +11,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//base/account/os_account/os_account.gni") import("//build/ohos.gni") import("//foundation/ability/ability_runtime/ability_runtime.gni") import( "//foundation/ability/ability_runtime/services/abilitymgr/abilitymgr.gni") -import("//foundation/distributeddatamgr/relational_store/relational_store.gni") -import("//foundation/resourceschedule/background_task_mgr/bgtaskmgr.gni") group("abilityms_target") { deps = [ @@ -39,28 +36,21 @@ config("abilityms_config") { "${ability_runtime_innerkits_path}/app_manager/include", "${ability_runtime_innerkits_path}/connectionobs_manager/include", "${ability_runtime_innerkits_path}/deps_wrapper/include", - "${ability_base_path}/interfaces/inner_api/base/include", - "${ability_base_kits_path}/extractortool/include", - "${ability_base_kits_path}/uri/include", - "${ability_base_kits_path}/want/include", "${ability_runtime_services_path}/common/include", "//prebuilts/jdk/jdk8/linux-x86/include", "//prebuilts/jdk/jdk8/linux-x86/include/linux", "//third_party/json/include", "${ability_runtime_path}/interfaces/kits/native/ability/native", "${relational_store_innerapi_path}/rdb/include", - "${relational_store_innerapi_path}/appdatafwk/include", "${relational_store_innerapi_path}/dataability/include", "${ability_runtime_innerkits_path}/dataobs_manager/include", "${ability_runtime_path}/tools/aa/include", - "${os_account_path}/frameworks/common/account_error/include", - "${os_account_path}/frameworks/common/database/include", - "${os_account_path}/interfaces/innerkits/osaccount/native/include", "${ability_runtime_innerkits_path}/wantagent/include", "${ability_runtime_innerkits_path}/session_handler/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", - "${bgtaskmgr_interfaces_path}/innerkits/include", + "${ability_runtime_utils_path}/global/constant", + "${ability_runtime_utils_path}/server/constant", "${bgtaskmgr_frameworks_path}/common/include", "${bgtaskmgr_frameworks_path}/include", "${init_path}/interfaces/innerkits/include/syspara/", @@ -116,6 +106,12 @@ config("abilityms_config") { } ohos_shared_library("abilityms") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" shlib_type = "sa" sources = abilityms_files cflags_cc = [] @@ -126,6 +122,7 @@ ohos_shared_library("abilityms") { include_dirs = [ "${ability_runtime_services_path}/appdfr/include" ] deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_innerkits_path}/ability_manager:process_options", @@ -138,16 +135,17 @@ ohos_shared_library("abilityms") { "${ability_runtime_native_path}/ability/native:auto_startup_callback", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:event_report", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_services_path}/common:task_handler_wrap", - "//third_party/icu/icu4c:shared_icuuc", ] external_deps = [ "ability_base:base", "ability_base:configuration", + "ability_base:extractortool", "ability_base:session_info", "ability_base:view_data", "ability_base:want", @@ -167,10 +165,13 @@ ohos_shared_library("abilityms") { "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", + "icu:shared_icuuc", "init:libbeget_proxy", "init:libbegetutil", "ipc:ipc_core", "kv_store:distributeddata_inner", + "os_account:os_account_innerkits", + "relational_store:native_appdatafwk", "relational_store:native_dataability", "relational_store:native_rdb", "safwk:system_ability_fwk", @@ -181,6 +182,7 @@ ohos_shared_library("abilityms") { "window_manager:session_manager_lite", "window_manager:sms", ] + public_external_deps = [ "background_task_mgr:bgtaskmgr_innerkits" ] if (background_task_mgr_continuous_task_enable) { external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] @@ -200,11 +202,10 @@ ohos_shared_library("abilityms") { } if (ability_runtime_graphics) { - deps += [ "//third_party/icu/icu4c:shared_icuuc" ] - external_deps += [ "ability_base:session_info", "i18n:intl_util", + "icu:shared_icuuc", "image_framework:image_native", "input:libmmi-client", "resource_management:global_resmgr", @@ -235,12 +236,6 @@ ohos_prebuilt_etc("uiextension_picker_config.json") { part_name = "ability_runtime" } -ohos_prebuilt_etc("proxy_authorization_uri.json") { - source = "resource/proxy_authorization_uri.json" - subsystem_name = "ability" - part_name = "ability_runtime" -} - ohos_prebuilt_etc("deeplink_reserve_config.json") { source = "resource/deeplink_reserve_config.json" subsystem_name = "ability" @@ -251,7 +246,6 @@ group("ams_service_config") { deps = [ ":ams_service_config.json", ":deeplink_reserve_config.json", - ":proxy_authorization_uri.json", ":uiextension_picker_config.json", ] } diff --git a/services/abilitymgr/abilitymgr.gni b/services/abilitymgr/abilitymgr.gni index 0594e38f2d..9607736fe5 100644 --- a/services/abilitymgr/abilitymgr.gni +++ b/services/abilitymgr/abilitymgr.gni @@ -14,7 +14,6 @@ import("//foundation/ability/ability_runtime/ability_runtime.gni") abilityms_files = [ - "src/ability_app_state_observer.cpp", "src/preload_uiext_state_observer.cpp", "src/ability_background_connection.cpp", "src/ability_connect_manager.cpp", @@ -23,10 +22,8 @@ abilityms_files = [ "src/disposed_observer.cpp", "src/ability_manager_service.cpp", "src/ability_manager_stub.cpp", - "src/ability_manager_proxy.cpp", "src/ability_record.cpp", "src/ability_manager_collaborator_proxy.cpp", - "src/ability_scheduler_stub.cpp", "src/ability_scheduler_proxy.cpp", "src/ability_token_stub.cpp", "src/app_scheduler.cpp", @@ -51,7 +48,6 @@ abilityms_files = [ "src/want_sender_info.cpp", "src/pending_want_record.cpp", "src/want_receiver_proxy.cpp", - "src/want_receiver_stub.cpp", "src/want_sender_proxy.cpp", "src/want_sender_stub.cpp", "src/pending_want_key.cpp", @@ -85,7 +81,6 @@ abilityms_files = [ "src/ui_extension_record_factory.cpp", "src/start_options.cpp", "src/user_callback_proxy.cpp", - "src/user_callback_stub.cpp", "src/call_container.cpp", "src/call_record.cpp", "src/inner_mission_info.cpp", @@ -94,18 +89,15 @@ abilityms_files = [ "src/mission_info_mgr.cpp", "src/mission_listener_controller.cpp", "src/mission_listener_proxy.cpp", - "src/mission_listener_stub.cpp", "src/rdb/ability_resident_process_rdb.cpp", "src/rdb/parser_util.cpp", "src/rdb/rdb_data_manager.cpp", "src/remote_mission_listener_proxy.cpp", - "src/remote_mission_listener_stub.cpp", "src/mission_list_manager.cpp", "src/mission_list.cpp", "src/scene_board/status_bar_delegate_manager.cpp", "src/scene_board/ui_ability_lifecycle_manager.cpp", - "src/open_link/open_link_options.cpp", - "src/deeplink_reserve/deeplink_reserve.cpp", + "src/deeplink_reserve/deeplink_reserve_config.cpp", #connection observer "src/connection_observer_controller.cpp", diff --git a/services/abilitymgr/include/ability_app_state_observer.h b/services/abilitymgr/include/ability_app_state_observer.h deleted file mode 100644 index 0b8d83e142..0000000000 --- a/services/abilitymgr/include/ability_app_state_observer.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2023 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 OHOS_ABILITY_RUNTIME_ABILITY_APP_STATE_OBSERVER_H -#define OHOS_ABILITY_RUNTIME_ABILITY_APP_STATE_OBSERVER_H - -#include - -#include "application_state_observer_stub.h" - -namespace OHOS { -namespace AAFwk { -class AbilityRecord; -class AbilityAppStateObserver : public AppExecFwk::ApplicationStateObserverStub { -public: - AbilityAppStateObserver(std::shared_ptr abilityRecord); - virtual void OnProcessDied(const AppExecFwk::ProcessData &processData) override; - -private: - std::weak_ptr abilityRecord_; -}; -} // namespace AAFwk -} // namespace OHOS -#endif // OHOS_ABILITY_RUNTIME_ABILITY_APP_STATE_OBSERVER_H \ No newline at end of file diff --git a/services/abilitymgr/include/ability_event_util.h b/services/abilitymgr/include/ability_event_util.h index a222bc1f43..e1be202905 100644 --- a/services/abilitymgr/include/ability_event_util.h +++ b/services/abilitymgr/include/ability_event_util.h @@ -22,9 +22,6 @@ namespace OHOS { namespace AAFwk { - -const std::string KEY_UID = "uid"; - class AbilityEventUtil { public: diff --git a/services/abilitymgr/include/ability_manager_proxy.h b/services/abilitymgr/include/ability_manager_proxy.h index fdd8ecd489..f4b67472e8 100644 --- a/services/abilitymgr/include/ability_manager_proxy.h +++ b/services/abilitymgr/include/ability_manager_proxy.h @@ -287,9 +287,10 @@ public: * Start ui ability with want, send want to ability manager service. * * @param sessionInfo the session info of the ability to start. + * @param isColdStart the session info of the ability is or not cold start. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartUIAbilityBySCB(sptr sessionInfo) override; + virtual int StartUIAbilityBySCB(sptr sessionInfo, bool &isColdStart) override; /** * Stop extension ability with want, send want to ability manager service. @@ -1241,6 +1242,17 @@ public: */ virtual int32_t GetAbilityStateByPersistentId(int32_t persistentId, bool &state) override; + /** + * Transfer resultCode & want to ability manager service. + * + * @param callerToken caller ability token. + * @param requestCode the resultCode of the ability to start. + * @param want Indicates the ability to start. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t TransferAbilityResultForExtension(const sptr &callerToken, int32_t resultCode, + const Want &want) override; + private: template int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); diff --git a/services/abilitymgr/include/ability_manager_service.h b/services/abilitymgr/include/ability_manager_service.h index ab6c739d38..f40d4aab1c 100644 --- a/services/abilitymgr/include/ability_manager_service.h +++ b/services/abilitymgr/include/ability_manager_service.h @@ -44,7 +44,7 @@ #include "bundle_constants.h" #include "bundle_mgr_helper.h" #include "data_ability_manager.h" -#include "deeplink_reserve/deeplink_reserve.h" +#include "deeplink_reserve/deeplink_reserve_config.h" #include "event_report.h" #include "free_install_manager.h" #include "hilog_wrapper.h" @@ -67,13 +67,16 @@ #include "dialog_session_record.h" #include "implicit_start_processor.h" #include "system_dialog_scheduler.h" -#include "window_focus_changed_listener.h" #endif namespace OHOS { namespace AbilityRuntime { class IStatusBarDelegate; } +namespace Rosen { +class FocusChangeInfo; +} + namespace AAFwk { using AutoStartupInfo = AbilityRuntime::AutoStartupInfo; enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; @@ -83,6 +86,8 @@ constexpr int32_t INVALID_USER_ID = -1; using OHOS::AppExecFwk::IAbilityController; class PendingWantManager; struct StartAbilityInfo; +class WindowFocusChangedListener; + /** * @class AbilityManagerService * AbilityManagerService provides a facility for managing ability life cycle. @@ -404,9 +409,10 @@ public: * Start ui ability with want, send want to ability manager service. * * @param sessionInfo the session info of the ability to start. + * @param isColdStart the session info of the ability is or not cold start. * @return Returns ERR_OK on success, others on failure. */ - virtual int StartUIAbilityBySCB(sptr sessionInfo) override; + virtual int StartUIAbilityBySCB(sptr sessionInfo, bool &isColdStart) override; /** * Stop extension ability with want, send want to ability manager service. @@ -1037,11 +1043,12 @@ public: int requestCode = DEFAULT_INVAL_VALUE, bool isSendDialogResult = false); - void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag); - void OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want); + void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag, int32_t requestId = 0); + void OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want, int32_t requestId = 0); - void OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag); - void OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want); + void OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag, + int32_t requestId = 0); + void OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want, int32_t requestId = 0); virtual int GetAbilityRunningInfos(std::vector &info) override; virtual int GetExtensionRunningInfos(int upperLimit, std::vector &info) override; @@ -1667,6 +1674,17 @@ public: */ virtual int32_t GetAbilityStateByPersistentId(int32_t persistentId, bool &state) override; + /** + * Transfer resultCode & want to ability manager service. + * + * @param callerToken Caller ability token. + * @param requestCode The resultCode of the ability to start. + * @param want Indicates the ability to start. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t TransferAbilityResultForExtension(const sptr &callerToken, int32_t resultCode, + const Want &want) override; + // MSG 0 - 20 represents timeout message static constexpr uint32_t LOAD_TIMEOUT_MSG = 0; static constexpr uint32_t ACTIVE_TIMEOUT_MSG = 1; @@ -1733,6 +1751,8 @@ protected: void NotifyStartResidentProcess(std::vector &bundleInfos) override; + void OnAppRemoteDied(const std::vector> &abilityTokens) override; + private: int TerminateAbilityWithFlag(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, const Want *resultWant = nullptr, bool flag = true); @@ -1908,6 +1928,12 @@ private: const std::string& args, std::vector& state, bool isClient, bool isUserID, int UserID); std::map dumpsysFuncMap_; + int CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo &abilityInfo, uint32_t tokenId); + + int CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest &abilityRequest, uint32_t tokenId); + + bool CheckOneSkillPermission(const AppExecFwk::Skill &skill, uint32_t tokenId); + int CheckStaticCfgPermission(const AppExecFwk::AbilityRequest &abilityRequest, bool isStartAsCaller, uint32_t callerTokenId, bool isData = false, bool isSaCall = false, bool isImplicit = false); @@ -2214,6 +2240,8 @@ private: void SetReserveInfo(const std::string &linkString); + void ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo &callerAbilityInfo, + const AppExecFwk::AbilityInfo &abilityInfo); #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE std::shared_ptr bgtaskObserver_; #endif @@ -2232,7 +2260,6 @@ private: #endif std::shared_ptr interceptorExecuter_; std::shared_ptr afterCheckExecuter_; - std::shared_ptr deepLinkReserveConfig_; std::unordered_map appRecoveryHistory_; // uid:time bool isPrepareTerminateEnable_ = false; diff --git a/services/abilitymgr/include/ability_manager_stub.h b/services/abilitymgr/include/ability_manager_stub.h index 58c0e0b69c..3db3377525 100644 --- a/services/abilitymgr/include/ability_manager_stub.h +++ b/services/abilitymgr/include/ability_manager_stub.h @@ -70,6 +70,7 @@ private: void SecondStepInit(); void ThirdStepInit(); void FourthStepInit(); + void FifthStepInit(); int TerminateAbilityInner(MessageParcel &data, MessageParcel &reply); int TerminateUIExtensionAbilityInner(MessageParcel &data, MessageParcel &reply); int CloseUIAbilityBySCBInner(MessageParcel &data, MessageParcel &reply); @@ -298,6 +299,7 @@ private: int32_t NotifyDebugAssertResultInner(MessageParcel &data, MessageParcel &reply); int32_t StartShortcutInner(MessageParcel &data, MessageParcel &reply); int32_t GetAbilityStateByPersistentIdInner(MessageParcel &data, MessageParcel &reply); + int32_t TransferAbilityResultForExtensionInner(MessageParcel &data, MessageParcel &reply); }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/ability_record.h b/services/abilitymgr/include/ability_record.h index c017f6202f..be3bf4e39a 100644 --- a/services/abilitymgr/include/ability_record.h +++ b/services/abilitymgr/include/ability_record.h @@ -57,7 +57,6 @@ class ConnectionRecord; class Mission; class MissionList; class CallContainer; -class AbilityAppStateObserver; constexpr const char* ABILITY_TOKEN_NAME = "AbilityToken"; constexpr const char* LAUNCHER_BUNDLE_NAME = "com.ohos.launcher"; @@ -358,6 +357,12 @@ public: */ void ProcessForegroundAbility(uint32_t tokenId, uint32_t sceneFlag = 0); + /** + * post foreground timeout task for ui ability. + * + */ + void PostForegroundTimeoutTask(); + /** * move the ability to back ground. * @@ -995,7 +1000,6 @@ private: */ void GetAbilityTypeString(std::string &typeStr); void OnSchedulerDied(const wptr &remote); - void RemoveAppStateObserver(bool force = false); void GrantUriPermission(Want &want, std::string targetBundleName, bool isSandboxApp, uint32_t tokenId); void GrantDmsUriPermission(Want &want, std::string targetBundleName); bool IsDmsCall(Want &want); @@ -1171,7 +1175,6 @@ private: // scene session sptr sessionInfo_ = nullptr; mutable ffrt::mutex sessionLock_; - sptr abilityAppStateObserver_; std::map abilityWindowStateMap_; sptr uiExtRequestSessionInfo_ = nullptr; diff --git a/services/abilitymgr/include/ability_util.h b/services/abilitymgr/include/ability_util.h index c4753270bb..b8abf0a737 100644 --- a/services/abilitymgr/include/ability_util.h +++ b/services/abilitymgr/include/ability_util.h @@ -37,18 +37,18 @@ namespace AAFwk { namespace AbilityUtil { constexpr const char* SYSTEM_BASIC = "system_basic"; constexpr const char* SYSTEM_CORE = "system_core"; +constexpr const char* DEFAULT_DEVICE_ID = ""; constexpr const char* DLP_BUNDLE_NAME = "com.ohos.dlpmanager"; +constexpr const char* DLP_MODULE_NAME = "entry"; constexpr const char* DLP_ABILITY_NAME = "ViewAbility"; constexpr const char* DLP_PARAMS_SANDBOX = "ohos.dlp.params.sandbox"; constexpr const char* DLP_PARAMS_BUNDLE_NAME = "ohos.dlp.params.bundleName"; constexpr const char* DLP_PARAMS_MODULE_NAME = "ohos.dlp.params.moduleName"; constexpr const char* DLP_PARAMS_ABILITY_NAME = "ohos.dlp.params.abilityName"; -const std::string MARKET_BUNDLE_NAME = "com.huawei.hmsapp.appgallery"; -const std::string MARKET_CROWD_TEST_BUNDLE_PARAM = "crowd_test_bundle_name"; -const std::string BUNDLE_NAME_SELECTOR_DIALOG = "com.ohos.amsdialog"; -const std::string JUMP_INTERCEPTOR_DIALOG_CALLER_PKG = "interceptor_callerPkg"; -// dlp White list -const std::unordered_set WHITE_LIST_DLP_SET = { BUNDLE_NAME_SELECTOR_DIALOG }; +constexpr const char* MARKET_BUNDLE_NAME = "com.huawei.hmsapp.appgallery"; +constexpr const char* MARKET_CROWD_TEST_BUNDLE_PARAM = "crowd_test_bundle_name"; +constexpr const char* BUNDLE_NAME_SELECTOR_DIALOG = "com.ohos.amsdialog"; +constexpr const char* JUMP_INTERCEPTOR_DIALOG_CALLER_PKG = "interceptor_callerPkg"; #define CHECK_POINTER_CONTINUE(object) \ if (!object) { \ @@ -214,7 +214,8 @@ static constexpr int64_t MICROSECONDS = 1000000; // MICROSECONDS mean 10^6 mi [[maybe_unused]] static bool HandleDlpApp(Want &want) { - if (WHITE_LIST_DLP_SET.find(want.GetBundle()) != WHITE_LIST_DLP_SET.end()) { + const std::unordered_set whiteListDlpSet = { BUNDLE_NAME_SELECTOR_DIALOG }; + if (whiteListDlpSet.find(want.GetBundle()) != whiteListDlpSet.end()) { TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, enter special app", __func__); return false; } @@ -222,7 +223,7 @@ static constexpr int64_t MICROSECONDS = 1000000; // MICROSECONDS mean 10^6 mi AppExecFwk::ElementName element = want.GetElement(); if (want.GetBoolParam(DLP_PARAMS_SANDBOX, false) && !element.GetBundleName().empty() && !element.GetAbilityName().empty()) { - want.SetElementName(DLP_BUNDLE_NAME, DLP_ABILITY_NAME); + want.SetElementName(DEFAULT_DEVICE_ID, DLP_BUNDLE_NAME, DLP_ABILITY_NAME, DLP_MODULE_NAME); want.SetParam(DLP_PARAMS_BUNDLE_NAME, element.GetBundleName()); want.SetParam(DLP_PARAMS_MODULE_NAME, element.GetModuleName()); want.SetParam(DLP_PARAMS_ABILITY_NAME, element.GetAbilityName()); diff --git a/services/abilitymgr/include/app_scheduler.h b/services/abilitymgr/include/app_scheduler.h index 9ef6ff0c3e..db716ce3a9 100644 --- a/services/abilitymgr/include/app_scheduler.h +++ b/services/abilitymgr/include/app_scheduler.h @@ -93,6 +93,8 @@ public: virtual void NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId) {} virtual void NotifyStartResidentProcess(std::vector &bundleInfos) {} + + virtual void OnAppRemoteDied(const std::vector> &abilityTokens) {} }; class StartSpecifiedAbilityResponse : public AppExecFwk::StartSpecifiedAbilityResponseStub { @@ -100,11 +102,13 @@ public: StartSpecifiedAbilityResponse() = default; virtual ~StartSpecifiedAbilityResponse() = default; - virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag) override; - virtual void OnTimeoutResponse(const AAFwk::Want &want) override; + virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag, + int32_t requestId) override; + virtual void OnTimeoutResponse(const AAFwk::Want &want, int32_t requestId) override; - virtual void OnNewProcessRequestResponse(const AAFwk::Want &want, const std::string &flag) override; - virtual void OnNewProcessRequestTimeoutResponse(const AAFwk::Want &want) override; + virtual void OnNewProcessRequestResponse(const AAFwk::Want &want, const std::string &flag, + int32_t requestId) override; + virtual void OnNewProcessRequestTimeoutResponse(const AAFwk::Want &want, int32_t requestId) override; }; /** @@ -275,10 +279,12 @@ public: */ void StartupResidentProcess(const std::vector &bundleInfos); - void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo); + void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId = 0); int GetProcessRunningInfos(std::vector &info); - void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo); + void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId = 0); /** * Start a user test @@ -328,6 +334,15 @@ public: */ int GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application, bool &debug); + /** + * Record process exit reason to appRunningRecord + * @param pid pid + * @param reason reason enum + * @param exitMsg exitMsg + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg); + /** * Set the current userId of appMgr, only used by abilityMgr. * @@ -413,14 +428,6 @@ public: */ void ClearProcessByToken(sptr token) const; - /** - * Set application assertion pause state. - * - * @param pid App process pid. - * @param flag assertion pause state. - */ - void SetAppAssertionPauseState(int32_t pid, bool flag); - /** * whether memory size is sufficent. * @return Returns true is sufficent memory size, others return false. @@ -456,6 +463,8 @@ protected: */ virtual void NotifyStartResidentProcess(std::vector &bundleInfos) override; + virtual void OnAppRemoteDied(const std::vector> &abilityTokens) override; + private: std::mutex lock_; bool isInit_ {false}; diff --git a/services/abilitymgr/include/application_util.h b/services/abilitymgr/include/application_util.h index d261eafe3d..b3befb45b6 100644 --- a/services/abilitymgr/include/application_util.h +++ b/services/abilitymgr/include/application_util.h @@ -27,8 +27,8 @@ namespace OHOS { namespace AAFwk { namespace ApplicationUtil { using Want = OHOS::AAFwk::Want; -const int32_t BOOT_COMPLETED_SIZE = 6; -const char* BOOTEVENT_BOOT_COMPLETED = "bootevent.boot.completed"; +constexpr int32_t BOOT_COMPLETED_SIZE = 6; +constexpr const char* BOOTEVENT_BOOT_COMPLETED = "bootevent.boot.completed"; [[maybe_unused]] static void AppFwkBootEventCallback(const char *key, const char *value, void *context) { diff --git a/services/abilitymgr/include/background_task_observer.h b/services/abilitymgr/include/background_task_observer.h index bf4ab13ab2..17ef08402c 100644 --- a/services/abilitymgr/include/background_task_observer.h +++ b/services/abilitymgr/include/background_task_observer.h @@ -24,8 +24,6 @@ namespace OHOS { namespace AAFwk { -const int32_t SUBSCRIBE_BACKGROUND_TASK_TRY = 5; -const int32_t REPOLL_TIME_MICRO_SECONDS = 1000000; class BackgroundTaskObserver : public BackgroundTaskMgr::BackgroundTaskSubscriber, public std::enable_shared_from_this { public: diff --git a/services/abilitymgr/include/connection_record.h b/services/abilitymgr/include/connection_record.h index fa08a42bfd..2c33406860 100644 --- a/services/abilitymgr/include/connection_record.h +++ b/services/abilitymgr/include/connection_record.h @@ -16,6 +16,7 @@ #ifndef OHOS_ABILITY_RUNTIME_CONNECTION_RECORD_H #define OHOS_ABILITY_RUNTIME_CONNECTION_RECORD_H +#include #include "ability_connect_callback_interface.h" #include "ability_record.h" #include "extension_config.h" @@ -145,6 +146,8 @@ private: ConnectionState state_; // service connection state sptr callerToken_ = nullptr; // from:caller token std::shared_ptr targetService_ = nullptr; // target:service need to be connected + + mutable std::mutex callbackMutex_; sptr connCallback_ = nullptr; // service connect callback int32_t callerUid_ = 0; // caller uid int32_t callerPid_ = 0; // caller pid diff --git a/services/abilitymgr/include/deeplink_reserve/deeplink_reserve.h b/services/abilitymgr/include/deeplink_reserve/deeplink_reserve_config.h similarity index 78% rename from services/abilitymgr/include/deeplink_reserve/deeplink_reserve.h rename to services/abilitymgr/include/deeplink_reserve/deeplink_reserve_config.h index cb19ba259e..e5001fc277 100644 --- a/services/abilitymgr/include/deeplink_reserve/deeplink_reserve.h +++ b/services/abilitymgr/include/deeplink_reserve/deeplink_reserve_config.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_ABILITY_RUNTIME_DEEPLINK_RESERVE_H -#define OHOS_ABILITY_RUNTIME_DEEPLINK_RESERVE_H +#ifndef OHOS_ABILITY_RUNTIME_DEEPLINK_RESERVE_CONFIG_H +#define OHOS_ABILITY_RUNTIME_DEEPLINK_RESERVE_CONFIG_H #include #include @@ -36,23 +36,31 @@ struct ReserveUri { std::string utd; }; -class DeepLinkReserveConfig : public DelayedSingleton { +class DeepLinkReserveConfig { public: - DeepLinkReserveConfig() = default; - virtual ~DeepLinkReserveConfig() = default; + static DeepLinkReserveConfig &GetInstance() + { + static DeepLinkReserveConfig instance; + return instance; + } + ~DeepLinkReserveConfig() = default; bool LoadConfiguration(); bool isLinkReserved(const std::string &linkString, std::string &bundleName); + private: std::string GetConfigPath(); bool ReadFileInfoJson(const std::string &filePath, nlohmann::json &jsonBuf); bool LoadReservedUriList(const nlohmann::json &object); bool isUriMatched(const ReserveUri &reservedUri, const std::string &link); void LoadReservedUrilItem(const nlohmann::json &jsonUriObject, std::vector &uriList); + DeepLinkReserveConfig() = default; + DISALLOW_COPY_AND_MOVE(DeepLinkReserveConfig); +private: std::map> deepLinkReserveUris_; }; } // OHOS } // AAFwk -#endif // OHOS_ABILITY_RUNTIME_DEEPLINK_RESERVE_H +#endif // OHOS_ABILITY_RUNTIME_DEEPLINK_RESERVE_CONFIG_H diff --git a/services/abilitymgr/include/dlp_utils.h b/services/abilitymgr/include/dlp_utils.h index ab047c962f..6e10b8e173 100644 --- a/services/abilitymgr/include/dlp_utils.h +++ b/services/abilitymgr/include/dlp_utils.h @@ -21,6 +21,7 @@ #ifdef WITH_DLP #include "dlp_permission_kit.h" #endif // WITH_DLP +#include "global_constant.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" #include "in_process_call_wrapper.h" @@ -49,7 +50,7 @@ using Dlp = Security::DlpPermission::DlpPermissionKit; TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability has already been destroyed."); return true; } - if (abilityRecord->GetAppIndex() == 0) { + if (abilityRecord->GetAppIndex() <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { return true; } if (abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) { @@ -74,7 +75,8 @@ using Dlp = Security::DlpPermission::DlpPermissionKit; { if (callerToken != nullptr) { auto abilityRecord = Token::GetAbilityRecordByToken(callerToken); - if (abilityRecord != nullptr && abilityRecord->GetAppIndex() != 0) { + if (abilityRecord != nullptr && + abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { return true; } } diff --git a/services/abilitymgr/include/ecological_rule/ability_ecological_rule_mgr_service_param.h b/services/abilitymgr/include/ecological_rule/ability_ecological_rule_mgr_service_param.h index db5541ffe7..ea12333645 100644 --- a/services/abilitymgr/include/ecological_rule/ability_ecological_rule_mgr_service_param.h +++ b/services/abilitymgr/include/ecological_rule/ability_ecological_rule_mgr_service_param.h @@ -21,6 +21,7 @@ #include "parcel.h" #include "want.h" +#include "ability_info.h" namespace OHOS { namespace EcologicalRuleMgrService { @@ -69,10 +70,11 @@ struct AbilityCallerInfo : public Parcelable { std::string targetAppDistType = ""; std::string targetLinkFeature = ""; int32_t targetLinkType = LINK_TYPE_INVALID; - int32_t callerAbilityType = 0L; + AppExecFwk::AbilityType callerAbilityType = AppExecFwk::AbilityType::UNKNOWN; int32_t embedded = 0; std::string callerAppProvisionType; std::string targetAppProvisionType; + AppExecFwk::ExtensionAbilityType callerExtensionAbilityType = AppExecFwk::ExtensionAbilityType::UNSPECIFIED; bool ReadFromParcel(Parcel &parcel); diff --git a/services/abilitymgr/include/extension_record_factory.h b/services/abilitymgr/include/extension_record_factory.h index 896b9b517c..9ae7ba2be2 100644 --- a/services/abilitymgr/include/extension_record_factory.h +++ b/services/abilitymgr/include/extension_record_factory.h @@ -39,12 +39,6 @@ struct ExtensionRecordConfig { uint32_t preCheckFlag = PRE_CHECK_FLAG_NONE; }; -const std::map EXTENSION_RECORD_CONFIG_MAP = { - { AppExecFwk::ExtensionAbilityType::EMBEDDED_UI, - { PROCESS_MODE_BUNDLE, PROCESS_MODE_SUPPORT_DEFAULT | PROCESS_MODE_HOST_SPECIFIED | PROCESS_MODE_HOST_INSTANCE, - PRE_CHECK_FLAG_CALLED_WITHIN_THE_BUNDLE | PRE_CHECK_FLAG_MULTIPLE_PROCESSES }}, -}; - class ExtensionRecordFactory : public std::enable_shared_from_this { public: ExtensionRecordFactory(); diff --git a/services/abilitymgr/include/interceptor/ecological_rule_interceptor.h b/services/abilitymgr/include/interceptor/ecological_rule_interceptor.h index 8e3b693fd3..9f9bd8aecf 100644 --- a/services/abilitymgr/include/interceptor/ecological_rule_interceptor.h +++ b/services/abilitymgr/include/interceptor/ecological_rule_interceptor.h @@ -40,7 +40,8 @@ public: }; private: - void GetEcologicalCallerInfo(const Want &want, ErmsCallerInfo &callerInfo, int32_t userId); + void GetEcologicalCallerInfo(const Want &want, ErmsCallerInfo &callerInfo, int32_t userId, + const sptr &callerToken = nullptr); void InitErmsCallerInfo(Want &want, ErmsCallerInfo &callerInfo) const; }; } // namespace AAFwk diff --git a/services/abilitymgr/include/mission_list_manager.h b/services/abilitymgr/include/mission_list_manager.h index 908548573c..84c7e74097 100644 --- a/services/abilitymgr/include/mission_list_manager.h +++ b/services/abilitymgr/include/mission_list_manager.h @@ -23,7 +23,6 @@ #include "cpp/mutex.h" #include "ability_running_info.h" -#include "foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp/include/device_manager.h" #include "mission_list.h" #include "mission_listener_controller.h" #include "mission_info.h" @@ -318,7 +317,7 @@ public: void EnableRecoverAbility(int32_t missionId); - #ifdef ABILITY_COMMAND_FOR_TEST +#ifdef ABILITY_COMMAND_FOR_TEST /** * Block ability. * @@ -326,7 +325,7 @@ public: * @return Returns ERR_OK on success, others on failure. */ int BlockAbility(int abilityRecordId); - #endif +#endif void UninstallApp(const std::string &bundleName, int32_t uid); @@ -344,7 +343,7 @@ public: int32_t pid = NO_PID); void CallRequestDone(const std::shared_ptr &abilityRecord, const sptr &callStub); - + int SetMissionContinueState(const sptr &token, const int32_t missionId, const AAFwk::ContinueState &state); @@ -543,13 +542,6 @@ private: std::queue waitingAbilityQueue_; std::shared_ptr listenerController_; bool isPrepareTerminateEnable_ = false; - - class MissionDmInitCallback : public DistributedHardware::DmInitCallback { - public: - void OnRemoteDied() override; - - static bool isInit_; - }; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/rdb/ability_resident_process_rdb.h b/services/abilitymgr/include/rdb/ability_resident_process_rdb.h index 9fdff34c4b..edab17dcc5 100644 --- a/services/abilitymgr/include/rdb/ability_resident_process_rdb.h +++ b/services/abilitymgr/include/rdb/ability_resident_process_rdb.h @@ -81,7 +81,6 @@ public: int32_t RemoveData(std::string &bundleName); private: - bool ready = false; std::unique_ptr rdbMgr_ = nullptr; }; } // namespace AbilityRuntime diff --git a/services/abilitymgr/include/scene_board/ui_ability_lifecycle_manager.h b/services/abilitymgr/include/scene_board/ui_ability_lifecycle_manager.h index dbd74452b6..10747b36c5 100644 --- a/services/abilitymgr/include/scene_board/ui_ability_lifecycle_manager.h +++ b/services/abilitymgr/include/scene_board/ui_ability_lifecycle_manager.h @@ -26,7 +26,6 @@ #include "ability_manager_constants.h" #include "ability_record.h" #include "isession_handler_interface.h" -#include "session/host/include/zidl/session_interface.h" namespace OHOS { namespace AAFwk { @@ -64,9 +63,10 @@ public: * * @param abilityRequest the request of the service ability to start. * @param sessionInfo the info of scene session + * @param isColdStart the session info of the ability is or not cold start. * @return Returns ERR_OK on success, others on failure. */ - int StartUIAbility(AbilityRequest &abilityRequest, sptr sessionInfo); + int StartUIAbility(AbilityRequest &abilityRequest, sptr sessionInfo, bool &isColdStart); /** * @brief execute after the ability schedule the lifecycle @@ -187,7 +187,7 @@ public: * @param abilityRequest the flag of the ability to start. * @return Returns ERR_OK on success, others on failure. */ - void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag); + void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag, int32_t requestId = 0); /** * OnStartSpecifiedProcessResponse. @@ -195,21 +195,21 @@ public: * @param want the want of the ability to start. * @param abilityRequest target ability request. */ - void OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag); + void OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag, int32_t requestId = 0); /** * OnStartSpecifiedAbilityTimeoutResponse. * * @param want the want of the ability to start. */ - void OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want); + void OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want, int32_t requestId = 0); /** * OnStartSpecifiedProcessTimeoutResponse. * * @param want the want of the ability to start. */ - void OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want); + void OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want, int32_t requestId = 0); /** * Start specified ability by SCB. @@ -336,6 +336,8 @@ private: int32_t GetReusedSpecifiedPersistentId(const AbilityRequest &abilityRequest, bool &reuse) const; int32_t GetReusedStandardPersistentId(const AbilityRequest &abilityRequest, bool &reuse) const; int32_t GetReusedCollaboratorPersistentId(const AbilityRequest &abilityRequest, bool &reuse) const; + std::string GenerateProcessNameForNewProcessMode(const AppExecFwk::AbilityInfo& abilityInfo); + void PreCreateProcessName(AbilityRequest &abilityRequest); void UpdateProcessName(const AbilityRequest &abilityRequest, std::shared_ptr &abilityRecord); void UpdateAbilityRecordLaunchReason(const AbilityRequest &abilityRequest, std::shared_ptr &abilityRecord) const; @@ -371,7 +373,6 @@ private: int ResolveAbility(const std::shared_ptr &targetAbility, const AbilityRequest &abilityRequest) const; std::vector> GetAbilityRecordsByNameInner(const AppExecFwk::ElementName &element); - void EnqueueAbilityToFront(const AbilityRequest &abilityRequest); void NotifyStartSpecifiedAbility(AbilityRequest &request, const AAFwk::Want &want); void NotifyRestartSpecifiedAbility(AbilityRequest &request, const sptr &token); int MoveAbilityToFront(const AbilityRequest &abilityRequest, const std::shared_ptr &abilityRecord, @@ -397,7 +398,7 @@ private: bool CheckPid(const std::shared_ptr abilityRecord, const int32_t pid) const; std::shared_ptr GetStatusBarDelegateManager(); int32_t DoProcessAttachment(std::shared_ptr abilityRecord); - void BatchCloseUIAbility(std::unordered_set>& abilitySet); + void BatchCloseUIAbility(const std::unordered_set>& abilitySet); int StartWithPersistentIdByDistributed(const AbilityRequest &abilityRequest, int32_t persistentId); int32_t userId_ = -1; @@ -405,9 +406,10 @@ private: std::unordered_map> sessionAbilityMap_; std::unordered_map> tmpAbilityMap_; std::list> terminateAbilityList_; - sptr rootSceneSession_; + sptr rootSceneSession_; std::map, key_compare> specifiedAbilityMap_; - std::queue abilityQueue_; + int32_t specifiedRequestId_ = 0; + std::map specifiedRequestMap_; std::queue specifiedInfoQueue_; sptr handler_; ffrt::mutex statusBarDelegateManagerLock_; diff --git a/services/abilitymgr/include/start_ability_utils.h b/services/abilitymgr/include/start_ability_utils.h index a94788af8c..287e54e2ba 100644 --- a/services/abilitymgr/include/start_ability_utils.h +++ b/services/abilitymgr/include/start_ability_utils.h @@ -30,6 +30,7 @@ struct StartAbilityInfo { AppExecFwk::AbilityInfo &abilityInfo); static std::shared_ptr CreateStartAbilityInfo(const Want &want, int32_t userId, int32_t appIndex); + static std::shared_ptr CreateCallerAbilityInfo(const sptr &callerToken); static std::shared_ptr CreateStartExtensionInfo(const Want &want, int32_t userId, int32_t appIndex); @@ -48,15 +49,18 @@ struct StartAbilityUtils { static int32_t GetAppIndex(const Want &want, sptr callerToken); static bool GetApplicationInfo(const std::string &bundleName, int32_t userId, AppExecFwk::ApplicationInfo &appInfo); + static bool GetCallerAbilityInfo(const sptr &callerToken, + AppExecFwk::AbilityInfo &abilityInfo); static thread_local std::shared_ptr startAbilityInfo; - + static thread_local std::shared_ptr callerAbilityInfo; static thread_local bool skipCrowTest; static thread_local bool skipStartOther; static thread_local bool skipErms; }; struct StartAbilityInfoWrap { - StartAbilityInfoWrap(const Want &want, int32_t validUserId, int32_t appIndex, bool isExtension = false); + StartAbilityInfoWrap(const Want &want, int32_t validUserId, int32_t appIndex, + const sptr &callerToken, bool isExtension = false); ~StartAbilityInfoWrap(); }; } diff --git a/services/abilitymgr/include/system_dialog_scheduler.h b/services/abilitymgr/include/system_dialog_scheduler.h index dd4acf09a0..064d3a2360 100644 --- a/services/abilitymgr/include/system_dialog_scheduler.h +++ b/services/abilitymgr/include/system_dialog_scheduler.h @@ -58,6 +58,7 @@ struct DialogAppInfo { std::string bundleName = {}; std::string abilityName = {}; std::string moduleName = {}; + bool visible = true; }; /** * @class SystemDialogScheduler diff --git a/services/abilitymgr/libabilityms.map b/services/abilitymgr/libabilityms.map index e8978d9681..ea7ce503c3 100644 --- a/services/abilitymgr/libabilityms.map +++ b/services/abilitymgr/libabilityms.map @@ -79,6 +79,7 @@ *WantReceiverProxy*; *WantSenderProxy*; *WantSenderStub*; + *DeepLinkReserveConfig*; }; local: *; diff --git a/services/abilitymgr/resource/proxy_authorization_uri.json b/services/abilitymgr/resource/proxy_authorization_uri.json deleted file mode 100644 index 91091a6671..0000000000 --- a/services/abilitymgr/resource/proxy_authorization_uri.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "proxyAuthorizationUri": - [ - { - "bundleName": "ohos.global.systemres" - }, - { - "bundleName": "com.ohos.camera" - }, - { - "bundleName": "com.ohos.photos" - }, - { - "bundleName": "com.ohos.medialibrary.medialibrarydata" - }, - { - "bundleName": "com.ohos.filepicker" - }, - { - "processName": "foundation" - }, - { - "processName": "wallpaper_service" - }, - { - "processName": "distributeddata" - }, - { - "processName": "pasteboard_service" - } - ] -} \ No newline at end of file diff --git a/services/abilitymgr/src/ability_app_state_observer.cpp b/services/abilitymgr/src/ability_app_state_observer.cpp deleted file mode 100644 index 866af1664c..0000000000 --- a/services/abilitymgr/src/ability_app_state_observer.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2023-2024 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 "ability_app_state_observer.h" -#include "ability_record.h" -#include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" - -namespace OHOS { -namespace AAFwk { -AbilityAppStateObserver::AbilityAppStateObserver(std::shared_ptr abilityRecord) - : abilityRecord_(abilityRecord) {} -void AbilityAppStateObserver::OnProcessDied(const AppExecFwk::ProcessData &processData) -{ - auto abilityRecord = abilityRecord_.lock(); - if (abilityRecord) { - const auto &abilityInfo = abilityRecord->GetAbilityInfo(); - if (abilityInfo.bundleName == processData.bundleName && - processData.processType == AppExecFwk::ProcessType::NORMAL && - abilityInfo.type == AppExecFwk::AbilityType::PAGE) { - abilityRecord->OnProcessDied(); - } - if (abilityRecord->IsSceneBoard() && abilityRecord->GetPid() == processData.pid) { - abilityRecord->OnProcessDied(); - } - } else { - TAG_LOGW(AAFwkTag::ABILITYMGR, "AbilityRecord null"); - } -} -} // namespace AAFwk -} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/ability_bundle_event_callback.cpp b/services/abilitymgr/src/ability_bundle_event_callback.cpp index 4ce2f38a56..f7874db96f 100644 --- a/services/abilitymgr/src/ability_bundle_event_callback.cpp +++ b/services/abilitymgr/src/ability_bundle_event_callback.cpp @@ -23,7 +23,8 @@ namespace OHOS { namespace AAFwk { namespace { -const std::string KEY_TOKEN = "accessTokenId"; +constexpr const char* KEY_TOKEN = "accessTokenId"; +constexpr const char* KEY_UID = "uid"; } AbilityBundleEventCallback::AbilityBundleEventCallback( std::shared_ptr taskHandler, std::shared_ptr abilityAutoStartupService) diff --git a/services/abilitymgr/src/ability_connect_manager.cpp b/services/abilitymgr/src/ability_connect_manager.cpp index 81b21f7f62..300766cbe6 100644 --- a/services/abilitymgr/src/ability_connect_manager.cpp +++ b/services/abilitymgr/src/ability_connect_manager.cpp @@ -592,6 +592,7 @@ int AbilityConnectManager::UnloadUIExtensionAbility(const std::shared_ptrGetWant().GetElement().GetAbilityName(), abilityRecord->GetWant().GetElement().GetBundleName(), abilityRecord->GetWant().GetElement().GetModuleName(), hostBundleName); @@ -723,10 +724,10 @@ int AbilityConnectManager::DisconnectAbilityLocked(const sptrGetURI(); + TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability: %{public}s", element.c_str()); if (taskHandler_ != nullptr) { int recordId = abilityRecord->GetRecordId(); std::string taskName = std::string("LoadTimeout_") + std::to_string(recordId); @@ -814,13 +817,13 @@ int AbilityConnectManager::AttachAbilityThreadLocked( eventHandler_->RemoveEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecord->GetAbilityRecordId()); } - std::string element = abilityRecord->GetURI(); - TAG_LOGD(AAFwkTag::ABILITYMGR, "Ability: %{public}s", element.c_str()); if (abilityRecord->IsSceneBoard()) { TAG_LOGI(AAFwkTag::ABILITYMGR, "Attach Ability: %{public}s", element.c_str()); sceneBoardTokenId_ = abilityRecord->GetAbilityInfo().applicationInfo.accessTokenId; } abilityRecord->SetScheduler(scheduler); + abilityRecord->RemoveSpecifiedWantParam(UIEXTENSION_ABILITY_ID); + abilityRecord->RemoveSpecifiedWantParam(UIEXTENSION_ROOT_HOST_PID); if (IsUIExtensionAbility(abilityRecord) && !abilityRecord->IsCreateByConnect() && !abilityRecord->GetWant().GetBoolParam(IS_PRELOAD_UIEXTENSION_ABILITY, false)) { DelayedSingleton::GetInstance()->MoveToForeground(token); @@ -1090,7 +1093,7 @@ int AbilityConnectManager::ScheduleCommandAbilityWindowDone( auto abilityRecord = Token::GetAbilityRecordByToken(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); std::string element = abilityRecord->GetURI(); - TAG_LOGD(AAFwkTag::ABILITYMGR, + TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability: %{public}s, persistentId: %{private}d, winCmd: %{public}d, abilityCmd: %{public}d", element.c_str(), sessionInfo->persistentId, winCmd, abilityCmd); @@ -1430,7 +1433,7 @@ void AbilityConnectManager::HandleStartTimeoutTask(const std::shared_ptrGetAbilityInfo().extensionAbilityType)) { if (uiExtensionAbilityRecordMgr_ != nullptr && IsCallerValid(abilityRecord)) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Start load timeout."); + TAG_LOGW(AAFwkTag::ABILITYMGR, "Start load timeout."); uiExtensionAbilityRecordMgr_->LoadTimeout(abilityRecord->GetUIExtensionAbilityId()); } PrintTimeOutLog(abilityRecord, AbilityManagerService::LOAD_TIMEOUT_MSG); diff --git a/services/abilitymgr/src/ability_manager_client.cpp b/services/abilitymgr/src/ability_manager_client.cpp index f161c8a16f..4901db3a80 100644 --- a/services/abilitymgr/src/ability_manager_client.cpp +++ b/services/abilitymgr/src/ability_manager_client.cpp @@ -333,7 +333,7 @@ ErrCode AbilityManagerClient::StartUIExtensionAbility(sptr extensio return abms->StartUIExtensionAbility(extensionSessionInfo, userId); } -ErrCode AbilityManagerClient::StartUIAbilityBySCB(sptr sessionInfo) +ErrCode AbilityManagerClient::StartUIAbilityBySCB(sptr sessionInfo, bool &isColdStart) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (sessionInfo == nullptr) { @@ -344,7 +344,7 @@ ErrCode AbilityManagerClient::StartUIAbilityBySCB(sptr sessionInfo) CHECK_POINTER_RETURN_NOT_CONNECTED(abms); TAG_LOGI(AAFwkTag::ABILITYMGR, "Start UIAbility by SCB: %{public}s.", sessionInfo->want.GetElement().GetURI().c_str()); - return abms->StartUIAbilityBySCB(sessionInfo); + return abms->StartUIAbilityBySCB(sessionInfo, isColdStart); } ErrCode AbilityManagerClient::StopExtensionAbility(const Want &want, sptr callerToken, @@ -1853,5 +1853,13 @@ int32_t AbilityManagerClient::GetAbilityStateByPersistentId(int32_t persistentId CHECK_POINTER_RETURN_INVALID_VALUE(abms); return abms->GetAbilityStateByPersistentId(persistentId, state); } + +int32_t AbilityManagerClient::TransferAbilityResultForExtension(const sptr &callerToken, + int32_t resultCode, const Want &want) +{ + auto abms = GetAbilityManager(); + CHECK_POINTER_RETURN_INVALID_VALUE(abms); + return abms->TransferAbilityResultForExtension(callerToken, resultCode, want); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_proxy.cpp b/services/abilitymgr/src/ability_manager_proxy.cpp index 37058440a1..8c51d6a2b8 100644 --- a/services/abilitymgr/src/ability_manager_proxy.cpp +++ b/services/abilitymgr/src/ability_manager_proxy.cpp @@ -22,7 +22,6 @@ #include "ability_connect_callback_proxy.h" #include "ability_connect_callback_stub.h" #include "ability_manager_errors.h" -#include "ability_scheduler_proxy.h" #include "ability_scheduler_stub.h" #include "ability_util.h" #include "appexecfwk_errors.h" @@ -656,12 +655,12 @@ int AbilityManagerProxy::PreloadUIExtensionAbility(const Want &want, std::string } PROXY_WRITE_PARCEL_AND_RETURN_IF_FAIL(data, Parcelable, &want); - + if (!data.WriteString16(Str8ToStr16(hostBundleName))) { TAG_LOGE(AAFwkTag::ABILITYMGR, "hostBundleName write failed."); return ERR_INVALID_VALUE; } - + PROXY_WRITE_PARCEL_AND_RETURN_IF_FAIL(data, Int32, userId); int error; MessageParcel reply; @@ -759,7 +758,7 @@ int AbilityManagerProxy::StartUIExtensionAbility(const sptr &extens return reply.ReadInt32(); } -int AbilityManagerProxy::StartUIAbilityBySCB(sptr sessionInfo) +int AbilityManagerProxy::StartUIAbilityBySCB(sptr sessionInfo, bool &isColdStart) { MessageParcel data; MessageParcel reply; @@ -783,6 +782,7 @@ int AbilityManagerProxy::StartUIAbilityBySCB(sptr sessionInfo) TAG_LOGE(AAFwkTag::ABILITYMGR, "Send request error: %{public}d", error); return error; } + isColdStart = reply.ReadBool(); return reply.ReadInt32(); } @@ -5225,5 +5225,35 @@ int32_t AbilityManagerProxy::GetAbilityStateByPersistentId(int32_t persistentId, state = reply.ReadBool(); return NO_ERROR; } + + +int32_t AbilityManagerProxy::TransferAbilityResultForExtension(const sptr &callerToken, + int32_t resultCode, const Want &want) +{ + if (callerToken == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken is nullptr"); + return INNER_ERR; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return IPC_PROXY_ERR; + } + if (!data.WriteRemoteObject(callerToken) || !data.WriteInt32(resultCode)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken or resultCode write failed."); + return INNER_ERR; + } + if (!data.WriteParcelable(&want)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "want write failed."); + return INNER_ERR; + } + auto error = SendRequest(AbilityManagerInterfaceCode::TRANSFER_ABILITY_RESULT, data, reply, option); + if (error != NO_ERROR) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Send request error: %{public}d", error); + return error; + } + return NO_ERROR; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp index 5769f93ce8..43e199e200 100644 --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -54,6 +54,7 @@ #include "errors.h" #include "extension_config.h" #include "freeze_util.h" +#include "global_constant.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" #include "hisysevent.h" @@ -86,11 +87,13 @@ #include "restart_app_manager.h" #include "sa_mgr_client.h" #include "scene_board_judgement.h" +#include "server_constant.h" #include "session_info.h" #include "softbus_bus_center.h" #include "start_ability_handler/start_ability_sandbox_savefile.h" #include "start_options.h" #include "start_ability_utils.h" +#include "startup_util.h" #include "status_bar_delegate_interface.h" #include "string_ex.h" #include "string_wrapper.h" @@ -108,6 +111,7 @@ #include "application_anr_listener.h" #include "input_manager.h" #include "ability_first_frame_state_observer_manager.h" +#include "window_focus_changed_listener.h" #endif #ifdef EFFICIENCY_MANAGER_ENABLE @@ -252,7 +256,6 @@ const std::string DMS_API_VERSION = "dmsApiVersion"; const std::string DMS_IS_CALLER_BACKGROUND = "dmsIsCallerBackGround"; const std::string DMS_PROCESS_NAME = "distributedsched"; const std::string DMS_MISSION_ID = "dmsMissionId"; -const std::string DLP_INDEX = "ohos.dlp.params.index"; const std::string BOOTEVENT_APPFWK_READY = "bootevent.appfwk.ready"; const std::string BOOTEVENT_BOOT_COMPLETED = "bootevent.boot.completed"; const std::string BOOTEVENT_BOOT_ANIMATION_STARTED = "bootevent.bootanimation.started"; @@ -423,12 +426,7 @@ bool AbilityManagerService::Init() void AbilityManagerService::InitDeepLinkReserve() { - deepLinkReserveConfig_ = DelayedSingleton::GetInstance(); - if (deepLinkReserveConfig_ == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Get DeepLinkReserveConfig instance is nullptr."); - return; - } - if (!deepLinkReserveConfig_->LoadConfiguration()) { + if (!DeepLinkReserveConfig::GetInstance().LoadConfiguration()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "InitDeepLinkReserve failed."); } } @@ -457,8 +455,6 @@ void AbilityManagerService::InitPushTask() TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler_ is nullptr."); return; } - auto startResidentAppsTask = [aams = shared_from_this()]() { aams->StartResidentApps(); }; - taskHandler_->SubmitTask(startResidentAppsTask, "StartResidentApps"); auto initStartupFlagTask = [aams = shared_from_this()]() { aams->InitStartupFlag(); }; taskHandler_->SubmitTask(initStartupFlagTask, "InitStartupFlag"); @@ -589,7 +585,7 @@ int32_t AbilityManagerService::StartAbilityByFreeInstall(const Want &want, sptr< return ERR_INVALID_CONTINUATION_FLAG; } - TAG_LOGI(AAFwkTag::ABILITYMGR, "Start ability come, ability is %{public}s, userId is %{public}d", + TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability come, ability is %{public}s, userId is %{public}d", want.GetElement().GetAbilityName().c_str(), userId); int32_t ret = StartAbilityWrap(want, callerToken, requestCode, userId); @@ -883,7 +879,7 @@ void AbilityManagerService::SetReserveInfo(const std::string &linkString) } std::string reservedBundleName = ""; - if (deepLinkReserveConfig_->isLinkReserved(linkString, reservedBundleName)) { + if (DeepLinkReserveConfig::GetInstance().isLinkReserved(linkString, reservedBundleName)) { implicitStartProcessor_->SetUriReservedFlag(true); implicitStartProcessor_->SetUriReservedBundle(reservedBundleName); } else { @@ -918,7 +914,6 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptrGetDialogCallerInfo(dialogSessionId) != nullptr) { isSendDialogResult = true; - dialogSessionRecord_->ClearDialogContext(dialogSessionId); } if (callerToken != nullptr && !VerificationAllToken(callerToken) && !isSendDialogResult) { auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()-> @@ -934,7 +929,7 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptr(abilityInfo.applicationInfo.singleton)); + if ((isSendDialogResult && want.GetBoolParam("isSelector", false))) { + isImplicit = true; + } result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller, abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, isImplicit); if (result != AppExecFwk::Constants::PERMISSION_GRANTED) { @@ -1230,7 +1228,7 @@ int AbilityManagerService::StartAbilityDetails(const Want &want, const AbilitySt int32_t oriValidUserId = GetValidUserId(userId); int32_t validUserId = oriValidUserId; StartAbilityInfoWrap threadLocalInfo(want, validUserId, - StartAbilityUtils::GetAppIndex(want, callerToken)); + StartAbilityUtils::GetAppIndex(want, callerToken), callerToken); AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(), true, nullptr); result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE : @@ -1387,7 +1385,7 @@ int AbilityManagerService::ImplicitStartAbility(const Want &want, const StartOpt { TAG_LOGD(AAFwkTag::ABILITYMGR, "Implicit Start ability with startOptions."); AbilityUtil::RemoveShowModeKey(const_cast(want)); - return StartUIAbilityForOptionWrap(want, startOptions, callerToken, userId, requestCode, true); + return StartUIAbilityForOptionWrap(want, startOptions, callerToken, userId, requestCode, 0, true); } int AbilityManagerService::StartUIAbilityForOptionWrap(const Want &want, const StartOptions &options, @@ -1510,7 +1508,7 @@ int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const St int32_t oriValidUserId = GetValidUserId(userId); int32_t validUserId = oriValidUserId; StartAbilityInfoWrap threadLocalInfo(want, validUserId, - StartAbilityUtils::GetAppIndex(want, callerToken)); + StartAbilityUtils::GetAppIndex(want, callerToken), callerToken); AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(), true, nullptr); auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE : @@ -1566,10 +1564,10 @@ int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const St abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_TOP, startOptions.GetWindowTop()); } if (startOptions.windowWidthUsed_) { - abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_HEIGHT, startOptions.GetWindowWidth()); + abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_WIDTH, startOptions.GetWindowWidth()); } if (startOptions.windowHeightUsed_) { - abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_WIDTH, startOptions.GetWindowHeight()); + abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_HEIGHT, startOptions.GetWindowHeight()); } bool withAnimation = startOptions.GetWithAnimation(); auto abilityRecord = Token::GetAbilityRecordByToken(callerToken); @@ -1691,8 +1689,11 @@ int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const St } if (PermissionVerification::GetInstance()->IsSystemAppCall()) { - bool windowFocused = startOptions.GetWindowFocused(); - abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_FOCUSED, windowFocused); + bool focused = abilityRequest.want.GetBoolParam(Want::PARAM_RESV_WINDOW_FOCUSED, true); + if (focused) { + bool windowfocused = startOptions.GetWindowFocused(); + abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_FOCUSED, windowfocused); + } } else { abilityRequest.want.RemoveParam(Want::PARAM_RESV_WINDOW_FOCUSED); } @@ -1890,7 +1891,7 @@ int32_t AbilityManagerService::OpenAtomicService(AAFwk::Want& want, const StartO return StartUIAbilityForOptionWrap(want, options, callerToken, userId, requestCode); } -int AbilityManagerService::StartUIAbilityBySCB(sptr sessionInfo) +int AbilityManagerService::StartUIAbilityBySCB(sptr sessionInfo, bool &isColdStart) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "Call."); @@ -1915,7 +1916,7 @@ int AbilityManagerService::StartUIAbilityBySCB(sptr sessionInfo) auto requestCode = sessionInfo->requestCode; StartAbilityInfoWrap threadLocalInfo(sessionInfo->want, currentUserId, - StartAbilityUtils::GetAppIndex(sessionInfo->want, sessionInfo->callerToken)); + StartAbilityUtils::GetAppIndex(sessionInfo->want, sessionInfo->callerToken), sessionInfo->callerToken); if (sessionInfo->want.GetBoolParam(IS_CALL_BY_SCB, true)) { TAG_LOGD(AAFwkTag::ABILITYMGR, "interceptorExecuter_ called."); AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(sessionInfo->want, requestCode, @@ -1984,7 +1985,7 @@ int AbilityManagerService::StartUIAbilityBySCB(sptr sessionInfo) ResourceSchedule::ResType::AssociatedStartType::SCB_START_ABILITY), sessionInfo->callerToken); auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid()); CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE); - return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo); + return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, isColdStart); } bool AbilityManagerService::CheckCallingTokenId(const std::string &bundleName, int32_t userId) @@ -2261,7 +2262,13 @@ void AbilityManagerService::UnSubscribeBackgroundTask() void AbilityManagerService::SubscribeBundleEventCallback() { - TAG_LOGD(AAFwkTag::ABILITYMGR, "SubscribeBundleEventCallback to receive hap updates."); + TAG_LOGI(AAFwkTag::ABILITYMGR, "SubscribeBundleEventCallback begin."); + if (taskHandler_) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "submit StartResidentApps task."); + auto startResidentAppsTask = [aams = shared_from_this()]() { aams->StartResidentApps(); }; + taskHandler_->SubmitTask(startResidentAppsTask, "StartResidentApps"); + } + if (abilityBundleEventCallback_) { return; } @@ -2430,6 +2437,12 @@ int AbilityManagerService::PreloadUIExtensionAbilityInner(const Want &want, std: return result; } abilityRequest.want.SetParam(IS_PRELOAD_UIEXTENSION_ABILITY, true); + auto abilityInfo = abilityRequest.abilityInfo; + auto res = JudgeAbilityVisibleControl(abilityInfo); + if (res != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Target ability is invisible"); + return res; + } auto connectManager = GetConnectManagerByUserId(validUserId); if (connectManager == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: %{public}d", validUserId); @@ -2443,6 +2456,10 @@ int AbilityManagerService::UnloadUIExtensionAbility(const std::shared_ptrGetToken()); + if (connectManager == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr."); + return ERR_INVALID_VALUE; + } return connectManager->UnloadUIExtensionAbility(abilityRecord, hostBundleName); } @@ -2543,7 +2560,7 @@ int AbilityManagerService::StartExtensionAbilityInner(const Want &want, const sp int32_t validUserId = GetValidUserId(userId); StartAbilityInfoWrap threadLocalInfo(want, validUserId, - StartAbilityUtils::GetAppIndex(want, callerToken), true); + StartAbilityUtils::GetAppIndex(want, callerToken), callerToken, true); AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr); result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE : interceptorExecuter_->DoProcess(interceptorParam); @@ -2738,6 +2755,7 @@ int AbilityManagerService::StartUIExtensionAbility(const sptr &exte } extensionSessionInfo->want.SetElementName(bundleInfo.name, bundleInfo.abilityInfos.begin()->name); } + extensionSessionInfo->want.SetParam("send_to_erms_embedded", 1); } std::string extensionTypeStr = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY); AppExecFwk::ExtensionAbilityType extensionType = extensionTypeStr.empty() ? @@ -2829,7 +2847,7 @@ int AbilityManagerService::StartUIExtensionAbility(const sptr &exte TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d", validUserId, static_cast(abilityInfo.applicationInfo.singleton)); - result = CheckOptExtensionAbility(extensionSessionInfo->want, abilityRequest, validUserId, extensionType); + result = CheckOptExtensionAbility(extensionSessionInfo->want, abilityRequest, validUserId, extensionType, true); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckOptExtensionAbility error."); eventInfo.errCode = result; @@ -3231,11 +3249,11 @@ int AbilityManagerService::CloseUIAbilityBySCB(const sptr &sessionI EventInfo eventInfo; eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName; eventInfo.abilityName = abilityRecord->GetAbilityInfo().name; - SendAbilityEvent(EventName::CLOSE_UI_ABILITY_BY_SCB, HiSysEventType::BEHAVIOR, eventInfo); + SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo); eventInfo.errCode = uiAbilityManager->CloseUIAbility(abilityRecord, sessionInfo->resultCode, &(sessionInfo->want), sessionInfo->isClearSession); if (eventInfo.errCode != ERR_OK) { - SendAbilityEvent(EventName::CLOSE_UI_ABILITY_BY_SCB_ERROR, HiSysEventType::FAULT, eventInfo); + SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo); } return eventInfo.errCode; } @@ -3922,9 +3940,9 @@ int AbilityManagerService::StartContinuation(const Want &want, const sptr& int32_t AbilityManagerService::GetMissionIdByToken(const sptr &token) { - TAG_LOGI(AAFwkTag::ABILITYMGR, "request GetMissionIdByToken."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "request GetMissionIdByToken."); auto abilityRecord = Token::GetAbilityRecordByToken(token); if (!abilityRecord) { TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is null."); @@ -5405,7 +5423,7 @@ int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptr &token) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGI(AAFwkTag::ABILITYMGR, "Schedule command ability done."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "Schedule command ability done."); if (!VerificationAllToken(token)) { return ERR_INVALID_VALUE; } @@ -5617,9 +5635,9 @@ int AbilityManagerService::GenerateAbilityRequest( { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto abilityRecord = Token::GetAbilityRecordByToken(callerToken); - if (abilityRecord && abilityRecord->GetAppIndex() != 0 && + if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX && abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) { - (const_cast(want)).SetParam(DLP_INDEX, abilityRecord->GetAppIndex()); + (const_cast(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex()); } if (abilityRecord != nullptr) { @@ -5633,11 +5651,12 @@ int AbilityManagerService::GenerateAbilityRequest( auto abilityInfo = StartAbilityUtils::startAbilityInfo; if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) { - abilityInfo = StartAbilityInfo::CreateStartAbilityInfo(want, userId, want.GetIntParam(DLP_INDEX, 0)); + abilityInfo = StartAbilityInfo::CreateStartAbilityInfo(want, userId, + AbilityRuntime::StartupUtil::GetAppIndex(want)); } CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED); - if (abilityInfo->status == RESOLVE_ABILITY_ERR) { - return RESOLVE_ABILITY_ERR; + if (abilityInfo->status != ERR_OK) { + return abilityInfo->status; } request.abilityInfo = abilityInfo->abilityInfo; request.extensionProcessMode = abilityInfo->extensionProcessMode; @@ -5688,9 +5707,9 @@ int AbilityManagerService::GenerateExtensionAbilityRequest( const Want &want, AbilityRequest &request, const sptr &callerToken, int32_t userId) { auto abilityRecord = Token::GetAbilityRecordByToken(callerToken); - if (abilityRecord && abilityRecord->GetAppIndex() != 0 && + if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX && abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) { - (const_cast(want)).SetParam(DLP_INDEX, abilityRecord->GetAppIndex()); + (const_cast(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex()); } request.want = want; request.callerToken = callerToken; @@ -5698,11 +5717,12 @@ int AbilityManagerService::GenerateExtensionAbilityRequest( auto abilityInfo = StartAbilityUtils::startAbilityInfo; if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) { - abilityInfo = StartAbilityInfo::CreateStartExtensionInfo(want, userId, want.GetIntParam(DLP_INDEX, 0)); + abilityInfo = StartAbilityInfo::CreateStartExtensionInfo(want, userId, + AbilityRuntime::StartupUtil::GetAppIndex(want)); } CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED); - if (abilityInfo->status == RESOLVE_ABILITY_ERR) { - return RESOLVE_ABILITY_ERR; + if (abilityInfo->status != ERR_OK) { + return abilityInfo->status; } auto result = InitialAbilityRequest(request, *abilityInfo); @@ -5965,7 +5985,7 @@ int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName void AbilityManagerService::PreLoadAppDataAbilitiesTask(const std::string &bundleName, const int32_t userId) { - TAG_LOGI(AAFwkTag::ABILITYMGR, "called"); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto dataAbilityManager = GetDataAbilityManagerByUserId(userId); if (dataAbilityManager == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid data ability manager when app data abilities preloading."); @@ -6611,7 +6631,7 @@ int AbilityManagerService::StartAbilityByCall(const Want &want, const sptr(want)); StartAbilityInfoWrap threadLocalInfo(want, GetUserId(), - StartAbilityUtils::GetAppIndex(want, callerToken)); + StartAbilityUtils::GetAppIndex(want, callerToken), callerToken); AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), true, nullptr); auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE : interceptorExecuter_->DoProcess(interceptorParam); @@ -6808,13 +6828,13 @@ int AbilityManagerService::LogoutUser(int32_t userId) } void AbilityManagerService::OnAcceptWantResponse( - const AAFwk::Want &want, const std::string &flag) + const AAFwk::Want &want, const std::string &flag, int32_t requestId) { TAG_LOGD(AAFwkTag::ABILITYMGR, "On accept want response"); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { auto uiAbilityManager = GetCurrentUIAbilityManager(); CHECK_POINTER(uiAbilityManager); - uiAbilityManager->OnAcceptWantResponse(want, flag); + uiAbilityManager->OnAcceptWantResponse(want, flag, requestId); return; } auto missionListManager = GetCurrentMissionListManager(); @@ -6824,13 +6844,13 @@ void AbilityManagerService::OnAcceptWantResponse( missionListManager->OnAcceptWantResponse(want, flag); } -void AbilityManagerService::OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want) +void AbilityManagerService::OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want, int32_t requestId) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s called.", __func__); + TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s.", want.GetElement().GetURI().c_str()); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { auto uiAbilityManager = GetCurrentUIAbilityManager(); CHECK_POINTER(uiAbilityManager); - uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want); + uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId); return; } auto missionListManager = GetCurrentMissionListManager(); @@ -6840,24 +6860,25 @@ void AbilityManagerService::OnStartSpecifiedAbilityTimeoutResponse(const AAFwk:: missionListManager->OnStartSpecifiedAbilityTimeoutResponse(want); } -void AbilityManagerService::OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag) +void AbilityManagerService::OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag, + int32_t requestId) { TAG_LOGD(AAFwkTag::ABILITYMGR, "flag = %{public}s", flag.c_str()); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { auto uiAbilityManager = GetCurrentUIAbilityManager(); CHECK_POINTER(uiAbilityManager); - uiAbilityManager->OnStartSpecifiedProcessResponse(want, flag); + uiAbilityManager->OnStartSpecifiedProcessResponse(want, flag, requestId); return; } } -void AbilityManagerService::OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want) +void AbilityManagerService::OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want, int32_t requestId) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s called.", __func__); + TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s.", want.GetElement().GetURI().c_str()); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { auto uiAbilityManager = GetCurrentUIAbilityManager(); CHECK_POINTER(uiAbilityManager); - uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want); + uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId); return; } } @@ -7747,6 +7768,60 @@ int AbilityManagerService::ForceTimeoutForTest(const std::string &abilityName, c } #endif +int AbilityManagerService::CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo &abilityInfo, + uint32_t tokenId) +{ + if (abilityInfo.permissions.empty() || AccessTokenKit::VerifyAccessToken(tokenId, + PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == ERR_OK) { + return AppExecFwk::Constants::PERMISSION_GRANTED; + } + + for (auto permission : abilityInfo.permissions) { + if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) != + AppExecFwk::Constants::PERMISSION_GRANTED) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, Ability permission: %{public}s", + permission.c_str()); + return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; + } + } + + return AppExecFwk::Constants::PERMISSION_GRANTED; +} + +bool AbilityManagerService::CheckOneSkillPermission(const AppExecFwk::Skill &skill, uint32_t tokenId) +{ + for (auto permission : skill.permissions) { + if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) != + AppExecFwk::Constants::PERMISSION_GRANTED) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, Skill permission: %{public}s", + permission.c_str()); + return false; + } + } + + return true; +} + +int AbilityManagerService::CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest &abilityRequest, + uint32_t tokenId) +{ + auto abilityInfo = abilityRequest.abilityInfo; + auto resultAbilityPermission = CheckStaticCfgPermissionForAbility(abilityInfo, tokenId); + if (resultAbilityPermission != AppExecFwk::Constants::PERMISSION_GRANTED) { + return resultAbilityPermission; + } + + if (abilityInfo.skills.empty()) { + return AppExecFwk::Constants::PERMISSION_GRANTED; + } + for (auto skill : abilityInfo.skills) { + if (skill.Match(abilityRequest.want) && CheckOneSkillPermission(skill, tokenId)) { + return AppExecFwk::Constants::PERMISSION_GRANTED; + } + } + return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; +} + int AbilityManagerService::CheckStaticCfgPermission(const AppExecFwk::AbilityRequest &abilityRequest, bool isStartAsCaller, uint32_t callerTokenId, bool isData, bool isSaCall, bool isImplicit) { @@ -7799,49 +7874,10 @@ int AbilityManagerService::CheckStaticCfgPermission(const AppExecFwk::AbilityReq } } - // verify permission if 'permission' is not empty if (!isImplicit) { - if (abilityInfo.permissions.empty() || AccessTokenKit::VerifyAccessToken(tokenId, - PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == ERR_OK) { - return AppExecFwk::Constants::PERMISSION_GRANTED; - } - } else { - if (abilityInfo.skills.empty()) { - return AppExecFwk::Constants::PERMISSION_GRANTED; - } + return CheckStaticCfgPermissionForAbility(abilityInfo, tokenId); } - - if (isImplicit) { - auto myskills = abilityInfo.skills; - for (auto skill : myskills) { - bool isSkillCheckOK = true; - if (skill.Match(abilityRequest.want)) { - for (auto permission : skill.permissions) { - if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) != - AppExecFwk::Constants::PERMISSION_GRANTED) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, permission: %{public}s", - permission.c_str()); - isSkillCheckOK = false; - break; - } - } - if (isSkillCheckOK) { - return AppExecFwk::Constants::PERMISSION_GRANTED; - } - } - } - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; - } else { - for (auto permission : abilityInfo.permissions) { - if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) != - AppExecFwk::Constants::PERMISSION_GRANTED) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, permission: %{public}s", permission.c_str()); - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; - } - } - } - - return AppExecFwk::Constants::PERMISSION_GRANTED; + return CheckStaticCfgPermissionForSkill(abilityRequest, tokenId); } bool AbilityManagerService::IsNeedTimeoutForTest(const std::string &abilityName, const std::string &state) const @@ -8617,6 +8653,7 @@ int AbilityManagerService::CheckCallOtherExtensionPermission(const AbilityReques return ERR_OK; } if (extensionType == AppExecFwk::ExtensionAbilityType::WINDOW) { + CHECK_CALLER_IS_SYSTEM_APP; return ERR_OK; } if (extensionType == AppExecFwk::ExtensionAbilityType::ADS_SERVICE) { @@ -8772,7 +8809,11 @@ int AbilityManagerService::IsCallFromBackground(const AbilityRequest &abilityReq return ERR_OK; } auto abilityState = callerAbility->GetAbilityState(); - if (abilityState == AbilityState::BACKGROUND || abilityState == AbilityState::BACKGROUNDING) { + if (abilityState == AbilityState::BACKGROUND || abilityState == AbilityState::BACKGROUNDING || + // If uiability or uiextensionability ability state is foreground when terminate, + // it will move to background firstly. So if startAbility in onBackground() lifecycle, + // the actual ability state may be had changed to terminating from background or backgrounding. + abilityState == AbilityState::TERMINATING) { return ERR_OK; } } else { @@ -9437,11 +9478,11 @@ int32_t AbilityManagerService::CheckProcessOptions(const Want &want, const Start { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (startOptions.processOptions == nullptr || - !ProcessOptions::IsNewProcessMode(startOptions.processOptions->processMode)) { + !ProcessOptions::IsValidProcessMode(startOptions.processOptions->processMode)) { return ERR_OK; } - TAG_LOGD(AAFwkTag::ABILITYMGR, "start ability in new process mode."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "start ability with process options."); bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions(); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Not support process options."); @@ -9462,9 +9503,9 @@ int32_t AbilityManagerService::CheckProcessOptions(const Want &want, const Start auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid()); CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE); - if (startOptions.processOptions->processMode == ProcessMode::NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM && + if (ProcessOptions::IsAttachToStatusBarMode(startOptions.processOptions->processMode) && !uiAbilityManager->IsCallerInStatusBar()) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller is not in status bar in NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM mode."); + TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller is not in status bar in attch to status bar mode."); return ERR_START_OPTIONS_CHECK_FAILED; } @@ -9828,10 +9869,25 @@ void AbilityManagerService::NotifyStartResidentProcess(std::vector> &abilityTokens) +{ + std::shared_ptr abilityRecord; + for (auto &token : abilityTokens) { + abilityRecord = Token::GetAbilityRecordByToken(token); + if (abilityRecord == nullptr) { + continue; + } + TAG_LOGI(AAFwkTag::ABILITYMGR, "App OnRemoteDied, ability is %{public}s, app is %{public}s", + abilityRecord->GetAbilityInfo().name.c_str(), abilityRecord->GetAbilityInfo().bundleName.c_str()); + abilityRecord->OnProcessDied(); + } +} + int32_t AbilityManagerService::OpenFile(const Uri& uri, uint32_t flag) { auto accessTokenId = IPCSkeleton::GetCallingTokenID(); - if (!AAFwk::UriPermissionManagerClient::GetInstance().VerifyUriPermission(uri, flag, accessTokenId)) { + if (!IN_PROCESS_CALL(AAFwk::UriPermissionManagerClient::GetInstance().VerifyUriPermission( + uri, flag, accessTokenId))) { TAG_LOGE(AAFwkTag::ABILITYMGR, "premission check failed"); return -1; } @@ -9930,6 +9986,9 @@ int AbilityManagerService::SendDialogResult(const Want &want, const std::string sptr callerToken = dialogCallerInfo->callerToken; int ret = StartAbilityAsCaller(targetWant, callerToken, nullptr, dialogCallerInfo->userId, dialogCallerInfo->requestCode, true); + if (ret == ERR_OK) { + dialogSessionRecord_->ClearDialogContext(dialogSessionId); + } return ret; } @@ -10064,10 +10123,10 @@ int32_t AbilityManagerService::RequestAssertFaultDialog( uint64_t assertFaultSessionId = reinterpret_cast(remoteCallback.GetRefPtr()); want.SetParam(Want::PARAM_ASSERT_FAULT_SESSION_ID, std::to_string(assertFaultSessionId)); want.SetParam(ASSERT_FAULT_DETAIL, wantParams.GetStringParam(ASSERT_FAULT_DETAIL)); - auto connection = std::make_shared(); + auto &connection = AbilityRuntime::ModalSystemAssertUIExtension::GetInstance(); want.SetParam(UIEXTENSION_MODAL_TYPE, 1); - if (connection == nullptr || !IN_PROCESS_CALL(connection->CreateModalUIExtension(want))) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Connection is nullptr or create modal ui extension failed."); + if (!IN_PROCESS_CALL(connection.CreateModalUIExtension(want))) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Create modal ui extension failed."); return ERR_INVALID_VALUE; } auto callbackDeathMgr = DelayedSingleton::GetInstance(); @@ -10282,9 +10341,7 @@ int32_t AbilityManagerService::CheckRestartAppWant(const AAFwk::Want &want) auto bms = GetBundleManager(); CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED); - auto abilityInfoFlag = (AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION | - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION | - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA); + auto abilityInfoFlag = AbilityRuntime::StartupUtil::BuildAbilityInfoFlag(); auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE; AppExecFwk::AbilityInfo abilityInfo; bool queryResult = IN_PROCESS_CALL(bms->QueryAbilityInfo(want, abilityInfoFlag, userId, abilityInfo)); @@ -10411,9 +10468,31 @@ bool AbilityManagerService::ShouldPreventStartAbility(const AbilityRequest &abil } TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceExtension %{public}s.", abilityRecord->GetURI().c_str()); + ReportPreventStartAbilityResult(callerAbilityInfo, abilityInfo); return true; } +void AbilityManagerService::ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo &callerAbilityInfo, + const AppExecFwk::AbilityInfo &abilityInfo) +{ + int32_t callerUid = IPCSkeleton::GetCallingUid(); + int32_t callerPid = IPCSkeleton::GetCallingRealPid(); + int32_t extensionAbilityType = static_cast(abilityInfo.extensionAbilityType); + TAG_LOGD(AAFwkTag::ABILITYMGR, + "Prevent start ability debug log CALLER_BUNDLE_NAME %{public}s CALLEE_BUNDLE_NAME" + "%{public}s ABILITY_NAME %{public}s", + callerAbilityInfo.bundleName.c_str(), abilityInfo.name.c_str(), abilityInfo.name.c_str()); + HiSysEventWrite(HiSysEvent::Domain::AAFWK, "PREVENT_START_ABILITY", HiSysEvent::EventType::BEHAVIOR, + "CALLER_UID", callerUid, + "CALLER_PID", callerPid, + "CALLER_PROCESS_NAME", callerAbilityInfo.process, + "CALLER_BUNDLE_NAME", callerAbilityInfo.bundleName, + "CALLEE_BUNDLE_NAME", abilityInfo.bundleName, + "CALLEE_PROCESS_NAME", abilityInfo.process, + "EXTENSION_ABILITY_TYPE", extensionAbilityType, + "ABILITY_NAME", abilityInfo.name); +} + bool AbilityManagerService::IsInWhiteList(const std::string &callerBundleName, const std::string &calleeBundleName, const std::string &calleeAbilityName) { @@ -10547,5 +10626,25 @@ int32_t AbilityManagerService::GetAbilityStateByPersistentId(int32_t persistentI TAG_LOGE(AAFwkTag::ABILITYMGR, "GetAbilityStateByPersistentId, mission not have persistent id."); return INNER_ERR; } + +int32_t AbilityManagerService::TransferAbilityResultForExtension(const sptr &callerToken, + int32_t resultCode, const Want &want) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + auto token = IPCSkeleton::GetCallingTokenID(); + auto abilityRecord = Token::GetAbilityRecordByToken(callerToken); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + auto type = abilityRecord->GetAbilityInfo().type; + if (type != AppExecFwk::AbilityType::EXTENSION) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "type is not uiextension."); + return ERR_INVALID_VALUE; + } + // save result to caller AbilityRecord. + Want* newWant = const_cast(&want); + newWant->RemoveParam(Want::PARAM_RESV_CALLER_TOKEN); + abilityRecord->SaveResultToCallers(resultCode, newWant); + abilityRecord->SendResultToCallers(); + return ERR_OK; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index a197384b14..da263e672b 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -45,6 +45,7 @@ AbilityManagerStub::AbilityManagerStub() SecondStepInit(); ThirdStepInit(); FourthStepInit(); + FifthStepInit(); } AbilityManagerStub::~AbilityManagerStub() @@ -439,6 +440,12 @@ void AbilityManagerStub::FourthStepInit() &AbilityManagerStub::GetAbilityStateByPersistentIdInner; } +void AbilityManagerStub::FifthStepInit() +{ + requestFuncMap_[static_cast(AbilityManagerInterfaceCode::TRANSFER_ABILITY_RESULT)] = + &AbilityManagerStub::TransferAbilityResultForExtensionInner; +} + int AbilityManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Received code : %{public}d", code); @@ -1481,13 +1488,13 @@ int AbilityManagerStub::ContinueMissionOfBundleNameInner(MessageParcel &data, Me return ERR_NULL_OBJECT; } std::unique_ptr wantParams(data.ReadParcelable()); - continueMissionInfo.wantParams = *wantParams; - continueMissionInfo.srcBundleName = data.ReadString(); - continueMissionInfo.continueType = data.ReadString(); if (wantParams == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "ContinueMissionInner wantParams readParcelable failed!"); return ERR_NULL_OBJECT; } + continueMissionInfo.wantParams = *wantParams; + continueMissionInfo.srcBundleName = data.ReadString(); + continueMissionInfo.continueType = data.ReadString(); int32_t result = ContinueMission(continueMissionInfo, callback); TAG_LOGI(AAFwkTag::ABILITYMGR, "ContinueMissionInner result = %{public}d", result); return result; @@ -1498,8 +1505,8 @@ int AbilityManagerStub::ContinueAbilityInner(MessageParcel &data, MessageParcel std::string deviceId = data.ReadString(); int32_t missionId = data.ReadInt32(); uint32_t versionCode = data.ReadUint32(); + AAFWK::ContinueRadar::GetInstance().SaveDataContinue("ContinueAbility"); int32_t result = ContinueAbility(deviceId, missionId, versionCode); - AAFWK::ContinueRadar::GetInstance().SaveDataContinue("ContinueAbility", result); TAG_LOGI(AAFwkTag::ABILITYMGR, "ContinueAbilityInner result = %{public}d", result); return result; } @@ -1774,7 +1781,9 @@ int AbilityManagerStub::StartUIAbilityBySCBInner(MessageParcel &data, MessagePar if (data.ReadBool()) { sessionInfo = data.ReadParcelable(); } - int32_t result = StartUIAbilityBySCB(sessionInfo); + bool isColdStart = false; + int32_t result = StartUIAbilityBySCB(sessionInfo, isColdStart); + reply.WriteBool(isColdStart); reply.WriteInt32(result); return NO_ERROR; } @@ -3415,5 +3424,15 @@ int32_t AbilityManagerStub::GetAbilityStateByPersistentIdInner(MessageParcel &da } return result; } + +int32_t AbilityManagerStub::TransferAbilityResultForExtensionInner(MessageParcel &data, MessageParcel &reply) +{ + sptr callerToken = data.ReadRemoteObject(); + int32_t resultCode = data.ReadInt32(); + sptr want = data.ReadParcelable(); + int32_t result = TransferAbilityResultForExtension(callerToken, resultCode, *want); + reply.WriteInt32(result); + return NO_ERROR; +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/ability_record.cpp b/services/abilitymgr/src/ability_record.cpp index 59da2ec847..820462fe99 100644 --- a/services/abilitymgr/src/ability_record.cpp +++ b/services/abilitymgr/src/ability_record.cpp @@ -21,7 +21,6 @@ #include #include "constants.h" -#include "ability_app_state_observer.h" #include "ability_event_handler.h" #include "ability_manager_service.h" #include "ability_resident_process_rdb.h" @@ -35,6 +34,7 @@ #include "configuration_convertor.h" #include "connection_state_manager.h" #include "freeze_util.h" +#include "global_constant.h" #include "hitrace_meter.h" #include "image_source.h" #include "in_process_call_wrapper.h" @@ -47,6 +47,8 @@ #include "parameters.h" #include "ui_extension_host_info.h" #include "scene_board_judgement.h" +#include "start_ability_utils.h" +#include "startup_util.h" #include "system_ability_token_callback.h" #include "ui_extension_utils.h" #include "uri_permission_manager_client.h" @@ -77,7 +79,6 @@ const std::string DMS_SRC_NETWORK_ID = "dmsSrcNetworkId"; const std::string ABILITY_OWNER_USERID = "AbilityMS_Owner_UserId"; const std::u16string SYSTEM_ABILITY_TOKEN_CALLBACK = u"ohos.aafwk.ISystemAbilityTokenCallback"; const std::string SHOW_ON_LOCK_SCREEN = "ShowOnLockScreen"; -const std::string DLP_INDEX = "ohos.dlp.params.index"; const std::string DLP_BUNDLE_NAME = "com.ohos.dlpmanager"; const std::string COMPONENT_STARTUP_NEW_RULES = "component.startup.newRules"; const std::string KEY_MISSION_ID = "ohos.anco.param.missionId"; @@ -199,9 +200,12 @@ std::shared_ptr Token::GetAbilityRecordByToken(const sptr theToken = iface_cast(token); if (!theToken) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Input token iface_cast error."); return nullptr; } - if (theToken->GetDescriptor() != u"ohos.aafwk.AbilityToken") { + std::u16string castDescriptor = theToken->GetDescriptor(); + if (castDescriptor != u"ohos.aafwk.AbilityToken") { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Input token iface_cast error:%{public}s.", Str16ToStr8(castDescriptor).c_str()); return nullptr; } @@ -226,7 +230,6 @@ AbilityRecord::AbilityRecord(const Want &want, const AppExecFwk::AbilityInfo &ab want_.SetParam(COMPONENT_STARTUP_NEW_RULES, flag); } restartCount_ = restartMax_; - appIndex_ = want.GetIntParam(DLP_INDEX, 0); isAppAutoStartup_ = want_.GetBoolParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON, false); if (want_.HasParameter(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON)) { want_.RemoveParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON); @@ -242,7 +245,6 @@ AbilityRecord::~AbilityRecord() } } want_.CloseAllFd(); - RemoveAppStateObserver(true); } std::shared_ptr AbilityRecord::CreateAbilityRecord(const AbilityRequest &abilityRequest) @@ -251,7 +253,7 @@ std::shared_ptr AbilityRecord::CreateAbilityRecord(const AbilityR abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); CHECK_POINTER_AND_RETURN(abilityRecord, nullptr); abilityRecord->SetUid(abilityRequest.uid); - abilityRecord->SetAppIndex(abilityRequest.want.GetIntParam(DLP_INDEX, 0)); + abilityRecord->SetAppIndex(AbilityRuntime::StartupUtil::GetAppIndex(abilityRequest.want)); abilityRecord->SetCallerAccessTokenId(abilityRequest.callerAccessTokenId); abilityRecord->sessionInfo_ = abilityRequest.sessionInfo; if (!abilityRecord->Init()) { @@ -269,31 +271,9 @@ std::shared_ptr AbilityRecord::CreateAbilityRecord(const AbilityR abilityRecord->collaboratorType_ = abilityRequest.collaboratorType; abilityRecord->missionAffinity_ = abilityRequest.want.GetStringParam(PARAM_MISSION_AFFINITY_KEY); - if (abilityRecord->IsDebug() || abilityRecord->IsSceneBoard()) { - abilityRecord->abilityAppStateObserver_ = sptr( - new AbilityAppStateObserver(abilityRecord)); - DelayedSingleton::GetInstance()->RegisterApplicationStateObserver( - abilityRecord->abilityAppStateObserver_, {abilityRequest.abilityInfo.bundleName}); - } return abilityRecord; } -void AbilityRecord::RemoveAppStateObserver(bool force) -{ - if (!force && IsSceneBoard()) { - TAG_LOGI(AAFwkTag::ABILITYMGR, "Special ability no need to RemoveAppStateObserver."); - return; - } - auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); - if (handler && abilityAppStateObserver_) { - handler->SubmitTask([appStateObserver = abilityAppStateObserver_]() { - DelayedSingleton::GetInstance()->UnregisterApplicationStateObserver( - appStateObserver); - }); - abilityAppStateObserver_ = nullptr; - } -} - bool AbilityRecord::Init() { lifecycleDeal_ = std::make_unique(); @@ -432,14 +412,6 @@ void AbilityRecord::ForegroundAbility(uint32_t sceneFlag) TAG_LOGI(AAFwkTag::ABILITYMGR, "ForegroundLifecycle: name:%{public}s.", abilityInfo_.name.c_str()); CHECK_POINTER(lifecycleDeal_); - if (!IsDebug()) { - int foregroundTimeout = - AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * FOREGROUND_TIMEOUT_MULTIPLE; - SendEvent(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, foregroundTimeout / HALF_TIMEOUT); - std::string methodName = "ForegroundAbility"; - g_addLifecycleEventTask(token_, FreezeUtil::TimeoutState::FOREGROUND, methodName); - } - // schedule active after updating AbilityState and sending timeout message to avoid ability async callback // earlier than above actions SetAbilityStateInner(AbilityState::FOREGROUNDING); @@ -519,6 +491,9 @@ void AbilityRecord::ProcessForegroundAbility(uint32_t tokenId, uint32_t sceneFla } if (isReady_) { + if (!IsDebug()) { + PostForegroundTimeoutTask(); + } if (IsAbilityState(AbilityState::FOREGROUND)) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Activate %{public}s", element.c_str()); ForegroundAbility(sceneFlag); @@ -541,6 +516,15 @@ void AbilityRecord::ProcessForegroundAbility(uint32_t tokenId, uint32_t sceneFla } } +void AbilityRecord::PostForegroundTimeoutTask() +{ + int foregroundTimeout = + AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * FOREGROUND_TIMEOUT_MULTIPLE; + SendEvent(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, foregroundTimeout / HALF_TIMEOUT); + std::string methodName = "ForegroundAbility"; + g_addLifecycleEventTask(token_, FreezeUtil::TimeoutState::FOREGROUND, methodName); +} + std::string AbilityRecord::GetLabel() { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); @@ -581,6 +565,9 @@ void AbilityRecord::ProcessForegroundAbility(const std::shared_ptr &scheduler) } }); } - RemoveAppStateObserver(); isReady_ = true; scheduler_ = scheduler; lifecycleDeal_->SetScheduler(scheduler); @@ -1626,7 +1615,7 @@ bool AbilityRecord::GrantUriPermissionForServiceExtension() std::lock_guard guard(wantLock_); auto callerTokenId = want_.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0); auto callerName = want_.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME); - TAG_LOGI(AAFwkTag::ABILITYMGR, + TAG_LOGD(AAFwkTag::ABILITYMGR, "CallerName is %{public}s, callerTokenId is %{public}u", callerName.c_str(), callerTokenId); GrantUriPermission(want_, applicationInfo_.bundleName, false, callerTokenId); return true; @@ -1724,8 +1713,9 @@ void AbilityRecord::SendSandboxSavefileResult(const Want &want, int resultCode, } Uri uri(uriStr); uint32_t initiatorTokenId = IPCSkeleton::GetCallingTokenID(); + bool flag = Want::FLAG_AUTH_WRITE_URI_PERMISSION; auto ret = IN_PROCESS_CALL(UriPermissionManagerClient::GetInstance().GrantUriPermission(uri, - Want::FLAG_AUTH_WRITE_URI_PERMISSION, abilityInfo_.bundleName, appIndex_, initiatorTokenId)); + flag, abilityInfo_.bundleName, appIndex_, initiatorTokenId, recordId_)); if (ret != ERR_OK) { TAG_LOGW(AAFwkTag::ABILITYMGR, "GrantUriPermission failed"); } @@ -1749,7 +1739,7 @@ void AbilityRecord::SendResultToCallers(bool schedulerdied) } std::shared_ptr callerAbilityRecord = caller->GetCaller(); if (callerAbilityRecord != nullptr && callerAbilityRecord->GetResult() != nullptr) { - bool isSandboxApp = appIndex_ > 0 ? true : false; + bool isSandboxApp = appIndex_ > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX ? true : false; callerAbilityRecord->SendResult(isSandboxApp, applicationInfo_.accessTokenId); } else { std::shared_ptr callerSystemAbilityRecord = caller->GetSaCaller(); @@ -1902,7 +1892,9 @@ void AbilityRecord::RemoveConnectRecordFromList(const std::shared_ptr &callerToken, int requestCode, std::string srcAbilityId, @@ -2374,7 +2366,10 @@ void AbilityRecord::OnSchedulerDied(const wptr &remote) void AbilityRecord::OnProcessDied() { std::lock_guard guard(lock_); - RemoveAppStateObserver(true); + if (!IsSceneBoard() && scheduler_ != nullptr) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "OnProcessDied: '%{public}s', attached.", abilityInfo_.name.c_str()); + return; + } isWindowAttached_ = false; auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); @@ -3022,7 +3017,7 @@ void AbilityRecord::GrantUriPermission(Want &want, std::string targetBundleName, // reject sandbox to grant uri permission by start ability if (!callerList_.empty() && callerList_.back()) { auto caller = callerList_.back()->GetCaller(); - if (caller && caller->appIndex_ > 0) { + if (caller && caller->appIndex_ > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Sandbox can not grant UriPermission by start ability."); return; } @@ -3038,7 +3033,7 @@ void AbilityRecord::GrantUriPermission(Want &want, std::string targetBundleName, } if ((want.GetFlags() & (Want::FLAG_AUTH_READ_URI_PERMISSION | Want::FLAG_AUTH_WRITE_URI_PERMISSION)) == 0) { - TAG_LOGW(AAFwkTag::ABILITYMGR, "Do not call uriPermissionMgr."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "Do not call uriPermissionMgr."); return; } if (IsDmsCall(want)) { @@ -3082,7 +3077,7 @@ void AbilityRecord::GrantUriPermissionInner(Want &want, std::vector return; } auto ret = IN_PROCESS_CALL(UriPermissionManagerClient::GetInstance().GrantUriPermission(validUriList, flag, - targetBundleName, appIndex_, callerTokenId)); + targetBundleName, appIndex_, callerTokenId, recordId_)); if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "grant uri permission failed, Error Code is %{public}d", ret); return; @@ -3093,21 +3088,21 @@ void AbilityRecord::GrantUriPermissionInner(Want &want, std::vector bool AbilityRecord::GrantPermissionToShell(const std::vector &strUriVec, uint32_t flag, std::string targetPkg) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Grant uri permission to shell."); std::vector uriVec; for (auto&& str : strUriVec) { Uri uri(str); auto&& scheme = uri.GetScheme(); if (scheme != "content") { return false; - } else { - uriVec.emplace_back(uri); } + uriVec.emplace_back(uri); } uint32_t initiatorTokenId = IPCSkeleton::GetCallingTokenID(); for (auto&& uri : uriVec) { auto ret = IN_PROCESS_CALL(UriPermissionManagerClient::GetInstance().GrantUriPermission(uri, flag, targetPkg, - appIndex_, initiatorTokenId)); + appIndex_, initiatorTokenId, recordId_)); if (ret == ERR_OK) { isGrantedUriPermission_ = true; } @@ -3115,31 +3110,6 @@ bool AbilityRecord::GrantPermissionToShell(const std::vector &strUr return true; } -void AbilityRecord::GrantUriPermissionFor2In1Inner(Want &want, std::vector &uriVec, - const std::string &targetBundleName, uint32_t tokenId) -{ - std::vector uriOtherVec; - std::vector uri2In1Vec; - for (auto &&str : uriVec) { - Uri uri(str); - auto &&authority = uri.GetAuthority(); - if (authority == "docs" && str.find("?networkid=") == std::string::npos) { - uri2In1Vec.emplace_back(uri); - } else { - uriOtherVec.emplace_back(str); - } - } - if (!uri2In1Vec.empty()) { - uint32_t flag = want.GetFlags(); - auto isSystemAppCall = PermissionVerification::GetInstance()->IsSystemAppCall(); - IN_PROCESS_CALL(AAFwk::UriPermissionManagerClient::GetInstance().GrantUriPermissionFor2In1( - uri2In1Vec, flag, targetBundleName, appIndex_, isSystemAppCall)); - } - if (!uriOtherVec.empty()) { - GrantUriPermissionInner(want, uriOtherVec, targetBundleName, tokenId); - } -} - bool AbilityRecord::IsDmsCall(Want &want) { auto fromTokenId = static_cast(want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, -1)); @@ -3184,7 +3154,7 @@ void AbilityRecord::RevokeUriPermission() { if (isGrantedUriPermission_) { TAG_LOGD(AAFwkTag::ABILITYMGR, "To remove uri permission."); - UriPermissionManagerClient::GetInstance().RevokeUriPermission(applicationInfo_.accessTokenId); + UriPermissionManagerClient::GetInstance().RevokeUriPermission(applicationInfo_.accessTokenId, recordId_); isGrantedUriPermission_ = false; } } diff --git a/services/abilitymgr/src/ams_configuration_parameter.cpp b/services/abilitymgr/src/ams_configuration_parameter.cpp index 6eb3dba3b7..10a40e1f02 100644 --- a/services/abilitymgr/src/ams_configuration_parameter.cpp +++ b/services/abilitymgr/src/ams_configuration_parameter.cpp @@ -46,11 +46,12 @@ void AmsConfigurationParameter::Parse() if (filePath == nullptr || filePath[0] == '\0' || strlen(filePath) > MAX_PATH_LEN) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Can not get config file"); LoadUIExtensionPickerConfig(AmsConfig::PICKER_CONFIG_FILE_PATH_DEFAULT); + return; } std::string customConfig = filePath; TAG_LOGI(AAFwkTag::ABILITYMGR, "The configuration file path is :%{private}s", customConfig.c_str()); LoadUIExtensionPickerConfig(customConfig); - TAG_LOGI(AAFwkTag::ABILITYMGR, "load config ref : %{public}d", ref); + TAG_LOGI(AAFwkTag::ABILITYMGR, "load config ref : %{private}d", ref); } bool AmsConfigurationParameter::NonConfigFile() const diff --git a/services/abilitymgr/src/app_exit_reason_helper.cpp b/services/abilitymgr/src/app_exit_reason_helper.cpp index a8c94f055e..f4b91ae153 100644 --- a/services/abilitymgr/src/app_exit_reason_helper.cpp +++ b/services/abilitymgr/src/app_exit_reason_helper.cpp @@ -73,6 +73,13 @@ int32_t AppExitReasonHelper::RecordAppExitReason(const ExitReason &exitReason) currentMissionListManager->GetActiveAbilityList(bundleName, abilityList); } + auto pid = IPCSkeleton::GetCallingRealPid(); + auto ret = DelayedSingleton::GetInstance()->NotifyAppMgrRecordExitReason(pid, exitReason.reason, + exitReason.exitMsg); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "NotifyAppMgrRecordExitReason failed.code: %{public}d", ret); + } + if (abilityList.empty()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Active abilityLists empty."); return ERR_GET_ACTIVE_ABILITY_LIST_EMPTY; @@ -118,6 +125,12 @@ int32_t AppExitReasonHelper::RecordProcessExitReason(const int32_t pid, const Ex GetActiveAbilityListByUser(bundleName, abilityLists, targetUserId, pid); } + auto ret = DelayedSingleton::GetInstance()->NotifyAppMgrRecordExitReason(pid, exitReason.reason, + exitReason.exitMsg); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "NotifyAppMgrRecordExitReason failed.code: %{public}d", ret); + } + if (abilityLists.empty()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Active abilityLists empty."); return ERR_GET_ACTIVE_ABILITY_LIST_EMPTY; diff --git a/services/abilitymgr/src/app_scheduler.cpp b/services/abilitymgr/src/app_scheduler.cpp index 3c0c21fa4d..a5de63c336 100644 --- a/services/abilitymgr/src/app_scheduler.cpp +++ b/services/abilitymgr/src/app_scheduler.cpp @@ -239,6 +239,13 @@ void AppScheduler::NotifyStartResidentProcess(std::vectorNotifyStartResidentProcess(bundleInfos); } +void AppScheduler::OnAppRemoteDied(const std::vector> &abilityTokens) +{ + auto callback = callback_.lock(); + CHECK_POINTER(callback); + callback->OnAppRemoteDied(abilityTokens); +} + int AppScheduler::KillApplication(const std::string &bundleName) { TAG_LOGI(AAFwkTag::ABILITYMGR, "[%{public}s(%{public}s)] enter", __FILE__, __FUNCTION__); @@ -331,39 +338,40 @@ void AppScheduler::StartupResidentProcess(const std::vectorStartupResidentProcess(bundleInfos); } -void AppScheduler::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +void AppScheduler::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId) { CHECK_POINTER(appMgrClient_); - IN_PROCESS_CALL_WITHOUT_RET(appMgrClient_->StartSpecifiedAbility(want, abilityInfo)); + IN_PROCESS_CALL_WITHOUT_RET(appMgrClient_->StartSpecifiedAbility(want, abilityInfo, requestId)); } void StartSpecifiedAbilityResponse::OnAcceptWantResponse( - const AAFwk::Want &want, const std::string &flag) + const AAFwk::Want &want, const std::string &flag, int32_t requestId) { - DelayedSingleton::GetInstance()->OnAcceptWantResponse(want, flag); + DelayedSingleton::GetInstance()->OnAcceptWantResponse(want, flag, requestId); } -void StartSpecifiedAbilityResponse::OnTimeoutResponse(const AAFwk::Want &want) +void StartSpecifiedAbilityResponse::OnTimeoutResponse(const AAFwk::Want &want, int32_t requestId) { - DelayedSingleton::GetInstance()->OnStartSpecifiedAbilityTimeoutResponse(want); + DelayedSingleton::GetInstance()->OnStartSpecifiedAbilityTimeoutResponse(want, requestId); } void AppScheduler::StartSpecifiedProcess( - const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) + const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, int32_t requestId) { CHECK_POINTER(appMgrClient_); - IN_PROCESS_CALL_WITHOUT_RET(appMgrClient_->StartSpecifiedProcess(want, abilityInfo)); + IN_PROCESS_CALL_WITHOUT_RET(appMgrClient_->StartSpecifiedProcess(want, abilityInfo, requestId)); } void StartSpecifiedAbilityResponse::OnNewProcessRequestResponse( - const AAFwk::Want &want, const std::string &flag) + const AAFwk::Want &want, const std::string &flag, int32_t requestId) { - DelayedSingleton::GetInstance()->OnStartSpecifiedProcessResponse(want, flag); + DelayedSingleton::GetInstance()->OnStartSpecifiedProcessResponse(want, flag, requestId); } -void StartSpecifiedAbilityResponse::OnNewProcessRequestTimeoutResponse(const AAFwk::Want &want) +void StartSpecifiedAbilityResponse::OnNewProcessRequestTimeoutResponse(const AAFwk::Want &want, int32_t requestId) { - DelayedSingleton::GetInstance()->OnStartSpecifiedProcessTimeoutResponse(want); + DelayedSingleton::GetInstance()->OnStartSpecifiedProcessTimeoutResponse(want, requestId); } int AppScheduler::GetProcessRunningInfos(std::vector &info) @@ -458,6 +466,17 @@ int AppScheduler::GetApplicationInfoByProcessID(const int pid, AppExecFwk::Appli return ERR_OK; } +int32_t AppScheduler::NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg) +{ + CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); + auto ret = static_cast(IN_PROCESS_CALL(appMgrClient_->NotifyAppMgrRecordExitReason(pid, reason, exitMsg))); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "NotifyAppMgrRecordExitReason failed."); + return ret; + } + return ERR_OK; +} + #ifdef ABILITY_COMMAND_FOR_TEST int AppScheduler::BlockAppService() { @@ -567,12 +586,6 @@ bool AppScheduler::IsAttachDebug(const std::string &bundleName) return ERR_OK; } -void AppScheduler::SetAppAssertionPauseState(int32_t pid, bool flag) -{ - CHECK_POINTER(appMgrClient_); - appMgrClient_->SetAppAssertionPauseState(pid, flag); -} - void AppScheduler::ClearProcessByToken(sptr token) const { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); diff --git a/services/abilitymgr/src/assert_fault_callback_death_mgr.cpp b/services/abilitymgr/src/assert_fault_callback_death_mgr.cpp index 0ae3a8abc1..ef60320c6f 100644 --- a/services/abilitymgr/src/assert_fault_callback_death_mgr.cpp +++ b/services/abilitymgr/src/assert_fault_callback_death_mgr.cpp @@ -65,7 +65,6 @@ void AssertFaultCallbackDeathMgr::AddAssertFaultCallback(sptr &re TAG_LOGE(AAFwkTag::ABILITYMGR, "Get app scheduler instance is nullptr."); return; } - IN_PROCESS_CALL_WITHOUT_RET(appScheduler->SetAppAssertionPauseState(callerPid, true)); } void AssertFaultCallbackDeathMgr::RemoveAssertFaultCallback(const wptr &remote, bool isCallbackDeath) @@ -126,7 +125,6 @@ void AssertFaultCallbackDeathMgr::CallAssertFaultCallback(uint64_t assertFaultSe TAG_LOGE(AAFwkTag::ABILITYMGR, "Get app scheduler instance is nullptr."); return; } - IN_PROCESS_CALL_WITHOUT_RET(appScheduler->SetAppAssertionPauseState(item.pid_, false)); } } // namespace AbilityRuntime } // namespace OHOS diff --git a/services/abilitymgr/src/assert_fault_proxy.cpp b/services/abilitymgr/src/assert_fault_proxy.cpp index 30f0844ef3..eddf9389bd 100644 --- a/services/abilitymgr/src/assert_fault_proxy.cpp +++ b/services/abilitymgr/src/assert_fault_proxy.cpp @@ -17,6 +17,7 @@ #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" #include "scene_board_judgement.h" +#include "task_handler_wrap.h" namespace OHOS { namespace AbilityRuntime { @@ -56,6 +57,8 @@ void AssertFaultProxy::NotifyDebugAssertResult(AAFwk::UserStatus status) if (remote->SendRequest(MessageCode::NOTIFY_DEBUG_ASSERT_RESULT, data, reply, option) != NO_ERROR) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Remote send request failed."); } + + ModalSystemAssertUIExtension::GetInstance().DisconnectSystemUI(); } AssertFaultRemoteDeathRecipient::AssertFaultRemoteDeathRecipient(RemoteDiedHandler handler) : handler_(handler) @@ -70,6 +73,12 @@ void AssertFaultRemoteDeathRecipient::OnRemoteDied(const wptr &re handler_(remote); } +ModalSystemAssertUIExtension &ModalSystemAssertUIExtension::GetInstance() +{ + static ModalSystemAssertUIExtension instance; + return instance; +} + ModalSystemAssertUIExtension::~ModalSystemAssertUIExtension() { dialogConnectionCallback_ = nullptr; @@ -90,22 +99,24 @@ sptr ModalSystemAssertUIEx bool ModalSystemAssertUIExtension::CreateModalUIExtension(const AAFwk::Want &want) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + std::unique_lock lockAssertResult(assertResultMutex_); + if (reqeustCount_++ != 0) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Task busy, waiting for processing."); + assertResultCV_.wait(lockAssertResult); + } auto callback = GetConnection(); if (callback == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Callback is nullptr."); + TryNotifyOneWaitingThread(); return false; } - if (callback->RequestShowDialog(want)) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Start consumption want."); - return true; - } - + callback->SetReqeustAssertDialogWant(want); auto abilityManagerClient = AAFwk::AbilityManagerClient::GetInstance(); if (abilityManagerClient == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectSystemUi AbilityManagerClient is nullptr"); + TryNotifyOneWaitingThread(); return false; } - AAFwk::Want systemUIWant; if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { systemUIWant.SetElementName("com.ohos.sceneboard", "com.ohos.sceneboard.systemdialog"); @@ -115,47 +126,66 @@ bool ModalSystemAssertUIExtension::CreateModalUIExtension(const AAFwk::Want &wan auto result = abilityManagerClient->ConnectAbility(systemUIWant, callback, INVALID_USERID); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectSystemUi ConnectAbility dialog failed, result = %{public}d", result); + TryNotifyOneWaitingThread(); return false; } return true; } -ModalSystemAssertUIExtension::AssertDialogConnection::~AssertDialogConnection() +bool ModalSystemAssertUIExtension::DisconnectSystemUI() { TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); - CleanUp(); + bool retVal = true; + do { + auto abilityManagerClient = AAFwk::AbilityManagerClient::GetInstance(); + if (abilityManagerClient == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerClient is nullptr"); + retVal = false; + break; + } + auto callback = GetConnection(); + if (callback == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Callback is nullptr."); + retVal = false; + break; + } + auto result = abilityManagerClient->DisconnectAbility(callback); + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "DisconnectAbility dialog failed, result = %{public}d", result); + retVal = false; + break; + } + } while (false); + + return retVal; } -bool ModalSystemAssertUIExtension::AssertDialogConnection::RequestShowDialog(const AAFwk::Want &want) +void ModalSystemAssertUIExtension::TryNotifyOneWaitingThreadInner() { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); - { - std::lock_guard lock(mutex_); - consumptionList_.push(want); + std::unique_lock lockAssertResult(assertResultMutex_); + if (--reqeustCount_ > 0) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Notify waiting Thread count is %{public}d.", reqeustCount_); + assertResultCV_.notify_one(); + return; } - if (!isDialogShow_) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Connection not ready."); - return false; - } - - AppExecFwk::ElementName element; - OnAbilityConnectDone(element, remoteObject_, DEFAULT_VAL); - return true; + reqeustCount_ = 0; + TAG_LOGD(AAFwkTag::ABILITYMGR, "Counter reset to 0."); } -void ModalSystemAssertUIExtension::AssertDialogConnection::CleanUp() +void ModalSystemAssertUIExtension::TryNotifyOneWaitingThread() { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); - std::lock_guard lock(mutex_); - if (!consumptionList_.empty()) { - std::queue temp; - consumptionList_.swap(temp); + auto handler = AAFwk::TaskHandlerWrap::GetFfrtHandler(); + if (handler != nullptr) { + auto notifyTask = [] () { + ModalSystemAssertUIExtension::GetInstance().TryNotifyOneWaitingThreadInner(); + }; + handler->SubmitTask(notifyTask, "TryNotifyOneWaitingThread"); } - if (remoteObject_ != nullptr) { - remoteObject_->RemoveDeathRecipient(deathRecipient_); - remoteObject_ = nullptr; - } - deathRecipient_ = nullptr; +} + +void ModalSystemAssertUIExtension::AssertDialogConnection::SetReqeustAssertDialogWant(const AAFwk::Want &want) +{ + want_ = want; } void ModalSystemAssertUIExtension::AssertDialogConnection::OnAbilityConnectDone( @@ -166,39 +196,23 @@ void ModalSystemAssertUIExtension::AssertDialogConnection::OnAbilityConnectDone( TAG_LOGE(AAFwkTag::ABILITYMGR, "Input remote object is nullptr."); return; } - std::lock_guard lock(mutex_); - if (remoteObject_ == nullptr) { - remoteObject_ = remote; - wptr weakThis = iface_cast(this->AsObject()); - deathRecipient_ = - new (std::nothrow) AssertFaultRemoteDeathRecipient([weakThis] (const wptr &remote) { - auto remoteObj = weakThis.promote(); - if (remoteObj == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid remote object."); - return; - } - remoteObj->CleanUp(); - }); - remoteObject_->AddDeathRecipient(deathRecipient_); - } + MessageParcel data; MessageParcel reply; MessageOption option; - auto &want = consumptionList_.front(); data.WriteInt32(MESSAGE_PARCEL_KEY_SIZE); data.WriteString16(u"bundleName"); - data.WriteString16(Str8ToStr16(want.GetElement().GetBundleName())); + data.WriteString16(Str8ToStr16(want_.GetElement().GetBundleName())); data.WriteString16(u"abilityName"); - data.WriteString16(Str8ToStr16(want.GetElement().GetAbilityName())); + data.WriteString16(Str8ToStr16(want_.GetElement().GetAbilityName())); data.WriteString16(u"parameters"); nlohmann::json param; - param[UIEXTENSION_TYPE_KEY] = want.GetStringParam(UIEXTENSION_TYPE_KEY); - param[ASSERT_FAULT_DETAIL] = want.GetStringParam(ASSERT_FAULT_DETAIL); + param[UIEXTENSION_TYPE_KEY] = want_.GetStringParam(UIEXTENSION_TYPE_KEY); + param[ASSERT_FAULT_DETAIL] = want_.GetStringParam(ASSERT_FAULT_DETAIL); param[AAFwk::Want::PARAM_ASSERT_FAULT_SESSION_ID] = - want.GetStringParam(AAFwk::Want::PARAM_ASSERT_FAULT_SESSION_ID); + want_.GetStringParam(AAFwk::Want::PARAM_ASSERT_FAULT_SESSION_ID); std::string paramStr = param.dump(); data.WriteString16(Str8ToStr16(paramStr)); - consumptionList_.pop(); uint32_t code = !Rosen::SceneBoardJudgement::IsSceneBoardEnabled() ? COMMAND_START_DIALOG : AAFwk::IAbilityConnection::ON_ABILITY_CONNECT_DONE; auto ret = remote->SendRequest(code, data, reply, option); @@ -206,14 +220,13 @@ void ModalSystemAssertUIExtension::AssertDialogConnection::OnAbilityConnectDone( TAG_LOGE(AAFwkTag::ABILITYMGR, "Show dialog is failed"); return; } - isDialogShow_ = true; } void ModalSystemAssertUIExtension::AssertDialogConnection::OnAbilityDisconnectDone( const AppExecFwk::ElementName &element, int resultCode) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); - CleanUp(); + ModalSystemAssertUIExtension::GetInstance().TryNotifyOneWaitingThread(); } } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/connection_record.cpp b/services/abilitymgr/src/connection_record.cpp index 225f8df3c7..f7abd410dd 100644 --- a/services/abilitymgr/src/connection_record.cpp +++ b/services/abilitymgr/src/connection_record.cpp @@ -75,11 +75,13 @@ std::shared_ptr ConnectionRecord::GetAbilityRecord() const sptr ConnectionRecord::GetAbilityConnectCallback() const { + std::lock_guard lock(callbackMutex_); return connCallback_; } void ConnectionRecord::ClearConnCallBack() { + std::lock_guard lock(callbackMutex_); if (connCallback_) { connCallback_.clear(); } @@ -136,7 +138,7 @@ void ConnectionRecord::CompleteConnect(int resultCode) AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name, abilityInfo.moduleName); auto remoteObject = targetService_->GetConnRemoteObject(); - auto callback = connCallback_; + auto callback = GetAbilityConnectCallback(); auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); if (remoteObject == nullptr) { TAG_LOGW(AAFwkTag::CONNECTION, "extension returned null object: %{public}s", element.GetURI().c_str()); @@ -170,10 +172,10 @@ void ConnectionRecord::CompleteDisconnect(int resultCode, bool isDied) AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name, abilityInfo.moduleName); auto code = isDied ? (resultCode - 1) : resultCode; - auto onDisconnectDoneTask = [connCallback = connCallback_, element, code]() { + auto onDisconnectDoneTask = [connCallback = GetAbilityConnectCallback(), element, code]() { TAG_LOGD(AAFwkTag::CONNECTION, "OnAbilityDisconnectDone."); if (!connCallback) { - TAG_LOGD(AAFwkTag::CONNECTION, "connCallback_ is nullptr."); + TAG_LOGD(AAFwkTag::CONNECTION, "connCallback is nullptr."); return; } connCallback->OnAbilityDisconnectDone(element, code); @@ -309,7 +311,7 @@ sptr ConnectionRecord::GetTargetToken() const sptr ConnectionRecord::GetConnection() const { - auto callback = connCallback_; + auto callback = GetAbilityConnectCallback(); if (!callback) { return nullptr; } diff --git a/services/abilitymgr/src/connection_state_manager.cpp b/services/abilitymgr/src/connection_state_manager.cpp index b4a8992091..7489c2d1fb 100644 --- a/services/abilitymgr/src/connection_state_manager.cpp +++ b/services/abilitymgr/src/connection_state_manager.cpp @@ -19,6 +19,7 @@ #include "app_mgr_interface.h" #include "connection_observer_errors.h" +#include "global_constant.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" #include "if_system_ability_manager.h" @@ -486,7 +487,7 @@ bool ConnectionStateManager::HandleDlpAbilityInner(const std::shared_ptrGetAppIndex() == 0) { + if (dlpAbility->GetAppIndex() <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { TAG_LOGD(AAFwkTag::CONNECTION, "this is not dlp ability, do not report connection stat."); return false; } diff --git a/services/abilitymgr/src/deeplink_reserve/deeplink_reserve.cpp b/services/abilitymgr/src/deeplink_reserve/deeplink_reserve_config.cpp similarity index 95% rename from services/abilitymgr/src/deeplink_reserve/deeplink_reserve.cpp rename to services/abilitymgr/src/deeplink_reserve/deeplink_reserve_config.cpp index bd06e07194..b89cfe266b 100644 --- a/services/abilitymgr/src/deeplink_reserve/deeplink_reserve.cpp +++ b/services/abilitymgr/src/deeplink_reserve/deeplink_reserve_config.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "deeplink_reserve/deeplink_reserve.h" +#include "deeplink_reserve/deeplink_reserve_config.h" #include #include #include @@ -59,13 +59,14 @@ bool DeepLinkReserveConfig::LoadConfiguration() { TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); std::string configPath = GetConfigPath(); - TAG_LOGI(AAFwkTag::ABILITYMGR, "Deeplink reserve config path is: %{public}s", configPath.c_str()); + TAG_LOGD(AAFwkTag::ABILITYMGR, "Deeplink reserve config path is: %{public}s", configPath.c_str()); nlohmann::json jsonBuf; - if (ReadFileInfoJson(configPath, jsonBuf)) { - if (!LoadReservedUriList(jsonBuf)) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "LoadConfiguration failed."); - return false; - } + if (!ReadFileInfoJson(configPath, jsonBuf)) { + return false; + } + if (!LoadReservedUriList(jsonBuf)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "LoadConfiguration failed."); + return false; } return true; @@ -252,7 +253,12 @@ bool DeepLinkReserveConfig::LoadReservedUriList(const nlohmann::json &object) bool DeepLinkReserveConfig::ReadFileInfoJson(const std::string &filePath, nlohmann::json &jsonBuf) { if (access(filePath.c_str(), F_OK) != 0) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, not existed", filePath.c_str()); + TAG_LOGE(AAFwkTag::ABILITYMGR, "Deeplink reserve config not exist."); + return false; + } + + if (filePath.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "File path is empty."); return false; } diff --git a/services/abilitymgr/src/dialog_session_info.cpp b/services/abilitymgr/src/dialog_session_info.cpp index ca9efcd4af..fa46604fb7 100644 --- a/services/abilitymgr/src/dialog_session_info.cpp +++ b/services/abilitymgr/src/dialog_session_info.cpp @@ -25,13 +25,14 @@ namespace OHOS { namespace AAFwk { constexpr int32_t CYCLE_LIMIT = 1000; -constexpr size_t MEMBER_NUM = 7; +constexpr size_t MEMBER_NUM = 8; std::string DialogAbilityInfo::GetURI() const { return bundleName + "/" + moduleName + "/" + abilityName + "/" + std::to_string(bundleIconId) + "/" + std::to_string(bundleLabelId) + "/" + - std::to_string(abilityIconId) + "/" + std::to_string(abilityLabelId); + std::to_string(abilityIconId) + "/" + std::to_string(abilityLabelId) + "/" + + std::to_string(visible); } bool DialogAbilityInfo::ParseURI(const std::string &uri) @@ -53,6 +54,7 @@ bool DialogAbilityInfo::ParseURI(const std::string &uri) bundleLabelId = static_cast(std::stoi(uriVec[index++])); abilityIconId = static_cast(std::stoi(uriVec[index++])); abilityLabelId = static_cast(std::stoi(uriVec[index++])); + visible = std::stoi(uriVec[index++]); return true; } diff --git a/services/abilitymgr/src/dialog_session_record.cpp b/services/abilitymgr/src/dialog_session_record.cpp index 54413eecc9..591805f41d 100644 --- a/services/abilitymgr/src/dialog_session_record.cpp +++ b/services/abilitymgr/src/dialog_session_record.cpp @@ -131,6 +131,7 @@ bool DialogSessionRecord::GenerateDialogSessionRecord(AbilityRequest &abilityReq targetDialogAbilityInfo.abilityLabelId = dialogAppInfo.abilityLabelId; targetDialogAbilityInfo.bundleIconId = dialogAppInfo.bundleIconId; targetDialogAbilityInfo.bundleLabelId = dialogAppInfo.bundleLabelId; + targetDialogAbilityInfo.visible = dialogAppInfo.visible; dialogSessionInfo->targetAbilityInfos.emplace_back(targetDialogAbilityInfo); } std::shared_ptr dialogCallerInfo = std::make_shared(); diff --git a/services/abilitymgr/src/dlp_state_item.cpp b/services/abilitymgr/src/dlp_state_item.cpp index b27dbbf694..2d6e9860aa 100644 --- a/services/abilitymgr/src/dlp_state_item.cpp +++ b/services/abilitymgr/src/dlp_state_item.cpp @@ -15,6 +15,7 @@ #include "dlp_state_item.h" +#include "global_constant.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" @@ -53,7 +54,7 @@ int32_t DlpStateItem::GetOpenedAbilitySize() const bool DlpStateItem::HandleDlpConnectionState(const std::shared_ptr &record, bool isAdd, AbilityRuntime::DlpStateData &data) { - if (!record || record->GetAppIndex() == 0) { + if (!record || record->GetAppIndex() <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { TAG_LOGW(AAFwkTag::ABILITYMGR, "invalid dlp ability."); return false; } diff --git a/services/abilitymgr/src/ecological_rule/ability_ecological_rule_mgr_service_param.cpp b/services/abilitymgr/src/ecological_rule/ability_ecological_rule_mgr_service_param.cpp index 60b12c2e91..704a24832a 100644 --- a/services/abilitymgr/src/ecological_rule/ability_ecological_rule_mgr_service_param.cpp +++ b/services/abilitymgr/src/ecological_rule/ability_ecological_rule_mgr_service_param.cpp @@ -125,15 +125,12 @@ AbilityCallerInfo *AbilityCallerInfo::Unmarshalling(Parcel &in) return nullptr; } - if (!in.ReadInt32(info->callerAbilityType)) { - TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "read callerAbilityType failed"); - delete info; - return nullptr; - } + info->callerAbilityType = static_cast(in.ReadInt32()); info->embedded = in.ReadInt32(); info->callerAppProvisionType = in.ReadString(); info->targetAppProvisionType = in.ReadString(); + info->callerExtensionAbilityType = static_cast(in.ReadInt32()); return info; } @@ -157,6 +154,11 @@ bool AbilityCallerInfo::Marshalling(Parcel &parcel) const TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "write targetAppProvisionType failed"); return false; } + + if (!parcel.WriteInt32(static_cast(callerExtensionAbilityType))) { + TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "write callerExtensionAbilityType failed"); + return false; + } return true; } @@ -207,10 +209,11 @@ bool AbilityCallerInfo::DoMarshallingOne(Parcel &parcel) const return false; } - if (!parcel.WriteInt32(callerAbilityType)) { + if (!parcel.WriteInt32(static_cast(callerAbilityType))) { TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "write callerAbilityType failed"); return false; } + return true; } @@ -220,7 +223,9 @@ std::string AbilityCallerInfo::ToString() const ",pid:" + std::to_string(pid) + ",callerAppType:" + std::to_string(callerAppType) + ",targetAppType:" + std::to_string(targetAppType) + ",callerModelType:" + std::to_string(callerModelType) + ",targetAppDistType:" + targetAppDistType + ",targetLinkFeature:" + targetLinkFeature + ",targetLinkType:" + - std::to_string(targetLinkType) + ",callerAbilityType:" + std::to_string(callerAbilityType) + ",embedded:" + + std::to_string(targetLinkType) + ",callerAbilityType:" + + std::to_string(static_cast(callerAbilityType)) + ",callerExtensionAbilityType:" + + std::to_string(static_cast(callerExtensionAbilityType)) + ",embedded:" + std::to_string(embedded) + ",callerAppProvisionType:" + callerAppProvisionType + ",targetAppProvisionType:" + targetAppProvisionType + "}"; return str; diff --git a/services/abilitymgr/src/extension_record_factory.cpp b/services/abilitymgr/src/extension_record_factory.cpp index 5def6f480e..5f294541e2 100644 --- a/services/abilitymgr/src/extension_record_factory.cpp +++ b/services/abilitymgr/src/extension_record_factory.cpp @@ -23,6 +23,12 @@ namespace OHOS { namespace AbilityRuntime { using namespace OHOS::AppExecFwk; namespace { +const std::map EXTENSION_RECORD_CONFIG_MAP = { + { AppExecFwk::ExtensionAbilityType::EMBEDDED_UI, + { PROCESS_MODE_BUNDLE, PROCESS_MODE_SUPPORT_DEFAULT | PROCESS_MODE_HOST_SPECIFIED | PROCESS_MODE_HOST_INSTANCE, + PRE_CHECK_FLAG_CALLED_WITHIN_THE_BUNDLE | PRE_CHECK_FLAG_MULTIPLE_PROCESSES }}, +}; + uint32_t GetPreCheckFlag(ExtensionAbilityType type) { auto iter = EXTENSION_RECORD_CONFIG_MAP.find(type); @@ -112,7 +118,7 @@ uint32_t ExtensionRecordFactory::GetExtensionProcessMode( int32_t ExtensionRecordFactory::CreateRecord( const AAFwk::AbilityRequest &abilityRequest, std::shared_ptr &extensionRecord) { - std::shared_ptr abilityRecord = AAFwk::AbilityRecord::CreateAbilityRecord(abilityRequest); + auto abilityRecord = AAFwk::AbilityRecord::CreateAbilityRecord(abilityRequest); if (abilityRecord == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to create ability record"); return ERR_NULL_OBJECT; diff --git a/services/abilitymgr/src/extension_record_manager.cpp b/services/abilitymgr/src/extension_record_manager.cpp index 29512f4023..1fc2c264c7 100644 --- a/services/abilitymgr/src/extension_record_manager.cpp +++ b/services/abilitymgr/src/extension_record_manager.cpp @@ -216,7 +216,7 @@ bool ExtensionRecordManager::IsHostSpecifiedProcessValid(const AAFwk::AbilityReq std::shared_ptr &record, const std::string &process) { std::lock_guard lock(mutex_); - for (auto &iter: extensionRecords_) { + for (const auto &iter: extensionRecords_) { if (iter.second == nullptr || iter.second->abilityRecord_ == nullptr) { continue; } @@ -275,10 +275,12 @@ int32_t ExtensionRecordManager::AddPreloadUIExtensionRecord(const std::shared_pt { TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); std::lock_guard lock(mutex_); + CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); std::shared_ptr extensionRecord = nullptr; auto extensionRecordId = abilityRecord->GetUIExtensionAbilityId(); if (extensionRecords_.find(extensionRecordId) != extensionRecords_.end()) { extensionRecord = extensionRecords_[extensionRecordId]; + CHECK_POINTER_AND_RETURN(extensionRecord, ERR_INVALID_VALUE); auto hostBundleName = extensionRecord->hostBundleName_; auto preLoadUIExtensionInfo = std::make_tuple(abilityRecord->GetWant().GetElement().GetAbilityName(), abilityRecord->GetWant().GetElement().GetBundleName(), @@ -390,7 +392,8 @@ int32_t ExtensionRecordManager::GetOrCreateExtensionRecordInner(const AAFwk::Abi std::shared_ptr abilityRecord = extensionRecord->abilityRecord_; CHECK_POINTER_AND_RETURN(abilityRecord, ERR_NULL_OBJECT); isLoaded = false; - extensionRecordId = GenerateExtensionRecordId(extensionRecordId); + // Reuse id or not has been checked, so alloc a new id here. + extensionRecordId = GenerateExtensionRecordId(INVALID_EXTENSION_RECORD_ID); extensionRecord->extensionRecordId_ = extensionRecordId; extensionRecord->hostBundleName_ = hostBundleName; abilityRecord->SetOwnerMissionUserId(userId_); @@ -447,6 +450,11 @@ sptr ExtensionRecordManager::GetRootCallerTokenLocked(int32_t ext it->second->SetRootCallerToken(callerToken); return callerToken; } + // If caller extension record id is same with current, need terminate, prevent possible stack-overflow. + if (callerAbilityRecord->GetUIExtensionAbilityId() == extensionRecordId) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid id: %{public}d, same with caller.", extensionRecordId); + return nullptr; + } rootCallerToken = GetRootCallerTokenLocked(callerAbilityRecord->GetUIExtensionAbilityId()); TAG_LOGD(AAFwkTag::ABILITYMGR, "update rootCallerToken, id: %{public}d.", extensionRecordId); it->second->SetRootCallerToken(rootCallerToken); diff --git a/services/abilitymgr/src/implicit_start_processor.cpp b/services/abilitymgr/src/implicit_start_processor.cpp index 09e6812c2e..eefc114f4d 100644 --- a/services/abilitymgr/src/implicit_start_processor.cpp +++ b/services/abilitymgr/src/implicit_start_processor.cpp @@ -359,7 +359,7 @@ int ImplicitStartProcessor::GenerateAbilityRequestByAction(int32_t userId, } if (uriReservedFlag_) { - abilityInfoFlag = abilityInfoFlag | + abilityInfoFlag = static_cast(abilityInfoFlag) | static_cast(AppExecFwk::GetAbilityInfoFlag::GET_ABILITY_INFO_ONLY_SYSTEM_APP); } @@ -380,7 +380,7 @@ int ImplicitStartProcessor::GenerateAbilityRequestByAction(int32_t userId, return ERR_IMPLICIT_START_ABILITY_FAIL; } - if (isOpenLink && !appLinkingOnly) { + if (!appLinkingOnly) { ProcessLinkType(abilityInfos); } @@ -452,6 +452,7 @@ int ImplicitStartProcessor::GenerateAbilityRequestByAction(int32_t userId, dialogAppInfo.abilityLabelId = info.labelId; dialogAppInfo.bundleIconId = info.applicationInfo.iconId; dialogAppInfo.bundleLabelId = info.applicationInfo.labelId; + dialogAppInfo.visible = info.visible; dialogAppInfos.emplace_back(dialogAppInfo); } @@ -725,6 +726,7 @@ void ImplicitStartProcessor::AddAbilityInfoToDialogInfos(const AddInfoParam &par dialogAppInfo.abilityLabelId = param.info.labelId; dialogAppInfo.bundleIconId = param.info.applicationInfo.iconId; dialogAppInfo.bundleLabelId = param.info.applicationInfo.labelId; + dialogAppInfo.visible = param.info.visible; dialogAppInfos.emplace_back(dialogAppInfo); } diff --git a/services/abilitymgr/src/interceptor/ecological_rule_interceptor.cpp b/services/abilitymgr/src/interceptor/ecological_rule_interceptor.cpp index 0960147d84..10b9bd0271 100644 --- a/services/abilitymgr/src/interceptor/ecological_rule_interceptor.cpp +++ b/services/abilitymgr/src/interceptor/ecological_rule_interceptor.cpp @@ -54,7 +54,7 @@ ErrCode EcologicalRuleInterceptor::DoProcess(AbilityInterceptorParam param) } AAFwk::Want newWant = param.want; newWant.RemoveAllFd(); - GetEcologicalCallerInfo(newWant, callerInfo, param.userId); + GetEcologicalCallerInfo(newWant, callerInfo, param.userId, param.callerToken); std::string supportErms = OHOS::system::GetParameter(ABILITY_SUPPORT_ECOLOGICAL_RULEMGRSERVICE, "true"); if (supportErms == "false") { TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "Abilityms not support Erms between applications."); @@ -128,30 +128,39 @@ bool EcologicalRuleInterceptor::DoProcess(Want &want, int32_t userId) return rule.isAllow; } -void EcologicalRuleInterceptor::GetEcologicalCallerInfo(const Want &want, ErmsCallerInfo &callerInfo, int32_t userId) +void EcologicalRuleInterceptor::GetEcologicalCallerInfo(const Want &want, ErmsCallerInfo &callerInfo, int32_t userId, + const sptr &callerToken) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); InitErmsCallerInfo(const_cast(want), callerInfo); - auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper(); - if (bundleMgrHelper == nullptr) { - TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "The bundleMgrHelper is nullptr."); - return; - } - - std::string callerBundleName; - ErrCode err = IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callerInfo.uid, callerBundleName)); - if (err != ERR_OK) { - TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "Get callerBundleName failed,uid: %{public}d.", callerInfo.uid); - return; - } AppExecFwk::ApplicationInfo callerAppInfo; - bool getCallerResult = IN_PROCESS_CALL(bundleMgrHelper->GetApplicationInfo(callerBundleName, - AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, callerAppInfo)); - if (!getCallerResult) { - TAG_LOGD(AAFwkTag::ECOLOGICAL_RULE, "Get callerAppInfo failed."); - return; + AppExecFwk::AbilityInfo callerAbilityInfo; + if (StartAbilityUtils::GetCallerAbilityInfo(callerToken, callerAbilityInfo)) { + callerAppInfo = callerAbilityInfo.applicationInfo; + callerInfo.callerAbilityType = callerAbilityInfo.type; + callerInfo.callerExtensionAbilityType = callerAbilityInfo.extensionAbilityType; + } else { + auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper(); + if (bundleMgrHelper == nullptr) { + TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "The bundleMgrHelper is nullptr."); + return; + } + + std::string callerBundleName; + ErrCode err = IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callerInfo.uid, callerBundleName)); + if (err != ERR_OK) { + TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "Get callerBundleName failed,uid: %{public}d.", callerInfo.uid); + return; + } + bool getCallerResult = IN_PROCESS_CALL(bundleMgrHelper->GetApplicationInfo(callerBundleName, + AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, callerAppInfo)); + if (!getCallerResult) { + TAG_LOGD(AAFwkTag::ECOLOGICAL_RULE, "Get callerAppInfo failed."); + return; + } } + callerInfo.callerAppProvisionType = callerAppInfo.appProvisionType; if (callerAppInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE) { TAG_LOGD(AAFwkTag::ECOLOGICAL_RULE, "the caller type is atomic service"); diff --git a/services/abilitymgr/src/mission_list_manager.cpp b/services/abilitymgr/src/mission_list_manager.cpp index 7084e42f5a..cd49219da0 100644 --- a/services/abilitymgr/src/mission_list_manager.cpp +++ b/services/abilitymgr/src/mission_list_manager.cpp @@ -22,13 +22,16 @@ #include "ability_util.h" #include "app_exit_reason_data_manager.h" #include "appfreeze_manager.h" -#include "hitrace_meter.h" #include "errors.h" +#include "global_constant.h" +#include "hitrace_meter.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" #include "hisysevent.h" #include "mission_info_mgr.h" #include "in_process_call_wrapper.h" +#include "server_constant.h" +#include "startup_util.h" #ifdef RESOURCE_SCHEDULE_SERVICE_ENABLE #include "res_sched_client.h" #include "res_type.h" @@ -44,29 +47,28 @@ namespace { constexpr uint32_t DELAY_NOTIFY_LABEL_TIME = 30; // 30ms constexpr uint32_t SCENE_FLAG_KEYGUARD = 1; constexpr uint32_t ONLY_ONE_ABILITY = 1; -constexpr char EVENT_KEY_UID[] = "UID"; -constexpr char EVENT_KEY_PID[] = "PID"; -constexpr char EVENT_KEY_MESSAGE[] = "MSG"; -constexpr char EVENT_KEY_PACKAGE_NAME[] = "PACKAGE_NAME"; -constexpr char EVENT_KEY_PROCESS_NAME[] = "PROCESS_NAME"; +constexpr const char* EVENT_KEY_UID = "UID"; +constexpr const char* EVENT_KEY_PID = "PID"; +constexpr const char* EVENT_KEY_MESSAGE = "MSG"; +constexpr const char* EVENT_KEY_PACKAGE_NAME = "PACKAGE_NAME"; +constexpr const char* EVENT_KEY_PROCESS_NAME = "PROCESS_NAME"; constexpr int32_t SINGLE_MAX_INSTANCE_COUNT = 128; constexpr int32_t MAX_INSTANCE_COUNT = 512; constexpr uint64_t NANO_SECOND_PER_SEC = 1000000000; // ns const std::string DMS_SRC_NETWORK_ID = "dmsSrcNetworkId"; const std::string DMS_MISSION_ID = "dmsMissionId"; -const int DEFAULT_DMS_MISSION_ID = -1; -const std::string DLP_INDEX = "ohos.dlp.params.index"; +constexpr int DEFAULT_DMS_MISSION_ID = -1; #ifdef SUPPORT_ASAN -const int KILL_TIMEOUT_MULTIPLE = 45; +constexpr int KILL_TIMEOUT_MULTIPLE = 45; #else -const int KILL_TIMEOUT_MULTIPLE = 3; +constexpr int KILL_TIMEOUT_MULTIPLE = 3; #endif constexpr int32_t PREPARE_TERMINATE_ENABLE_SIZE = 6; -const char* PREPARE_TERMINATE_ENABLE_PARAMETER = "persist.sys.prepare_terminate"; -const int32_t PREPARE_TERMINATE_TIMEOUT_MULTIPLE = 10; +constexpr const char* PREPARE_TERMINATE_ENABLE_PARAMETER = "persist.sys.prepare_terminate"; +constexpr int32_t PREPARE_TERMINATE_TIMEOUT_MULTIPLE = 10; constexpr int32_t TRACE_ATOMIC_SERVICE_ID = 201; const std::string TRACE_ATOMIC_SERVICE = "StartAtomicService"; -const int GET_TARGET_MISSION_OVER = 200; +constexpr int GET_TARGET_MISSION_OVER = 200; std::string GetCurrentTime() { struct timespec tn; @@ -75,11 +77,18 @@ std::string GetCurrentTime() static_cast(tn.tv_nsec); return std::to_string(uTime); } -const std::unordered_map stateMap = { - { AbilityManagerService::LOAD_TIMEOUT_MSG, FreezeUtil::TimeoutState::LOAD }, - { AbilityManagerService::FOREGROUND_TIMEOUT_MSG, FreezeUtil::TimeoutState::FOREGROUND }, - { AbilityManagerService::BACKGROUND_TIMEOUT_MSG, FreezeUtil::TimeoutState::BACKGROUND } -}; + +FreezeUtil::TimeoutState MsgId2State(uint32_t msgId) +{ + if (msgId == AbilityManagerService::LOAD_TIMEOUT_MSG) { + return FreezeUtil::TimeoutState::LOAD; + } else if (msgId == AbilityManagerService::FOREGROUND_TIMEOUT_MSG) { + return FreezeUtil::TimeoutState::FOREGROUND; + } else if (msgId == AbilityManagerService::BACKGROUND_TIMEOUT_MSG) { + return FreezeUtil::TimeoutState::BACKGROUND; + } + return FreezeUtil::TimeoutState::UNKNOWN; +} auto g_deleteLifecycleEventTask = [](const sptr &token, FreezeUtil::TimeoutState state) { CHECK_POINTER_LOG(token, "token is nullptr."); @@ -423,7 +432,7 @@ int MissionListManager::StartAbilityLocked(const std::shared_ptr if (ret != GET_TARGET_MISSION_OVER) { return ret; } - + // 3. move mission to target list bool isCallerFromLauncher = (callerAbility && callerAbility->IsLauncherAbility()); MoveMissionToTargetList(isCallerFromLauncher, targetList, targetMission); @@ -544,7 +553,7 @@ bool MissionListManager::HandleReusedMissionAndAbility(const AbilityRequest &abi std::string MissionListManager::GetMissionName(const AbilityRequest &abilityRequest) const { - int32_t appIndex = abilityRequest.want.GetIntParam(DLP_INDEX, 0); + int32_t appIndex = AbilityRuntime::StartupUtil::GetAppIndex(abilityRequest.want); return AbilityUtil::ConvertBundleNameSingleton(abilityRequest.abilityInfo.bundleName, abilityRequest.abilityInfo.name, abilityRequest.abilityInfo.moduleName, appIndex); } @@ -673,7 +682,8 @@ void MissionListManager::BuildInnerMissionInfo(InnerMissionInfo &info, const std info.missionInfo.want = abilityRequest.want; info.missionInfo.unclearable = abilityRequest.abilityInfo.unclearableMission; info.isTemporary = abilityRequest.abilityInfo.removeMissionAfterTerminate; - if (abilityRequest.want.GetIntParam(DLP_INDEX, 0) != 0) { + auto dlpIndex = abilityRequest.want.GetIntParam(AbilityRuntime::ServerConstant::DLP_INDEX, 0); + if (dlpIndex > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { info.isTemporary = true; } info.specifiedFlag = abilityRequest.specifiedFlag; @@ -852,7 +862,7 @@ std::shared_ptr MissionListManager::GetReusedStandardMission(const Abil if (!missionList) { continue; } - + auto mission = missionList->GetRecentStandardMission(missionName); if (mission && mission->GetMissionTime() >= missionTime) { missionTime = mission->GetMissionTime(); @@ -1785,8 +1795,8 @@ void MissionListManager::CompleteTerminateAndUpdateMission(const std::shared_ptr terminateAbilityList_.remove(it); // update inner mission info time bool excludeFromMissions = abilityRecord->GetAbilityInfo().excludeFromMissions; - if ((abilityRecord->GetAppIndex() != 0) || abilityRecord->GetAbilityInfo().removeMissionAfterTerminate || - excludeFromMissions) { + if ((abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) || + abilityRecord->GetAbilityInfo().removeMissionAfterTerminate || excludeFromMissions) { RemoveMissionLocked(abilityRecord->GetMissionId(), excludeFromMissions); return; } @@ -2007,7 +2017,7 @@ void MissionListManager::UpdateSnapShot(const sptr &token, return; } int32_t missionId = abilityRecord->GetMissionId(); - auto isPrivate = abilityRecord->GetAppIndex() != 0; + auto isPrivate = abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX; DelayedSingleton::GetInstance()->UpdateMissionSnapshot(missionId, pixelMap, isPrivate); if (listenerController_) { listenerController_->NotifyMissionSnapshotChanged(missionId); @@ -2090,11 +2100,7 @@ void MissionListManager::PrintTimeOutLog(const std::shared_ptr &a } int typeId = AppExecFwk::AppfreezeManager::TypeAttribute::NORMAL_TIMEOUT; std::string msgContent = "ability:" + ability->GetAbilityInfo().name + " "; - FreezeUtil::TimeoutState state = FreezeUtil::TimeoutState::UNKNOWN; - auto search = stateMap.find(msgId); - if (search != stateMap.end()) { - state = search->second; - } + FreezeUtil::TimeoutState state = MsgId2State(msgId); if (!GetContentAndTypeId(msgId, msgContent, typeId)) { TAG_LOGW(AAFwkTag::ABILITYMGR, "msgId is invalid!"); return; @@ -2169,7 +2175,7 @@ void MissionListManager::UpdateMissionSnapshot(const std::shared_ptrGetMissionId(); MissionSnapshot snapshot; - snapshot.isPrivate = (abilityRecord->GetAppIndex() != 0); + snapshot.isPrivate = (abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX); DelayedSingleton::GetInstance()->UpdateMissionSnapshot(missionId, abilityRecord->GetToken(), snapshot); if (listenerController_) { @@ -2694,8 +2700,8 @@ void MissionListManager::HandleAbilityDiedByDefault(std::shared_ptrGetMissionId(); if (!ability->IsUninstallAbility()) { - if ((ability->GetAppIndex() != 0) || ability->GetAbilityInfo().removeMissionAfterTerminate || - ability->GetAbilityInfo().excludeFromMissions) { + if ((ability->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) || + ability->GetAbilityInfo().removeMissionAfterTerminate || ability->GetAbilityInfo().excludeFromMissions) { RemoveMissionLocked(missionId, ability->GetAbilityInfo().excludeFromMissions); } else { InnerMissionInfo info; @@ -3332,7 +3338,7 @@ std::shared_ptr MissionListManager::GetAbilityRecordByNameFromCur return defaultStandardAbility; } } - + // find in launcherList_ if (launcherList_ != nullptr) { return launcherList_->GetAbilityRecordByName(element); @@ -3584,13 +3590,6 @@ bool MissionListManager::IsReachToSingleLimitLocked(const int32_t uid) const return false; } -bool MissionListManager::MissionDmInitCallback::isInit_ = false; -void MissionListManager::MissionDmInitCallback::OnRemoteDied() -{ - isInit_ = false; - TAG_LOGW(AAFwkTag::ABILITYMGR, "DeviceManager died."); -} - void MissionListManager::RegisterSnapshotHandler(const sptr& handler) { DelayedSingleton::GetInstance()->RegisterSnapshotHandler(handler); @@ -3607,7 +3606,8 @@ bool MissionListManager::GetMissionSnapshot(int32_t missionId, const sptrIsAbilityState(FOREGROUND)) { forceSnapshot = true; - missionSnapshot.isPrivate = (abilityRecord->GetAppIndex() != 0); + missionSnapshot.isPrivate = + (abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX); } } return DelayedSingleton::GetInstance()->GetMissionSnapshot( diff --git a/services/abilitymgr/src/pending_want_manager.cpp b/services/abilitymgr/src/pending_want_manager.cpp index f7ca346c13..e7321e3519 100644 --- a/services/abilitymgr/src/pending_want_manager.cpp +++ b/services/abilitymgr/src/pending_want_manager.cpp @@ -41,7 +41,7 @@ PendingWantManager::PendingWantManager() PendingWantManager::~PendingWantManager() { - TAG_LOGD(AAFwkTag::WANTAGENT, "%{public}s(%{public}d)", __PRETTY_FUNCTION__, __LINE__); + TAG_LOGI(AAFwkTag::WANTAGENT, "%{public}s(%{public}d)", __PRETTY_FUNCTION__, __LINE__); } sptr PendingWantManager::GetWantSender(int32_t callingUid, int32_t uid, const bool isSystemApp, @@ -134,8 +134,8 @@ sptr PendingWantManager::GetPendingWantRecordByKey(const std: { TAG_LOGD(AAFwkTag::WANTAGENT, "begin"); for (const auto &item : wantRecords_) { - const auto &pendingKey = item.first; - const auto &pendingRecord = item.second; + const auto pendingKey = item.first; + const auto pendingRecord = item.second; if ((pendingRecord != nullptr) && CheckPendingWantRecordByKey(pendingKey, key)) { return pendingRecord; } @@ -146,6 +146,10 @@ sptr PendingWantManager::GetPendingWantRecordByKey(const std: bool PendingWantManager::CheckPendingWantRecordByKey( const std::shared_ptr &inputKey, const std::shared_ptr &key) { + if (!inputKey || !key) { + TAG_LOGW(AAFwkTag::WANTAGENT, "inputKey or key is nullptr!"); + return false; + } if (inputKey->GetBundleName().compare(key->GetBundleName()) != 0) { return false; } @@ -178,11 +182,21 @@ int32_t PendingWantManager::SendWantSender(sptr target, const Sende TAG_LOGI(AAFwkTag::WANTAGENT, "begin"); if (target == nullptr) { + if (senderInfo.finishedReceiver != nullptr) { + Want want; + WantParams wantParams = {}; + senderInfo.finishedReceiver->PerformReceive(want, senderInfo.code, "canceled", wantParams, false, false, 0); + } TAG_LOGE(AAFwkTag::WANTAGENT, "sender is nullptr."); return ERR_INVALID_VALUE; } sptr obj = target->AsObject(); if (obj == nullptr || obj->IsProxyObject()) { + if (senderInfo.finishedReceiver != nullptr) { + Want want; + WantParams wantParams = {}; + senderInfo.finishedReceiver->PerformReceive(want, senderInfo.code, "canceled", wantParams, false, false, 0); + } TAG_LOGE(AAFwkTag::WANTAGENT, "target obj is nullptr or is a proxy object."); return ERR_INVALID_VALUE; } @@ -339,7 +353,6 @@ int32_t PendingWantManager::PendingRecordIdCreate() sptr PendingWantManager::GetPendingWantRecordByCode(int32_t code) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::WANTAGENT, "begin. wantRecords_ size = %{public}zu", wantRecords_.size()); std::lock_guard locker(mutex_); auto iter = std::find_if(wantRecords_.begin(), wantRecords_.end(), [&code](const auto &pair) { @@ -605,6 +618,7 @@ void PendingWantManager::ClearPendingWantRecordTask(const std::string &bundleNam void PendingWantManager::Dump(std::vector &info) { + TAG_LOGD(AAFwkTag::WANTAGENT, "dump begin."); std::string dumpInfo = " PendingWantRecords:"; info.push_back(dumpInfo); @@ -636,6 +650,7 @@ void PendingWantManager::Dump(std::vector &info) } void PendingWantManager::DumpByRecordId(std::vector &info, const std::string &args) { + TAG_LOGD(AAFwkTag::WANTAGENT, "dump by id begin."); std::string dumpInfo = " PendingWantRecords:"; info.push_back(dumpInfo); diff --git a/services/abilitymgr/src/process_options.cpp b/services/abilitymgr/src/process_options.cpp index f0abe807c0..47163efec5 100644 --- a/services/abilitymgr/src/process_options.cpp +++ b/services/abilitymgr/src/process_options.cpp @@ -24,6 +24,7 @@ bool ProcessOptions::ReadFromParcel(Parcel &parcel) { processMode = static_cast(parcel.ReadInt32()); startupVisibility = static_cast(parcel.ReadInt32()); + processName = parcel.ReadString(); return true; } @@ -52,6 +53,10 @@ bool ProcessOptions::Marshalling(Parcel &parcel) const TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to write startupVisibility"); return false; } + if (!parcel.WriteString(processName)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to write processName"); + return false; + } return true; } @@ -78,5 +83,16 @@ bool ProcessOptions::IsNewProcessMode(ProcessMode value) return (value == ProcessMode::NEW_PROCESS_ATTACH_TO_PARENT) || (value == ProcessMode::NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM); } + +bool ProcessOptions::IsAttachToStatusBarMode(ProcessMode value) +{ + return (value == ProcessMode::NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM) || + (value == ProcessMode::ATTACH_TO_STATUS_BAR_ITEM); +} + +bool ProcessOptions::IsValidProcessMode(ProcessMode value) +{ + return (value > ProcessMode::UNSPECIFIED) && (value < ProcessMode::END); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/rdb/parser_util.cpp b/services/abilitymgr/src/rdb/parser_util.cpp index feab00dddc..4738451f73 100644 --- a/services/abilitymgr/src/rdb/parser_util.cpp +++ b/services/abilitymgr/src/rdb/parser_util.cpp @@ -16,6 +16,7 @@ #include "parser_util.h" #include +#include #include "config_policy_utils.h" #include "hilog_tag_wrapper.h" @@ -145,6 +146,11 @@ void ParserUtil::GetPreInstallRootDirList(std::vector &rootDirList) bool ParserUtil::ReadFileIntoJson(const std::string &filePath, nlohmann::json &jsonBuf) { + if (access(filePath.c_str(), F_OK) != 0) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "File path is not exist."); + return false; + } + if (filePath.empty()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "File path empty."); return false; diff --git a/services/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp b/services/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp index 825cdb09f2..fe3c37058e 100644 --- a/services/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp +++ b/services/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp @@ -58,41 +58,32 @@ int32_t StatusBarDelegateManager::DoProcessAttachment(std::shared_ptr int32_t { - auto sessionInfo = abilityRecord->GetSessionInfo(); - CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE); - auto processOptions = sessionInfo->processOptions; - if (processOptions == nullptr) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "no need to attach process."); - return ERR_OK; - } - if (processOptions->processMode == ProcessMode::NEW_PROCESS_ATTACH_TO_PARENT) { - auto callerRecord = abilityRecord->GetCallerRecord(); - CHECK_POINTER_AND_RETURN(callerRecord, ERR_INVALID_VALUE); - TAG_LOGI(AAFwkTag::ABILITYMGR, "attach pid to parent."); - IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton::GetInstance()->AttachPidToParent( - abilityRecord->GetToken(), callerRecord->GetToken())); - } - if (processOptions->processMode == ProcessMode::NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM) { - auto statusBarDelegate = GetStatusBarDelegate(); - CHECK_POINTER_AND_RETURN(statusBarDelegate, ERR_INVALID_VALUE); - auto accessTokenId = abilityRecord->GetApplicationInfo().accessTokenId; - auto ret = statusBarDelegate->AttachPidToStatusBarItem(accessTokenId, abilityRecord->GetPid()); - if (ret != ERR_OK) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "AttachPidToStatusBarItem failed, ret: %{public}d", ret); - return ret; - } - TAG_LOGI(AAFwkTag::ABILITYMGR, "AttachPidToStatusBarItem success."); - } + auto sessionInfo = abilityRecord->GetSessionInfo(); + CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE); + auto processOptions = sessionInfo->processOptions; + if (processOptions == nullptr) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "no need to attach process."); return ERR_OK; - }; - auto ret = func(); - if (ret != ERR_OK) { - std::vector pids; - pids.push_back(abilityRecord->GetPid()); - IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton::GetInstance()->KillProcessesByPids(pids)); } - return ret; + if (processOptions->processMode == ProcessMode::NEW_PROCESS_ATTACH_TO_PARENT) { + auto callerRecord = abilityRecord->GetCallerRecord(); + CHECK_POINTER_AND_RETURN(callerRecord, ERR_INVALID_VALUE); + TAG_LOGI(AAFwkTag::ABILITYMGR, "attach pid to parent."); + IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton::GetInstance()->AttachPidToParent( + abilityRecord->GetToken(), callerRecord->GetToken())); + } + if (ProcessOptions::IsAttachToStatusBarMode(processOptions->processMode)) { + auto statusBarDelegate = GetStatusBarDelegate(); + CHECK_POINTER_AND_RETURN(statusBarDelegate, ERR_INVALID_VALUE); + auto accessTokenId = abilityRecord->GetApplicationInfo().accessTokenId; + auto ret = statusBarDelegate->AttachPidToStatusBarItem(accessTokenId, abilityRecord->GetPid()); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "AttachPidToStatusBarItem failed, ret: %{public}d", ret); + return ret; + } + TAG_LOGI(AAFwkTag::ABILITYMGR, "AttachPidToStatusBarItem success."); + } + return ERR_OK; } } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp b/services/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp index 57bcb20dd2..0892d6b3e3 100644 --- a/services/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp +++ b/services/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp @@ -34,6 +34,8 @@ #include "scene_board/status_bar_delegate_manager.h" #include "session_info.h" #include "session_manager_lite.h" +#include "session/host/include/zidl/session_interface.h" +#include "startup_util.h" #ifdef SUPPORT_GRAPHICS #include "ability_first_frame_state_observer_manager.h" #endif @@ -43,31 +45,32 @@ using AbilityRuntime::FreezeUtil; namespace AAFwk { namespace { constexpr const char* SEPARATOR = ":"; -constexpr char EVENT_KEY_UID[] = "UID"; -constexpr char EVENT_KEY_PID[] = "PID"; -constexpr char EVENT_KEY_MESSAGE[] = "MSG"; -constexpr char EVENT_KEY_PACKAGE_NAME[] = "PACKAGE_NAME"; -constexpr char EVENT_KEY_PROCESS_NAME[] = "PROCESS_NAME"; -const std::string DLP_INDEX = "ohos.dlp.params.index"; constexpr int32_t PREPARE_TERMINATE_TIMEOUT_MULTIPLE = 10; -const std::string PARAM_MISSION_AFFINITY_KEY = "ohos.anco.param.missionAffinity"; -const std::string DMS_SRC_NETWORK_ID = "dmsSrcNetworkId"; -const std::string DMS_MISSION_ID = "dmsMissionId"; -const int DEFAULT_DMS_MISSION_ID = -1; -const std::string PARAM_SPECIFIED_PROCESS_FLAG = "ohoSpecifiedProcessFlag"; -const std::string DMS_PROCESS_NAME = "distributedsched"; -const std::string DMS_PERSISTENT_ID = "ohos.dms.persistentId"; +constexpr const char* PARAM_MISSION_AFFINITY_KEY = "ohos.anco.param.missionAffinity"; +constexpr const char* DMS_SRC_NETWORK_ID = "dmsSrcNetworkId"; +constexpr const char* DMS_MISSION_ID = "dmsMissionId"; +constexpr int DEFAULT_DMS_MISSION_ID = -1; +constexpr const char* PARAM_SPECIFIED_PROCESS_FLAG = "ohoSpecifiedProcessFlag"; +constexpr const char* DMS_PROCESS_NAME = "distributedsched"; +constexpr const char* DMS_PERSISTENT_ID = "ohos.dms.persistentId"; #ifdef SUPPORT_ASAN -const int KILL_TIMEOUT_MULTIPLE = 45; +constexpr int KILL_TIMEOUT_MULTIPLE = 45; #else -const int KILL_TIMEOUT_MULTIPLE = 3; +constexpr int KILL_TIMEOUT_MULTIPLE = 3; #endif constexpr int32_t DEFAULT_USER_ID = 0; -const std::unordered_map stateMap = { - { AbilityManagerService::LOAD_TIMEOUT_MSG, FreezeUtil::TimeoutState::LOAD }, - { AbilityManagerService::FOREGROUND_TIMEOUT_MSG, FreezeUtil::TimeoutState::FOREGROUND }, - { AbilityManagerService::BACKGROUND_TIMEOUT_MSG, FreezeUtil::TimeoutState::BACKGROUND } -}; + +FreezeUtil::TimeoutState MsgId2State(uint32_t msgId) +{ + if (msgId == AbilityManagerService::LOAD_TIMEOUT_MSG) { + return FreezeUtil::TimeoutState::LOAD; + } else if (msgId == AbilityManagerService::FOREGROUND_TIMEOUT_MSG) { + return FreezeUtil::TimeoutState::FOREGROUND; + } else if (msgId == AbilityManagerService::BACKGROUND_TIMEOUT_MSG) { + return FreezeUtil::TimeoutState::BACKGROUND; + } + return FreezeUtil::TimeoutState::UNKNOWN; +} auto g_deleteLifecycleEventTask = [](const sptr &token, FreezeUtil::TimeoutState state) { CHECK_POINTER_LOG(token, "token is nullptr."); @@ -78,7 +81,8 @@ auto g_deleteLifecycleEventTask = [](const sptr &token, FreezeUtil::Timeo UIAbilityLifecycleManager::UIAbilityLifecycleManager(int32_t userId): userId_(userId) {} -int UIAbilityLifecycleManager::StartUIAbility(AbilityRequest &abilityRequest, sptr sessionInfo) +int UIAbilityLifecycleManager::StartUIAbility(AbilityRequest &abilityRequest, sptr sessionInfo, + bool &isColdStart) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard guard(sessionLock_); @@ -102,6 +106,7 @@ int UIAbilityLifecycleManager::StartUIAbility(AbilityRequest &abilityRequest, sp } } else { uiAbilityRecord = CreateAbilityRecord(abilityRequest, sessionInfo); + isColdStart = true; UpdateProcessName(abilityRequest, uiAbilityRecord); } CHECK_POINTER_AND_RETURN(uiAbilityRecord, ERR_INVALID_VALUE); @@ -252,7 +257,8 @@ int UIAbilityLifecycleManager::AttachAbilityThread(const sptr abilityRecord->SetScheduler(scheduler); if (DoProcessAttachment(abilityRecord) != ERR_OK) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "do process attachment failed."); + TAG_LOGE(AAFwkTag::ABILITYMGR, "do process attachment failed, close the ability."); + BatchCloseUIAbility({abilityRecord}); return ERR_INVALID_VALUE; } if (abilityRecord->IsStartedByCall()) { @@ -327,15 +333,19 @@ int UIAbilityLifecycleManager::NotifySCBToStartUIAbility(const AbilityRequest &a bool isUIAbility = (abilityInfo.type == AppExecFwk::AbilityType::PAGE && abilityInfo.isStageBasedModel); if (abilityInfo.isolationProcess && AppUtils::GetInstance().IsStartSpecifiedProcess() && isUIAbility) { TAG_LOGI(AAFwkTag::ABILITYMGR, "StartSpecifiedProcess"); - EnqueueAbilityToFront(abilityRequest); - DelayedSingleton::GetInstance()->StartSpecifiedProcess(abilityRequest.want, abilityInfo); + specifiedRequestMap_.emplace(specifiedRequestId_, abilityRequest); + DelayedSingleton::GetInstance()->StartSpecifiedProcess(abilityRequest.want, abilityInfo, + specifiedRequestId_); + ++specifiedRequestId_; return ERR_OK; } auto isSpecified = (abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED); if (isSpecified) { - EnqueueAbilityToFront(abilityRequest); + PreCreateProcessName(const_cast(abilityRequest)); + specifiedRequestMap_.emplace(specifiedRequestId_, abilityRequest); DelayedSingleton::GetInstance()->StartSpecifiedAbility( - abilityRequest.want, abilityRequest.abilityInfo); + abilityRequest.want, abilityRequest.abilityInfo, specifiedRequestId_); + ++specifiedRequestId_; return ERR_OK; } auto sessionInfo = CreateSessionInfo(abilityRequest); @@ -614,6 +624,28 @@ void UIAbilityLifecycleManager::EraseSpecifiedAbilityRecord(const std::shared_pt } } +std::string UIAbilityLifecycleManager::GenerateProcessNameForNewProcessMode(const AppExecFwk::AbilityInfo& abilityInfo) +{ + static uint32_t index = 0; + std::string processName = abilityInfo.bundleName + SEPARATOR + abilityInfo.moduleName + SEPARATOR + + abilityInfo.name + SEPARATOR + std::to_string(index++); + TAG_LOGI(AAFwkTag::ABILITYMGR, "processName: %{public}s", processName.c_str()); + return processName; +} + +void UIAbilityLifecycleManager::PreCreateProcessName(AbilityRequest &abilityRequest) +{ + if (abilityRequest.processOptions == nullptr || + !ProcessOptions::IsNewProcessMode(abilityRequest.processOptions->processMode)) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "No need to pre create process name."); + return; + } + TAG_LOGI(AAFwkTag::ABILITYMGR, "create process name in advance."); + std::string processName = GenerateProcessNameForNewProcessMode(abilityRequest.abilityInfo); + abilityRequest.processOptions->processName = processName; + abilityRequest.abilityInfo.process = processName; +} + void UIAbilityLifecycleManager::UpdateProcessName(const AbilityRequest &abilityRequest, std::shared_ptr &abilityRecord) { @@ -623,11 +655,13 @@ void UIAbilityLifecycleManager::UpdateProcessName(const AbilityRequest &abilityR TAG_LOGD(AAFwkTag::ABILITYMGR, "No need to update process name."); return; } - static uint32_t index = 0; - std::string processName = abilityRequest.abilityInfo.bundleName + SEPARATOR + - abilityRequest.abilityInfo.moduleName + SEPARATOR + abilityRequest.abilityInfo.name + - SEPARATOR + std::to_string(index++); - TAG_LOGD(AAFwkTag::ABILITYMGR, "processName: %{public}s", processName.c_str()); + std::string processName; + if (!abilityRequest.sessionInfo->processOptions->processName.empty()) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "The process name has been generated in advance."); + processName = abilityRequest.sessionInfo->processOptions->processName; + } else { + processName = GenerateProcessNameForNewProcessMode(abilityRequest.abilityInfo); + } abilityRecord->SetProcessName(processName); } @@ -907,7 +941,8 @@ int UIAbilityLifecycleManager::NotifySCBPendingActivation(sptr &ses TAG_LOGI(AAFwkTag::ABILITYMGR, "Call PendingSessionActivation by callerSession."); return static_cast(callerSession->PendingSessionActivation(sessionInfo)); } - CHECK_POINTER_AND_RETURN(rootSceneSession_, ERR_INVALID_VALUE); + auto tmpSceneSession = iface_cast(rootSceneSession_); + CHECK_POINTER_AND_RETURN(tmpSceneSession, ERR_INVALID_VALUE); if (sessionInfo->persistentId == 0) { const auto &abilityInfo = abilityRequest.abilityInfo; auto isStandard = abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD && !abilityRequest.startRecent; @@ -918,7 +953,7 @@ int UIAbilityLifecycleManager::NotifySCBPendingActivation(sptr &ses } } TAG_LOGI(AAFwkTag::ABILITYMGR, "Call PendingSessionActivation by rootSceneSession."); - return static_cast(rootSceneSession_->PendingSessionActivation(sessionInfo)); + return static_cast(tmpSceneSession->PendingSessionActivation(sessionInfo)); } int UIAbilityLifecycleManager::ResolveAbility( @@ -989,11 +1024,7 @@ void UIAbilityLifecycleManager::PrintTimeOutLog(std::shared_ptr a .eventName = eventName, .bundleName = ability->GetAbilityInfo().bundleName, }; - FreezeUtil::TimeoutState state = FreezeUtil::TimeoutState::UNKNOWN; - auto search = stateMap.find(msgId); - if (search != stateMap.end()) { - state = search->second; - } + FreezeUtil::TimeoutState state = MsgId2State(msgId); if (state != FreezeUtil::TimeoutState::UNKNOWN) { auto flow = std::make_unique(); if (ability->GetToken() != nullptr) { @@ -1286,7 +1317,7 @@ bool UIAbilityLifecycleManager::CheckProperties(const std::shared_ptrGetAppIndex(); + AbilityRuntime::StartupUtil::GetAppIndex(abilityRequest.want) == abilityRecord->GetAppIndex(); } void UIAbilityLifecycleManager::OnTimeOut(uint32_t msgId, int64_t abilityRecordId, bool isHalf) @@ -1328,17 +1359,12 @@ void UIAbilityLifecycleManager::OnTimeOut(uint32_t msgId, int64_t abilityRecordI void UIAbilityLifecycleManager::SetRootSceneSession(const sptr &rootSceneSession) { TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); - if (rootSceneSession == nullptr) { + auto tmpSceneSession = iface_cast(rootSceneSession); + if (tmpSceneSession == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "rootSceneSession is invalid."); return; } - auto tmpSceneSession = iface_cast(rootSceneSession); - auto descriptor = Str16ToStr8(tmpSceneSession->GetDescriptor()); - if (descriptor != "OHOS.ISession") { - TAG_LOGE(AAFwkTag::ABILITYMGR, "token's Descriptor: %{public}s", descriptor.c_str()); - return; - } - rootSceneSession_ = tmpSceneSession; + rootSceneSession_ = rootSceneSession; } void UIAbilityLifecycleManager::NotifySCBToHandleException(const std::shared_ptr &abilityRecord, @@ -1423,20 +1449,24 @@ void UIAbilityLifecycleManager::OnAbilityDied(std::shared_ptr abi EraseSpecifiedAbilityRecord(abilityRecord); } -void UIAbilityLifecycleManager::OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag) +void UIAbilityLifecycleManager::OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag, + int32_t requestId) { TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard guard(sessionLock_); - if (abilityQueue_.empty()) { + auto it = specifiedRequestMap_.find(requestId); + if (it == specifiedRequestMap_.end()) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "Not find for %{public}s.", want.GetElement().GetURI().c_str()); return; } - AbilityRequest abilityRequest = abilityQueue_.front(); - abilityQueue_.pop(); + AbilityRequest abilityRequest = it->second; + specifiedRequestMap_.erase(it); if (abilityRequest.abilityInfo.launchMode != AppExecFwk::LaunchMode::SPECIFIED) { return; } + TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s.", want.GetElement().GetURI().c_str()); auto callerAbility = GetAbilityRecordByToken(abilityRequest.callerToken); if (!flag.empty()) { abilityRequest.specifiedFlag = flag; @@ -1459,35 +1489,34 @@ void UIAbilityLifecycleManager::OnAcceptWantResponse(const AAFwk::Want &want, co StartAbilityBySpecifed(abilityRequest, callerAbility); } -void UIAbilityLifecycleManager::OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want) +void UIAbilityLifecycleManager::OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want, int32_t requestId) { TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s called.", __func__); std::lock_guard guard(sessionLock_); - if (abilityQueue_.empty()) { - return; - } - abilityQueue_.pop(); + specifiedRequestMap_.erase(requestId); } -void UIAbilityLifecycleManager::OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag) +void UIAbilityLifecycleManager::OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag, + int32_t requestId) { TAG_LOGD(AAFwkTag::ABILITYMGR, "call."); HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard guard(sessionLock_); - if (abilityQueue_.empty()) { + auto it = specifiedRequestMap_.find(requestId); + if (it == specifiedRequestMap_.end()) { return; } - AbilityRequest abilityRequest = abilityQueue_.front(); - abilityQueue_.pop(); + TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s.", want.GetElement().GetURI().c_str()); + AbilityRequest abilityRequest = it->second; std::string specifiedProcessFlag = flag; abilityRequest.want.SetParam(PARAM_SPECIFIED_PROCESS_FLAG, specifiedProcessFlag); auto isSpecified = (abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED); if (isSpecified) { - EnqueueAbilityToFront(abilityRequest); DelayedSingleton::GetInstance()->StartSpecifiedAbility( - abilityRequest.want, abilityRequest.abilityInfo); + abilityRequest.want, abilityRequest.abilityInfo, requestId); return; } + specifiedRequestMap_.erase(it); auto sessionInfo = CreateSessionInfo(abilityRequest); sessionInfo->requestCode = abilityRequest.requestCode; sessionInfo->persistentId = GetPersistentIdByAbilityRequest(abilityRequest, sessionInfo->reuse); @@ -1497,15 +1526,11 @@ void UIAbilityLifecycleManager::OnStartSpecifiedProcessResponse(const AAFwk::Wan NotifySCBPendingActivation(sessionInfo, abilityRequest); } -void UIAbilityLifecycleManager::OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want) +void UIAbilityLifecycleManager::OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want, int32_t requestId) { TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s called.", __func__); std::lock_guard guard(sessionLock_); - TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityQueue_.size() = %{public}zu", abilityQueue_.size()); - if (abilityQueue_.empty()) { - return; - } - abilityQueue_.pop(); + specifiedRequestMap_.erase(requestId); } void UIAbilityLifecycleManager::StartSpecifiedAbilityBySCB(const Want &want) @@ -1518,13 +1543,15 @@ void UIAbilityLifecycleManager::StartSpecifiedAbilityBySCB(const Want &want) TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot find generate ability request"); return; } + int32_t requestId = 0; { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard guard(sessionLock_); - EnqueueAbilityToFront(abilityRequest); + requestId = specifiedRequestId_++; + specifiedRequestMap_.emplace(requestId, abilityRequest); } DelayedSingleton::GetInstance()->StartSpecifiedAbility( - abilityRequest.want, abilityRequest.abilityInfo); + abilityRequest.want, abilityRequest.abilityInfo, requestId); } std::shared_ptr UIAbilityLifecycleManager::GetReusedSpecifiedAbility(const AAFwk::Want &want, @@ -1540,11 +1567,6 @@ std::shared_ptr UIAbilityLifecycleManager::GetReusedSpecifiedAbil return nullptr; } -void UIAbilityLifecycleManager::EnqueueAbilityToFront(const AbilityRequest &abilityRequest) -{ - abilityQueue_.push(abilityRequest); -} - void UIAbilityLifecycleManager::NotifyRestartSpecifiedAbility(AbilityRequest &request, const sptr &token) { @@ -1608,6 +1630,7 @@ int UIAbilityLifecycleManager::SendSessionInfoToSCB(std::shared_ptr &sessionInfo) { TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); + auto tmpSceneSession = iface_cast(rootSceneSession_); if (callerAbility != nullptr) { auto callerSessionInfo = callerAbility->GetSessionInfo(); if (callerSessionInfo != nullptr && callerSessionInfo->sessionToken != nullptr) { @@ -1617,12 +1640,12 @@ int UIAbilityLifecycleManager::SendSessionInfoToSCB(std::shared_ptrhasContinuousTask = hasContinuousTask; callerSession->PendingSessionActivation(sessionInfo); } else { - CHECK_POINTER_AND_RETURN(rootSceneSession_, ERR_INVALID_VALUE); - rootSceneSession_->PendingSessionActivation(sessionInfo); + CHECK_POINTER_AND_RETURN(tmpSceneSession, ERR_INVALID_VALUE); + tmpSceneSession->PendingSessionActivation(sessionInfo); } } else { - CHECK_POINTER_AND_RETURN(rootSceneSession_, ERR_INVALID_VALUE); - rootSceneSession_->PendingSessionActivation(sessionInfo); + CHECK_POINTER_AND_RETURN(tmpSceneSession, ERR_INVALID_VALUE); + tmpSceneSession->PendingSessionActivation(sessionInfo); } return ERR_OK; } @@ -2121,7 +2144,8 @@ void UIAbilityLifecycleManager::DumpMissionListByRecordId(std::vector startOptions) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - CHECK_POINTER_AND_RETURN(rootSceneSession_, ERR_INVALID_VALUE); + auto tmpSceneSession = iface_cast(rootSceneSession_); + CHECK_POINTER_AND_RETURN(tmpSceneSession, ERR_INVALID_VALUE); std::shared_ptr abilityRecord = GetAbilityRecordsById(sessionId); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); if (startOptions != nullptr) { @@ -2130,7 +2154,7 @@ int UIAbilityLifecycleManager::MoveMissionToFront(int32_t sessionId, std::shared sptr sessionInfo = abilityRecord->GetSessionInfo(); CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE); TAG_LOGI(AAFwkTag::ABILITYMGR, "Call PendingSessionActivation by rootSceneSession."); - return static_cast(rootSceneSession_->PendingSessionActivation(sessionInfo)); + return static_cast(tmpSceneSession->PendingSessionActivation(sessionInfo)); } std::shared_ptr UIAbilityLifecycleManager::GetStatusBarDelegateManager() @@ -2197,7 +2221,8 @@ int32_t UIAbilityLifecycleManager::KillProcessWithPrepareTerminate(const std::ve return ERR_OK; } -void UIAbilityLifecycleManager::BatchCloseUIAbility(std::unordered_set>& abilitySet) +void UIAbilityLifecycleManager::BatchCloseUIAbility( + const std::unordered_set>& abilitySet) { auto closeTask = [ self = shared_from_this(), abilitySet]() { TAG_LOGI(AAFwkTag::ABILITYMGR, "The abilities need to be closed."); @@ -2230,7 +2255,7 @@ int UIAbilityLifecycleManager::ChangeAbilityVisibility(sptr token auto sessionInfo = abilityRecord->GetSessionInfo(); CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE); if (sessionInfo->processOptions == nullptr || - sessionInfo->processOptions->processMode != ProcessMode::NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM) { + !ProcessOptions::IsAttachToStatusBarMode(sessionInfo->processOptions->processMode)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Process options check failed."); return ERR_START_OPTIONS_CHECK_FAILED; } diff --git a/services/abilitymgr/src/start_ability_handler/start_ability_sandbox_savefile.cpp b/services/abilitymgr/src/start_ability_handler/start_ability_sandbox_savefile.cpp index 6bd44f65a6..98385c73d5 100644 --- a/services/abilitymgr/src/start_ability_handler/start_ability_sandbox_savefile.cpp +++ b/services/abilitymgr/src/start_ability_handler/start_ability_sandbox_savefile.cpp @@ -28,7 +28,6 @@ namespace AAFwk { namespace { const std::string DLP_BUNDLE_NAME = "com.ohos.dlpmanager"; const std::string DLP_ABILITY_NAME = "SaveAsAbility"; -const std::string DLP_INDEX = "ohos.dlp.params.index"; class EmptyConnection : public IRemoteStub { public: diff --git a/services/abilitymgr/src/start_ability_utils.cpp b/services/abilitymgr/src/start_ability_utils.cpp index 8fcfa24f27..49bd7a25af 100644 --- a/services/abilitymgr/src/start_ability_utils.cpp +++ b/services/abilitymgr/src/start_ability_utils.cpp @@ -19,30 +19,37 @@ #include "ability_util.h" #include "bundle_constants.h" #include "bundle_mgr_helper.h" +#include "global_constant.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" #include "hitrace_meter.h" +#include "server_constant.h" +#include "startup_util.h" namespace OHOS { namespace AAFwk { namespace { -constexpr const char* DLP_INDEX = "ohos.dlp.params.index"; constexpr const char* SCREENSHOT_BUNDLE_NAME = "com.huawei.ohos.screenshot"; constexpr const char* SCREENSHOT_ABILITY_NAME = "com.huawei.ohos.screenshot.ServiceExtAbility"; } thread_local std::shared_ptr StartAbilityUtils::startAbilityInfo; +thread_local std::shared_ptr StartAbilityUtils::callerAbilityInfo; thread_local bool StartAbilityUtils::skipCrowTest = false; thread_local bool StartAbilityUtils::skipStartOther = false; thread_local bool StartAbilityUtils::skipErms = false; int32_t StartAbilityUtils::GetAppIndex(const Want &want, sptr callerToken) { + int32_t appIndex = want.GetIntParam(AbilityRuntime::ServerConstant::APP_CLONE_INDEX, 0); + if (appIndex > 0 && appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { + return appIndex; + } auto abilityRecord = Token::GetAbilityRecordByToken(callerToken); - if (abilityRecord && abilityRecord->GetAppIndex() != 0 && + if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX && abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) { return abilityRecord->GetAppIndex(); } - return want.GetIntParam(DLP_INDEX, 0); + return want.GetIntParam(AbilityRuntime::ServerConstant::DLP_INDEX, 0); } bool StartAbilityUtils::GetApplicationInfo(const std::string &bundleName, int32_t userId, @@ -66,8 +73,26 @@ bool StartAbilityUtils::GetApplicationInfo(const std::string &bundleName, int32_ return true; } +bool StartAbilityUtils::GetCallerAbilityInfo(const sptr &callerToken, + AppExecFwk::AbilityInfo &abilityInfo) +{ + if (StartAbilityUtils::callerAbilityInfo) { + abilityInfo = StartAbilityUtils::callerAbilityInfo->abilityInfo; + } else { + if (callerToken == nullptr) { + return false; + } + auto abilityRecord = Token::GetAbilityRecordByToken(callerToken); + if (abilityRecord == nullptr) { + return false; + } + abilityInfo = abilityRecord->GetAbilityInfo(); + } + return true; +} + StartAbilityInfoWrap::StartAbilityInfoWrap(const Want &want, int32_t validUserId, int32_t appIndex, - bool isExtension) + const sptr &callerToken, bool isExtension) { if (StartAbilityUtils::startAbilityInfo != nullptr) { TAG_LOGW(AAFwkTag::ABILITYMGR, "startAbilityInfo has been created"); @@ -91,11 +116,17 @@ StartAbilityInfoWrap::StartAbilityInfoWrap(const Want &want, int32_t validUserId StartAbilityUtils::skipCrowTest = true; StartAbilityUtils::skipStartOther = true; } + + if (StartAbilityUtils::callerAbilityInfo != nullptr) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "callerAbilityInfo has been created"); + } + StartAbilityUtils::callerAbilityInfo = StartAbilityInfo::CreateCallerAbilityInfo(callerToken); } StartAbilityInfoWrap::~StartAbilityInfoWrap() { StartAbilityUtils::startAbilityInfo.reset(); + StartAbilityUtils::callerAbilityInfo.reset(); StartAbilityUtils::skipCrowTest = false; StartAbilityUtils::skipStartOther = false; StartAbilityUtils::skipErms = false; @@ -145,11 +176,17 @@ std::shared_ptr StartAbilityInfo::CreateStartAbilityInfo(const HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto bms = AbilityUtil::GetBundleManagerHelper(); CHECK_POINTER_AND_RETURN(bms, nullptr); - auto abilityInfoFlag = (AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION | - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION | - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA | - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_SKILL); + auto abilityInfoFlag = static_cast(AbilityRuntime::StartupUtil::BuildAbilityInfoFlag()) | + static_cast(AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_SKILL); auto request = std::make_shared(); + if (appIndex != 0 && appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { + IN_PROCESS_CALL_WITHOUT_RET(bms->QueryCloneAbilityInfo(want.GetElement(), abilityInfoFlag, appIndex, + request->abilityInfo, userId)); + if (request->abilityInfo.name.empty() || request->abilityInfo.bundleName.empty()) { + request->status = ERR_APP_CLONE_INDEX_INVALID; + } + return request; + } if (appIndex == 0) { IN_PROCESS_CALL_WITHOUT_RET(bms->QueryAbilityInfo(want, abilityInfoFlag, userId, request->abilityInfo)); } else { @@ -191,10 +228,8 @@ std::shared_ptr StartAbilityInfo::CreateStartExtensionInfo(con HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto bms = AbilityUtil::GetBundleManagerHelper(); CHECK_POINTER_AND_RETURN(bms, nullptr); - auto abilityInfoFlag = (AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION | - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION | - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA | - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_SKILL); + auto abilityInfoFlag = static_cast(AbilityRuntime::StartupUtil::BuildAbilityInfoFlag()) | + static_cast(AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_SKILL); auto abilityInfo = std::make_shared(); std::vector extensionInfos; @@ -222,5 +257,22 @@ std::shared_ptr StartAbilityInfo::CreateStartExtensionInfo(con return abilityInfo; } + +std::shared_ptr StartAbilityInfo::CreateCallerAbilityInfo(const sptr &callerToken) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + if (callerToken == nullptr) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "not call from context."); + return nullptr; + } + auto abilityRecord = Token::GetAbilityRecordByToken(callerToken); + if (abilityRecord == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "can not find abilityRecord"); + return nullptr; + } + auto request = std::make_shared(); + request->abilityInfo = abilityRecord->GetAbilityInfo(); + return request; +} } } \ No newline at end of file diff --git a/services/abilitymgr/src/ui_extension_record_factory.cpp b/services/abilitymgr/src/ui_extension_record_factory.cpp index 754df8ec8a..99dba41aff 100644 --- a/services/abilitymgr/src/ui_extension_record_factory.cpp +++ b/services/abilitymgr/src/ui_extension_record_factory.cpp @@ -14,10 +14,10 @@ */ #include "ui_extension_record_factory.h" -#include "ui_extension_record.h" #include "ability_util.h" #include "extension_record_manager.h" #include "hilog_tag_wrapper.h" +#include "ui_extension_record.h" namespace OHOS { namespace AbilityRuntime { @@ -39,7 +39,7 @@ bool UIExtensionRecordFactory::NeedReuse(const AAFwk::AbilityRequest &abilityReq } TAG_LOGI(AAFwkTag::ABILITYMGR, "UIExtensionAbility id: %{public}d.", uiExtensionAbilityId); extensionRecordId = uiExtensionAbilityId; - return ExtensionRecordFactory::NeedReuse(abilityRequest, extensionRecordId); + return true; } int32_t UIExtensionRecordFactory::PreCheck( @@ -51,7 +51,7 @@ int32_t UIExtensionRecordFactory::PreCheck( int32_t UIExtensionRecordFactory::CreateRecord( const AAFwk::AbilityRequest &abilityRequest, std::shared_ptr &extensionRecord) { - std::shared_ptr abilityRecord = AAFwk::AbilityRecord::CreateAbilityRecord(abilityRequest); + auto abilityRecord = AAFwk::AbilityRecord::CreateAbilityRecord(abilityRequest); if (abilityRecord == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to create ability record"); return ERR_NULL_OBJECT; diff --git a/services/appdfr/include/appfreeze_manager.h b/services/appdfr/include/appfreeze_manager.h index 111b206363..bef4d74219 100644 --- a/services/appdfr/include/appfreeze_manager.h +++ b/services/appdfr/include/appfreeze_manager.h @@ -47,6 +47,17 @@ public: CRITICAL_TIMEOUT = 1, }; + enum AppFreezeState { + APPFREEZE_STATE_IDLE = 0, + APPFREEZE_STATE_FREEZE = 1, + }; + + struct AppFreezeInfo { + int32_t pid = 0; + int state = 0; + int64_t occurTime = 0; + }; + struct ParamInfo { int typeId = TypeAttribute::NORMAL_TIMEOUT; int32_t pid = 0; @@ -66,6 +77,7 @@ public: std::string WriteToFile(const std::string& fileName, std::string& content); bool IsHandleAppfreeze(const std::string& bundleName); bool IsProcessDebug(int32_t pid, std::string processName); + bool IsNeedIgnoreFreezeEvent(int32_t pid); private: AppfreezeManager& operator=(const AppfreezeManager&) = delete; @@ -78,11 +90,18 @@ private: std::string CatcherStacktrace(int pid) const; int AcquireStack(const FaultData& faultData, const AppInfo& appInfo); int NotifyANR(const FaultData& faultData, const AppfreezeManager::AppInfo& appInfo, const std::string& binderInfo); + int64_t GetFreezeCurrentTime(); + void SetFreezeState(int32_t pid, int state); + int GetFreezeState(int32_t pid); + int64_t GetFreezeTime(int32_t pid); + void ClearOldInfo(); static const inline std::string LOGGER_DEBUG_PROC_PATH = "/proc/transaction_proc"; std::string name_; static ffrt::mutex singletonMutex_; static std::shared_ptr instance_; + static ffrt::mutex freezeMutex_; + std::map appfreezeInfo_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appdfr/src/appfreeze_manager.cpp b/services/appdfr/src/appfreeze_manager.cpp index 20436499e6..e54611ac35 100644 --- a/services/appdfr/src/appfreeze_manager.cpp +++ b/services/appdfr/src/appfreeze_manager.cpp @@ -47,10 +47,15 @@ constexpr char EVENT_STACK[] = "STACK"; constexpr char BINDER_INFO[] = "BINDER_INFO"; constexpr char APP_RUNNING_UNIQUE_ID[] = "APP_RUNNING_UNIQUE_ID"; constexpr int MAX_LAYER = 8; +constexpr int FREEZEMAP_SIZE_MAX = 20; +constexpr int FREEZE_TIME_LIMIT = 60000; +static constexpr int64_t NANOSECONDS = 1000000000; // NANOSECONDS mean 10^9 nano second +static constexpr int64_t MICROSECONDS = 1000000; // MICROSECONDS mean 10^6 millias second const std::string LOG_FILE_PATH = "data/log/eventlog"; } std::shared_ptr AppfreezeManager::instance_ = nullptr; ffrt::mutex AppfreezeManager::singletonMutex_; +ffrt::mutex AppfreezeManager::freezeMutex_; AppfreezeManager::AppfreezeManager() { @@ -128,6 +133,14 @@ int AppfreezeManager::AppfreezeHandleWithStack(const FaultData& faultData, const HITRACE_METER_FMT(HITRACE_TAG_APP, "AppfreezeHandleWithStack pid:%d-name:%s", appInfo.pid, faultData.errorObject.name.c_str()); + if (faultData.errorObject.name == AppFreezeType::LIFECYCLE_HALF_TIMEOUT + || faultData.errorObject.name == AppFreezeType::APP_INPUT_BLOCK + || faultData.errorObject.name == AppFreezeType::THREAD_BLOCK_6S) { + if (AppExecFwk::AppfreezeManager::GetInstance()->IsNeedIgnoreFreezeEvent(appInfo.pid)) { + TAG_LOGE(AAFwkTag::APPDFR, "AppFreeze already happend in a short period of time."); + return 0; + } + } std::string fileName = faultData.errorObject.name + "_" + std::to_string(appInfo.pid) + "_stack"; std::string catcherStack = ""; @@ -419,5 +432,90 @@ bool AppfreezeManager::IsProcessDebug(int32_t pid, std::string processName) } return false; } + +int64_t AppfreezeManager::GetFreezeCurrentTime() +{ + struct timespec t; + t.tv_sec = 0; + t.tv_nsec = 0; + clock_gettime(CLOCK_MONOTONIC, &t); + return static_cast(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS); +} + +void AppfreezeManager::SetFreezeState(int32_t pid, int state) +{ + std::lock_guard lock(freezeMutex_); + if (appfreezeInfo_.find(pid) != appfreezeInfo_.end()) { + appfreezeInfo_[pid].state = state; + appfreezeInfo_[pid].occurTime = GetFreezeCurrentTime(); + } else { + AppFreezeInfo info; + info.pid = pid; + info.state = state; + info.occurTime = GetFreezeCurrentTime(); + appfreezeInfo_.emplace(pid, info); + } +} + +int AppfreezeManager::GetFreezeState(int32_t pid) +{ + std::lock_guard lock(freezeMutex_); + auto it = appfreezeInfo_.find(pid); + if (it != appfreezeInfo_.end()) { + return it->second.state; + } + return AppFreezeState::APPFREEZE_STATE_IDLE; +} + +int64_t AppfreezeManager::GetFreezeTime(int32_t pid) +{ + std::lock_guard lock(freezeMutex_); + auto it = appfreezeInfo_.find(pid); + if (it != appfreezeInfo_.end()) { + return it->second.occurTime; + } + return 0; +} + +void AppfreezeManager::ClearOldInfo() +{ + std::lock_guard lock(freezeMutex_); + int64_t currentTime = GetFreezeCurrentTime(); + for (auto it = appfreezeInfo_.begin(); it != appfreezeInfo_.end();) { + auto diff = currentTime - it->second.occurTime; + if (diff > FREEZE_TIME_LIMIT) { + it = appfreezeInfo_.erase(it); + } else { + ++it; + } + } +} + +bool AppfreezeManager::IsNeedIgnoreFreezeEvent(int32_t pid) +{ + if (appfreezeInfo_.size() >= FREEZEMAP_SIZE_MAX) { + ClearOldInfo(); + } + int state = GetFreezeState(pid); + int64_t currentTime = GetFreezeCurrentTime(); + int64_t lastTime = GetFreezeTime(pid); + auto diff = currentTime - lastTime; + if (state == AppFreezeState::APPFREEZE_STATE_FREEZE) { + if (diff >= FREEZE_TIME_LIMIT) { + TAG_LOGI(AAFwkTag::APPDFR, "IsNeedIgnoreFreezeEvent durationTime: " + "%{public}" PRId64 "state: %{public}d", diff, state); + return false; + } + return true; + } else { + if (diff < FREEZE_TIME_LIMIT) { + return true; + } + SetFreezeState(pid, AppFreezeState::APPFREEZE_STATE_FREEZE); + TAG_LOGI(AAFwkTag::APPDFR, "IsNeedIgnoreFreezeEvent durationTime: " + "%{public}" PRId64 " SetFreezeState: %{public}d", diff, state); + return false; + } +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/BUILD.gn b/services/appmgr/BUILD.gn index ae21f7baa3..356af19f64 100644 --- a/services/appmgr/BUILD.gn +++ b/services/appmgr/BUILD.gn @@ -23,20 +23,22 @@ config("appmgr_config") { "${ability_runtime_services_path}/common/include", "${ability_runtime_path}/tools/aa/include", "${ability_runtime_path}/utils/global/time/include", - "${distributeddatamgr_path}/kv_store/interfaces/innerkits/distributeddatamgr/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_utils_path}/global/constant", ] } -config("appmgr_exception_config") { - cflags_cc = [ "-fexceptions" ] -} - group("appms_target") { deps = [ ":libappms" ] } ohos_shared_library("libappms") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" shlib_type = "sa" include_dirs = [ "${ability_runtime_services_path}/appdfr/include" ] sources = [ @@ -83,10 +85,7 @@ ohos_shared_library("libappms") { defines += [ "ABILITY_FAULT_AND_EXIT_TEST" ] } - configs = [ - ":appmgr_config", - ":appmgr_exception_config", - ] + configs = [ ":appmgr_config" ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] @@ -97,6 +96,7 @@ ohos_shared_library("libappms") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:event_report", "${ability_runtime_services_path}/common:perm_verification", @@ -129,8 +129,7 @@ ohos_shared_library("libappms") { "safwk:system_ability_fwk", "samgr:samgr_proxy", ] - - defines += [ "OHOS_ACCOUNT_ENABLED" ] + public_external_deps = [ "kv_store:distributeddata_mgr" ] if (product_name != "ohcore") { external_deps += [ "netmanager_base:net_conn_manager_if" ] diff --git a/services/appmgr/include/ams_mgr_scheduler.h b/services/appmgr/include/ams_mgr_scheduler.h index 7c70d3a2e4..b0fce3f9c1 100644 --- a/services/appmgr/include/ams_mgr_scheduler.h +++ b/services/appmgr/include/ams_mgr_scheduler.h @@ -165,6 +165,8 @@ public: int GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application, bool &debug) override; + virtual int32_t NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg) override; + virtual void AbilityAttachTimeOut(const sptr &token) override; virtual void PrepareTerminate(const sptr &token) override; @@ -172,8 +174,6 @@ public: virtual void GetRunningProcessInfoByToken( const sptr &token, AppExecFwk::RunningProcessInfo &info) override; - void GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) override; - /** * Set AbilityForegroundingFlag of an app-record to true. * @@ -183,11 +183,12 @@ public: void SetAbilityForegroundingFlagToAppRecord(const pid_t pid) override; virtual void StartSpecifiedAbility( - const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) override; + const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, int32_t requestId = 0) override; virtual void RegisterStartSpecifiedAbilityResponse(const sptr &response) override; - virtual void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) override; + virtual void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId = 0) override; virtual void SetCurrentUserId(const int32_t userId) override; @@ -274,14 +275,6 @@ public: */ void SetKeepAliveEnableState(const std::string &bundleName, bool enable) override; - /** - * Set application assertion pause state. - * - * @param pid App process pid. - * @param flag assertion pause state. - */ - void SetAppAssertionPauseState(int32_t pid, bool flag) override; - /** * To clear the process by ability token. * diff --git a/services/appmgr/include/app_lifecycle_deal.h b/services/appmgr/include/app_lifecycle_deal.h index 441ca00ec2..7dac5b7c64 100644 --- a/services/appmgr/include/app_lifecycle_deal.h +++ b/services/appmgr/include/app_lifecycle_deal.h @@ -223,6 +223,8 @@ public: int DumpIpcStat(std::string& result); + int DumpFfrt(std::string& result); + private: mutable std::mutex schedulerMutex_; sptr appThread_ = nullptr; diff --git a/services/appmgr/include/app_mgr_service.h b/services/appmgr/include/app_mgr_service.h index ce653ae473..5eae50c846 100644 --- a/services/appmgr/include/app_mgr_service.h +++ b/services/appmgr/include/app_mgr_service.h @@ -147,6 +147,17 @@ public: */ virtual int32_t GetAllRunningProcesses(std::vector &info) override; + /** + * GetRunningMultiAppInfoByBundleName, call GetRunningMultiAppInfoByBundleName() through proxy project. + * Obtains information about multiapp that are running on the device. + * + * @param bundlename, input. + * @param info, output multiapp information. + * @return ERR_OK ,return back success,others fail. + */ + virtual int32_t GetRunningMultiAppInfoByBundleName(const std::string &bundleName, + RunningMultiAppInfo &info) override; + /** * GetRunningProcessesByBundleType, call GetRunningProcessesByBundleType() through proxy project. * Obtains information about application processes by bundle type that are running on the device. @@ -309,7 +320,7 @@ public: virtual int StartRenderProcess(const std::string &renderParam, int32_t ipcFd, int32_t sharedFd, - int32_t crashFd, pid_t &renderPid) override; + int32_t crashFd, pid_t &renderPid, bool isGPU = false) override; virtual void AttachRenderProcess(const sptr &shceduler) override; @@ -367,6 +378,15 @@ public: */ virtual int32_t GetBundleNameByPid(const int32_t pid, std::string &bundleName, int32_t &uid) override; + /** + * Get running process information by pid. + * + * @param pid process id. + * @param info Output parameters, return runningProcessInfo. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) override; + /** * Notify Fault Data * @@ -503,6 +523,19 @@ public: int32_t NotifyMemorySizeStateChanged(bool isMemorySizeSufficent) override; int32_t SetSupportedProcessCacheSelf(bool isSupport) override; + + void SetAppAssertionPauseState(bool flag) override; + /** + * Start native child process, callde by ChildProcessManager. + * @param libName lib file name to be load in child process + * @param childProcessCount current started child process count + * @param callback callback for notify start result + * @return Returns ERR_OK on success, others on failure. + */ + int32_t StartNativeChildProcess(const std::string &libName, int32_t childProcessCount, + const sptr &callback) override; + + virtual void SaveBrowserChannel(sptr browser) override; private: /** * Init, Initialize application services. @@ -577,7 +610,7 @@ private: virtual int32_t GetForegroundApplications(std::vector &list) override; int Dump(const std::vector& args, std::string& result); - void ShowHelp(std::string& result) const; + int ShowHelp(const std::vector& args, std::string& result); int DumpIpc(const std::vector& args, std::string& result); int DumpIpcAllStart(std::string& result); int DumpIpcAllStop(std::string& result); @@ -586,6 +619,8 @@ private: int DumpIpcStop(const int32_t pid, std::string& result); int DumpIpcStat(const int32_t pid, std::string& result); + int DumpFfrt(const std::vector& args, std::string& result); + bool JudgeAppSelfCalled(int32_t recordId); /** @@ -633,6 +668,8 @@ private: int DumpIpcWithPidInner(const AppMgrService::DumpIpcKey key, const std::string& optionPid, std::string& result); + int DumpFfrtInner(const std::string& pidsRaw, std::string& result); + private: std::shared_ptr appMgrServiceInner_; AppMgrServiceState appMgrServiceState_; @@ -641,6 +678,9 @@ private: sptr systemAbilityMgr_; sptr amsMgrScheduler_; + using DumpFuncType = int (AppMgrService::*)(const std::vector& args, std::string& result); + const static std::map dumpFuncMap_; + const static std::map dumpIpcMap; using DumpIpcAllFuncType = int (AppMgrService::*)(std::string& result); diff --git a/services/appmgr/include/app_mgr_service_event_handler.h b/services/appmgr/include/app_mgr_service_event_handler.h index b9a13bc3a8..c738554c10 100644 --- a/services/appmgr/include/app_mgr_service_event_handler.h +++ b/services/appmgr/include/app_mgr_service_event_handler.h @@ -40,6 +40,7 @@ public: #ifdef SUPPORT_ASAN static constexpr uint32_t TERMINATE_ABILITY_TIMEOUT = 45000; // ms static constexpr uint32_t TERMINATE_APPLICATION_TIMEOUT = 150000; // ms + static constexpr uint32_t BACKGROUND_APPLICATION_TIMEOUT = 45000; // ms static constexpr uint32_t ADD_ABILITY_STAGE_INFO_TIMEOUT = 45000; // ms static constexpr uint32_t START_SPECIFIED_ABILITY_TIMEOUT = 45000; // ms static constexpr uint32_t START_PROCESS_SPECIFIED_ABILITY_TIMEOUT = 75000; // ms @@ -48,6 +49,7 @@ public: #else static constexpr uint32_t TERMINATE_ABILITY_TIMEOUT = 3000; // ms static constexpr uint32_t TERMINATE_APPLICATION_TIMEOUT = 10000; // ms + static constexpr uint32_t BACKGROUND_APPLICATION_TIMEOUT = 3000; // ms static constexpr uint32_t ADD_ABILITY_STAGE_INFO_TIMEOUT = 3000; // ms static constexpr uint32_t START_SPECIFIED_ABILITY_TIMEOUT = 3000; // ms static constexpr uint32_t START_PROCESS_SPECIFIED_ABILITY_TIMEOUT = 5000; // ms diff --git a/services/appmgr/include/app_mgr_service_inner.h b/services/appmgr/include/app_mgr_service_inner.h index 8e94a1331f..9ccaae542b 100644 --- a/services/appmgr/include/app_mgr_service_inner.h +++ b/services/appmgr/include/app_mgr_service_inner.h @@ -65,13 +65,19 @@ #include "shared/base_shared_bundle_info.h" #include "task_handler_wrap.h" #include "want.h" -#include "window_focus_changed_listener.h" -#include "window_visibility_changed_listener.h" #include "app_jsheap_mem_info.h" +#include "running_multi_info.h" namespace OHOS { +namespace Rosen { +class WindowVisibilityInfo; +class FocusChangeInfo; +} namespace AppExecFwk { using OHOS::AAFwk::Want; +class WindowFocusChangedListener; +class WindowVisibilityChangedListener; + class AppMgrServiceInner : public std::enable_shared_from_this { public: AppMgrServiceInner(); @@ -305,6 +311,17 @@ public: */ virtual int32_t GetAllRunningProcesses(std::vector &info); + /** + * GetRunningMultiAppInfoByBundleName, call GetRunningMultiAppInfoByBundleName through proxy project. + * Obtains information about TwinApp that are running on the device. + * + * @param bundleName, input. + * @param info, output multiapp information. + * @return void. + */ + virtual int32_t GetRunningMultiAppInfoByBundleName(const std::string &bundleName, + RunningMultiAppInfo &info); + /** * GetRunningProcessesByBundleType, Obtains information about application processes by bundle type. * @@ -399,7 +416,7 @@ public: */ int32_t IsApplicationRunning(const std::string &bundleName, bool &isRunning); - int32_t StartNativeProcessForDebugger(const AAFwk::Want &want) const; + int32_t StartNativeProcessForDebugger(const AAFwk::Want &want); std::shared_ptr CreateAppRunningRecord( sptr token, @@ -572,7 +589,7 @@ public: void GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info); - void GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const; + int32_t GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const; /** * Set AbilityForegroundingFlag of an app-record to true. @@ -666,9 +683,11 @@ public: int FinishUserTest( const std::string &msg, const int64_t &resultCode, const std::string &bundleName, const pid_t &pid); - void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo); + void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId = 0); - void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo); + void StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId = 0); void RegisterStartSpecifiedAbilityResponse(const sptr &response); @@ -690,7 +709,7 @@ public: virtual int32_t StartRenderProcess(const pid_t hostPid, const std::string &renderParam, int32_t ipcFd, int32_t sharedFd, - int32_t crashFd, pid_t &renderPid); + int32_t crashFd, pid_t &renderPid, bool isGPU = false); virtual void AttachRenderProcess(const pid_t pid, const sptr &scheduler); @@ -707,6 +726,9 @@ public: void TerminateApplication(const std::shared_ptr &appRecord); int GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application, bool &debug); + + int32_t NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg); + /** * Notify application status. * @@ -990,6 +1012,17 @@ public: */ virtual void ExitChildProcessSafelyByChildPid(const pid_t pid); + /** + * Start native child process, callde by ChildProcessManager. + * @param hostPid Host process pid. + * @param childProcessCount current started child process count + * @param libName lib file name to be load in child process + * @param callback callback for notify start result + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t StartNativeChildProcess(const pid_t hostPid, + const std::string &libName, int32_t childProcessCount, const sptr &callback); + /** * Whether the current application process is the last surviving process. * @param bundleName To query the bundle name of a process. @@ -1025,7 +1058,7 @@ public: int32_t SignRestartAppFlag(const std::string &bundleName); - void SetAppAssertionPauseState(int32_t pid, bool flag); + void SetAppAssertionPauseState(bool flag); void SetKeepAliveEnableState(const std::string &bundleName, bool enable); @@ -1047,9 +1080,13 @@ public: virtual int DumpIpcStat(const int32_t pid, std::string& result); + virtual int DumpFfrt(const std::vector& pids, std::string& result); + int32_t SetSupportedProcessCacheSelf(bool isSupport); void OnAppCacheStateChanged(const std::shared_ptr &appRecord); + + virtual void SaveBrowserChannel(const pid_t hostPid, sptr browser); private: std::string FaultTypeToString(FaultDataType type); @@ -1097,7 +1134,7 @@ private: const HapModuleInfo &hapModuleInfo, std::shared_ptr want, int32_t abilityRecordId); int32_t StartPerfProcess(const std::shared_ptr &appRecord, const std::string& perfCmd, - const std::string& debugCmd, bool isSandboxApp) const; + const std::string& debugCmd, bool isSandboxApp); void StartProcessVerifyPermission(const BundleInfo &bundleInfo, bool &hasAccessBundleDirReq, uint8_t &setAllowInternet, uint8_t &allowInternet, std::vector &gids); @@ -1118,7 +1155,8 @@ private: void StartProcess(const std::string &appName, const std::string &processName, uint32_t startFlags, std::shared_ptr appRecord, const int uid, const BundleInfo &bundleInfo, const std::string &bundleName, const int32_t bundleIndex, bool appExistFlag = true, - bool isPreload = false); + bool isPreload = false, const std::string &moduleName = "", const std::string &abilityName = "", + bool strictMode = false, int32_t maxChildProcess = 0); /** * PushAppFront, Adjust the latest application record to the top level. @@ -1246,7 +1284,7 @@ private: void GetRenderProcesses(const std::shared_ptr &appRecord, std::vector &info); int StartRenderProcessImpl(const std::shared_ptr &renderRecord, - const std::shared_ptr appRecord, pid_t &renderPid); + const std::shared_ptr appRecord, pid_t &renderPid, bool isGPU = false); void OnRenderRemoteDied(const wptr &remote); @@ -1281,6 +1319,8 @@ private: void KillAttachedChildProcess(const std::shared_ptr &appRecord); + void PresetMaxChildProcess(const std::shared_ptr &abilityInfo, int32_t &maxChildProcess); + private: /** * ClearUpApplicationData, clear the application data. @@ -1336,7 +1376,6 @@ private: bool JudgeSelfCalledByToken(const sptr &token, const PageStateData &pageStateData); void ParseServiceExtMultiProcessWhiteList(); - int32_t GetFlag() const; void ClearData(std::shared_ptr appRecord); /** @@ -1351,6 +1390,9 @@ private: void NotifyAppRunningStatusEvent( const std::string &bundle, int32_t uid, AbilityRuntime::RunningStatus runningStatus); + void GetRunningCloneAppInfo(const std::shared_ptr &appRecord, + RunningMultiAppInfo &info); + /** * To Prevent process being killed when ability is starting in an existing process, * we need notify memmgr to increase process priority. @@ -1378,6 +1420,27 @@ private: bool isPreload); int32_t CheckSetProcessCachePermission() const; + + int32_t CreatNewStartMsg(const Want &want, const AbilityInfo &abilityInfo, + const std::shared_ptr &appInfo, const std::string &processName, + AppSpawnStartMsg &startMsg); + + int32_t CreateStartMsg(const std::string &processName, uint32_t startFlags, const int uid, + const BundleInfo &bundleInfo, const int32_t bundleIndex, BundleType bundleType, + AppSpawnStartMsg &startMsg, const std::string &moduleName = "", const std::string &abilityName = "", + bool strictMode = false); + + void QueryExtensionSandBox(const std::string &moduleName, const std::string &abilityName, + const BundleInfo &bundleInfo, AppSpawnStartMsg &startMsg, DataGroupInfoList& dataGroupInfoList, + bool strictMode); + + int32_t StartPerfProcessByStartMsg(AppSpawnStartMsg &startMsg, const std::string& perfCmd, + const std::string& debugCmd, bool isSandboxApp); + + void SetAtomicServiceInfo(BundleType bundleType, AppSpawnStartMsg &startMsg); + + void SetAppInfo(const BundleInfo &bundleInfo, AppSpawnStartMsg &startMsg); + private: /** * Notify application status. @@ -1418,6 +1481,7 @@ private: ffrt::mutex appStateCallbacksLock_; ffrt::mutex renderUidSetLock_; ffrt::mutex exceptionLock_; + ffrt::mutex browserHostLock_; sptr startSpecifiedAbilityResponse_; ffrt::mutex configurationObserverLock_; std::vector> configurationObservers_; diff --git a/services/appmgr/include/app_running_manager.h b/services/appmgr/include/app_running_manager.h index 57997917ae..3868f6d603 100644 --- a/services/appmgr/include/app_running_manager.h +++ b/services/appmgr/include/app_running_manager.h @@ -28,7 +28,6 @@ #include "app_state_data.h" #include "application_info.h" #include "bundle_info.h" -#include "cpp/mutex.h" #include "iremote_object.h" #include "record_query_result.h" #include "refbase.h" @@ -36,6 +35,9 @@ #include "app_jsheap_mem_info.h" namespace OHOS { +namespace Rosen { +class WindowVisibilityInfo; +} namespace AppExecFwk { class AppRunningManager { public: @@ -222,7 +224,7 @@ public: std::shared_ptr GetTerminatingAppRunningRecord(const sptr &abilityToken); void GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info); - void GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info); + int32_t GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info); void ClipStringContent(const std::regex &re, const std::string &source, std::string &afterCutStr); void HandleAddAbilityStageTimeOut(const int64_t eventId); @@ -296,19 +298,19 @@ public: int DumpIpcStat(const int32_t pid, std::string& result); + int DumpFfrt(const std::vector& pids, std::string& result); + private: std::shared_ptr GetAbilityRunningRecord(const int64_t eventId); - void AssignRunningProcessInfoByAppRecord( + int32_t AssignRunningProcessInfoByAppRecord( std::shared_ptr appRecord, AppExecFwk::RunningProcessInfo &info) const; - std::shared_ptr GetAppRunningRecordByPidInner(const pid_t pid); - std::shared_ptr GetAppRunningRecordByTokenInner(const sptr &abilityToken); bool isCollaboratorReserveType(const std::shared_ptr &appRecord); private: + std::mutex runningRecordMapMutex_; std::map> appRunningRecordMap_; - std::map processRestartRecord_; - ffrt::mutex lock_; - ffrt::mutex uiExtensionMapLock_; + + std::mutex uiExtensionMapLock_; std::map> uiExtensionLauncherMap_; }; } // namespace AppExecFwk diff --git a/services/appmgr/include/app_running_record.h b/services/appmgr/include/app_running_record.h index 5809280bb0..a470a7bc75 100644 --- a/services/appmgr/include/app_running_record.h +++ b/services/appmgr/include/app_running_record.h @@ -43,10 +43,12 @@ #include "module_running_record.h" #include "app_spawn_client.h" #include "app_malloc_info.h" -#include "window_visibility_changed_listener.h" #include "app_jsheap_mem_info.h" namespace OHOS { +namespace Rosen { +class WindowVisibilityInfo; +} namespace AppExecFwk { class AbilityRunningRecord; class AppMgrServiceInner; @@ -89,6 +91,7 @@ public: void RegisterDeathRecipient(); void SetState(int32_t state); int32_t GetState() const; + void SetProcessType(ProcessType type); private: void SetHostUid(const int32_t hostUid); @@ -543,6 +546,8 @@ public: void SetKeepAliveEnableState(bool isKeepAliveEnable); + void SetSingleton(bool isSingleton); + void SetStageModelState(bool isStageBasedModel); std::list> GetAllModuleRecord() const; @@ -579,18 +584,21 @@ public: std::shared_ptr GetUserTestInfo(); void SetProcessAndExtensionType(const std::shared_ptr &abilityInfo); - void SetSpecifiedAbilityFlagAndWant(const bool flag, const AAFwk::Want &want, const std::string &moduleName); - void SetScheduleNewProcessRequestState(const bool isNewProcessRequest, const AAFwk::Want &want, - const std::string &moduleName); + void SetSpecifiedAbilityFlagAndWant(int requestId, const AAFwk::Want &want, const std::string &moduleName); + void SetScheduleNewProcessRequestState(int32_t requestId, const AAFwk::Want &want, const std::string &moduleName); bool IsNewProcessRequest() const; bool IsStartSpecifiedAbility() const; + int32_t GetSpecifiedRequestId() const; + void ResetSpecifiedRequestId(); void ScheduleAcceptWant(const std::string &moduleName); void ScheduleAcceptWantDone(); void ScheduleNewProcessRequest(const AAFwk::Want &want, const std::string &moduleName); void ScheduleNewProcessRequestDone(); void ApplicationTerminated(); - const AAFwk::Want &GetSpecifiedWant() const; - const AAFwk::Want &GetNewProcessRequestWant() const; + AAFwk::Want GetSpecifiedWant() const; + AAFwk::Want GetNewProcessRequestWant() const; + int32_t GetNewProcessRequestId() const; + void ResetNewProcessRequestId(); void SetDebugApp(bool isDebugApp); bool IsDebugApp(); bool IsDebugging() const; @@ -761,8 +769,23 @@ public: int DumpIpcStop(std::string& result); int DumpIpcStat(std::string& result); + int DumpFfrt(std::string &result); + + void SetExitReason(int32_t reason); + int32_t GetExitReason() const; + + void SetExitMsg(const std::string &exitMsg); + std::string GetExitMsg() const; + bool SetSupportedProcessCache(bool isSupport); SupportProcessCacheState GetSupportProcessCacheState(); + + void SetBrowserHost(sptr browser); + sptr GetBrowserHost(); + void SetIsGPU(bool gpu); + bool GetIsGPU(); + void SetGPUPid(pid_t gpuPid); + pid_t GetGPUPid(); private: /** * SearchTheModuleInfoNeedToUpdated, Get an uninitialized abilityStage data. @@ -826,6 +849,7 @@ private: bool isKeepAliveApp_ = false; // Only resident processes can be set to true, please choose carefully bool isEmptyKeepAliveApp_ = false; // Only empty resident processes can be set to true, please choose carefully + bool isSingleton_ = false; bool isStageBasedModel_ = false; ApplicationState curState_ = ApplicationState::APP_STATE_CREATE; // current state of this process ApplicationPendingState pendingState_ = ApplicationPendingState::READY; @@ -847,7 +871,7 @@ private: std::unordered_set, RemoteObjHash> foregroundingAbilityTokens_; std::weak_ptr appMgrServiceInner_; sptr appDeathRecipient_ = nullptr; - std::shared_ptr priorityObject_ = nullptr; + std::shared_ptr priorityObject_; std::shared_ptr appLifeCycleDeal_ = nullptr; std::shared_ptr taskHandler_; std::shared_ptr eventHandler_; @@ -863,11 +887,14 @@ private: bool isLauncherApp_; std::string mainAppName_; int restartResidentProcCount_ = 0; - bool isSpecifiedAbility_ = false; - AAFwk::Want SpecifiedWant_; + + mutable std::mutex specifiedMutex_; + int32_t specifiedRequestId_ = -1; + AAFwk::Want specifiedWant_; std::string moduleName_; - bool isNewProcessRequest_; + int32_t newProcessRequestId_ = -1; AAFwk::Want newProcessRequestWant_; + bool isDebugApp_ = false; bool isNativeDebug_ = false; bool isAttachDebug_ = false; @@ -876,6 +903,8 @@ private: int64_t restartTimeMillis_ = 0; // The time of last trying app restart bool jitEnabled_ = false; PreloadState preloadState_ = PreloadState::NONE; + int32_t exitReason_ = 0; + std::string exitMsg_ = ""; std::shared_ptr userTestRecord_ = nullptr; @@ -912,6 +941,9 @@ private: bool isNativeStart_ = false; bool isMultiThread_ = false; SupportProcessCacheState procCacheSupportState_ = SupportProcessCacheState::UNSPECIFIED; + sptr browserHost_; + bool isGPU_ = false; + pid_t gpuPid_ = 0; }; } // namespace AppExecFwk diff --git a/services/appmgr/include/app_spawn_client.h b/services/appmgr/include/app_spawn_client.h index bdfc4c789e..693dfab866 100644 --- a/services/appmgr/include/app_spawn_client.h +++ b/services/appmgr/include/app_spawn_client.h @@ -65,8 +65,14 @@ struct AppSpawnStartMsg { std::set permissions; std::map appEnv; // environment variable to be set to the process std::string ownerId; + std::string provisionType; bool atomicServiceFlag = false; std::string atomicAccount = ""; + bool isolatedExtension = false; // whether is isolatedExtension + std::string extensionSandboxPath; + bool strictMode = false; // whether is strict mode + std::string processType = ""; + int32_t maxChildProcess = 0; }; constexpr auto LEN_PID = sizeof(pid_t); @@ -160,6 +166,22 @@ public: */ int32_t SetAtomicServiceFlag(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle); + /** + * Set strict mode flags. + * + * @param startMsg, request message. + * @param reqHandle, handle for request message + */ + int32_t SetStrictMode(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle); + + /** + * Set app extension flags. + * + * @param startMsg, request message. + * @param reqHandle, handle for request message + */ + int32_t SetAppExtension(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle); + /** * Set extra info: render-cmd, HspList, Overlay, DataGroup, AppEnv. * @@ -168,6 +190,14 @@ public: */ int32_t AppspawnSetExtMsg(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle); + /** + * Set extra info: provision_type, max_child_process. + * + * @param startMsg, request message. + * @param reqHandle, handle for request message + */ + int32_t AppspawnSetExtMsgMore(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle); + /** * Create default appspawn msg. * diff --git a/services/appmgr/include/child_process_record.h b/services/appmgr/include/child_process_record.h index bb3565a946..dd3690b9e2 100644 --- a/services/appmgr/include/child_process_record.h +++ b/services/appmgr/include/child_process_record.h @@ -22,6 +22,7 @@ #include "app_death_recipient.h" #include "child_scheduler_interface.h" +#include "child_process_info.h" namespace OHOS { namespace AppExecFwk { @@ -31,10 +32,15 @@ class ChildProcessRecord { public: ChildProcessRecord(pid_t hostPid, const std::string &srcEntry, const std::shared_ptr hostRecord, int32_t childProcessCount, bool isStartWithDebug); + ChildProcessRecord(pid_t hostPid, const std::string &libName, const std::shared_ptr hostRecord, + const sptr &mainProcessCb, int32_t childProcessCount, bool isStartWithDebug); virtual ~ChildProcessRecord(); static std::shared_ptr CreateChildProcessRecord(pid_t hostPid, const std::string &srcEntry, const std::shared_ptr hostRecord, int32_t childProcessCount, bool isStartWithDebug); + static std::shared_ptr CreateNativeChildProcessRecord(pid_t hostPid, const std::string &libName, + const std::shared_ptr hostRecord, const sptr &mainProcessCb, + int32_t childProcessCount, bool isStartWithDebug); void SetPid(pid_t pid); pid_t GetPid() const; @@ -51,6 +57,9 @@ public: void RemoveDeathRecipient(); void ScheduleExitProcessSafely(); bool isStartWithDebug(); + int32_t GetProcessType() const; + sptr GetMainProcessCallback() const; + void ClearMainProcessCallback(); private: void MakeProcessName(const std::shared_ptr hostRecord); @@ -58,11 +67,13 @@ private: pid_t hostPid_ = 0; int32_t uid_ = 0; int32_t childProcessCount_ = 0; + int32_t childProcessType_ = CHILD_PROCESS_TYPE_JS; std::string processName_; std::string srcEntry_; std::weak_ptr hostRecord_; sptr scheduler_ = nullptr; sptr deathRecipient_ = nullptr; + sptr mainProcessCb_ = nullptr; bool isStartWithDebug_; }; } // namespace AppExecFwk diff --git a/services/appmgr/include/utils/app_mgr_service_const.h b/services/appmgr/include/utils/app_mgr_service_const.h index f67b588c5e..311780d2c5 100644 --- a/services/appmgr/include/utils/app_mgr_service_const.h +++ b/services/appmgr/include/utils/app_mgr_service_const.h @@ -16,19 +16,19 @@ #ifndef OHOS_ABILITY_RUNTIME_APP_MGR_SERVICE_CONST_H #define OHOS_ABILITY_RUNTIME_APP_MGR_SERVICE_CONST_H -#include +#include namespace OHOS { namespace AppExecFwk { -const std::string MSG_DUMP_IPC_START_STAT = "StartIpcStatistics\t"; -const std::string MSG_DUMP_IPC_STOP_STAT = "StopIpcStatistics\t"; -const std::string MSG_DUMP_IPC_STAT = "IpcStatistics\t"; -const std::string MSG_DUMP_IPC_FAIL = "fail\n"; -const std::string MSG_DUMP_IPC_FAIL_REASON_INTERNAL = "internal error.\n"; -const std::string MSG_DUMP_IPC_FAIL_REASON_INVALILD_CMD = "invalid cmd.\n"; -const std::string MSG_DUMP_IPC_FAIL_REASON_INVALILD_PID = "invalid pid.\n"; -const std::string MSG_DUMP_IPC_FAIL_REASON_INVALILD_NUM_ARGS = "invalid number of arguments.\n"; -const std::string MSG_DUMP_IPC_FAIL_REASON_PERMISSION_DENY = "permission deny.\n"; +constexpr const char* MSG_DUMP_IPC_START_STAT = "StartIpcStatistics\t"; +constexpr const char* MSG_DUMP_IPC_STOP_STAT = "StopIpcStatistics\t"; +constexpr const char* MSG_DUMP_IPC_STAT = "IpcStatistics\t"; +constexpr const char* MSG_DUMP_FAIL = "fail\n"; +constexpr const char* MSG_DUMP_FAIL_REASON_INTERNAL = "internal error.\n"; +constexpr const char* MSG_DUMP_FAIL_REASON_INVALILD_CMD = "invalid cmd.\n"; +constexpr const char* MSG_DUMP_FAIL_REASON_INVALILD_PID = "invalid pid.\n"; +constexpr const char* MSG_DUMP_FAIL_REASON_INVALILD_NUM_ARGS = "invalid number of arguments.\n"; +constexpr const char* MSG_DUMP_FAIL_REASON_PERMISSION_DENY = "permission deny.\n"; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/ams_mgr_scheduler.cpp b/services/appmgr/src/ams_mgr_scheduler.cpp index 771f9b797c..bb8f322331 100644 --- a/services/appmgr/src/ams_mgr_scheduler.cpp +++ b/services/appmgr/src/ams_mgr_scheduler.cpp @@ -339,19 +339,6 @@ void AmsMgrScheduler::GetRunningProcessInfoByToken( amsMgrServiceInner_->GetRunningProcessInfoByToken(token, info); } -void AmsMgrScheduler::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) -{ - if (!IsReady()) { - return; - } - - if (amsMgrServiceInner_->VerifyRequestPermission() != ERR_OK) { - TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed."); - return; - } - amsMgrServiceInner_->GetRunningProcessInfoByPid(pid, info); -} - void AmsMgrScheduler::SetAbilityForegroundingFlagToAppRecord(const pid_t pid) { if (!IsReady()) { @@ -360,7 +347,8 @@ void AmsMgrScheduler::SetAbilityForegroundingFlagToAppRecord(const pid_t pid) amsMgrServiceInner_->SetAbilityForegroundingFlagToAppRecord(pid); } -void AmsMgrScheduler::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +void AmsMgrScheduler::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId) { if (!IsReady()) { return; @@ -370,11 +358,12 @@ void AmsMgrScheduler::StartSpecifiedAbility(const AAFwk::Want &want, const AppEx TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed."); return; } - auto task = [=]() { amsMgrServiceInner_->StartSpecifiedAbility(want, abilityInfo); }; + auto task = [=]() { amsMgrServiceInner_->StartSpecifiedAbility(want, abilityInfo, requestId); }; amsHandler_->SubmitTask(task, AAFwk::TaskQoS::USER_INTERACTIVE); } -void AmsMgrScheduler::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +void AmsMgrScheduler::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId) { if (!IsReady()) { TAG_LOGW(AAFwkTag::APPMGR, "not ready."); @@ -385,7 +374,7 @@ void AmsMgrScheduler::StartSpecifiedProcess(const AAFwk::Want &want, const AppEx TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed."); return; } - auto task = [=]() { amsMgrServiceInner_->StartSpecifiedProcess(want, abilityInfo); }; + auto task = [=]() { amsMgrServiceInner_->StartSpecifiedProcess(want, abilityInfo, requestId); }; amsHandler_->SubmitTask(task, AAFwk::TaskQoS::USER_INTERACTIVE); } @@ -406,6 +395,14 @@ int AmsMgrScheduler::GetApplicationInfoByProcessID(const int pid, AppExecFwk::Ap return amsMgrServiceInner_->GetApplicationInfoByProcessID(pid, application, debug); } +int32_t AmsMgrScheduler::NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg) +{ + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + return amsMgrServiceInner_->NotifyAppMgrRecordExitReason(pid, reason, exitMsg); +} + void AmsMgrScheduler::SetCurrentUserId(const int32_t userId) { if (!IsReady()) { @@ -521,15 +518,6 @@ bool AmsMgrScheduler::IsAttachDebug(const std::string &bundleName) return amsMgrServiceInner_->IsAttachDebug(bundleName); } -void AmsMgrScheduler::SetAppAssertionPauseState(int32_t pid, bool flag) -{ - if (!IsReady()) { - TAG_LOGE(AAFwkTag::APPMGR, "AmsMgrService is not ready."); - return; - } - amsMgrServiceInner_->SetAppAssertionPauseState(pid, flag); -} - void AmsMgrScheduler::SetKeepAliveEnableState(const std::string &bundleName, bool enable) { if (!IsReady()) { diff --git a/services/appmgr/src/app_lifecycle_deal.cpp b/services/appmgr/src/app_lifecycle_deal.cpp index a553af006a..7387db0b90 100644 --- a/services/appmgr/src/app_lifecycle_deal.cpp +++ b/services/appmgr/src/app_lifecycle_deal.cpp @@ -334,9 +334,9 @@ int AppLifeCycleDeal::DumpIpcStart(std::string& result) TAG_LOGD(AAFwkTag::APPMGR, "Called."); auto appThread = GetApplicationClient(); if (appThread == nullptr) { - result.append(MSG_DUMP_IPC_START_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "appThread is nullptr."); return DumpErrorCode::ERR_INTERNAL_ERROR; } @@ -348,9 +348,9 @@ int AppLifeCycleDeal::DumpIpcStop(std::string& result) TAG_LOGD(AAFwkTag::APPMGR, "Called."); auto appThread = GetApplicationClient(); if (appThread == nullptr) { - result.append(MSG_DUMP_IPC_STOP_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "appThread is nullptr."); return DumpErrorCode::ERR_INTERNAL_ERROR; } @@ -362,13 +362,26 @@ int AppLifeCycleDeal::DumpIpcStat(std::string& result) TAG_LOGD(AAFwkTag::APPMGR, "Called."); auto appThread = GetApplicationClient(); if (appThread == nullptr) { - result.append(MSG_DUMP_IPC_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "appThread is nullptr."); return DumpErrorCode::ERR_INTERNAL_ERROR; } return appThread->ScheduleDumpIpcStat(result); } + +int AppLifeCycleDeal::DumpFfrt(std::string& result) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called."); + auto appThread = GetApplicationClient(); + if (appThread == nullptr) { + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); + TAG_LOGE(AAFwkTag::APPMGR, "appThread is nullptr."); + return DumpErrorCode::ERR_INTERNAL_ERROR; + } + return appThread->ScheduleDumpFfrt(result); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_mgr_service.cpp b/services/appmgr/src/app_mgr_service.cpp index 19980e00cc..c51a627243 100644 --- a/services/appmgr/src/app_mgr_service.cpp +++ b/services/appmgr/src/app_mgr_service.cpp @@ -16,6 +16,7 @@ #include "app_mgr_service.h" #include +#include #include #include #include @@ -23,6 +24,7 @@ #include "app_death_recipient.h" #include "app_mgr_constants.h" #include "datetime_ex.h" +#include "global_constant.h" #include "hilog_tag_wrapper.h" #include "hitrace_meter.h" #include "in_process_call_wrapper.h" @@ -40,10 +42,15 @@ namespace OHOS { namespace AppExecFwk { const std::string OPTION_KEY_HELP = "-h"; const std::string OPTION_KEY_DUMP_IPC = "--ipc"; +const std::string OPTION_KEY_DUMP_FFRT = "--ffrt"; const int32_t HIDUMPER_SERVICE_UID = 1212; constexpr const int INDEX_PID = 1; constexpr const int INDEX_CMD = 2; constexpr const size_t VALID_DUMP_IPC_ARG_SIZE = 3; +constexpr const size_t VALID_DUMP_FFRT_ARG_SIZE = 2; +constexpr const int MAX_DUMP_FFRT_PID_NUMBER = 3; +constexpr const int BASE_TEN = 10; +constexpr const char SIGN_TERMINAL = '\0'; namespace { using namespace std::chrono_literals; #ifdef ABILITY_COMMAND_FOR_TEST @@ -70,6 +77,12 @@ constexpr int32_t USER_UID = 2000; REGISTER_SYSTEM_ABILITY_BY_ID(AppMgrService, APP_MGR_SERVICE_ID, true); +const std::map AppMgrService::dumpFuncMap_ = { + std::map::value_type(OPTION_KEY_HELP, &AppMgrService::ShowHelp), + std::map::value_type(OPTION_KEY_DUMP_IPC, &AppMgrService::DumpIpc), + std::map::value_type(OPTION_KEY_DUMP_FFRT, &AppMgrService::DumpFfrt), +}; + const std::map AppMgrService::dumpIpcMap = { std::map::value_type("--start-stat", KEY_DUMP_IPC_START), std::map::value_type("--stop-stat", KEY_DUMP_IPC_STOP), @@ -244,6 +257,7 @@ void AppMgrService::ApplicationBackgrounded(const int32_t recordId) if (!JudgeAppSelfCalled(recordId)) { return; } + taskHandler_->CancelTask("appbackground_" + std::to_string(recordId)); std::function applicationBackgroundedFunc = std::bind(&AppMgrServiceInner::ApplicationBackgrounded, appMgrServiceInner_, recordId); taskHandler_->SubmitTask(applicationBackgroundedFunc, AAFwk::TaskAttribute{ @@ -378,6 +392,26 @@ int32_t AppMgrService::GetAllRunningProcesses(std::vector &i return appMgrServiceInner_->GetAllRunningProcesses(info); } +int32_t AppMgrService::GetRunningMultiAppInfoByBundleName(const std::string &bundleName, + RunningMultiAppInfo &info) +{ + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + + if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "The caller is not system-app, can not use system-api"); + return ERR_INVALID_OPERATION; + } + + bool isCallingPermission = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm(); + if (!isCallingPermission) { + TAG_LOGE(AAFwkTag::APPMGR, "GetRunningMultiAppInfoByBundleName, Permission verification failed."); + return ERR_PERMISSION_DENIED; + } + return appMgrServiceInner_->GetRunningMultiAppInfoByBundleName(bundleName, info); +} + int32_t AppMgrService::GetRunningProcessesByBundleType(BundleType bundleType, std::vector &info) { @@ -402,7 +436,7 @@ int32_t AppMgrService::JudgeSandboxByPid(pid_t pid, bool &isSandbox) return ERR_INVALID_OPERATION; } auto appRunningRecord = appMgrServiceInner_->GetAppRunningRecordByPid(pid); - if (appRunningRecord && appRunningRecord->GetAppIndex() > 0) { + if (appRunningRecord && appRunningRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { isSandbox = true; TAG_LOGD(AAFwkTag::APPMGR, "current app is a sandbox."); return ERR_OK; @@ -615,42 +649,50 @@ int AppMgrService::Dump(const std::vector& args, std::string& re TAG_LOGD(AAFwkTag::APPMGR, "Called."); auto size = args.size(); if (size == 0) { - ShowHelp(result); - return DumpErrorCode::ERR_OK; + return ShowHelp(args, result); } std::string optionKey = Str16ToStr8(args[0]); - if (optionKey == OPTION_KEY_HELP) { - ShowHelp(result); - return DumpErrorCode::ERR_OK; - } - if (optionKey == OPTION_KEY_DUMP_IPC) { - return DumpIpc(args, result); + auto itDumpFunc = dumpFuncMap_.find(optionKey); + if (itDumpFunc == dumpFuncMap_.end()) { + TAG_LOGE(AAFwkTag::APPMGR, "option key %{public}s does not exist", optionKey.c_str()); + result.append("error: unkown option.\n"); + return DumpErrorCode::ERR_UNKNOWN_OPTION_ERROR; } - result.append("error: unkown option.\n"); - return DumpErrorCode::ERR_UNKNOWN_OPTION_ERROR; + auto dumpFunc = itDumpFunc->second; + if (dumpFunc == nullptr) { + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); + TAG_LOGE(AAFwkTag::APPMGR, "dump ffrt function does not exist"); + return DumpErrorCode::ERR_INTERNAL_ERROR; + } + return (this->*dumpFunc)(args, result); } -void AppMgrService::ShowHelp(std::string& result) const +int AppMgrService::ShowHelp(const std::vector& args, std::string& result) { result.append("Usage:\n") .append("-h ") .append("help text for the tool\n"); + + return ERR_OK; } int AppMgrService::DumpIpcAllInner(const AppMgrService::DumpIpcKey key, std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGI(AAFwkTag::APPMGR, "Called."); auto itFunc = dumpIpcAllFuncMap_.find(key); if (itFunc == dumpIpcAllFuncMap_.end()) { - result.append(MSG_DUMP_IPC_FAIL).append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "option key %{public}d does not exist", key); return DumpErrorCode::ERR_INTERNAL_ERROR; } auto dumpFunc = itFunc->second; if (dumpFunc == nullptr) { - result.append(MSG_DUMP_IPC_FAIL).append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "dump ipc all function does not exist"); return DumpErrorCode::ERR_INTERNAL_ERROR; } @@ -660,47 +702,88 @@ int AppMgrService::DumpIpcAllInner(const AppMgrService::DumpIpcKey key, std::str int AppMgrService::DumpIpcWithPidInner(const AppMgrService::DumpIpcKey key, const std::string& optionPid, std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGI(AAFwkTag::APPMGR, "Called."); int32_t pid = -1; - try { - pid = static_cast(std::stoi(optionPid)); - } catch (...) { - result.append(MSG_DUMP_IPC_FAIL).append(MSG_DUMP_IPC_FAIL_REASON_INVALILD_PID); - TAG_LOGE(AAFwkTag::APPMGR, "stoi(%{public}s) failed", optionPid.c_str()); + char* end = nullptr; + pid = static_cast(std::strtol(optionPid.c_str(), &end, BASE_TEN)); + if (end && *end != SIGN_TERMINAL) { + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID)); + TAG_LOGE(AAFwkTag::APPMGR, "invalid pid: %{public}s", optionPid.c_str()); return DumpErrorCode::ERR_INVALID_PID_ERROR; } if (pid < 0) { - result.append(MSG_DUMP_IPC_FAIL).append(MSG_DUMP_IPC_FAIL_REASON_INVALILD_PID); + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID)); TAG_LOGE(AAFwkTag::APPMGR, "invalid pid: %{public}s", optionPid.c_str()); return DumpErrorCode::ERR_INVALID_PID_ERROR; } auto itFunc = dumpIpcFuncMap_.find(key); if (itFunc == dumpIpcFuncMap_.end()) { - result.append(MSG_DUMP_IPC_FAIL).append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "option key %{public}d does not exist", key); return DumpErrorCode::ERR_INTERNAL_ERROR; } auto dumpFunc = itFunc->second; if (dumpFunc == nullptr) { - result.append(MSG_DUMP_IPC_FAIL).append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "dump ipc function does not exist"); return DumpErrorCode::ERR_INTERNAL_ERROR; } return (this->*dumpFunc)(pid, result); } +int AppMgrService::DumpFfrtInner(const std::string& pidsRaw, std::string& result) +{ + TAG_LOGI(AAFwkTag::APPMGR, "Called"); + std::vector pidsStr; + SplitStr(pidsRaw, ",", pidsStr); + if (pidsStr.empty()) { + TAG_LOGE(AAFwkTag::APPMGR, "no valid pids are found"); + return DumpErrorCode::ERR_INVALID_PID_ERROR; + } + if (pidsStr.size() > MAX_DUMP_FFRT_PID_NUMBER) { + pidsStr.resize(MAX_DUMP_FFRT_PID_NUMBER); + } + std::vector pids; + for (const auto& pidStr : pidsStr) { + int pid = -1; + char* end = nullptr; + pid = static_cast(std::strtol(pidStr.c_str(), &end, BASE_TEN)); + if (end && *end != SIGN_TERMINAL) { + TAG_LOGE(AAFwkTag::APPMGR, "invalid pid:%{public}s", pidStr.c_str()); + continue; + } + if (pid < 0) { + TAG_LOGE(AAFwkTag::APPMGR, "invalid pid: %{public}s", pidStr.c_str()); + continue; + } + TAG_LOGD(AAFwkTag::APPMGR, "valid pid:%{public}d", pid); + pids.push_back(pid); + } + TAG_LOGD(AAFwkTag::APPMGR, "number of valid pids:%{public}d", static_cast(pids.size())); + if (pids.empty()) { + TAG_LOGE(AAFwkTag::APPMGR, "no valid pids are found"); + return DumpErrorCode::ERR_INVALID_PID_ERROR; + } + return appMgrServiceInner_->DumpFfrt(pids, result); +} + int AppMgrService::DumpIpc(const std::vector& args, std::string& result) { TAG_LOGD(AAFwkTag::APPMGR, "Called. AppMgrService::DumpIpc start"); if (args.size() != VALID_DUMP_IPC_ARG_SIZE) { - result.append(MSG_DUMP_IPC_FAIL).append(MSG_DUMP_IPC_FAIL_REASON_INVALILD_NUM_ARGS); + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INVALILD_NUM_ARGS, strlen(MSG_DUMP_FAIL_REASON_INVALILD_NUM_ARGS)); TAG_LOGE(AAFwkTag::APPMGR, "invalid number of arguments"); return DumpErrorCode::ERR_INVALID_NUM_ARGS_ERROR; } - auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall(); auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID); - if (!isShellCall && !isHidumperServiceCall) { - result.append(MSG_DUMP_IPC_FAIL).append(MSG_DUMP_IPC_FAIL_REASON_PERMISSION_DENY); + if (!isHidumperServiceCall) { + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_PERMISSION_DENY, strlen(MSG_DUMP_FAIL_REASON_PERMISSION_DENY)); TAG_LOGE(AAFwkTag::APPMGR, "Permission deny."); return DumpErrorCode::ERR_PERMISSION_DENY_ERROR; } @@ -712,7 +795,8 @@ int AppMgrService::DumpIpc(const std::vector& args, std::string& auto itDumpKey = dumpIpcMap.find(optionCmd); if (itDumpKey == dumpIpcMap.end()) { - result.append(MSG_DUMP_IPC_FAIL).append(MSG_DUMP_IPC_FAIL_REASON_INVALILD_CMD); + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INVALILD_CMD, strlen(MSG_DUMP_FAIL_REASON_INVALILD_CMD)); TAG_LOGE(AAFwkTag::APPMGR, "option command %{public}s does not exist", optionCmd.c_str()); return DumpErrorCode::ERR_INVALID_CMD_ERROR; } @@ -724,6 +808,29 @@ int AppMgrService::DumpIpc(const std::vector& args, std::string& return DumpIpcWithPidInner(key, optionPid, result); } +int AppMgrService::DumpFfrt(const std::vector& args, std::string& result) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called. AppMgrService::DumpFfrt start"); + if (args.size() != VALID_DUMP_FFRT_ARG_SIZE) { + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INVALILD_NUM_ARGS, strlen(MSG_DUMP_FAIL_REASON_INVALILD_NUM_ARGS)); + TAG_LOGE(AAFwkTag::APPMGR, "invalid number of arguments"); + return DumpErrorCode::ERR_INVALID_NUM_ARGS_ERROR; + } + auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID); + if (!isHidumperServiceCall) { + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_PERMISSION_DENY, strlen(MSG_DUMP_FAIL_REASON_PERMISSION_DENY)); + TAG_LOGE(AAFwkTag::APPMGR, "Permission deny."); + return DumpErrorCode::ERR_PERMISSION_DENY_ERROR; + } + + std::string pidsRaw = Str16ToStr8(args[INDEX_PID]); + TAG_LOGD(AAFwkTag::APPMGR, "pids:%{public}s", pidsRaw.c_str()); + + return DumpFfrtInner(pidsRaw, result); +} + int AppMgrService::DumpIpcAllStart(std::string& result) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); @@ -813,7 +920,7 @@ int32_t AppMgrService::PreStartNWebSpawnProcess() } int32_t AppMgrService::StartRenderProcess(const std::string &renderParam, int32_t ipcFd, - int32_t sharedFd, int32_t crashFd, pid_t &renderPid) + int32_t sharedFd, int32_t crashFd, pid_t &renderPid, bool isGPU) { if (!IsReady()) { TAG_LOGE(AAFwkTag::APPMGR, "StartRenderProcess failed, AppMgrService not ready."); @@ -821,7 +928,7 @@ int32_t AppMgrService::StartRenderProcess(const std::string &renderParam, int32_ } return appMgrServiceInner_->StartRenderProcess(IPCSkeleton::GetCallingRealPid(), - renderParam, ipcFd, sharedFd, crashFd, renderPid); + renderParam, ipcFd, sharedFd, crashFd, renderPid, isGPU); } void AppMgrService::AttachRenderProcess(const sptr &scheduler) @@ -841,6 +948,16 @@ void AppMgrService::AttachRenderProcess(const sptr &scheduler) }); } +void AppMgrService::SaveBrowserChannel(sptr browser) +{ + if (!IsReady()) { + TAG_LOGE(AAFwkTag::APPMGR, "SaveBrowserChannel not ready"); + return; + } + + appMgrServiceInner_->SaveBrowserChannel(IPCSkeleton::GetCallingRealPid(), browser); +} + int32_t AppMgrService::GetRenderProcessTerminationStatus(pid_t renderPid, int &status) { if (!IsReady()) { @@ -1016,6 +1133,15 @@ int32_t AppMgrService::GetBundleNameByPid(const int32_t pid, std::string &bundle return appMgrServiceInner_->GetBundleNameByPid(pid, bundleName, uid); } +int32_t AppMgrService::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) +{ + if (!IsReady()) { + TAG_LOGE(AAFwkTag::APPMGR, "AppMgrService is not ready."); + return ERR_INVALID_OPERATION; + } + return appMgrServiceInner_->GetRunningProcessInfoByPid(pid, info); +} + int32_t AppMgrService::NotifyAppFault(const FaultData &faultData) { if (!IsReady()) { @@ -1355,5 +1481,29 @@ int32_t AppMgrService::SetSupportedProcessCacheSelf(bool isSupport) } return appMgrServiceInner_->SetSupportedProcessCacheSelf(isSupport); } + +void AppMgrService::SetAppAssertionPauseState(bool flag) +{ + TAG_LOGI(AAFwkTag::APPMGR, "Called"); + if (!IsReady()) { + TAG_LOGE(AAFwkTag::APPMGR, "Not ready."); + return; + } + return appMgrServiceInner_->SetAppAssertionPauseState(flag); +} + +int32_t AppMgrService::StartNativeChildProcess(const std::string &libName, int32_t childProcessCount, + const sptr &callback) +{ + TAG_LOGI(AAFwkTag::APPMGR, "Called"); + if (!IsReady()) { + TAG_LOGE(AAFwkTag::APPMGR, "Not ready."); + return ERR_INVALID_OPERATION; + } + + return appMgrServiceInner_->StartNativeChildProcess( + IPCSkeleton::GetCallingPid(), libName, childProcessCount, callback); +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_mgr_service_inner.cpp b/services/appmgr/src/app_mgr_service_inner.cpp index 8d37cc8503..37da9e6ccc 100644 --- a/services/appmgr/src/app_mgr_service_inner.cpp +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -43,6 +43,7 @@ #include "distributed_data_mgr.h" #include "exit_resident_process_manager.h" #include "freeze_util.h" +#include "global_constant.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" #include "hitrace_meter.h" @@ -66,8 +67,9 @@ #include "permission_constants.h" #include "permission_verification.h" #include "render_state_observer_manager.h" -#include "system_ability_definition.h" +#include "startup_util.h" #include "string_ex.h" +#include "system_ability_definition.h" #include "time_util.h" #include "ui_extension_utils.h" #include "uri_permission_manager_client.h" @@ -79,6 +81,8 @@ #include "app_mgr_service_const.h" #include "app_mgr_service_dump_error_code.h" #include "cache_process_manager.h" +#include "window_focus_changed_listener.h" +#include "window_visibility_changed_listener.h" namespace OHOS { namespace AppExecFwk { @@ -124,7 +128,6 @@ const std::string PERF_CMD = "perfCmd"; const std::string MULTI_THREAD = "multiThread"; const std::string DEBUG_CMD = "debugCmd"; const std::string ENTER_SANDBOX = "sandboxApp"; -const std::string DLP_PARAMS_INDEX = "ohos.dlp.params.index"; const std::string PERMISSION_INTERNET = "ohos.permission.INTERNET"; const std::string PERMISSION_MANAGE_VPN = "ohos.permission.MANAGE_VPN"; const std::string PERMISSION_ACCESS_BUNDLE_DIR = "ohos.permission.ACCESS_BUNDLE_DIR"; @@ -141,6 +144,13 @@ const std::string TSAN_FLAG_NAME = "tsanEnabled"; const std::string MEMMGR_PROC_NAME = "memmgrservice"; const std::string UIEXTENSION_ABILITY_ID = "ability.want.params.uiExtensionAbilityId"; const std::string UIEXTENSION_ROOT_HOST_PID = "ability.want.params.uiExtensionRootHostPid"; +const std::string STRICT_MODE = "strictMode"; +const std::string RENDER_PROCESS_NAME = ":render"; +const std::string RENDER_PROCESS_TYPE = "render"; +const std::string GPU_PROCESS_NAME = ":gpu"; +const std::string GPU_PROCESS_TYPE = "gpu"; +const std::string FONT_WGHT_SCALE = "persist.sys.font_wght_scale_for_user0"; +const std::string FONT_SCALE = "persist.sys.font_scale_for_user0"; const int32_t SIGNAL_KILL = 9; constexpr int32_t USER_SCALE = 200000; #define ENUM_TO_STRING(s) #s @@ -240,14 +250,15 @@ void AppMgrServiceInner::Init() AppMgrServiceInner::~AppMgrServiceInner() {} -void AppMgrServiceInner::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +void AppMgrServiceInner::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId) { TAG_LOGD(AAFwkTag::APPMGR, "call."); BundleInfo bundleInfo; HapModuleInfo hapModuleInfo; auto appInfo = std::make_shared(abilityInfo.applicationInfo); - int32_t appIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0); + int32_t appIndex = AbilityRuntime::StartupUtil::GetAppIndex(want); if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) { return; } @@ -260,7 +271,7 @@ void AppMgrServiceInner::StartSpecifiedProcess(const AAFwk::Want &want, const Ap appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo); if (mainAppRecord != nullptr) { TAG_LOGD(AAFwkTag::APPMGR, "main process exists."); - mainAppRecord->SetScheduleNewProcessRequestState(true, want, hapModuleInfo.moduleName); + mainAppRecord->SetScheduleNewProcessRequestState(requestId, want, hapModuleInfo.moduleName); auto moduleRecord = mainAppRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); if (!moduleRecord) { TAG_LOGD(AAFwkTag::APPMGR, "module record is nullptr, add modules"); @@ -275,7 +286,7 @@ void AppMgrServiceInner::StartSpecifiedProcess(const AAFwk::Want &want, const Ap } TAG_LOGD(AAFwkTag::APPMGR, "main process do not exists."); if (startSpecifiedAbilityResponse_) { - startSpecifiedAbilityResponse_->OnNewProcessRequestResponse(want, ""); + startSpecifiedAbilityResponse_->OnNewProcessRequestResponse(want, "", requestId); } } @@ -397,7 +408,7 @@ void AppMgrServiceInner::LoadAbility(sptr token, sptrGetIntParam(DLP_PARAMS_INDEX, 0); + int32_t appIndex = (want == nullptr) ? 0 : AbilityRuntime::StartupUtil::GetAppIndex(*want); if (!GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) { TAG_LOGE(AAFwkTag::APPMGR, "GetBundleAndHapInfo failed"); return; @@ -641,9 +652,13 @@ void AppMgrServiceInner::LoadAbilityNoAppRecord(const std::shared_ptrGetIntParam(DLP_PARAMS_INDEX, 0); + int32_t bundleIndex = (want == nullptr) ? 0 : AbilityRuntime::StartupUtil::GetAppIndex(*want); + bool strictMode = (want == nullptr) ? false : want->GetBoolParam(STRICT_MODE, false); + int32_t maxChildProcess = 0; + PresetMaxChildProcess(abilityInfo, maxChildProcess); StartProcess(abilityInfo->applicationName, processName, startFlags, appRecord, - appInfo->uid, bundleInfo, appInfo->bundleName, bundleIndex, appExistFlag, isPreload); + appInfo->uid, bundleInfo, appInfo->bundleName, bundleIndex, appExistFlag, isPreload, abilityInfo->moduleName, + abilityInfo->name, strictMode, maxChildProcess); std::string perfCmd = (want == nullptr) ? "" : want->GetStringParam(PERF_CMD); bool isSandboxApp = (want == nullptr) ? false : want->GetBoolParam(ENTER_SANDBOX, false); (void)StartPerfProcess(appRecord, perfCmd, "", isSandboxApp); @@ -721,29 +736,33 @@ bool AppMgrServiceInner::GetBundleAndHapInfo(const AbilityInfo &abilityInfo, auto userId = GetUserIdByUid(appInfo->uid); TAG_LOGD(AAFwkTag::APPMGR, "UserId:%{public}d.", userId); - bool bundleMgrResult; + int32_t bundleMgrResult; if (appIndex == 0) { - bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfo(appInfo->bundleName, - BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId)); + bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfoV9(appInfo->bundleName, + static_cast(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) | + static_cast(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) | + static_cast(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE), bundleInfo, userId)); + } else if (appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { + bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetCloneBundleInfo(appInfo->bundleName, + static_cast(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION), appIndex, bundleInfo, userId)); } else { - bundleMgrResult = (IN_PROCESS_CALL(bundleMgrHelper->GetSandboxBundleInfo(appInfo->bundleName, - appIndex, userId, bundleInfo)) == 0); + bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetSandboxBundleInfo(appInfo->bundleName, + appIndex, userId, bundleInfo)); } - - if (!bundleMgrResult) { + if (bundleMgrResult != ERR_OK) { TAG_LOGE(AAFwkTag::APPMGR, "GetBundleInfo is fail."); return false; } - if (appIndex == 0) { - bundleMgrResult = bundleMgrHelper->GetHapModuleInfo(abilityInfo, userId, hapModuleInfo); + bool hapQueryResult = false; + if (appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { + hapQueryResult = bundleMgrHelper->GetHapModuleInfo(abilityInfo, userId, hapModuleInfo); } else { - bundleMgrResult = (bundleMgrHelper->GetSandboxHapModuleInfo(abilityInfo, appIndex, userId, hapModuleInfo) == 0); + hapQueryResult = (bundleMgrHelper->GetSandboxHapModuleInfo(abilityInfo, appIndex, userId, hapModuleInfo) == 0); } - if (!bundleMgrResult) { + if (!hapQueryResult) { TAG_LOGE(AAFwkTag::APPMGR, "GetHapModuleInfo is fail."); return false; } - return true; } @@ -1404,6 +1423,78 @@ int32_t AppMgrServiceInner::GetRunningProcessesByBundleType(BundleType bundleTyp return ERR_OK; } +int32_t AppMgrServiceInner::GetRunningMultiAppInfoByBundleName(const std::string &bundleName, + RunningMultiAppInfo &info) +{ + if (bundleName.empty()) { + TAG_LOGE(AAFwkTag::APPMGR, "bundlename is nullptr."); + return ERR_INVALID_VALUE; + } + if (!appRunningManager_) { + TAG_LOGE(AAFwkTag::APPMGR, "The appRunningManager is nullptr!"); + return ERR_INVALID_VALUE; + } + auto multiAppInfoMap = appRunningManager_->GetAppRunningRecordMap(); + if (multiAppInfoMap.empty()) { + return ERR_INVALID_VALUE; + } + for (const auto &item : multiAppInfoMap) { + const std::shared_ptr &appRecord = item.second; + if (appRecord == nullptr || appRecord->GetBundleName() != bundleName) { + continue; + } + auto appInfo = appRecord->GetApplicationInfo(); + if (!appInfo) { + continue; + } + info.bundleName = bundleName; + info.mode = static_cast(appInfo->multiAppMode.multiAppModeType); + if (info.mode == static_cast(MultiAppModeType::UNSPECIFIED)) { + return AAFwk::ERR_MULTI_APP_NOT_SUPPORTED; + } + GetRunningCloneAppInfo(appRecord, info); + } + return ERR_OK; +} + +void AppMgrServiceInner::GetRunningCloneAppInfo(const std::shared_ptr &appRecord, + RunningMultiAppInfo &info) +{ + if (!appRecord) { + TAG_LOGE(AAFwkTag::APPMGR, "The appRecord is nullptr!"); + return; + } + auto PriorityObject = appRecord->GetPriorityObject(); + if (!PriorityObject) { + TAG_LOGE(AAFwkTag::APPMGR, "The PriorityObject is nullptr!"); + return; + } + if (info.mode == static_cast(MultiAppModeType::APP_CLONE)) { + size_t index = 0; + for (; index < info.runningAppClones.size(); index++) { + if (info.runningAppClones[index].appCloneIndex == appRecord->GetAppIndex()) { + break; + } + } + auto childProcessRecordMap = appRecord->GetChildProcessRecordMap(); + if (index < info.runningAppClones.size()) { + info.runningAppClones[index].pids.emplace_back(PriorityObject->GetPid()); + for (auto it : childProcessRecordMap) { + info.runningAppClones[index].pids.emplace_back(it.first); + } + } else { + RunningAppClone cloneInfo; + cloneInfo.appCloneIndex = appRecord->GetAppIndex(); + cloneInfo.uid = appRecord->GetUid(); + cloneInfo.pids.emplace_back(PriorityObject->GetPid()); + for (auto it : childProcessRecordMap) { + cloneInfo.pids.emplace_back(it.first); + } + info.runningAppClones.emplace_back(cloneInfo); + } + } +} + int32_t AppMgrServiceInner::GetProcessRunningInfosByUserId(std::vector &info, int32_t userId) { if (VerifyAccountPermission(AAFwk::PermissionConstants::PERMISSION_GET_RUNNING_INFO, userId) == @@ -1604,13 +1695,16 @@ int32_t AppMgrServiceInner::KillProcessByPid(const pid_t pid, const std::string& return AAFwk::ERR_KILL_PROCESS_NOT_EXIST; } std::string killReason = KILL_PROCESS_REASON_PREFIX + reason; + auto appRecord = GetAppRunningRecordByPid(pid); + if (appRecord) { + appRecord->SetExitMsg(killReason); + } int32_t ret = -1; if (pid > 0) { TAG_LOGI(AAFwkTag::APPMGR, "kill pid %{public}d", pid); ret = kill(pid, SIGNAL_KILL); } AAFwk::EventInfo eventInfo; - auto appRecord = GetAppRunningRecordByPid(pid); if (!appRecord) { return ret; } @@ -1735,6 +1829,9 @@ std::shared_ptr AppMgrServiceInner::CreateAppRunningRecord(spt } appRecord->SetProcessAndExtensionType(abilityInfo); + bool isKeepAlive = bundleInfo.isKeepAlive && bundleInfo.singleton; + appRecord->SetKeepAliveEnableState(isKeepAlive); + appRecord->SetEmptyKeepAliveAppState(false); appRecord->SetTaskHandler(taskHandler_); appRecord->SetEventHandler(eventHandler_); appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want, abilityRecordId); @@ -1746,7 +1843,7 @@ std::shared_ptr AppMgrServiceInner::CreateAppRunningRecord(spt } appRecord->SetPerfCmd(want->GetStringParam(PERF_CMD)); appRecord->SetMultiThread(want->GetBoolParam(MULTI_THREAD, false)); - appRecord->SetAppIndex(want->GetIntParam(DLP_PARAMS_INDEX, 0)); + appRecord->SetAppIndex(AbilityRuntime::StartupUtil::GetAppIndex(*want)); appRecord->SetSecurityFlag(want->GetBoolParam(DLP_PARAMS_SECURITY_FLAG, false)); appRecord->SetRequestProcCode(want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0)); appRecord->SetCallerPid(want->GetIntParam(Want::PARAM_RESV_CALLER_PID, -1)); @@ -2291,19 +2388,17 @@ void AppMgrServiceInner::StateChangedNotifyObserver( abilityStateData, isAbility, isFromWindowFocusChanged); } -int32_t AppMgrServiceInner::StartPerfProcess(const std::shared_ptr &appRecord, - const std::string& perfCmd, const std::string& debugCmd, bool isSandboxApp) const +int32_t AppMgrServiceInner::StartPerfProcessByStartMsg(AppSpawnStartMsg &startMsg, + const std::string& perfCmd, const std::string& debugCmd, bool isSandboxApp) { - if (!remoteClientManager_->GetSpawnClient() || !appRecord) { - TAG_LOGE(AAFwkTag::APPMGR, "appSpawnClient or appRecord is null"); - return ERR_INVALID_OPERATION; + if (!remoteClientManager_ || !remoteClientManager_->GetSpawnClient()) { + TAG_LOGE(AAFwkTag::APPMGR, "appSpawnClient is null"); + return ERR_NO_INIT; } if (perfCmd.empty() && debugCmd.empty()) { TAG_LOGD(AAFwkTag::APPMGR, "perfCmd is empty"); return ERR_INVALID_OPERATION; } - - auto&& startMsg = appRecord->GetStartMsg(); startMsg.code = static_cast(MSG_SPAWN_NATIVE_PROCESS); if (!isSandboxApp) { TAG_LOGD(AAFwkTag::APPMGR, "debuggablePipe sandbox: false."); @@ -2327,6 +2422,18 @@ int32_t AppMgrServiceInner::StartPerfProcess(const std::shared_ptr &appRecord, + const std::string& perfCmd, const std::string& debugCmd, bool isSandboxApp) +{ + if (!appRecord) { + TAG_LOGE(AAFwkTag::APPMGR, "appRecord is null"); + return ERR_INVALID_OPERATION; + } + + auto&& startMsg = appRecord->GetStartMsg(); + return StartPerfProcessByStartMsg(startMsg, perfCmd, debugCmd, isSandboxApp); +} + void AppMgrServiceInner::SetOverlayInfo(const std::string &bundleName, const int32_t userId, AppSpawnStartMsg &startMsg) @@ -2434,84 +2541,43 @@ void AppMgrServiceInner::StartProcessVerifyPermission(const BundleInfo &bundleIn } } -void AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName, uint32_t startFlags, - std::shared_ptr appRecord, const int uid, const BundleInfo &bundleInfo, - const std::string &bundleName, const int32_t bundleIndex, bool appExistFlag, bool isPreload) +int32_t AppMgrServiceInner::CreatNewStartMsg(const Want &want, const AbilityInfo &abilityInfo, + const std::shared_ptr &appInfo, const std::string &processName, AppSpawnStartMsg &startMsg) { - HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); - if (!appRecord) { - TAG_LOGE(AAFwkTag::APPMGR, "appRecord is null"); - return; + TAG_LOGD(AAFwkTag::APPMGR, "CreatNewStartMsg called."); + if (!remoteClientManager_) { + TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager is null."); + return ERR_NO_INIT; } - - if (!remoteClientManager_->GetSpawnClient()) { - TAG_LOGE(AAFwkTag::APPMGR, "appSpawnClient is null"); - appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId()); - return; - } - auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper(); - if (bundleMgrHelper == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "Get bundle manager helper fail."); - appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId()); - return; + if (!bundleMgrHelper) { + TAG_LOGE(AAFwkTag::APPMGR, "The bundleMgrHelper is nullptr."); + return ERR_NO_INIT; } - if (otherTaskHandler_ == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "other handler null."); - appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId()); - return; - } - AppSpawnStartMsg startMsg; - AAFwk::AutoSyncTaskHandle autoSync(otherTaskHandler_->SubmitTask([&]() { - AddMountPermission(bundleInfo.applicationInfo.accessTokenId, startMsg.permissions); - })); - auto userId = GetUserIdByUid(uid); - HspList hspList; - ErrCode ret = bundleMgrHelper->GetBaseSharedBundleInfos(bundleName, hspList, - AppExecFwk::GetDependentBundleInfoFlag::GET_ALL_DEPENDENT_BUNDLE_INFO); + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + int32_t appIndex = want.GetIntParam(AppspawnUtil::DLP_PARAMS_INDEX, 0); + if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) { + TAG_LOGE(AAFwkTag::APPMGR, "GetBundleAndHapInfo failed."); + return ERR_NO_INIT; + } + + uint32_t startFlags = AppspawnUtil::BuildStartFlags(want, abilityInfo); + auto uid = appInfo->uid; + auto bundleType = appInfo->bundleType; + auto ret = CreateStartMsg(processName, startFlags, uid, bundleInfo, appIndex, bundleType, startMsg); if (ret != ERR_OK) { - TAG_LOGE(AAFwkTag::APPMGR, "GetBaseSharedBundleInfos failed: %{public}d", ret); - appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId()); - return; - } - - DataGroupInfoList dataGroupInfoList; - bool result = bundleMgrHelper->QueryDataGroupInfos(bundleName, userId, dataGroupInfoList); - if (!result || dataGroupInfoList.empty()) { - TAG_LOGD(AAFwkTag::APPMGR, "the bundle has no groupInfos"); - } - - bool hasAccessBundleDirReq; - uint8_t setAllowInternet = 0; - uint8_t allowInternet = 1; - std::vector gids; - - StartProcessVerifyPermission(bundleInfo, hasAccessBundleDirReq, setAllowInternet, allowInternet, gids); - startMsg.uid = bundleInfo.uid; - startMsg.gid = bundleInfo.gid; - startMsg.gids = gids; - startMsg.accessTokenId = bundleInfo.applicationInfo.accessTokenId; - startMsg.apl = bundleInfo.applicationInfo.appPrivilegeLevel; - startMsg.bundleName = bundleName; - startMsg.renderParam = RENDER_PARAM; - startMsg.flags = startFlags; - startMsg.bundleIndex = bundleIndex; - startMsg.setAllowInternet = setAllowInternet; - startMsg.allowInternet = allowInternet; - startMsg.hspList = hspList; - startMsg.dataGroupInfoList = dataGroupInfoList; - startMsg.hapFlags = bundleInfo.isPreInstallApp ? 1 : 0; - - startMsg.ownerId = bundleInfo.signatureInfo.appIdentifier; - if (hasAccessBundleDirReq) { - startMsg.flags = startMsg.flags | APP_ACCESS_BUNDLE_DIR; + TAG_LOGE(AAFwkTag::APPMGR, "CreateStartMsg failed."); } + return ret; +} +void AppMgrServiceInner::SetAtomicServiceInfo(BundleType bundleType, AppSpawnStartMsg &startMsg) +{ #ifdef OHOS_ACCOUNT_ENABLED TAG_LOGI(AAFwkTag::APPMGR, "execute with OHOS_ACCOUNT_ENABLED on"); - auto appInfo = appRecord->GetApplicationInfo(); - if (appInfo && appInfo->bundleType == BundleType::ATOMIC_SERVICE) { + if (bundleType == BundleType::ATOMIC_SERVICE) { TAG_LOGI(AAFwkTag::APPMGR, "application is of atomic service type"); AccountSA::OhosAccountInfo accountInfo; auto errCode = AccountSA::OhosAccountKits::GetInstance().GetOhosAccountInfo(accountInfo); @@ -2526,29 +2592,165 @@ void AppMgrServiceInner::StartProcess(const std::string &appName, const std::str #else TAG_LOGI(AAFwkTag::APPMGR, "execute with OHOS_ACCOUNT_ENABLED off"); #endif // OHOS_ACCOUNT_ENABLED +} - SetOverlayInfo(bundleName, userId, startMsg); +void AppMgrServiceInner::SetAppInfo(const BundleInfo &bundleInfo, AppSpawnStartMsg &startMsg) +{ + bool hasAccessBundleDirReq; + uint8_t setAllowInternet = 0; + uint8_t allowInternet = 1; + std::vector gids; + StartProcessVerifyPermission(bundleInfo, hasAccessBundleDirReq, setAllowInternet, allowInternet, gids); + startMsg.uid = bundleInfo.uid; + startMsg.gid = bundleInfo.gid; + startMsg.hapFlags = bundleInfo.isPreInstallApp ? 1 : 0; + startMsg.accessTokenId = bundleInfo.applicationInfo.accessTokenId; + startMsg.accessTokenIdEx = bundleInfo.applicationInfo.accessTokenIdEx; + startMsg.apl = bundleInfo.applicationInfo.appPrivilegeLevel; + startMsg.ownerId = bundleInfo.signatureInfo.appIdentifier; + startMsg.provisionType = bundleInfo.applicationInfo.appProvisionType; + if (startMsg.maxChildProcess == 0) { + startMsg.maxChildProcess = bundleInfo.applicationInfo.maxChildProcess; + } + startMsg.setAllowInternet = setAllowInternet; + startMsg.allowInternet = allowInternet; + startMsg.gids = gids; + startMsg.flags |= hasAccessBundleDirReq ? APP_ACCESS_BUNDLE_DIR : 0; SetAppEnvInfo(bundleInfo, startMsg); +} - TAG_LOGI(AAFwkTag::APPMGR, - "apl is %{public}s, bundleName is %{public}s, startFlags is %{public}d, isPreload:%{public}d", - startMsg.apl.c_str(), bundleName.c_str(), startFlags, isPreload); +int32_t AppMgrServiceInner::CreateStartMsg(const std::string &processName, uint32_t startFlags, const int uid, + const BundleInfo &bundleInfo, const int32_t bundleIndex, BundleType bundleType, AppSpawnStartMsg &startMsg, + const std::string &moduleName, const std::string &abilityName, bool strictMode) +{ + if (!remoteClientManager_ || !otherTaskHandler_) { + TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager or otherTaskHandler is nullptr."); + return ERR_NO_INIT; + } - bool bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetBundleGidsByUid(bundleName, uid, startMsg.gids)); - if (!bundleMgrResult) { + auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper(); + if (!bundleMgrHelper) { + TAG_LOGE(AAFwkTag::APPMGR, "Get bundle manager helper failed."); + return ERR_NO_INIT; + } + + AAFwk::AutoSyncTaskHandle autoSync(otherTaskHandler_->SubmitTask([&]() { + AddMountPermission(bundleInfo.applicationInfo.accessTokenId, startMsg.permissions); + })); + + HspList hspList; + auto ret = bundleMgrHelper->GetBaseSharedBundleInfos(bundleInfo.name, hspList, + AppExecFwk::GetDependentBundleInfoFlag::GET_ALL_DEPENDENT_BUNDLE_INFO); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::APPMGR, "GetBaseSharedBundleInfos failed: %{public}d.", ret); + return ret; + } + startMsg.hspList = hspList; + + auto userId = GetUserIdByUid(uid); + DataGroupInfoList dataGroupInfoList; + bool result = bundleMgrHelper->QueryDataGroupInfos(bundleInfo.name, userId, dataGroupInfoList); + if (!result || dataGroupInfoList.empty()) { + TAG_LOGD(AAFwkTag::APPMGR, "the bundle has no groupInfos."); + } + QueryExtensionSandBox(moduleName, abilityName, bundleInfo, startMsg, dataGroupInfoList, strictMode); + startMsg.bundleName = bundleInfo.name; + startMsg.renderParam = RENDER_PARAM; + startMsg.flags = startFlags; + startMsg.bundleIndex = bundleIndex; + startMsg.procName = processName; + + SetAtomicServiceInfo(bundleType, startMsg); + SetOverlayInfo(bundleInfo.name, userId, startMsg); + SetAppInfo(bundleInfo, startMsg); + + TAG_LOGI(AAFwkTag::APPMGR, "apl is %{public}s, bundleName is %{public}s, startFlags is %{public}d", + startMsg.apl.c_str(), bundleInfo.name.c_str(), startFlags); + + if (!IN_PROCESS_CALL(bundleMgrHelper->GetBundleGidsByUid(bundleInfo.name, uid, startMsg.gids))) { TAG_LOGE(AAFwkTag::APPMGR, "GetBundleGids is fail."); + return ERR_INVALID_OPERATION; + } + autoSync.Sync(); + return ERR_OK; +} + +void AppMgrServiceInner::QueryExtensionSandBox(const std::string &moduleName, const std::string &abilityName, + const BundleInfo &bundleInfo, AppSpawnStartMsg &startMsg, DataGroupInfoList& dataGroupInfoList, bool strictMode) +{ + std::vector extensionInfos; + for (auto hapModuleInfo: bundleInfo.hapModuleInfos) { + extensionInfos.insert(extensionInfos.end(), hapModuleInfo.extensionInfos.begin(), + hapModuleInfo.extensionInfos.end()); + } + auto infoExisted = [&moduleName, &abilityName](const ExtensionAbilityInfo& info) { + return info.moduleName == moduleName && info.name == abilityName && info.needCreateSandbox; + }; + auto infoIter = std::find_if(extensionInfos.begin(), extensionInfos.end(), infoExisted); + DataGroupInfoList extensionDataGroupInfoList; + if (infoIter != extensionInfos.end()) { + startMsg.isolatedExtension = infoIter->needCreateSandbox; + startMsg.extensionSandboxPath = infoIter->moduleName + "/" + infoIter->name; + startMsg.strictMode = strictMode; + for (auto dataGroupInfo : dataGroupInfoList) { + auto groupIdExisted = [&dataGroupInfo](const std::string &dataGroupId) { + return dataGroupInfo.dataGroupId == dataGroupId; + }; + if (std::find_if(infoIter->dataGroupIds.begin(), infoIter->dataGroupIds.end(), groupIdExisted) != + infoIter->dataGroupIds.end()) { + extensionDataGroupInfoList.emplace_back(dataGroupInfo); + } + } + startMsg.dataGroupInfoList = extensionDataGroupInfoList; + } else { + startMsg.dataGroupInfoList = dataGroupInfoList; + } +} + +void AppMgrServiceInner::PresetMaxChildProcess(const std::shared_ptr &abilityInfo, + int32_t &maxChildProcess) +{ + auto type = abilityInfo->type; + auto extensionType = abilityInfo->extensionAbilityType; + if (type == AppExecFwk::AbilityType::EXTENSION && + extensionType != AppExecFwk::ExtensionAbilityType::DATASHARE && + extensionType != AppExecFwk::ExtensionAbilityType::SERVICE) { + maxChildProcess = 1; + } +} + +void AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName, uint32_t startFlags, + std::shared_ptr appRecord, const int uid, const BundleInfo &bundleInfo, + const std::string &bundleName, const int32_t bundleIndex, bool appExistFlag, bool isPreload, + const std::string &moduleName, const std::string &abilityName, bool strictMode, int32_t maxChildProcess) +{ + HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); + TAG_LOGD(AAFwkTag::APPMGR, "bundleName: %{public}s, isPreload: %{public}d", bundleName.c_str(), isPreload); + if (!appRecord) { + TAG_LOGE(AAFwkTag::APPMGR, "appRecord is null"); + return; + } + + if (!remoteClientManager_ || !remoteClientManager_->GetSpawnClient()) { + TAG_LOGE(AAFwkTag::APPMGR, "appSpawnClient is null"); appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId()); return; } - startMsg.procName = processName; - startMsg.accessTokenIdEx = bundleInfo.applicationInfo.accessTokenIdEx; + AppSpawnStartMsg startMsg; + auto appInfo = appRecord->GetApplicationInfo(); + auto bundleType = appInfo ? appInfo->bundleType : BundleType::APP; + startMsg.maxChildProcess = maxChildProcess; + if (CreateStartMsg(processName, startFlags, uid, bundleInfo, bundleIndex, bundleType, startMsg, moduleName, + abilityName, strictMode) != ERR_OK) { + TAG_LOGE(AAFwkTag::APPMGR, "CreateStartMsg failed."); + appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId()); + return; + }; SetProcessJITState(appRecord); - autoSync.Sync(); PerfProfile::GetInstance().SetAppForkStartTime(GetTickCount()); pid_t pid = 0; - TAG_LOGD(AAFwkTag::APPMGR, "bundleName: %{public}s.", bundleName.c_str()); ErrCode errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid); if (FAILED(errCode)) { TAG_LOGE(AAFwkTag::APPMGR, "failed to spawn new app process, errCode %{public}08x", errCode); @@ -2557,7 +2759,7 @@ void AppMgrServiceInner::StartProcess(const std::string &appName, const std::str } TAG_LOGI(AAFwkTag::APPMGR, "Start process success, pid: %{public}d, processName: %{public}s.", pid, processName.c_str()); - SetRunningSharedBundleList(bundleName, hspList); + SetRunningSharedBundleList(bundleName, startMsg.hspList); appRecord->GetPriorityObject()->SetPid(pid); appRecord->SetUid(startMsg.uid); appRecord->SetStartMsg(startMsg); @@ -2822,6 +3024,15 @@ void AppMgrServiceInner::OnRemoteDied(const wptr &remote, bool is return; } + std::vector> abilityTokens; + for (const auto &token : appRecord->GetAbilities()) { + abilityTokens.emplace_back(token.first); + } + for (const auto &callback : appStateCallbacks_) { + if (callback != nullptr) { + callback->OnAppRemoteDied(abilityTokens); + } + } ClearData(appRecord); } @@ -3028,12 +3239,16 @@ void AppMgrServiceInner::HandleAddAbilityStageTimeOut(const int64_t eventId) } if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) { - startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant()); + startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant(), + appRecord->GetSpecifiedRequestId()); } + appRecord->ResetSpecifiedRequestId(); if (appRecord->IsNewProcessRequest() && startSpecifiedAbilityResponse_) { - startSpecifiedAbilityResponse_->OnNewProcessRequestTimeoutResponse(appRecord->GetNewProcessRequestWant()); + startSpecifiedAbilityResponse_->OnNewProcessRequestTimeoutResponse(appRecord->GetNewProcessRequestWant(), + appRecord->GetNewProcessRequestId()); } + appRecord->ResetNewProcessRequestId(); KillApplicationByRecord(appRecord); } @@ -3050,14 +3265,15 @@ void AppMgrServiceInner::GetRunningProcessInfoByToken( appRunningManager_->GetRunningProcessInfoByToken(token, info); } -void AppMgrServiceInner::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const +int32_t AppMgrServiceInner::GetRunningProcessInfoByPid(const pid_t pid, + OHOS::AppExecFwk::RunningProcessInfo &info) const { TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!CheckGetRunningInfoPermission()) { - return; + return ERR_PERMISSION_DENIED; } - appRunningManager_->GetRunningProcessInfoByPid(pid, info); + return appRunningManager_->GetRunningProcessInfoByPid(pid, info); } void AppMgrServiceInner::SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const @@ -3449,10 +3665,10 @@ int AppMgrServiceInner::StartEmptyProcess(const AAFwk::Want &want, const sptruserId = userId; appRecord->SetUserTestInfo(testRecord); - int32_t bundleIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0); + int32_t appIndex = AbilityRuntime::StartupUtil::GetAppIndex(want); uint32_t startFlags = AppspawnUtil::BuildStartFlags(want, info.applicationInfo); StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, info, appInfo->bundleName, - bundleIndex, appExistFlag); + appIndex, appExistFlag); // If it is empty, the startup failed if (!appRecord) { @@ -3528,7 +3744,8 @@ int AppMgrServiceInner::FinishUserTestLocked( return ERR_OK; } -void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) +void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo, + int32_t requestId) { TAG_LOGD(AAFwkTag::APPMGR, "Start specified ability."); if (!CheckRemoteClient()) { @@ -3539,7 +3756,7 @@ void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const Ap HapModuleInfo hapModuleInfo; auto appInfo = std::make_shared(abilityInfo.applicationInfo); - int32_t appIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0); + int32_t appIndex = AbilityRuntime::StartupUtil::GetAppIndex(want); if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) { return; } @@ -3591,11 +3808,10 @@ void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const Ap appRecord->SendEventForSpecifiedAbility(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG, AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT); uint32_t startFlags = AppspawnUtil::BuildStartFlags(want, abilityInfo); - int32_t bundleIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0); StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, bundleInfo, appInfo->bundleName, - bundleIndex, appExistFlag); + appIndex, appExistFlag); - appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName); + appRecord->SetSpecifiedAbilityFlagAndWant(requestId, want, hapModuleInfo.moduleName); appRecord->AddModules(appInfo, hapModules); } else { TAG_LOGD(AAFwkTag::APPMGR, "process is exist"); @@ -3604,7 +3820,7 @@ void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const Ap ProcessAppDebug(appRecord, isDebugApp); } - appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName); + appRecord->SetSpecifiedAbilityFlagAndWant(requestId, want, hapModuleInfo.moduleName); auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); if (!moduleRecord) { TAG_LOGD(AAFwkTag::APPMGR, "module record is nullptr, add modules"); @@ -3647,8 +3863,10 @@ void AppMgrServiceInner::ScheduleAcceptWantDone( appRecord->ScheduleAcceptWantDone(); if (startSpecifiedAbilityResponse_) { - startSpecifiedAbilityResponse_->OnAcceptWantResponse(want, flag); + startSpecifiedAbilityResponse_->OnAcceptWantResponse(want, flag, + appRecord->GetSpecifiedRequestId()); } + appRecord->ResetSpecifiedRequestId(); } void AppMgrServiceInner::HandleStartSpecifiedAbilityTimeOut(const int64_t eventId) @@ -3666,8 +3884,10 @@ void AppMgrServiceInner::HandleStartSpecifiedAbilityTimeOut(const int64_t eventI } if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) { - startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant()); + startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant(), + appRecord->GetSpecifiedRequestId()); } + appRecord->ResetSpecifiedRequestId(); KillApplicationByRecord(appRecord); } @@ -3685,8 +3905,10 @@ void AppMgrServiceInner::ScheduleNewProcessRequestDone( appRecord->ScheduleNewProcessRequestDone(); if (startSpecifiedAbilityResponse_) { - startSpecifiedAbilityResponse_->OnNewProcessRequestResponse(want, flag); + startSpecifiedAbilityResponse_->OnNewProcessRequestResponse(want, flag, + appRecord->GetNewProcessRequestId()); } + appRecord->ResetNewProcessRequestId(); } void AppMgrServiceInner::HandleStartSpecifiedProcessTimeout(const int64_t eventId) @@ -3704,8 +3926,10 @@ void AppMgrServiceInner::HandleStartSpecifiedProcessTimeout(const int64_t eventI } if (startSpecifiedAbilityResponse_) { - startSpecifiedAbilityResponse_->OnNewProcessRequestTimeoutResponse(appRecord->GetNewProcessRequestWant()); + startSpecifiedAbilityResponse_->OnNewProcessRequestTimeoutResponse(appRecord->GetNewProcessRequestWant(), + appRecord->GetNewProcessRequestId()); } + appRecord->ResetNewProcessRequestId(); } int32_t AppMgrServiceInner::UpdateConfiguration(const Configuration &config) @@ -3851,6 +4075,12 @@ void AppMgrServiceInner::InitGlobalConfiguration() auto deviceType = GetDeviceType(); TAG_LOGI(AAFwkTag::APPMGR, "current deviceType is %{public}s", deviceType); configuration_->AddItem(AAFwk::GlobalConfigurationKey::DEVICE_TYPE, deviceType); + auto fontSizeScale = OHOS::system::GetParameter(FONT_SCALE, "1.0"); + auto fontWeightScale = OHOS::system::GetParameter(FONT_WGHT_SCALE, "1.0"); + TAG_LOGI(AAFwkTag::APPMGR, "current fontSizeScale is: %{public}s, fontWeightScale is: %{public}s", + fontSizeScale.c_str(), fontWeightScale.c_str()); + configuration_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_FONT_SIZE_SCALE, fontSizeScale); + configuration_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_FONT_WEIGHT_SCALE, fontWeightScale); } std::shared_ptr AppMgrServiceInner::GetConfiguration() @@ -4004,6 +4234,25 @@ int AppMgrServiceInner::GetApplicationInfoByProcessID(const int pid, AppExecFwk: return ERR_OK; } +int32_t AppMgrServiceInner::NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg) +{ + TAG_LOGD(AAFwkTag::APPMGR, "NotifyAppMgrRecordExitReason pid:%{public}d, reason:%{public}d, exitMsg:%{public}s.", + pid, reason, exitMsg.c_str()); + auto callerUid = IPCSkeleton::GetCallingUid(); + if (callerUid != FOUNDATION_UID) { + TAG_LOGE(AAFwkTag::APPMGR, "Not foundation call."); + return ERR_PERMISSION_DENIED; + } + auto appRecord = GetAppRunningRecordByPid(pid); + if (!appRecord) { + TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord for pid:%{public}d", pid); + return ERR_NAME_NOT_FOUND; + } + appRecord->SetExitReason(reason); + appRecord->SetExitMsg(exitMsg); + return ERR_OK; +} + int AppMgrServiceInner::VerifyProcessPermission() const { auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); @@ -4196,7 +4445,7 @@ int AppMgrServiceInner::PreStartNWebSpawnProcess(const pid_t hostPid) } int AppMgrServiceInner::StartRenderProcess(const pid_t hostPid, const std::string &renderParam, - int32_t ipcFd, int32_t sharedFd, int32_t crashFd, pid_t &renderPid) + int32_t ipcFd, int32_t sharedFd, int32_t crashFd, pid_t &renderPid, bool isGPU) { TAG_LOGI(AAFwkTag::APPMGR, "start render process, hostPid:%{public}d", hostPid); if (hostPid <= 0 || renderParam.empty() || ipcFd <= 0 || sharedFd <= 0 || @@ -4219,7 +4468,7 @@ int AppMgrServiceInner::StartRenderProcess(const pid_t hostPid, const std::strin } auto renderRecordMap = appRecord->GetRenderRecordMap(); - if (!renderRecordMap.empty() && !AAFwk::AppUtils::GetInstance().IsUseMultiRenderProcess()) { + if (!isGPU && !renderRecordMap.empty() && !AAFwk::AppUtils::GetInstance().IsUseMultiRenderProcess()) { for (auto iter : renderRecordMap) { if (iter.second != nullptr) { renderPid = iter.second->GetPid(); @@ -4236,10 +4485,11 @@ int AppMgrServiceInner::StartRenderProcess(const pid_t hostPid, const std::strin } } } - + appRecord->SetIsGPU(isGPU); + int32_t childNumLimit = appRecord->GetIsGPU() ? PHONE_MAX_RENDER_PROCESS_NUM + 1 : PHONE_MAX_RENDER_PROCESS_NUM; // The phone device allows a maximum of 40 render processes to be created. if (AAFwk::AppUtils::GetInstance().IsLimitMaximumOfRenderProcess() && - renderRecordMap.size() >= PHONE_MAX_RENDER_PROCESS_NUM) { + renderRecordMap.size() >= static_cast(childNumLimit)) { TAG_LOGE(AAFwkTag::APPMGR, "Reaching the maximum render process limitation, hostPid:%{public}d", hostPid); return ERR_REACHING_MAXIMUM_RENDER_PROCESS_LIMITATION; } @@ -4250,7 +4500,7 @@ int AppMgrServiceInner::StartRenderProcess(const pid_t hostPid, const std::strin return ERR_INVALID_VALUE; } - return StartRenderProcessImpl(renderRecord, appRecord, renderPid); + return StartRenderProcessImpl(renderRecord, appRecord, renderPid, isGPU); } void AppMgrServiceInner::AttachRenderProcess(const pid_t pid, const sptr &scheduler) @@ -4293,9 +4543,27 @@ void AppMgrServiceInner::AttachRenderProcess(const pid_t pid, const sptrNotifyBrowserFd(renderRecord->GetIpcFd(), - renderRecord->GetSharedFd(), - renderRecord->GetCrashFd()); + if (appRecord->GetBrowserHost() != nullptr && appRecord->GetIsGPU()) { + TAG_LOGD(AAFwkTag::APPMGR, "GPU has host remote object"); + scheduler->NotifyBrowserFd(renderRecord->GetIpcFd(), + renderRecord->GetSharedFd(), renderRecord->GetCrashFd(), appRecord->GetBrowserHost()); + } else { + scheduler->NotifyBrowserFd(renderRecord->GetIpcFd(), + renderRecord->GetSharedFd(), renderRecord->GetCrashFd(), nullptr); + } +} + +void AppMgrServiceInner::SaveBrowserChannel(const pid_t hostPid, sptr browser) +{ + std::lock_guard lock(browserHostLock_); + TAG_LOGD(AAFwkTag::APPMGR, "save browser channel."); + auto appRecord = GetAppRunningRecordByPid(hostPid); + if (!appRecord) { + TAG_LOGE(AAFwkTag::APPMGR, "save browser host no such appRecord, pid:%{public}d", + hostPid); + return; + } + appRecord->SetBrowserHost(browser); } bool AppMgrServiceInner::GenerateRenderUid(int32_t &renderUid) @@ -4339,7 +4607,7 @@ bool AppMgrServiceInner::GenerateRenderUid(int32_t &renderUid) } int AppMgrServiceInner::StartRenderProcessImpl(const std::shared_ptr &renderRecord, - const std::shared_ptr appRecord, pid_t &renderPid) + const std::shared_ptr appRecord, pid_t &renderPid, bool isGPU) { if (!renderRecord || !appRecord) { TAG_LOGE(AAFwkTag::APPMGR, "renderRecord or appRecord is nullptr."); @@ -4362,6 +4630,13 @@ int AppMgrServiceInner::StartRenderProcessImpl(const std::shared_ptrGetRenderParam(); startMsg.uid = renderUid; startMsg.gid = renderUid; + if (isGPU) { + startMsg.procName += GPU_PROCESS_NAME; + startMsg.processType = GPU_PROCESS_TYPE; + } else { + startMsg.procName += RENDER_PROCESS_NAME; + startMsg.processType = RENDER_PROCESS_TYPE; + } startMsg.code = 0; // 0: DEFAULT pid_t pid = 0; ErrCode errCode = nwebSpawnClient->StartProcess(startMsg, pid); @@ -4374,6 +4649,10 @@ int AppMgrServiceInner::StartRenderProcessImpl(const std::shared_ptrSetPid(pid); renderRecord->SetUid(renderUid); + if (isGPU) { + renderRecord->SetProcessType(ProcessType::GPU); + appRecord->SetGPUPid(pid); + } appRecord->AddRenderRecord(renderRecord); TAG_LOGI(AAFwkTag::APPMGR, "start render process success, hostPid:%{public}d, hostUid:%{public}d, pid:%{public}d, uid:%{public}d", @@ -4776,6 +5055,11 @@ int32_t AppMgrServiceInner::NotifyAppFault(const FaultData &faultData) TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord"); return ERR_INVALID_VALUE; } + if (appRecord->GetState() == ApplicationState::APP_STATE_TERMINATED || + appRecord->GetState() == ApplicationState::APP_STATE_END) { + TAG_LOGE(AAFwkTag::APPMGR, "Appfreeze detect end."); + return ERR_OK; + } std::string bundleName = appRecord->GetBundleName(); if (faultData.faultType == FaultDataType::APP_FREEZE) { @@ -4910,7 +5194,7 @@ int32_t AppMgrServiceInner::NotifyAppFaultBySA(const AppFaultDataBySA &faultData transformedFaultData.timeoutMarkers = "notifyFault:" + transformedFaultData.errorObject.name + std::to_string(pid) + "-" + std::to_string(SystemTimeMillisecond()); } - const int64_t timeout = 11000; + const int64_t timeout = 1000; if (faultData.faultType == FaultDataType::APP_FREEZE) { if (!AppExecFwk::AppfreezeManager::GetInstance()->IsHandleAppfreeze(bundleName) || record->IsDebugging()) { return ERR_OK; @@ -5001,25 +5285,26 @@ int32_t AppMgrServiceInner::IsApplicationRunning(const std::string &bundleName, return ERR_OK; } -int32_t AppMgrServiceInner::StartNativeProcessForDebugger(const AAFwk::Want &want) const +int32_t AppMgrServiceInner::StartNativeProcessForDebugger(const AAFwk::Want &want) { + if (!remoteClientManager_ || !appRunningManager_) { + TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager or appRunningManager is nullptr!"); + return ERR_INVALID_OPERATION; + } auto&& bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper(); - if (bundleMgrHelper == nullptr) { + if (!bundleMgrHelper) { TAG_LOGE(AAFwkTag::APPMGR, "Get bundle manager helper error."); return ERR_INVALID_OPERATION; } - if (appRunningManager_ == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr."); - return ERR_INVALID_OPERATION; - } TAG_LOGI(AAFwkTag::APPMGR, "debuggablePipe bundleName:%{public}s", want.GetElement().GetBundleName().c_str()); TAG_LOGI(AAFwkTag::APPMGR, "debuggablePipe moduleName:%{public}s", want.GetElement().GetModuleName().c_str()); TAG_LOGI(AAFwkTag::APPMGR, "debuggablePipe abilityName:%{public}s", want.GetElement().GetAbilityName().c_str()); AbilityInfo abilityInfo; auto userId = GetCurrentAccountId(); - IN_PROCESS_CALL_WITHOUT_RET(bundleMgrHelper->QueryAbilityInfo(want, GetFlag(), userId, abilityInfo)); + auto abilityInfoFlag = AbilityRuntime::StartupUtil::BuildAbilityInfoFlag(); + IN_PROCESS_CALL_WITHOUT_RET(bundleMgrHelper->QueryAbilityInfo(want, abilityInfoFlag, userId, abilityInfo)); BundleInfo bundleInfo; HapModuleInfo hapModuleInfo; auto appInfo = std::make_shared(abilityInfo.applicationInfo); @@ -5034,34 +5319,26 @@ int32_t AppMgrServiceInner::StartNativeProcessForDebugger(const AAFwk::Want &wan auto&& appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo); - if (appRecord == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "The appRecord not found."); + AppSpawnStartMsg startMsg; + bool isDevelopeMode = system::GetBoolParameter(DEVELOPER_MODE_STATE, false); + if (appRecord) { + startMsg = appRecord->GetStartMsg(); + } else if (!isDevelopeMode || CreatNewStartMsg(want, abilityInfo, appInfo, processName, startMsg) != ERR_OK) { + TAG_LOGE(AAFwkTag::APPMGR, "Invalid Operation"); return ERR_INVALID_OPERATION; } bool isSandboxApp = want.GetBoolParam(ENTER_SANDBOX, false); - if (isSandboxApp) { - TAG_LOGI(AAFwkTag::APPMGR, "debuggablePipe sandbox: true"); - } - auto&& cmd = want.GetStringParam(PERF_CMD); - if (cmd.size() == 0) { - cmd = want.GetStringParam(DEBUG_CMD); - TAG_LOGI(AAFwkTag::APPMGR, "debuggablePipe debugCmd:%{public}s", cmd.c_str()); + auto&& pefCmd = want.GetStringParam(PERF_CMD); + std::string debugCmd = ""; + if (pefCmd.empty()) { if (!appInfo->debug) { TAG_LOGE(AAFwkTag::APPMGR, "The app is not debug mode."); return ERR_INVALID_OPERATION; } - return StartPerfProcess(appRecord, "", cmd, isSandboxApp); - } else { - return StartPerfProcess(appRecord, cmd, "", isSandboxApp); + debugCmd = want.GetStringParam(DEBUG_CMD); } -} - -int32_t AppMgrServiceInner::GetFlag() const -{ - return AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION | - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION | - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA; + return StartPerfProcessByStartMsg(startMsg, pefCmd, debugCmd, isSandboxApp); } int32_t AppMgrServiceInner::GetCurrentAccountId() const @@ -5805,6 +6082,7 @@ int32_t AppMgrServiceInner::GetChildProcessInfo(const std::shared_ptrGetPid(); info.hostPid = childProcessRecord->GetHostPid(); info.uid = childProcessRecord->GetUid(); + info.processType = childProcessRecord->GetProcessType(); info.bundleName = appRecord->GetBundleName(); info.processName = childProcessRecord->GetProcessName(); info.srcEntry = childProcessRecord->GetSrcEntry(); @@ -5853,7 +6131,12 @@ void AppMgrServiceInner::AttachChildProcess(const pid_t pid, const sptrSetDeathRecipient(appDeathRecipient); childRecord->RegisterDeathRecipient(); - childScheduler->ScheduleLoadJs(); + if (childRecord->GetProcessType() != CHILD_PROCESS_TYPE_NATIVE) { + childScheduler->ScheduleLoadJs(); + } else { + childScheduler->ScheduleRunNativeProc(childRecord->GetMainProcessCallback()); + childRecord->ClearMainProcessCallback(); + } } void AppMgrServiceInner::OnChildProcessRemoteDied(const wptr &remote) @@ -5957,9 +6240,9 @@ int AppMgrServiceInner::DumpIpcAllStart(std::string& result) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (!appRunningManager_) { - result.append(MSG_DUMP_IPC_START_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null"); return DumpErrorCode::ERR_INTERNAL_ERROR; } @@ -5970,9 +6253,9 @@ int AppMgrServiceInner::DumpIpcAllStop(std::string& result) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (!appRunningManager_) { - result.append(MSG_DUMP_IPC_STOP_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null"); return DumpErrorCode::ERR_INTERNAL_ERROR; } @@ -5983,9 +6266,9 @@ int AppMgrServiceInner::DumpIpcAllStat(std::string& result) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (!appRunningManager_) { - result.append(MSG_DUMP_IPC_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null"); return DumpErrorCode::ERR_INTERNAL_ERROR; } @@ -5996,9 +6279,9 @@ int AppMgrServiceInner::DumpIpcStart(const int32_t pid, std::string& result) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (!appRunningManager_) { - result.append(MSG_DUMP_IPC_START_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null"); return DumpErrorCode::ERR_INTERNAL_ERROR; } @@ -6009,9 +6292,9 @@ int AppMgrServiceInner::DumpIpcStop(const int32_t pid, std::string& result) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (!appRunningManager_) { - result.append(MSG_DUMP_IPC_STOP_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null"); return DumpErrorCode::ERR_INTERNAL_ERROR; } @@ -6022,15 +6305,27 @@ int AppMgrServiceInner::DumpIpcStat(const int32_t pid, std::string& result) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (!appRunningManager_) { - result.append(MSG_DUMP_IPC_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null"); return DumpErrorCode::ERR_INTERNAL_ERROR; } return appRunningManager_->DumpIpcStat(pid, result); } +int AppMgrServiceInner::DumpFfrt(const std::vector& pids, std::string& result) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called."); + if (!appRunningManager_) { + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); + TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null"); + return DumpErrorCode::ERR_INTERNAL_ERROR; + } + return appRunningManager_->DumpFfrt(pids, result); +} + void AppMgrServiceInner::NotifyAppRunningStatusEvent( const std::string &bundle, int32_t uid, AbilityRuntime::RunningStatus runningStatus) { @@ -6167,7 +6462,7 @@ int32_t AppMgrServiceInner::UnregisterRenderStateObserver(const sptr::GetInstance()->UnregisterRenderStateObserver(observer); } -void AppMgrServiceInner::SetAppAssertionPauseState(int32_t pid, bool flag) +void AppMgrServiceInner::SetAppAssertionPauseState(bool flag) { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "Called."); @@ -6180,14 +6475,10 @@ void AppMgrServiceInner::SetAppAssertionPauseState(int32_t pid, bool flag) return; } - auto callerUid = IPCSkeleton::GetCallingUid(); - if (callerUid != FOUNDATION_UID) { - TAG_LOGE(AAFwkTag::APPMGR, "Caller is not foundation."); - return; - } - auto appRecord = GetAppRunningRecordByPid(pid); + auto callerPid = IPCSkeleton::GetCallingRealPid(); + auto appRecord = GetAppRunningRecordByPid(callerPid); if (appRecord == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "No such appRecord pid is %{public}d.", pid); + TAG_LOGE(AAFwkTag::APPMGR, "No such appRecord pid is %{public}d.", callerPid); return; } appRecord->SetAssertionPauseFlag(flag); @@ -6436,5 +6727,48 @@ void AppMgrServiceInner::OnAppCacheStateChanged(const std::shared_ptr::GetInstance()->OnAppCacheStateChanged(appRecord); } + +int32_t AppMgrServiceInner::StartNativeChildProcess(const pid_t hostPid, const std::string &libName, + int32_t childProcessCount, const sptr &callback) +{ + TAG_LOGI(AAFwkTag::APPMGR, "StartNativeChildProcess, hostPid:%{public}d", hostPid); + if (hostPid <= 0 || libName.empty() || !callback) { + TAG_LOGE(AAFwkTag::APPMGR, "Invalid param: hostPid:%{public}d libName:%{private}s", + hostPid, libName.c_str()); + return ERR_INVALID_VALUE; + } + + if (!AAFwk::AppUtils::GetInstance().IsSupportNativeChildProcess()) { + TAG_LOGE(AAFwkTag::APPMGR, "Unsupport native child process"); + return ERR_INVALID_OPERATION; + } + + int32_t errCode = StartChildProcessPreCheck(hostPid); + if (errCode != ERR_OK) { + return errCode; + } + + auto appRecord = GetAppRunningRecordByPid(hostPid); + if (!appRecord) { + TAG_LOGI(AAFwkTag::APPMGR, "Get app runnning record(hostPid:%{public}d) failed.", hostPid); + return ERR_INVALID_OPERATION; + } + + auto childRecordMap = appRecord->GetChildProcessRecordMap(); + auto itNativeChildInfo = find_if(childRecordMap.begin(), childRecordMap.end(), [] (const auto &pair) -> bool { + return pair.second->GetProcessType() == CHILD_PROCESS_TYPE_NATIVE; + }); + + if (itNativeChildInfo != childRecordMap.end()) { + TAG_LOGI(AAFwkTag::APPMGR, "Native child process still alive(hostPid:%{public}d childPid:%{public}d)", + hostPid, itNativeChildInfo->second->GetPid()); + return ERR_OVERFLOW; + } + + pid_t dummyChildPid = 0; + auto nativeChildRecord = ChildProcessRecord::CreateNativeChildProcessRecord( + hostPid, libName, appRecord, callback, childProcessCount, false); + return StartChildProcessImpl(nativeChildRecord, appRecord, dummyChildPid); +} } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/src/app_preloader.cpp b/services/appmgr/src/app_preloader.cpp index 08dad23849..f3bbc76cc1 100644 --- a/services/appmgr/src/app_preloader.cpp +++ b/services/appmgr/src/app_preloader.cpp @@ -23,6 +23,7 @@ #include "hitrace_meter.h" #include "res_sched_client.h" #include "res_type.h" +#include "startup_util.h" namespace OHOS { namespace AppExecFwk { @@ -114,9 +115,7 @@ bool AppPreloader::GetLaunchAbilityInfo(const AAFwk::Want &want, int32_t userId, return false; } - auto abilityInfoFlag = (AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION | - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION | - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA); + auto abilityInfoFlag = AbilityRuntime::StartupUtil::BuildAbilityInfoFlag(); if (!IN_PROCESS_CALL(bundleMgrHelper->QueryAbilityInfo(want, abilityInfoFlag, userId, abilityInfo))) { TAG_LOGE(AAFwkTag::APPMGR, "PreloadApplication GetLaunchAbilityInfo failed."); return false; diff --git a/services/appmgr/src/app_running_manager.cpp b/services/appmgr/src/app_running_manager.cpp index d32ccb4657..c63485c342 100644 --- a/services/appmgr/src/app_running_manager.cpp +++ b/services/appmgr/src/app_running_manager.cpp @@ -36,6 +36,7 @@ #include "suspend_manager_client.h" #endif #include "app_mgr_service_dump_error_code.h" +#include "window_visibility_info.h" namespace OHOS { namespace AppExecFwk { @@ -79,9 +80,10 @@ std::shared_ptr AppRunningManager::CreateAppRunningRecord( processName.c_str(), isStageBasedModel, recordId); appRecord->SetStageModelState(isStageBasedModel); + appRecord->SetSingleton(bundleInfo.singleton); appRecord->SetSignCode(signCode); appRecord->SetJointUserId(bundleInfo.jointUserId); - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); appRunningRecordMap_.emplace(recordId, appRecord); return appRecord; } @@ -111,13 +113,12 @@ std::shared_ptr AppRunningManager::CheckAppRunningRecordIsExis !(pair.second->IsKilling()) && !(pair.second->GetRestartAppFlag()); }; - // If it is not empty, look for whether it can come in the same process - std::lock_guard guard(lock_); + auto appRunningMap = GetAppRunningRecordMap(); if (!jointUserId.empty()) { - auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), FindSameProcess); - return ((iter == appRunningRecordMap_.end()) ? nullptr : iter->second); + auto iter = std::find_if(appRunningMap.begin(), appRunningMap.end(), FindSameProcess); + return ((iter == appRunningMap.end()) ? nullptr : iter->second); } - for (const auto &item : appRunningRecordMap_) { + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; if (appRecord && appRecord->GetProcessName() == processName && (specifiedProcessFlag.empty() || @@ -143,7 +144,7 @@ std::shared_ptr AppRunningManager::CheckAppRunningRecordIsExis bool AppRunningManager::CheckAppRunningRecordIsExistByBundleName(const std::string &bundleName) { - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); if (appRunningRecordMap_.empty()) { return false; } @@ -159,7 +160,7 @@ bool AppRunningManager::CheckAppRunningRecordIsExistByBundleName(const std::stri int32_t AppRunningManager::GetAllAppRunningRecordCountByBundleName(const std::string &bundleName) { int32_t count = 0; - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (appRecord && appRecord->GetBundleName() == bundleName) { @@ -172,12 +173,7 @@ int32_t AppRunningManager::GetAllAppRunningRecordCountByBundleName(const std::st std::shared_ptr AppRunningManager::GetAppRunningRecordByPid(const pid_t pid) { - std::lock_guard guard(lock_); - return GetAppRunningRecordByPidInner(pid); -} - -std::shared_ptr AppRunningManager::GetAppRunningRecordByPidInner(const pid_t pid) -{ + std::lock_guard guard(runningRecordMapMutex_); auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) { return pair.second->GetPriorityObject()->GetPid() == pid; }); @@ -186,15 +182,9 @@ std::shared_ptr AppRunningManager::GetAppRunningRecordByPidInn std::shared_ptr AppRunningManager::GetAppRunningRecordByAbilityToken( const sptr &abilityToken) -{ - std::lock_guard guard(lock_); - return GetAppRunningRecordByTokenInner(abilityToken); -} - -std::shared_ptr AppRunningManager::GetAppRunningRecordByTokenInner( - const sptr &abilityToken) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (appRecord && appRecord->GetAbilityRunningRecordByToken(abilityToken)) { @@ -206,8 +196,8 @@ std::shared_ptr AppRunningManager::GetAppRunningRecordByTokenI bool AppRunningManager::ProcessExitByBundleName(const std::string &bundleName, std::list &pids) { - std::lock_guard guard(lock_); - for (const auto &item : appRunningRecordMap_) { + auto appRunningMap = GetAppRunningRecordMap(); + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; // condition [!appRecord->IsKeepAliveApp()] Is to not kill the resident process. // Before using this method, consider whether you need. @@ -231,8 +221,8 @@ bool AppRunningManager::ProcessExitByBundleName(const std::string &bundleName, s bool AppRunningManager::GetPidsByUserId(int32_t userId, std::list &pids) { - std::lock_guard guard(lock_); - for (const auto &item : appRunningRecordMap_) { + auto appRunningMap = GetAppRunningRecordMap(); + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; if (appRecord) { int32_t id = -1; @@ -252,9 +242,9 @@ bool AppRunningManager::GetPidsByUserId(int32_t userId, std::list &pids) int32_t AppRunningManager::ProcessUpdateApplicationInfoInstalled(const ApplicationInfo &appInfo) { - std::lock_guard guard(lock_); + auto appRunningMap = GetAppRunningRecordMap(); int32_t result = ERR_OK; - for (const auto &item : appRunningRecordMap_) { + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; if (!appRecord) { continue; @@ -273,8 +263,8 @@ int32_t AppRunningManager::ProcessUpdateApplicationInfoInstalled(const Applicati bool AppRunningManager::ProcessExitByBundleNameAndUid( const std::string &bundleName, const int uid, std::list &pids) { - std::lock_guard guard(lock_); - for (const auto &item : appRunningRecordMap_) { + auto appRunningMap = GetAppRunningRecordMap(); + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; if (appRecord) { auto appInfoList = appRecord->GetAppInfoList(); @@ -297,19 +287,12 @@ bool AppRunningManager::ProcessExitByBundleNameAndUid( bool AppRunningManager::ProcessExitByPid(pid_t pid) { - std::lock_guard guard(lock_); - for (const auto &item : appRunningRecordMap_) { - const auto &appRecord = item.second; - if (appRecord) { - pid_t appPid = appRecord->GetPriorityObject()->GetPid(); - if (appPid == pid) { - appRecord->SetKilling(); - appRecord->ScheduleProcessSecurityExit(); - return true; - } - } + auto appRecord = GetAppRunningRecordByPid(pid); + if (appRecord != nullptr) { + appRecord->SetKilling(); + appRecord->ScheduleProcessSecurityExit(); + return true; } - return false; } @@ -328,7 +311,7 @@ std::shared_ptr AppRunningManager::OnRemoteDied(const wptr appRecord = nullptr; { - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); const auto &iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&object](const auto &pair) { if (pair.second && pair.second->GetApplicationClient() != nullptr) { @@ -341,18 +324,17 @@ std::shared_ptr AppRunningManager::OnRemoteDied(const wptrsecond; - if (appRecord != nullptr) { - appRecord->RemoveAppDeathRecipient(); - appRecord->SetApplicationClient(nullptr); - TAG_LOGI(AAFwkTag::APPMGR, "processName: %{public}s.", appRecord->GetProcessName().c_str()); - auto priorityObject = appRecord->GetPriorityObject(); - if (priorityObject != nullptr) { - TAG_LOGI(AAFwkTag::APPMGR, "pid: %{public}d.", priorityObject->GetPid()); - } - } appRunningRecordMap_.erase(iter); } - + if (appRecord != nullptr) { + appRecord->RemoveAppDeathRecipient(); + appRecord->SetApplicationClient(nullptr); + TAG_LOGI(AAFwkTag::APPMGR, "processName: %{public}s.", appRecord->GetProcessName().c_str()); + auto priorityObject = appRecord->GetPriorityObject(); + if (priorityObject != nullptr) { + TAG_LOGI(AAFwkTag::APPMGR, "pid: %{public}d.", priorityObject->GetPid()); + } + } if (appRecord != nullptr && appRecord->GetPriorityObject() != nullptr) { RemoveUIExtensionLauncherItem(appRecord->GetPriorityObject()->GetPid()); } @@ -362,7 +344,7 @@ std::shared_ptr AppRunningManager::OnRemoteDied(const wptr> AppRunningManager::GetAppRunningRecordMap() { - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); return appRunningRecordMap_; } @@ -370,10 +352,11 @@ void AppRunningManager::RemoveAppRunningRecordById(const int32_t recordId) { std::shared_ptr appRecord = nullptr; { - std::lock_guard guard(lock_); - if (appRunningRecordMap_.find(recordId) != appRunningRecordMap_.end()) { - appRecord = appRunningRecordMap_.at(recordId); - appRunningRecordMap_.erase(recordId); + std::lock_guard guard(runningRecordMapMutex_); + auto it = appRunningRecordMap_.find(recordId); + if (it != appRunningRecordMap_.end()) { + appRecord = it->second; + appRunningRecordMap_.erase(it); } } @@ -384,7 +367,7 @@ void AppRunningManager::RemoveAppRunningRecordById(const int32_t recordId) void AppRunningManager::ClearAppRunningRecordMap() { - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); appRunningRecordMap_.clear(); } @@ -408,7 +391,7 @@ void AppRunningManager::HandleTerminateTimeOut(int64_t eventId) std::shared_ptr AppRunningManager::GetTerminatingAppRunningRecord( const sptr &abilityToken) { - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (appRecord && appRecord->GetAbilityByTerminateLists(abilityToken)) { @@ -421,7 +404,7 @@ std::shared_ptr AppRunningManager::GetTerminatingAppRunningRec std::shared_ptr AppRunningManager::GetAbilityRunningRecord(const int64_t eventId) { TAG_LOGD(AAFwkTag::APPMGR, "called"); - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); for (auto &item : appRunningRecordMap_) { if (item.second) { auto abilityRecord = item.second->GetAbilityRunningRecord(eventId); @@ -436,7 +419,7 @@ std::shared_ptr AppRunningManager::GetAbilityRunningRecord std::shared_ptr AppRunningManager::GetAppRunningRecord(const int64_t eventId) { TAG_LOGD(AAFwkTag::APPMGR, "called"); - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&eventId](const auto &pair) { return pair.second->GetEventId() == eventId; }); @@ -573,27 +556,27 @@ void AppRunningManager::GetRunningProcessInfoByToken( const sptr &token, AppExecFwk::RunningProcessInfo &info) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - std::lock_guard guard(lock_); - auto appRecord = GetAppRunningRecordByTokenInner(token); - + auto appRecord = GetAppRunningRecordByAbilityToken(token); AssignRunningProcessInfoByAppRecord(appRecord, info); } -void AppRunningManager::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) +int32_t AppRunningManager::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) { - std::lock_guard guard(lock_); - auto appRecord = GetAppRunningRecordByPidInner(pid); - - AssignRunningProcessInfoByAppRecord(appRecord, info); + if (pid <= 0) { + TAG_LOGE(AAFwkTag::APPMGR, "invalid process pid:%{public}d", pid); + return ERR_INVALID_OPERATION; + } + auto appRecord = GetAppRunningRecordByPid(pid); + return AssignRunningProcessInfoByAppRecord(appRecord, info); } -void AppRunningManager::AssignRunningProcessInfoByAppRecord( +int32_t AppRunningManager::AssignRunningProcessInfoByAppRecord( std::shared_ptr appRecord, AppExecFwk::RunningProcessInfo &info) const { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (!appRecord) { TAG_LOGE(AAFwkTag::APPMGR, "appRecord is nullptr"); - return; + return ERR_INVALID_OPERATION; } info.processName_ = appRecord->GetProcessName(); @@ -614,12 +597,12 @@ void AppRunningManager::AssignRunningProcessInfoByAppRecord( if (appInfo) { info.bundleType = static_cast(appInfo->bundleType); } + return ERR_OK; } void AppRunningManager::SetAbilityForegroundingFlagToAppRecord(const pid_t pid) { - std::lock_guard guard(lock_); - auto appRecord = GetAppRunningRecordByPidInner(pid); + auto appRecord = GetAppRunningRecordByPid(pid); if (appRecord == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "appRecord is nullptr"); return; @@ -637,7 +620,7 @@ void AppRunningManager::ClipStringContent(const std::regex &re, const std::strin void AppRunningManager::GetForegroundApplications(std::vector &list) { - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (!appRecord) { @@ -702,10 +685,10 @@ void AppRunningManager::HandleStartSpecifiedAbilityTimeOut(const int64_t eventId int32_t AppRunningManager::UpdateConfiguration(const Configuration &config) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - std::lock_guard guard(lock_); - TAG_LOGD(AAFwkTag::APPMGR, "current app size %{public}zu", appRunningRecordMap_.size()); + auto appRunningMap = GetAppRunningRecordMap(); + TAG_LOGD(AAFwkTag::APPMGR, "current app size %{public}zu", appRunningMap.size()); int32_t result = ERR_OK; - for (const auto &item : appRunningRecordMap_) { + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; if (appRecord && appRecord->GetState() == ApplicationState::APP_STATE_CREATE) { TAG_LOGD(AAFwkTag::APPMGR, "app not ready, appName is %{public}s", appRecord->GetBundleName().c_str()); @@ -721,9 +704,9 @@ int32_t AppRunningManager::UpdateConfiguration(const Configuration &config) int32_t AppRunningManager::UpdateConfigurationByBundleName(const Configuration &config, const std::string &name) { - std::lock_guard guard(lock_); + auto appRunningMap = GetAppRunningRecordMap(); int32_t result = ERR_OK; - for (const auto &item : appRunningRecordMap_) { + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; if (appRecord && appRecord->GetState() == ApplicationState::APP_STATE_CREATE) { TAG_LOGD(AAFwkTag::APPMGR, "app not ready, appName is %{public}s", appRecord->GetBundleName().c_str()); @@ -764,8 +747,8 @@ int32_t AppRunningManager::NotifyMemoryLevel(int32_t level) } } #endif - std::lock_guard guard(lock_); - for (const auto &item : appRunningRecordMap_) { + auto appRunningMap = GetAppRunningRecordMap(); + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; if (!appRecord) { TAG_LOGE(AAFwkTag::APPMGR, "appRecord null"); @@ -804,8 +787,8 @@ int32_t AppRunningManager::NotifyProcMemoryLevel(const std::map guard(lock_); - for (const auto &item : appRunningRecordMap_) { + auto appRunningMap = GetAppRunningRecordMap(); + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; if (!appRecord) { TAG_LOGE(AAFwkTag::APPMGR, "appRecord null"); @@ -836,7 +819,7 @@ int32_t AppRunningManager::DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::M { std::shared_ptr appRecord; { - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); TAG_LOGI(AAFwkTag::APPMGR, "current app size %{public}zu", appRunningRecordMap_.size()); auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) { auto priorityObject = pair.second->GetPriorityObject(); @@ -858,17 +841,8 @@ int32_t AppRunningManager::DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::M int32_t AppRunningManager::DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info) { - std::lock_guard guard(lock_); int32_t pid = static_cast(info.pid); - auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) { - auto priorityObject = pair.second->GetPriorityObject(); - return priorityObject && priorityObject->GetPid() == pid; - }); - if (iter == appRunningRecordMap_.end()) { - TAG_LOGE(AAFwkTag::APPMGR, "No matching application was found."); - return ERR_INVALID_VALUE; - } - std::shared_ptr appRecord = iter->second; + auto appRecord = GetAppRunningRecordByPid(pid); if (appRecord == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "appRecord is nullptr."); return ERR_INVALID_VALUE; @@ -879,7 +853,7 @@ int32_t AppRunningManager::DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &in std::shared_ptr AppRunningManager::GetAppRunningRecordByRenderPid(const pid_t pid) { - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) { auto renderRecordMap = pair.second->GetRenderRecordMap(); if (renderRecordMap.empty()) { @@ -908,7 +882,7 @@ std::shared_ptr AppRunningManager::OnRemoteRenderDied(const wptr guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); std::shared_ptr renderRecord; const auto &it = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), @@ -945,7 +919,7 @@ bool AppRunningManager::GetAppRunningStateByBundleName(const std::string &bundle { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "function called."); - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (appRecord && appRecord->GetBundleName() == bundleName) { @@ -964,7 +938,6 @@ int32_t AppRunningManager::NotifyLoadRepairPatch(const std::string &bundleName, { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "function called."); - std::lock_guard guard(lock_); int32_t result = ERR_OK; bool loadSucceed = false; auto callbackByRecord = sptr::MakeSptr(callback); @@ -973,7 +946,8 @@ int32_t AppRunningManager::NotifyLoadRepairPatch(const std::string &bundleName, return ERR_INVALID_VALUE; } - for (const auto &item : appRunningRecordMap_) { + auto appRunningMap = GetAppRunningRecordMap(); + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; if (appRecord && appRecord->GetBundleName() == bundleName) { auto recordId = appRecord->GetRecordId(); @@ -995,7 +969,6 @@ int32_t AppRunningManager::NotifyHotReloadPage(const std::string &bundleName, co { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "function called."); - std::lock_guard guard(lock_); int32_t result = ERR_OK; bool reloadPageSucceed = false; auto callbackByRecord = sptr::MakeSptr(callback); @@ -1004,7 +977,8 @@ int32_t AppRunningManager::NotifyHotReloadPage(const std::string &bundleName, co return ERR_INVALID_VALUE; } - for (const auto &item : appRunningRecordMap_) { + auto appRunningMap = GetAppRunningRecordMap(); + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; if (appRecord && appRecord->GetBundleName() == bundleName) { auto recordId = appRecord->GetRecordId(); @@ -1027,7 +1001,6 @@ int32_t AppRunningManager::NotifyUnLoadRepairPatch(const std::string &bundleName { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "function called."); - std::lock_guard guard(lock_); int32_t result = ERR_OK; bool unLoadSucceed = false; auto callbackByRecord = sptr::MakeSptr(callback); @@ -1036,7 +1009,8 @@ int32_t AppRunningManager::NotifyUnLoadRepairPatch(const std::string &bundleName return ERR_INVALID_VALUE; } - for (const auto &item : appRunningRecordMap_) { + auto appRunningMap = GetAppRunningRecordMap(); + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; if (appRecord && appRecord->GetBundleName() == bundleName) { auto recordId = appRecord->GetRecordId(); @@ -1057,11 +1031,12 @@ int32_t AppRunningManager::NotifyUnLoadRepairPatch(const std::string &bundleName bool AppRunningManager::IsApplicationFirstForeground(const AppRunningRecord &foregroundingRecord) { TAG_LOGD(AAFwkTag::APPMGR, "function called."); - std::lock_guard guard(lock_); if (AAFwk::UIExtensionUtils::IsUIExtension(foregroundingRecord.GetExtensionType()) || AAFwk::UIExtensionUtils::IsWindowExtension(foregroundingRecord.GetExtensionType())) { return false; } + + std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (appRecord == nullptr || appRecord->GetBundleName() != foregroundingRecord.GetBundleName() @@ -1081,7 +1056,7 @@ bool AppRunningManager::IsApplicationFirstForeground(const AppRunningRecord &for bool AppRunningManager::IsApplicationBackground(const std::string &bundleName) { TAG_LOGD(AAFwkTag::APPMGR, "function called."); - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (appRecord == nullptr) { @@ -1128,7 +1103,7 @@ void AppRunningManager::OnWindowVisibilityChanged( bool AppRunningManager::IsApplicationFirstFocused(const AppRunningRecord &focusedRecord) { TAG_LOGD(AAFwkTag::APPMGR, "check focus function called."); - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (appRecord == nullptr || appRecord->GetBundleName() != focusedRecord.GetBundleName()) { @@ -1144,7 +1119,7 @@ bool AppRunningManager::IsApplicationFirstFocused(const AppRunningRecord &focuse bool AppRunningManager::IsApplicationUnfocused(const std::string &bundleName) { TAG_LOGD(AAFwkTag::APPMGR, "check is application unfocused."); - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (appRecord && appRecord->GetBundleName() == bundleName && appRecord->GetFocusFlag()) { @@ -1157,8 +1132,8 @@ bool AppRunningManager::IsApplicationUnfocused(const std::string &bundleName) void AppRunningManager::SetAttachAppDebug(const std::string &bundleName, const bool &isAttachDebug) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); - std::lock_guard guard(lock_); - for (const auto &item : appRunningRecordMap_) { + auto appRunningMap = GetAppRunningRecordMap(); + for (const auto &item : appRunningMap) { const auto &appRecord = item.second; if (appRecord == nullptr) { continue; @@ -1174,7 +1149,7 @@ std::vector AppRunningManager::GetAppDebugInfosByBundleName( const std::string &bundleName, const bool &isDetachDebug) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); std::vector debugInfos; for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; @@ -1200,7 +1175,7 @@ void AppRunningManager::GetAbilityTokensByBundleName( const std::string &bundleName, std::vector> &abilityTokens) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (appRecord == nullptr || appRecord->GetBundleName() != bundleName) { @@ -1215,7 +1190,7 @@ void AppRunningManager::GetAbilityTokensByBundleName( std::shared_ptr AppRunningManager::GetAppRunningRecordByChildProcessPid(const pid_t pid) { - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) { auto childProcessRecordMap = pair.second->GetChildProcessRecordMap(); return childProcessRecordMap.find(pid) != childProcessRecordMap.end(); @@ -1239,7 +1214,7 @@ std::shared_ptr AppRunningManager::OnChildProcessRemoteDied( return nullptr; } - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); std::shared_ptr childRecord; const auto &it = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&object, &childRecord](const auto &pair) { @@ -1274,7 +1249,7 @@ std::shared_ptr AppRunningManager::OnChildProcessRemoteDied( int32_t AppRunningManager::SignRestartAppFlag(const std::string &bundleName) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); - std::lock_guard guard(lock_); + std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (appRecord == nullptr || appRecord->GetBundleName() != bundleName) { @@ -1291,16 +1266,7 @@ int32_t AppRunningManager::SignRestartAppFlag(const std::string &bundleName) int32_t AppRunningManager::GetAppRunningUniqueIdByPid(pid_t pid, std::string &appRunningUniqueId) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); - std::lock_guard guard(lock_); - auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) { - auto priorityObject = pair.second ? pair.second->GetPriorityObject() : nullptr; - return priorityObject && priorityObject->GetPid() == pid; - }); - if (iter == appRunningRecordMap_.end()) { - TAG_LOGE(AAFwkTag::APPMGR, "No matching application was found."); - return ERR_INVALID_VALUE; - } - std::shared_ptr appRecord = iter->second; + auto appRecord = GetAppRunningRecordByPid(pid); if (appRecord == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "appRecord is nullptr."); return ERR_INVALID_VALUE; @@ -1312,7 +1278,7 @@ int32_t AppRunningManager::GetAppRunningUniqueIdByPid(pid_t pid, std::string &ap int32_t AppRunningManager::GetAllUIExtensionRootHostPid(pid_t pid, std::vector &hostPids) { - std::lock_guard guard(uiExtensionMapLock_); + std::lock_guard guard(uiExtensionMapLock_); for (auto &item: uiExtensionLauncherMap_) { auto temp = item.second.second; if (temp == pid) { @@ -1325,7 +1291,7 @@ int32_t AppRunningManager::GetAllUIExtensionRootHostPid(pid_t pid, std::vector

&providerPids) { - std::lock_guard guard(uiExtensionMapLock_); + std::lock_guard guard(uiExtensionMapLock_); for (auto &item: uiExtensionLauncherMap_) { auto temp = item.second.first; if (temp == hostPid) { @@ -1338,14 +1304,14 @@ int32_t AppRunningManager::GetAllUIExtensionProviderPid(pid_t hostPid, std::vect int32_t AppRunningManager::AddUIExtensionLauncherItem(int32_t uiExtensionAbilityId, pid_t hostPid, pid_t providerPid) { - std::lock_guard guard(uiExtensionMapLock_); + std::lock_guard guard(uiExtensionMapLock_); uiExtensionLauncherMap_.emplace(uiExtensionAbilityId, std::pair(hostPid, providerPid)); return ERR_OK; } int32_t AppRunningManager::RemoveUIExtensionLauncherItem(pid_t pid) { - std::lock_guard guard(uiExtensionMapLock_); + std::lock_guard guard(uiExtensionMapLock_); for (auto it = uiExtensionLauncherMap_.begin(); it != uiExtensionLauncherMap_.end();) { if (it->second.first == pid || it->second.second == pid) { it = uiExtensionLauncherMap_.erase(it); @@ -1359,7 +1325,7 @@ int32_t AppRunningManager::RemoveUIExtensionLauncherItem(pid_t pid) int32_t AppRunningManager::RemoveUIExtensionLauncherItemById(int32_t uiExtensionAbilityId) { - std::lock_guard guard(uiExtensionMapLock_); + std::lock_guard guard(uiExtensionMapLock_); for (auto it = uiExtensionLauncherMap_.begin(); it != uiExtensionLauncherMap_.end();) { if (it->first == uiExtensionAbilityId) { it = uiExtensionLauncherMap_.erase(it); @@ -1430,9 +1396,9 @@ int AppRunningManager::DumpIpcStart(const int32_t pid, std::string& result) TAG_LOGD(AAFwkTag::APPMGR, "Called."); const auto& appRecord = GetAppRunningRecordByPid(pid); if (!appRecord) { - result.append(MSG_DUMP_IPC_START_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INVALILD_PID); + result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID)); TAG_LOGE(AAFwkTag::APPMGR, "pid %{public}d does not exist", pid); return DumpErrorCode::ERR_INVALID_PID_ERROR; } @@ -1444,9 +1410,9 @@ int AppRunningManager::DumpIpcStop(const int32_t pid, std::string& result) TAG_LOGD(AAFwkTag::APPMGR, "Called."); const auto& appRecord = GetAppRunningRecordByPid(pid); if (!appRecord) { - result.append(MSG_DUMP_IPC_STOP_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INVALILD_PID); + result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID)); TAG_LOGE(AAFwkTag::APPMGR, "pid %{public}d does not exist", pid); return DumpErrorCode::ERR_INVALID_PID_ERROR; } @@ -1458,13 +1424,44 @@ int AppRunningManager::DumpIpcStat(const int32_t pid, std::string& result) TAG_LOGD(AAFwkTag::APPMGR, "Called."); const auto& appRecord = GetAppRunningRecordByPid(pid); if (!appRecord) { - result.append(MSG_DUMP_IPC_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INVALILD_PID); + result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID)); TAG_LOGE(AAFwkTag::APPMGR, "pid %{public}d does not exist", pid); return DumpErrorCode::ERR_INVALID_PID_ERROR; } return appRecord->DumpIpcStat(result); } + +int AppRunningManager::DumpFfrt(const std::vector& pids, std::string& result) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called."); + int errCode = DumpErrorCode::ERR_OK; + size_t count = 0; + for (const auto& pid : pids) { + TAG_LOGD(AAFwkTag::APPMGR, "DumpFfrt current pid:%{public}d", pid); + const auto& appRecord = GetAppRunningRecordByPid(pid); + if (!appRecord) { + TAG_LOGE(AAFwkTag::APPMGR, "pid %{public}d does not exist", pid); + ++count; + continue; + } + std::string currentResult; + errCode = appRecord->DumpFfrt(currentResult); + if (errCode != DumpErrorCode::ERR_OK) { + continue; + } + result += currentResult + "\n"; + } + if (count == pids.size()) { + TAG_LOGE(AAFwkTag::APPMGR, "no valid pid"); + return DumpErrorCode::ERR_INVALID_PID_ERROR; + } + if (result.empty()) { + TAG_LOGE(AAFwkTag::APPMGR, "no ffrt usage is found"); + return DumpErrorCode::ERR_INTERNAL_ERROR; + } + return DumpErrorCode::ERR_OK; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_running_record.cpp b/services/appmgr/src/app_running_record.cpp index 4882dea1ed..8e3cf63c57 100644 --- a/services/appmgr/src/app_running_record.cpp +++ b/services/appmgr/src/app_running_record.cpp @@ -24,15 +24,16 @@ #include "app_mgr_service_const.h" #include "app_mgr_service_dump_error_code.h" #include "cache_process_manager.h" +#include "window_visibility_info.h" namespace OHOS { namespace AppExecFwk { namespace { -static constexpr int64_t NANOSECONDS = 1000000000; // NANOSECONDS mean 10^9 nano second -static constexpr int64_t MICROSECONDS = 1000000; // MICROSECONDS mean 10^6 millias second +constexpr int64_t NANOSECONDS = 1000000000; // NANOSECONDS mean 10^9 nano second +constexpr int64_t MICROSECONDS = 1000000; // MICROSECONDS mean 10^6 millias second constexpr int32_t MAX_RESTART_COUNT = 3; constexpr int32_t RESTART_INTERVAL_TIME = 120000; -const std::string LAUNCHER_NAME = "com.ohos.sceneboard"; +constexpr const char* LAUNCHER_NAME = "com.ohos.sceneboard"; } int64_t AppRunningRecord::appEventId_ = 0; @@ -178,6 +179,11 @@ void RenderRecord::RegisterDeathRecipient() } } +void RenderRecord::SetProcessType(ProcessType type) +{ + processType_ = type; +} + void RenderRecord::SetState(int32_t state) { state_ = state; @@ -198,6 +204,7 @@ AppRunningRecord::AppRunningRecord( isLauncherApp_ = info->isLauncherApp; mainAppName_ = info->name; } + priorityObject_ = std::make_shared(); struct timespec t; t.tv_sec = 0; @@ -552,14 +559,14 @@ void AppRunningRecord::AddAbilityStageDone() } // Should proceed to the next notification - if (isSpecifiedAbility_) { + if (IsStartSpecifiedAbility()) { ScheduleAcceptWant(moduleName_); return; } - if (isNewProcessRequest_) { + if (IsNewProcessRequest()) { TAG_LOGD(AAFwkTag::APPMGR, "ScheduleNewProcessRequest."); - ScheduleNewProcessRequest(newProcessRequestWant_, moduleName_); + ScheduleNewProcessRequest(GetNewProcessRequestWant(), moduleName_); return; } @@ -625,6 +632,19 @@ void AppRunningRecord::ScheduleForegroundRunning() void AppRunningRecord::ScheduleBackgroundRunning() { + int32_t recordId = GetRecordId(); + auto serviceInner = appMgrServiceInner_; + auto appbackgroundtask = [recordId, serviceInner]() { + auto serviceInnerObj = serviceInner.lock(); + if (serviceInnerObj == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "APPManager is invalid"); + return; + } + TAG_LOGE(AAFwkTag::APPMGR, "APPManager move to background timeout"); + serviceInnerObj->ApplicationBackgrounded(recordId); + }; + PostTask("appbackground_" + std::to_string(recordId), AMSEventHandler::BACKGROUND_APPLICATION_TIMEOUT, + appbackgroundtask); if (appLifeCycleDeal_) { appLifeCycleDeal_->ScheduleBackgroundRunning(); } @@ -1189,10 +1209,6 @@ void AppRunningRecord::SetAppDeathRecipient(const sptr &appDe std::shared_ptr AppRunningRecord::GetPriorityObject() { - if (!priorityObject_) { - priorityObject_ = std::make_shared(); - } - return priorityObject_; } @@ -1354,7 +1370,7 @@ bool AppRunningRecord::IsTerminating() bool AppRunningRecord::IsKeepAliveApp() const { - return isKeepAliveApp_; + return isKeepAliveApp_ && isSingleton_; } void AppRunningRecord::SetKeepAliveEnableState(bool isKeepAliveEnable) @@ -1372,6 +1388,11 @@ void AppRunningRecord::SetEmptyKeepAliveAppState(bool isEmptyKeepAliveApp) isEmptyKeepAliveApp_ = isEmptyKeepAliveApp; } +void AppRunningRecord::SetSingleton(bool isSingleton) +{ + isSingleton_ = isSingleton; +} + void AppRunningRecord::SetStageModelState(bool isStageBasedModel) { isStageBasedModel_ = isStageBasedModel; @@ -1480,29 +1501,51 @@ void AppRunningRecord::SetProcessAndExtensionType(const std::shared_ptrScheduleAcceptWant(SpecifiedWant_, moduleName); + appLifeCycleDeal_->ScheduleAcceptWant(GetSpecifiedWant(), moduleName); } void AppRunningRecord::ScheduleAcceptWantDone() @@ -1566,16 +1609,30 @@ void AppRunningRecord::ApplicationTerminated() eventHandler_->RemoveEvent(AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG, eventId_); } -const AAFwk::Want &AppRunningRecord::GetSpecifiedWant() const +AAFwk::Want AppRunningRecord::GetSpecifiedWant() const { - return SpecifiedWant_; + std::lock_guard lock(specifiedMutex_); + return specifiedWant_; } -const AAFwk::Want &AppRunningRecord::GetNewProcessRequestWant() const +AAFwk::Want AppRunningRecord::GetNewProcessRequestWant() const { + std::lock_guard lock(specifiedMutex_); return newProcessRequestWant_; } +int32_t AppRunningRecord::GetNewProcessRequestId() const +{ + std::lock_guard lock(specifiedMutex_); + return newProcessRequestId_; +} + +void AppRunningRecord::ResetNewProcessRequestId() +{ + std::lock_guard lock(specifiedMutex_); + newProcessRequestId_ = -1; +} + int32_t AppRunningRecord::UpdateConfiguration(const Configuration &config) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); @@ -2087,13 +2144,33 @@ bool AppRunningRecord::isNativeStart() const return isNativeStart_; } +void AppRunningRecord::SetExitReason(int32_t reason) +{ + exitReason_ = reason; +} + +int32_t AppRunningRecord::GetExitReason() const +{ + return exitReason_; +} + +void AppRunningRecord::SetExitMsg(const std::string &exitMsg) +{ + exitMsg_ = exitMsg; +} + +std::string AppRunningRecord::GetExitMsg() const +{ + return exitMsg_; +} + int AppRunningRecord::DumpIpcStart(std::string& result) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (appLifeCycleDeal_ == nullptr) { - result.append(MSG_DUMP_IPC_START_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ is null"); return DumpErrorCode::ERR_INTERNAL_ERROR; } @@ -2104,9 +2181,9 @@ int AppRunningRecord::DumpIpcStop(std::string& result) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (appLifeCycleDeal_ == nullptr) { - result.append(MSG_DUMP_IPC_STOP_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ is null"); return DumpErrorCode::ERR_INTERNAL_ERROR; } @@ -2117,15 +2194,27 @@ int AppRunningRecord::DumpIpcStat(std::string& result) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (appLifeCycleDeal_ == nullptr) { - result.append(MSG_DUMP_IPC_STAT) - .append(MSG_DUMP_IPC_FAIL) - .append(MSG_DUMP_IPC_FAIL_REASON_INTERNAL); + result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT)) + .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ is null"); return DumpErrorCode::ERR_INTERNAL_ERROR; } return appLifeCycleDeal_->DumpIpcStat(result); } +int AppRunningRecord::DumpFfrt(std::string& result) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called."); + if (appLifeCycleDeal_ == nullptr) { + result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) + .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL)); + TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ is null"); + return DumpErrorCode::ERR_INTERNAL_ERROR; + } + return appLifeCycleDeal_->DumpFfrt(result); +} + bool AppRunningRecord::SetSupportedProcessCache(bool isSupport) { TAG_LOGI(AAFwkTag::APPMGR, "Called"); @@ -2141,5 +2230,37 @@ SupportProcessCacheState AppRunningRecord::GetSupportProcessCacheState() { return procCacheSupportState_; } + +void AppRunningRecord::SetBrowserHost(sptr browser) +{ + browserHost_ = browser; +} + +sptr AppRunningRecord::GetBrowserHost() +{ + return browserHost_; +} + +void AppRunningRecord::SetIsGPU(bool gpu) +{ + if (gpu) { + isGPU_ = gpu; + } +} + +bool AppRunningRecord::GetIsGPU() +{ + return isGPU_; +} + +void AppRunningRecord::SetGPUPid(pid_t gpuPid) +{ + gpuPid_ = gpuPid; +} + +pid_t AppRunningRecord::GetGPUPid() +{ + return gpuPid_; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_spawn_client.cpp b/services/appmgr/src/app_spawn_client.cpp index d420dbcc4d..3aaab43f99 100644 --- a/services/appmgr/src/app_spawn_client.cpp +++ b/services/appmgr/src/app_spawn_client.cpp @@ -37,10 +37,11 @@ namespace { const std::string APPSPAWN_CLIENT_USER_NAME = "APP_MANAGER_SERVICE"; constexpr int32_t RIGHT_SHIFT_STEP = 1; constexpr int32_t START_FLAG_TEST_NUM = 1; + const std::string MAX_CHILD_PROCESS = "MaxChildProcess"; } AppSpawnClient::AppSpawnClient(bool isNWebSpawn) { - TAG_LOGI(AAFwkTag::APPMGR, "AppspawnCreateClient"); + TAG_LOGD(AAFwkTag::APPMGR, "AppspawnCreateClient"); if (isNWebSpawn) { serviceName_ = NWEBSPAWN_SERVER_NAME; } @@ -76,7 +77,7 @@ ErrCode AppSpawnClient::OpenConnection() void AppSpawnClient::CloseConnection() { - TAG_LOGI(AAFwkTag::APPMGR, "AppspawnDestroyClient"); + TAG_LOGD(AAFwkTag::APPMGR, "AppspawnDestroyClient"); if (state_ == SpawnConnectionState::STATE_CONNECTED) { AppSpawnClientDestroy(handle_); } @@ -129,6 +130,15 @@ static std::string DumpAppEnvToJson(const std::map &ap return appEnvJson.dump(); } +static std::string DumpExtensionSandboxDirsToJson(const std::map &extensionSandboxDirs) +{ + nlohmann::json extensionSandboxDirsJson; + for (auto &[userId, sandboxDir] : extensionSandboxDirs) { + extensionSandboxDirsJson[userId] = sandboxDir; + } + return extensionSandboxDirsJson.dump(); +} + int32_t AppSpawnClient::SetDacInfo(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle) { int32_t ret = 0; @@ -161,7 +171,6 @@ int32_t AppSpawnClient::SetMountPermission(const AppSpawnStartMsg &startMsg, App return ret; } } - return ret; } @@ -187,9 +196,35 @@ int32_t AppSpawnClient::SetStartFlags(const AppSpawnStartMsg &startMsg, AppSpawn int32_t AppSpawnClient::SetAtomicServiceFlag(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle) { int32_t ret = 0; - if (startMsg.atomicServiceFlag && - (ret = AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_ATOMIC_SERVICE))) { - HILOG_ERROR("AppSpawnReqMsgSetAppFlag failed, ret: %{public}d", ret); + if (startMsg.atomicServiceFlag) { + ret = AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_ATOMIC_SERVICE); + if (ret) { + TAG_LOGE(AAFwkTag::APPMGR, "AppSpawnReqMsgSetAppFlag failed, ret: %{public}d", ret); + } + } + return ret; +} + +int32_t AppSpawnClient::SetStrictMode(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle) +{ + int32_t ret = 0; + if (startMsg.strictMode) { + ret = AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_ISOLATED_SANDBOX); + if (ret) { + TAG_LOGE(AAFwkTag::APPMGR, "AppSpawnReqMsgSetAppFlag failed, ret: %{public}d", ret); + } + } + return ret; +} + +int32_t AppSpawnClient::SetAppExtension(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle) +{ + int32_t ret = 0; + if (startMsg.isolatedExtension) { + ret = AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_EXTENSION_SANDBOX); + if (ret) { + TAG_LOGE(AAFwkTag::APPMGR, "AppSpawnReqMsgSetAppFlag failed, ret: %{public}d", ret); + } } return ret; } @@ -235,13 +270,56 @@ int32_t AppSpawnClient::AppspawnSetExtMsg(const AppSpawnStartMsg &startMsg, AppS return ret; } } - if (!startMsg.atomicAccount.empty() && - (ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_ACCOUNT_ID, - reinterpret_cast(startMsg.atomicAccount.c_str()), - startMsg.atomicAccount.size()))) { - HILOG_ERROR("AppSpawnReqMsgAddExtInfo failed, ret: %{public}d", ret); + + if (!startMsg.atomicAccount.empty()) { + ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_ACCOUNT_ID, + reinterpret_cast(startMsg.atomicAccount.c_str()), startMsg.atomicAccount.size()); + if (ret) { + TAG_LOGE(AAFwkTag::APPMGR, "AppSpawnReqMsgAddExtInfo failed, ret: %{public}d", ret); + return ret; + } + } + + return AppspawnSetExtMsgMore(startMsg, reqHandle); +} + +int32_t AppSpawnClient::AppspawnSetExtMsgMore(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle) +{ + int32_t ret = 0; + + if (!startMsg.provisionType.empty()) { + ret = AppSpawnReqMsgAddStringInfo(reqHandle, MSG_EXT_NAME_PROVISION_TYPE, startMsg.provisionType.c_str()); + if (ret) { + TAG_LOGE(AAFwkTag::APPMGR, "SetExtraProvisionType failed, ret: %{public}d", ret); + return ret; + } + } + + if (!startMsg.extensionSandboxPath.empty()) { + ret = AppSpawnReqMsgAddStringInfo(reqHandle, MSG_EXT_NAME_APP_EXTENSION, + startMsg.extensionSandboxPath.c_str()); + if (ret) { + TAG_LOGE(AAFwkTag::APPMGR, "SetExtraExtensionSandboxDirs failed, ret: %{public}d", ret); + return ret; + } + } + + if (!startMsg.processType.empty()) { + ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_PROCESS_TYPE, + reinterpret_cast(startMsg.processType.c_str()), startMsg.processType.size()); + if (ret) { + TAG_LOGE(AAFwkTag::APPMGR, "AppSpawnReqMsgAddExtInfo failed, ret: %{public}d", ret); + return ret; + } + } + + std::string maxChildProcessStr = std::to_string(startMsg.maxChildProcess); + if ((ret = AppSpawnReqMsgAddExtInfo(reqHandle, MAX_CHILD_PROCESS.c_str(), + reinterpret_cast(maxChildProcessStr.c_str()), maxChildProcessStr.size()))) { + TAG_LOGE(AAFwkTag::APPMGR, "Send maxChildProcess failed, ret: %{public}d", ret); return ret; } + TAG_LOGI(AAFwkTag::APPMGR, "Send maxChildProcess %{public}s success.", maxChildProcessStr.c_str()); return ret; } @@ -297,7 +375,14 @@ int32_t AppSpawnClient::AppspawnCreateDefaultMsg(const AppSpawnStartMsg &startMs if (AppspawnSetExtMsg(startMsg, reqHandle)) { break; } - + if ((ret = SetStrictMode(startMsg, reqHandle))) { + TAG_LOGE(AAFwkTag::APPMGR, "SetStrictMode failed, ret: %{public}d", ret); + break; + } + if ((ret = SetAppExtension(startMsg, reqHandle))) { + TAG_LOGE(AAFwkTag::APPMGR, "SetAppExtension failed, ret: %{public}d", ret); + break; + } return ret; } while (0); diff --git a/services/appmgr/src/app_spawn_msg_wrapper.cpp b/services/appmgr/src/app_spawn_msg_wrapper.cpp index 7c3bcd3be4..fb7c74b7e6 100644 --- a/services/appmgr/src/app_spawn_msg_wrapper.cpp +++ b/services/appmgr/src/app_spawn_msg_wrapper.cpp @@ -170,7 +170,7 @@ void AppSpawnMsgWrapper::BuildExtraInfo(const AppSpawnStartMsg &startMsg) if (!startMsg.appEnv.empty()) { auto appEnvStr = DumpAppEnvToJson(startMsg.appEnv); - TAG_LOGI(AAFwkTag::APPMGR, "AppEnv: %{public}s", appEnvStr.c_str()); + TAG_LOGD(AAFwkTag::APPMGR, "AppEnv: %{public}s", appEnvStr.c_str()); extraInfoStr_ += APP_ENV_TYPE + appEnvStr + APP_ENV_TYPE; } diff --git a/services/appmgr/src/app_state_observer_manager.cpp b/services/appmgr/src/app_state_observer_manager.cpp index 1ccbadb965..e742c8eb8e 100644 --- a/services/appmgr/src/app_state_observer_manager.cpp +++ b/services/appmgr/src/app_state_observer_manager.cpp @@ -596,8 +596,9 @@ void AppStateObserverManager::HandleOnProcessStateChanged(const std::shared_ptr< } ProcessData data = WrapProcessData(appRecord); TAG_LOGD(AAFwkTag::APPMGR, - "bundle:%{public}s pid:%{public}d uid:%{public}d state:%{public}d isContinuousTask:%{public}d", - data.bundleName.c_str(), data.pid, data.uid, data.state, data.isContinuousTask); + "bundle:%{public}s, pid:%{public}d, uid:%{public}d, state:%{public}d, " + "isContinuousTask:%{public}d, gpuPid:%{public}d", + data.bundleName.c_str(), data.pid, data.uid, data.state, data.isContinuousTask, data.gpuPid); auto appStateObserverMapCopy = GetAppStateObserverMapCopy(); for (auto it = appStateObserverMapCopy.begin(); it != appStateObserverMapCopy.end(); ++it) { std::vector::iterator iter = std::find(it->second.begin(), @@ -615,8 +616,9 @@ void AppStateObserverManager::HandleOnAppProcessDied(const std::shared_ptrGetUserTestInfo() != nullptr && system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) { processData.isTestMode = true; } + processData.exitReason = appRecord->GetExitReason(); + processData.exitMsg = appRecord->GetExitMsg(); + processData.gpuPid = appRecord->GetGPUPid(); return processData; } @@ -679,6 +684,7 @@ ProcessData AppStateObserverManager::WrapRenderProcessData(const std::shared_ptr processData.renderUid = renderRecord->GetUid(); processData.processName = renderRecord->GetProcessName(); processData.processType = renderRecord->GetProcessType(); + processData.hostPid = renderRecord->GetHostPid(); return processData; } @@ -806,7 +812,7 @@ AbilityforegroundObserverSet AppStateObserverManager::GetAbilityforegroundObserv void AppStateObserverManager::OnObserverDied(const wptr &remote, const ObserverType &type) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGI(AAFwkTag::APPMGR, "OnObserverDied"); + TAG_LOGD(AAFwkTag::APPMGR, "OnObserverDied"); auto object = remote.promote(); if (object == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "observer nullptr."); diff --git a/services/appmgr/src/child_process_record.cpp b/services/appmgr/src/child_process_record.cpp index 2bf2e9f341..a5a3b9d828 100644 --- a/services/appmgr/src/child_process_record.cpp +++ b/services/appmgr/src/child_process_record.cpp @@ -29,6 +29,15 @@ ChildProcessRecord::ChildProcessRecord(pid_t hostPid, const std::string &srcEntr MakeProcessName(hostRecord); } +ChildProcessRecord::ChildProcessRecord(pid_t hostPid, const std::string &libName, + const std::shared_ptr hostRecord, const sptr &mainProcessCb, + int32_t childProcessCount, bool isStartWithDebug) + : hostPid_(hostPid), childProcessCount_(childProcessCount), childProcessType_(CHILD_PROCESS_TYPE_NATIVE), + srcEntry_(libName), hostRecord_(hostRecord), mainProcessCb_(mainProcessCb), isStartWithDebug_(isStartWithDebug) +{ + MakeProcessName(hostRecord); +} + ChildProcessRecord::~ChildProcessRecord() { TAG_LOGD(AAFwkTag::APPMGR, "Called."); @@ -46,6 +55,19 @@ std::shared_ptr ChildProcessRecord::CreateChildProcessRecord return std::make_shared(hostPid, srcEntry, hostRecord, childProcessCount, isStartWithDebug); } +std::shared_ptr ChildProcessRecord::CreateNativeChildProcessRecord( + pid_t hostPid, const std::string &libName, const std::shared_ptr hostRecord, + const sptr &mainProcessCb, int32_t childProcessCount, bool isStartWithDebug) +{ + TAG_LOGD(AAFwkTag::APPMGR, "hostPid: %{public}d, libName: %{public}s", hostPid, libName.c_str()); + if (hostPid <= 0 || libName.empty() || !hostRecord || !mainProcessCb) { + TAG_LOGE(AAFwkTag::APPMGR, "Invalid parameter."); + return nullptr; + } + return std::make_shared(hostPid, libName, hostRecord, mainProcessCb, + childProcessCount, isStartWithDebug); +} + void ChildProcessRecord::SetPid(pid_t pid) { pid_ = pid; @@ -148,6 +170,10 @@ void ChildProcessRecord::MakeProcessName(const std::shared_ptr std::string filename = std::filesystem::path(srcEntry_).stem(); if (!filename.empty()) { processName_.append(":"); + if (childProcessType_ == CHILD_PROCESS_TYPE_NATIVE) { + processName_.append("Native_"); + } + processName_.append(filename); } processName_.append(std::to_string(childProcessCount_)); @@ -158,5 +184,21 @@ bool ChildProcessRecord::isStartWithDebug() { return isStartWithDebug_; } + +int32_t ChildProcessRecord::GetProcessType() const +{ + return childProcessType_; +} + +sptr ChildProcessRecord::GetMainProcessCallback() const +{ + return mainProcessCb_; +} + +void ChildProcessRecord::ClearMainProcessCallback() +{ + mainProcessCb_.clear(); +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/module_running_record.cpp b/services/appmgr/src/module_running_record.cpp index 8fa674b59f..face85c1ee 100644 --- a/services/appmgr/src/module_running_record.cpp +++ b/services/appmgr/src/module_running_record.cpp @@ -248,7 +248,7 @@ void ModuleRunningRecord::TerminateAbility(const std::shared_ptr::GetInstance()->QueryEnableProcessCache(); + bool isCachedProcess = DelayedSingleton::GetInstance()->IsAppShouldCache(appRecord); appLifeCycleDeal_->ScheduleCleanAbility(token, isCachedProcess); } else { TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ is null"); diff --git a/services/common/BUILD.gn b/services/common/BUILD.gn index 6ef92e16be..451de687bc 100644 --- a/services/common/BUILD.gn +++ b/services/common/BUILD.gn @@ -30,6 +30,7 @@ config("common_config") { "${ability_runtime_innerkits_path}/*", "${ability_runtime_napi_path}/*", "${ability_runtime_native_path}/ability/native/*", + "${ability_runtime_native_path}/child_process/*", "${ability_runtime_path}/frameworks/simulator/ability_simulator/*", "${ability_runtime_path}/tools/aa/*", "${ability_runtime_services_path}/common/*", @@ -52,6 +53,8 @@ config("common_config") { #build so ohos_shared_library("perm_verification") { + include_dirs = [ "${ability_runtime_utils_path}/server/constant" ] + public_configs = [ ":common_config" ] sources = [ "src/permission_verification.cpp" ] diff --git a/services/common/include/ability_manager_radar.h b/services/common/include/ability_manager_radar.h index 8b2bbb6faa..728469cf03 100644 --- a/services/common/include/ability_manager_radar.h +++ b/services/common/include/ability_manager_radar.h @@ -23,19 +23,6 @@ namespace OHOS { namespace AAFWK { -const std::string ORG_PKG_NAME = "ohos.abilitymanagerservice"; -const std::string APPLICATION_CONTINUE_BEHAVIOR = "APPLICATION_CONTINUE_BEHAVIOR"; -const std::string DMS_PKG_NAME = "ohos.distributedschedule"; -const std::string ORG_PKG = "ORG_PKG"; -const std::string FUNC = "FUNC"; -const std::string BIZ_SCENE = "BIZ_SCENE"; -const std::string BIZ_STAGE = "BIZ_STAGE"; -const std::string STAGE_RES = "STAGE_RES"; -const std::string BIZ_STATE = "BIZ_STATE"; -const std::string TO_CALL_PKG = "TO_CALL_PKG"; -const std::string ERROR_CODE = "ERROR_CODE"; -constexpr char APP_CONTINUE_DOMAIN[] = "APP_CONTINUE"; - enum class BizScene : int32_t { CLICK_ICON = 10, SAVE_DATA = 11, @@ -73,9 +60,9 @@ public: bool ClickIconContinue(const std::string& func); bool ClickIconStartAbility(const std::string& func, int32_t errCode); bool ClickIconRecvOver(const std::string& func); - bool SaveDataContinue(const std::string& func, int32_t errCode); + bool SaveDataContinue(const std::string& func); bool SaveDataRes(const std::string& func); - bool SaveDataRemoteWant(const std::string& func, int32_t errCode); + bool SaveDataRemoteWant(const std::string& func); }; } // namespace AAFWK } // namespace OHOS diff --git a/services/common/include/app_utils.h b/services/common/include/app_utils.h index b1203d9394..509ab97bbf 100644 --- a/services/common/include/app_utils.h +++ b/services/common/include/app_utils.h @@ -47,6 +47,7 @@ public: bool IsStartOptionsWithProcessOptions(); bool EnableMoveUIAbilityToBackgroundApi(); bool IsLaunchEmbededUIAbility(); + bool IsSupportNativeChildProcess(); private: AppUtils(); @@ -65,6 +66,7 @@ private: volatile DeviceConfiguration isStartOptionsWithProcessOptions_ = {false, false}; volatile DeviceConfiguration enableMoveUIAbilityToBackgroundApi_ = {false, true}; volatile DeviceConfiguration isLaunchEmbededUIAbility_ = {false, false}; + volatile DeviceConfiguration isSupportNativeChildProcess_ = {false, false}; DISALLOW_COPY_AND_MOVE(AppUtils); }; } // namespace AAFwk diff --git a/services/common/include/event_report.h b/services/common/include/event_report.h index 1589826d96..50dbc9c52c 100644 --- a/services/common/include/event_report.h +++ b/services/common/include/event_report.h @@ -62,13 +62,11 @@ enum class EventName { STOP_EXTENSION_ERROR, CONNECT_SERVICE_ERROR, DISCONNECT_SERVICE_ERROR, - CLOSE_UI_ABILITY_BY_SCB_ERROR, // ability behavior event START_ABILITY, TERMINATE_ABILITY, CLOSE_ABILITY, - CLOSE_UI_ABILITY_BY_SCB, ABILITY_ONFOREGROUND, ABILITY_ONBACKGROUND, ABILITY_ONACTIVE, diff --git a/services/common/include/hilog_tag_wrapper.h b/services/common/include/hilog_tag_wrapper.h index 4e87a6f54a..f6102af751 100644 --- a/services/common/include/hilog_tag_wrapper.h +++ b/services/common/include/hilog_tag_wrapper.h @@ -94,72 +94,109 @@ enum class AAFwkLogTag : uint32_t { END = 256, // N.B. never use it }; -const std::map AAFWK_DOMAIN_MAP = { - { AAFwkLogTag::DEFAULT, "AAFwk" }, - { AAFwkLogTag::ABILITY, "AAFwkAbility" }, - { AAFwkLogTag::TEST, "AAFwkTest" }, - { AAFwkLogTag::AA_TOOL, "AAFwkAATool" }, - { AAFwkLogTag::ABILITY_SIM, "AAFwkAbilitySimulator" }, +inline uint32_t GetOffset(AAFwkLogTag tag, AAFwkLogTag base) +{ + return static_cast(tag) - static_cast(base); +} - { AAFwkLogTag::APPDFR, "AAFwkAppDfr"}, - { AAFwkLogTag::APPMGR, "AAFwkAppMgr" }, - { AAFwkLogTag::DBOBSMGR, "AAFwkDbObsMgr" }, - { AAFwkLogTag::DIALOG, "AAFwkDialog" }, - { AAFwkLogTag::QUICKFIX, "AAFwkQuickfix" }, - { AAFwkLogTag::URIPERMMGR, "AAFwkUriPermMgr" }, - { AAFwkLogTag::BUNDLEMGRHELPER, "AAFwkBundleMgrHelper" }, - { AAFwkLogTag::APPKIT, "AAFwkAppKit" }, +inline const char* GetDomainName0(AAFwkLogTag tag) +{ + const char* tagNames[] = { "AAFwk", "AAFwkAbility", "AAFwkTest", "AAFwkAATool", "AAFwkAbilitySimulator" }; + uint32_t offset = GetOffset(tag, AAFwkLogTag::DEFAULT); + if (offset >= sizeof(tagNames) / sizeof(const char*)) { + return "AAFwkUN"; + } + return tagNames[offset]; +} - { AAFwkLogTag::JSENV, "AAFwkJsEnv" }, - { AAFwkLogTag::JSRUNTIME, "AAFwkJsRuntime" }, - { AAFwkLogTag::FA, "AAFwkFA" }, - { AAFwkLogTag::INTENT, "AAFwkIntent" }, - { AAFwkLogTag::JSNAPI, "AAFwkJsNapi" }, +inline const char* GetDomainName1(AAFwkLogTag tag) +{ + const char* tagNames[] = { "AAFwkAppDfr", "AAFwkAppMgr", "AAFwkDbObsMgr", "AAFwkDialog", "AAFwkQuickfix", + "AAFwkUriPermMgr", "AAFwkBundleMgrHelper", "AAFwkAppKit" }; + uint32_t offset = GetOffset(tag, AAFwkLogTag::APPDFR); + if (offset >= sizeof(tagNames) / sizeof(const char*)) { + return "AAFwkUN"; + } + return tagNames[offset]; +} - { AAFwkLogTag::DELEGATOR, "AAFwkDelegator" }, - { AAFwkLogTag::CONTEXT, "AAFwkContext" }, - { AAFwkLogTag::UIABILITY, "AAFwkUIAbility" }, - { AAFwkLogTag::WANT, "AAFwkWant" }, - { AAFwkLogTag::MISSION, "AAFwkMission" }, - { AAFwkLogTag::CONNECTION, "AAFwkConnection" }, - { AAFwkLogTag::ATOMIC_SERVICE, "AAFwkAtomicService" }, - { AAFwkLogTag::ABILITYMGR, "AAFwkAbilityMgr" }, - { AAFwkLogTag::ECOLOGICAL_RULE, "AAFwkEcologicalRule" }, - { AAFwkLogTag::DATA_ABILITY, "AAFwkDataAbility" }, +inline const char* GetDomainName2(AAFwkLogTag tag) +{ + const char* tagNames[] = { "AAFwkJsEnv", "AAFwkJsRuntime", "AAFwkFA", "AAFwkIntent", "AAFwkJsNapi" }; + uint32_t offset = GetOffset(tag, AAFwkLogTag::JSENV); + if (offset >= sizeof(tagNames) / sizeof(const char*)) { + return "AAFwkUN"; + } + return tagNames[offset]; +} - { AAFwkLogTag::EXT, "AAFwkExt" }, - { AAFwkLogTag::AUTOFILL_EXT, "AAFwkAutoFillExt" }, - { AAFwkLogTag::SERVICE_EXT, "AAFwkServiceExt" }, - { AAFwkLogTag::FORM_EXT, "AAFwkFormExt" }, - { AAFwkLogTag::SHARE_EXT, "AAFwkShareExt" }, - { AAFwkLogTag::UI_EXT, "AAFwkUIExt" }, - { AAFwkLogTag::ACTION_EXT, "AAFwkActionExt" }, - { AAFwkLogTag::EMBEDDED_EXT, "AAFwkEmbeddedExt" }, +inline const char* GetDomainName3(AAFwkLogTag tag) +{ + const char* tagNames[] = { "AAFwkDelegator", "AAFwkContext", "AAFwkUIAbility", "AAFwkWant", "AAFwkMission", + "AAFwkConnection", "AAFwkAtomicService", "AAFwkAbilityMgr", "AAFwkEcologicalRule", "AAFwkDataAbility" }; + uint32_t offset = GetOffset(tag, AAFwkLogTag::DELEGATOR); + if (offset >= sizeof(tagNames) / sizeof(const char*)) { + return "AAFwkUN"; + } + return tagNames[offset]; +} - { AAFwkLogTag::WANTAGENT, "AAFwkWantAgent" }, - { AAFwkLogTag::AUTOFILLMGR, "AAFwkAutoFillMgr" }, - { AAFwkLogTag::EXTMGR, "AAFwkExtMgr" }, - { AAFwkLogTag::SER_ROUTER, "AAFwkServiceRouter" }, - { AAFwkLogTag::AUTO_STARTUP, "AAFwkAutoStartup" }, - { AAFwkLogTag::STARTUP, "AAFwkStartup" }, - { AAFwkLogTag::RECOVERY, "AAFwkRecovery" }, - { AAFwkLogTag::PROCESSMGR, "AAFwkProcessMgr" }, - { AAFwkLogTag::CONTINUATION, "AAFwkContinuation" }, - { AAFwkLogTag::DISTRIBUTED, "AAFwkDistributed" }, - { AAFwkLogTag::FREE_INSTALL, "AAFwkFreeInstall" }, +inline const char* GetDomainName4(AAFwkLogTag tag) +{ + const char* tagNames[] = { "AAFwkExt", "AAFwkAutoFillExt", "AAFwkServiceExt", "AAFwkFormExt", "AAFwkShareExt", + "AAFwkUIExt", "AAFwkActionExt", "AAFwkEmbeddedExt" }; + uint32_t offset = GetOffset(tag, AAFwkLogTag::EXT); + if (offset >= sizeof(tagNames) / sizeof(const char*)) { + return "AAFwkUN"; + } + return tagNames[offset]; +} - { AAFwkLogTag::LOCAL_CALL, "AAFwkLocalCall" }, -}; +inline const char* GetDomainName5(AAFwkLogTag tag) +{ + const char* tagNames[] = { "AAFwkWantAgent", "AAFwkAutoFillMgr", "AAFwkExtMgr", "AAFwkServiceRouter", + "AAFwkAutoStartup", "AAFwkStartup", "AAFwkRecovery", "AAFwkProcessMgr", "AAFwkContinuation", + "AAFwkDistributed", "AAFwkFreeInstall" }; + uint32_t offset = GetOffset(tag, AAFwkLogTag::WANTAGENT); + if (offset >= sizeof(tagNames) / sizeof(const char*)) { + return "AAFwkUN"; + } + return tagNames[offset]; +} + +inline const char* GetDomainName6(AAFwkLogTag tag) +{ + const char* tagNames[] = { "AAFwkLocalCall" }; + uint32_t offset = GetOffset(tag, AAFwkLogTag::LOCAL_CALL); + if (offset >= sizeof(tagNames) / sizeof(const char*)) { + return "AAFwkUN"; + } + return tagNames[offset]; +} + +constexpr uint32_t BASE_DEFAULT = 0; +constexpr uint32_t BASE_APPDFR = 1; +constexpr uint32_t BASE_JSENV = 2; +constexpr uint32_t BASE_DELEGATOR = 3; +constexpr uint32_t BASE_EXT = 4; +constexpr uint32_t BASE_WANTAGENT = 5; +constexpr uint32_t BASE_LOCAL_CALL = 6; static inline const char* GetTagInfoFromDomainId(AAFwkLogTag tag) { - auto iter = AAFWK_DOMAIN_MAP.find(tag); - if (iter != AAFWK_DOMAIN_MAP.end() && iter->second) { - return iter->second; + uint32_t offset = GetOffset(tag, AAFwkLogTag::DEFAULT); + uint32_t base = offset >> 4; + switch (base) { + case BASE_DEFAULT: return GetDomainName0(tag); + case BASE_APPDFR: return GetDomainName1(tag); + case BASE_JSENV: return GetDomainName2(tag); + case BASE_DELEGATOR: return GetDomainName3(tag); + case BASE_EXT: return GetDomainName4(tag); + case BASE_WANTAGENT: return GetDomainName5(tag); + case BASE_LOCAL_CALL: return GetDomainName6(tag); + default: return "AAFwkUN"; } - return "AAFwkUN"; } - } // OHOS::AAFwk using AAFwkTag = OHOS::AAFwk::AAFwkLogTag; diff --git a/services/common/include/ui_extension_utils.h b/services/common/include/ui_extension_utils.h index 07f057505a..12e2e80b8b 100755 --- a/services/common/include/ui_extension_utils.h +++ b/services/common/include/ui_extension_utils.h @@ -23,71 +23,73 @@ namespace OHOS { namespace AAFwk { +namespace { +constexpr int EDM_SA_UID = 3057; +} namespace UIExtensionUtils { // ui extension type list -const std::unordered_set UI_EXTENSION_SET = { - AppExecFwk::ExtensionAbilityType::SHARE, - AppExecFwk::ExtensionAbilityType::ACTION, - AppExecFwk::ExtensionAbilityType::EMBEDDED_UI, - AppExecFwk::ExtensionAbilityType::INSIGHT_INTENT_UI, - AppExecFwk::ExtensionAbilityType::AUTO_FILL_PASSWORD, - AppExecFwk::ExtensionAbilityType::UI, - AppExecFwk::ExtensionAbilityType::SYSPICKER_MEDIACONTROL, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_USERAUTH, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_COMMON, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_ATOMICSERVICEPANEL, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_POWER, - AppExecFwk::ExtensionAbilityType::SYSPICKER_SHARE, - AppExecFwk::ExtensionAbilityType::HMS_ACCOUNT, - AppExecFwk::ExtensionAbilityType::ADS, - AppExecFwk::ExtensionAbilityType::VOIP, - AppExecFwk::ExtensionAbilityType::STATUS_BAR_VIEW, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_MEETIMECALL, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_MEETIMECONTACT, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_MEETIMEMESSAGE, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_PRINT, - AppExecFwk::ExtensionAbilityType::SYSPICKER_MEETIMECONTACT, - AppExecFwk::ExtensionAbilityType::SYSPICKER_MEETIMECALLLOG, - AppExecFwk::ExtensionAbilityType::SYSPICKER_PHOTOPICKER, - AppExecFwk::ExtensionAbilityType::SYS_COMMON_UI, - AppExecFwk::ExtensionAbilityType::SYSPICKER_NAVIGATION, - AppExecFwk::ExtensionAbilityType::SYSPICKER_APPSELECTOR, - AppExecFwk::ExtensionAbilityType::SYSPICKER_CAMERA, - AppExecFwk::ExtensionAbilityType::SYSPICKER_FILEPICKER, - AppExecFwk::ExtensionAbilityType::AUTO_FILL_SMART, - AppExecFwk::ExtensionAbilityType::LIVEVIEW_LOCKSCREEN -}; - -// The following extension ability types can be used only in system applications. -const std::unordered_set SYSTEM_UI_EXTENSION_SET = { - AppExecFwk::ExtensionAbilityType::SYSDIALOG_COMMON, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_ATOMICSERVICEPANEL, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_POWER, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_MEETIMECALL, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_MEETIMECONTACT, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_MEETIMEMESSAGE, - AppExecFwk::ExtensionAbilityType::SYSDIALOG_PRINT, - AppExecFwk::ExtensionAbilityType::SYSPICKER_MEDIACONTROL, - AppExecFwk::ExtensionAbilityType::SYSPICKER_SHARE, - AppExecFwk::ExtensionAbilityType::SYSPICKER_MEETIMECONTACT, - AppExecFwk::ExtensionAbilityType::SYSPICKER_MEETIMECALLLOG, - AppExecFwk::ExtensionAbilityType::SYSPICKER_PHOTOPICKER, - AppExecFwk::ExtensionAbilityType::SYSPICKER_NAVIGATION, - AppExecFwk::ExtensionAbilityType::SYSPICKER_APPSELECTOR, - AppExecFwk::ExtensionAbilityType::UI, - AppExecFwk::ExtensionAbilityType::SYS_COMMON_UI, -}; - -const int EDM_SA_UID = 3057; +inline std::unordered_set GetUiExtensionSet() +{ + return std::unordered_set { + AppExecFwk::ExtensionAbilityType::SHARE, + AppExecFwk::ExtensionAbilityType::ACTION, + AppExecFwk::ExtensionAbilityType::EMBEDDED_UI, + AppExecFwk::ExtensionAbilityType::INSIGHT_INTENT_UI, + AppExecFwk::ExtensionAbilityType::AUTO_FILL_PASSWORD, + AppExecFwk::ExtensionAbilityType::UI, + AppExecFwk::ExtensionAbilityType::SYSPICKER_MEDIACONTROL, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_USERAUTH, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_COMMON, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_ATOMICSERVICEPANEL, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_POWER, + AppExecFwk::ExtensionAbilityType::SYSPICKER_SHARE, + AppExecFwk::ExtensionAbilityType::HMS_ACCOUNT, + AppExecFwk::ExtensionAbilityType::ADS, + AppExecFwk::ExtensionAbilityType::VOIP, + AppExecFwk::ExtensionAbilityType::STATUS_BAR_VIEW, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_MEETIMECALL, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_MEETIMECONTACT, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_MEETIMEMESSAGE, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_PRINT, + AppExecFwk::ExtensionAbilityType::SYSPICKER_MEETIMECONTACT, + AppExecFwk::ExtensionAbilityType::SYSPICKER_MEETIMECALLLOG, + AppExecFwk::ExtensionAbilityType::SYSPICKER_PHOTOPICKER, + AppExecFwk::ExtensionAbilityType::SYS_COMMON_UI, + AppExecFwk::ExtensionAbilityType::SYSPICKER_NAVIGATION, + AppExecFwk::ExtensionAbilityType::SYSPICKER_APPSELECTOR, + AppExecFwk::ExtensionAbilityType::SYSPICKER_CAMERA, + AppExecFwk::ExtensionAbilityType::SYSPICKER_FILEPICKER, + AppExecFwk::ExtensionAbilityType::AUTO_FILL_SMART, + AppExecFwk::ExtensionAbilityType::LIVEVIEW_LOCKSCREEN + }; +} inline bool IsUIExtension(const AppExecFwk::ExtensionAbilityType type) { - return UI_EXTENSION_SET.find(type) != UI_EXTENSION_SET.end(); + return GetUiExtensionSet().count(type) > 0; } inline bool IsSystemUIExtension(const AppExecFwk::ExtensionAbilityType type) { - return SYSTEM_UI_EXTENSION_SET.find(type) != SYSTEM_UI_EXTENSION_SET.end(); + const std::unordered_set systemUiExtensionSet = { + AppExecFwk::ExtensionAbilityType::SYSDIALOG_COMMON, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_ATOMICSERVICEPANEL, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_POWER, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_MEETIMECALL, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_MEETIMECONTACT, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_MEETIMEMESSAGE, + AppExecFwk::ExtensionAbilityType::SYSDIALOG_PRINT, + AppExecFwk::ExtensionAbilityType::SYSPICKER_MEDIACONTROL, + AppExecFwk::ExtensionAbilityType::SYSPICKER_SHARE, + AppExecFwk::ExtensionAbilityType::SYSPICKER_MEETIMECONTACT, + AppExecFwk::ExtensionAbilityType::SYSPICKER_MEETIMECALLLOG, + AppExecFwk::ExtensionAbilityType::SYSPICKER_PHOTOPICKER, + AppExecFwk::ExtensionAbilityType::SYSPICKER_NAVIGATION, + AppExecFwk::ExtensionAbilityType::SYSPICKER_APPSELECTOR, + AppExecFwk::ExtensionAbilityType::UI, + AppExecFwk::ExtensionAbilityType::SYS_COMMON_UI, + }; + return systemUiExtensionSet.find(type) != systemUiExtensionSet.end(); } inline bool IsEnterpriseAdmin(const AppExecFwk::ExtensionAbilityType type) diff --git a/services/common/src/ability_manager_radar.cpp b/services/common/src/ability_manager_radar.cpp index 8e700b3181..2b017c1401 100644 --- a/services/common/src/ability_manager_radar.cpp +++ b/services/common/src/ability_manager_radar.cpp @@ -22,7 +22,19 @@ namespace OHOS { namespace AAFWK { - +namespace { +constexpr const char* ORG_PKG_NAME = "ohos.abilitymanagerservice"; +constexpr const char* APPLICATION_CONTINUE_BEHAVIOR = "APPLICATION_CONTINUE_BEHAVIOR"; +constexpr const char* DMS_PKG_NAME = "ohos.distributedschedule"; +constexpr const char* ORG_PKG = "ORG_PKG"; +constexpr const char* FUNC = "FUNC"; +constexpr const char* BIZ_SCENE = "BIZ_SCENE"; +constexpr const char* BIZ_STAGE = "BIZ_STAGE"; +constexpr const char* STAGE_RES = "STAGE_RES"; +constexpr const char* TO_CALL_PKG = "TO_CALL_PKG"; +constexpr const char* ERROR_CODE = "ERROR_CODE"; +constexpr char APP_CONTINUE_DOMAIN[] = "APP_CONTINUE"; +} ContinueRadar &ContinueRadar::GetInstance() { static ContinueRadar instance; @@ -99,32 +111,17 @@ bool ContinueRadar::ClickIconRecvOver(const std::string& func) return true; } -bool ContinueRadar::SaveDataContinue(const std::string& func, int32_t errCode) +bool ContinueRadar::SaveDataContinue(const std::string& func) { - int32_t res = ERR_OK; - StageRes stageRes = (errCode == ERR_OK) ? StageRes::STAGE_SUCC : StageRes::STAGE_FAIL; - if (stageRes == StageRes::STAGE_SUCC) { - res = HiSysEventWrite( - APP_CONTINUE_DOMAIN, - APPLICATION_CONTINUE_BEHAVIOR, - HiviewDFX::HiSysEvent::EventType::BEHAVIOR, - ORG_PKG, ORG_PKG_NAME, - FUNC, func, - BIZ_SCENE, static_cast(BizScene::SAVE_DATA), - BIZ_STAGE, static_cast(SaveData::SAVEDATA_CONTINUE), - STAGE_RES, static_cast(StageRes::STAGE_SUCC)); - } else { - res = HiSysEventWrite( - APP_CONTINUE_DOMAIN, - APPLICATION_CONTINUE_BEHAVIOR, - HiviewDFX::HiSysEvent::EventType::BEHAVIOR, - ORG_PKG, ORG_PKG_NAME, - FUNC, func, - BIZ_SCENE, static_cast(BizScene::SAVE_DATA), - BIZ_STAGE, static_cast(SaveData::SAVEDATA_CONTINUE), - STAGE_RES, static_cast(StageRes::STAGE_FAIL), - ERROR_CODE, errCode); - } + int32_t res = HiSysEventWrite( + APP_CONTINUE_DOMAIN, + APPLICATION_CONTINUE_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + ORG_PKG, ORG_PKG_NAME, + FUNC, func, + BIZ_SCENE, static_cast(BizScene::SAVE_DATA), + BIZ_STAGE, static_cast(SaveData::SAVEDATA_CONTINUE), + STAGE_RES, static_cast(StageRes::STAGE_SUCC)); if (res != ERR_OK) { TAG_LOGE(AAFwkTag::DEFAULT, "SaveDataContinue error, res:%{public}d", res); return false; @@ -150,35 +147,18 @@ bool ContinueRadar::SaveDataRes(const std::string& func) return true; } -bool ContinueRadar::SaveDataRemoteWant(const std::string& func, int32_t errCode) +bool ContinueRadar::SaveDataRemoteWant(const std::string& func) { - int32_t res = ERR_OK; - StageRes stageRes = (errCode == ERR_OK) ? StageRes::STAGE_SUCC : StageRes::STAGE_FAIL; - if (stageRes == StageRes::STAGE_SUCC) { - res = HiSysEventWrite( - APP_CONTINUE_DOMAIN, - APPLICATION_CONTINUE_BEHAVIOR, - HiviewDFX::HiSysEvent::EventType::BEHAVIOR, - ORG_PKG, ORG_PKG_NAME, - FUNC, func, - BIZ_SCENE, static_cast(BizScene::SAVE_DATA), - BIZ_STAGE, static_cast(SaveData::SAVEDATA_REMOTE_WANT), - STAGE_RES, static_cast(StageRes::STAGE_SUCC), - TO_CALL_PKG, DMS_PKG_NAME); - } else { - res = HiSysEventWrite( - APP_CONTINUE_DOMAIN, - APPLICATION_CONTINUE_BEHAVIOR, - HiviewDFX::HiSysEvent::EventType::BEHAVIOR, - ORG_PKG, ORG_PKG_NAME, - FUNC, func, - BIZ_SCENE, static_cast(BizScene::SAVE_DATA), - BIZ_STAGE, static_cast(SaveData::SAVEDATA_REMOTE_WANT), - STAGE_RES, static_cast(StageRes::STAGE_FAIL), - "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), - TO_CALL_PKG, DMS_PKG_NAME, - ERROR_CODE, errCode); - } + int32_t res = HiSysEventWrite( + APP_CONTINUE_DOMAIN, + APPLICATION_CONTINUE_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + ORG_PKG, ORG_PKG_NAME, + FUNC, func, + BIZ_SCENE, static_cast(BizScene::SAVE_DATA), + BIZ_STAGE, static_cast(SaveData::SAVEDATA_REMOTE_WANT), + STAGE_RES, static_cast(StageRes::STAGE_SUCC), + TO_CALL_PKG, DMS_PKG_NAME); if (res != ERR_OK) { TAG_LOGE(AAFwkTag::DEFAULT, "SaveDataRemoteWant error, res:%{public}d", res); return false; diff --git a/services/common/src/app_utils.cpp b/services/common/src/app_utils.cpp index 7d47ade7dd..803ccdda86 100644 --- a/services/common/src/app_utils.cpp +++ b/services/common/src/app_utils.cpp @@ -41,7 +41,9 @@ const std::string START_OPTIONS_WITH_PROCESS_OPTION = "persist.sys.abilityms.sta const std::string MOVE_UI_ABILITY_TO_BACKGROUND_API_ENABLE = "persist.sys.abilityms.move_ui_ability_to_background_api_enable"; const std::string LAUNCH_EMBEDED_UI_ABILITY = "const.abilityms.launch_embeded_ui_ability"; +const std::string SUPPROT_NATIVE_CHILD_PROCESS = "persist.sys.abilityms.start_native_child_process"; } + AppUtils::~AppUtils() {} AppUtils::AppUtils() @@ -81,7 +83,7 @@ bool AppUtils::IsInheritWindowSplitScreenMode() isInheritWindowSplitScreenMode_.value = system::GetBoolParameter(INHERIT_WINDOW_SPLIT_SCREEN_MODE, true); isInheritWindowSplitScreenMode_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, "isInheritWindowSplitScreenMode is %{public}d", isInheritWindowSplitScreenMode_.value); + TAG_LOGD(AAFwkTag::DEFAULT, "isInheritWindowSplitScreenMode is %{public}d", isInheritWindowSplitScreenMode_.value); return isInheritWindowSplitScreenMode_.value; } @@ -101,7 +103,7 @@ int32_t AppUtils::GetTimeoutUnitTimeRatio() timeoutUnitTimeRatio_.value = system::GetIntParameter(TIMEOUT_UNIT_TIME_RATIO, 1); timeoutUnitTimeRatio_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, "timeoutUnitTimeRatio is %{public}d", timeoutUnitTimeRatio_.value); + TAG_LOGD(AAFwkTag::DEFAULT, "timeoutUnitTimeRatio is %{public}d", timeoutUnitTimeRatio_.value); return timeoutUnitTimeRatio_.value; } @@ -171,7 +173,7 @@ bool AppUtils::IsMultiProcessModel() isMultiProcessModel_.value = system::GetBoolParameter(MULTI_PROCESS_MODEL, false); isMultiProcessModel_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, "isMultiProcessModel_ is %{public}d", isMultiProcessModel_.value); + TAG_LOGD(AAFwkTag::DEFAULT, "isMultiProcessModel_ is %{public}d", isMultiProcessModel_.value); return isMultiProcessModel_.value; } @@ -207,5 +209,16 @@ bool AppUtils::IsLaunchEmbededUIAbility() TAG_LOGI(AAFwkTag::DEFAULT, "isLaunchEmbededUIAbility_ is %{public}d", isLaunchEmbededUIAbility_.value); return isLaunchEmbededUIAbility_.value; } + +bool AppUtils::IsSupportNativeChildProcess() +{ + if (!isSupportNativeChildProcess_.isLoaded) { + isSupportNativeChildProcess_.value = system::GetBoolParameter(SUPPROT_NATIVE_CHILD_PROCESS, false); + isSupportNativeChildProcess_.isLoaded = true; + } + TAG_LOGI(AAFwkTag::DEFAULT, "isSupportNativeChildProcess_ is %{public}d", isSupportNativeChildProcess_.value); + return isSupportNativeChildProcess_.value; +} + } // namespace AAFwk } // namespace OHOS diff --git a/services/common/src/permission_verification.cpp b/services/common/src/permission_verification.cpp index e2a4794f78..c851f29542 100644 --- a/services/common/src/permission_verification.cpp +++ b/services/common/src/permission_verification.cpp @@ -21,13 +21,13 @@ #include "hilog_wrapper.h" #include "hitrace_meter.h" #include "permission_constants.h" +#include "server_constant.h" #include "support_system_ability_permission.h" #include "tokenid_kit.h" #include "hilog_tag_wrapper.h" namespace OHOS { namespace AAFwk { -const std::string DLP_PARAMS_INDEX = "ohos.dlp.params.index"; const std::string DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag"; namespace { const int32_t SHELL_START_EXTENSION_FLOOR = 0; // FORM @@ -152,7 +152,7 @@ bool PermissionVerification::VerifyControllerPerm() const bool PermissionVerification::VerifyDlpPermission(Want &want) const { - if (want.GetIntParam(DLP_PARAMS_INDEX, 0) == 0) { + if (want.GetIntParam(AbilityRuntime::ServerConstant::DLP_INDEX, 0) == 0) { want.RemoveParam(DLP_PARAMS_SECURITY_FLAG); return true; } @@ -400,7 +400,7 @@ bool PermissionVerification::JudgeAssociatedWakeUp(const uint32_t accessTokenId, int PermissionVerification::JudgeInvisibleAndBackground(const VerificationInfo &verificationInfo) const { uint32_t specifyTokenId = verificationInfo.specifyTokenId; - TAG_LOGI(AAFwkTag::DEFAULT, "specifyTokenId = %{public}u", specifyTokenId); + TAG_LOGD(AAFwkTag::DEFAULT, "specifyTokenId = %{public}u", specifyTokenId); if (specifyTokenId == 0 && IPCSkeleton::GetCallingUid() != BROKER_UID && SupportSystemAbilityPermission::IsSupportSaCallPermission() && IsSACall()) { TAG_LOGD(AAFwkTag::DEFAULT, "Support SA call"); diff --git a/services/dialog_ui/ams_system_dialog/AppScope/app.json b/services/dialog_ui/ams_system_dialog/AppScope/app.json index 03e1745a64..1a0d7f436c 100644 --- a/services/dialog_ui/ams_system_dialog/AppScope/app.json +++ b/services/dialog_ui/ams_system_dialog/AppScope/app.json @@ -2,7 +2,7 @@ "app": { "bundleName": "com.ohos.amsdialog", "vendor": "example", - "versionCode": 1000002, + "versionCode": 1000003, "versionName": "1.0.0", "icon": "$media:app_icon", "label": "$string:app_name", diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/SelectorExtensionAbility.ets b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/SelectorExtensionAbility.ets index 001c44426e..0fcc947b69 100644 --- a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/SelectorExtensionAbility.ets +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/SelectorExtensionAbility.ets @@ -15,12 +15,17 @@ import UIExtensionAbility from '@ohos.app.ability.UIExtensionAbility' import UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession' import Want from '@ohos.app.ability.Want' +import systemparameter from '@ohos.systemParameterEnhance'; +import dataPreferences from '@ohos.data.preferences'; const TAG = 'SelectorExtensionAbility'; export default class SelectorExtensionAbility extends UIExtensionAbility { onCreate() { console.info(TAG, 'SelectorExtensionAbility onCreate'); + globalThis.currentExtensionContext = this.context; + let options = {name:'dialogStore'}; + globalThis.preferences = dataPreferences.getPreferencesSync(this.context, options); } onSessionCreate(want: Want, session: UIExtensionContentSession) { @@ -29,8 +34,14 @@ export default class SelectorExtensionAbility extends UIExtensionAbility { "extensionAbility": this, "callerWant": want } as Record); - - session.loadContent("pages/PhonePage", storage); + globalThis.ExtensionType = 'UIExtension'; + if (systemparameter.getSync('persist.sys.abilityms.isdialogconfirmpermission', 'false') === 'false' && + globalThis.preferences.getSync('isdialogconfirmpermission', 'false') === 'false') { + globalThis.currentURL = 'pages/PhonePage'; + session.loadContent("pages/permissionConfirmDialog", storage); + } else { + session.loadContent("pages/PhonePage", storage); + } try { const bgColor: string = '#40FFFFFF'; } catch (e) { diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/SelectorServiceExtAbility.ts b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/SelectorServiceExtAbility.ts index a61719a267..981182fb84 100644 --- a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/SelectorServiceExtAbility.ts +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/SelectorServiceExtAbility.ts @@ -22,6 +22,8 @@ import type image from '@ohos.multimedia.image'; import window from '@ohos.window'; import PositionUtils from '../utils/PositionUtils'; import deviceInfo from '@ohos.deviceInfo'; +import systemparameter from '@ohos.systemParameterEnhance'; +import dataPreferences from '@ohos.data.preferences'; const TAG = 'SelectorDialog_Service'; @@ -32,8 +34,12 @@ export default class SelectorServiceExtensionAbility extends extension { onCreate(want) { console.debug(TAG, 'onCreate, want: ' + JSON.stringify(want)); globalThis.selectExtensionContext = this.context; + globalThis.currentExtensionContext = this.context; + globalThis.ExtensionType = 'ServiceExtension'; globalThis.defaultAppManager = defaultAppManager; globalThis.bundleManager = bundleManager; + let options = {name:'dialogStore'}; + globalThis.preferences = dataPreferences.getPreferencesSync(this.context, options); } async getPhoneShowHapList() { @@ -218,10 +224,20 @@ export default class SelectorServiceExtensionAbility extends extension { } await win.moveTo(rect.left, rect.top); await win.resetSize(rect.width, rect.height); - if (globalThis.params.isDefaultSelector) { - await win.loadContent('pages/selectorPhoneDialog'); + if (systemparameter.getSync('persist.sys.abilityms.isdialogconfirmpermission', 'false') === 'false' && + globalThis.preferences.getSync('isdialogconfirmpermission', 'false') === 'false') { + if (globalThis.params.isDefaultSelector) { + globalThis.currentURL = 'pages/selectorPhoneDialog'; + } else { + globalThis.currentURL = 'pages/selectorPcDialog'; + } + await win.loadContent('pages/permissionConfirmDialog'); } else { - await win.loadContent('pages/selectorPcDialog'); + if (globalThis.params.isDefaultSelector) { + await win.loadContent('pages/selectorPhoneDialog'); + } else { + await win.loadContent('pages/selectorPcDialog'); + } } await win.setBackgroundColor('#00000000'); await win.show(); diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ShareExtAbility/AssertFaultShareExtAbility.ts b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ShareExtAbility/AssertFaultShareExtAbility.ts index 32505ff930..4e9a66694e 100644 --- a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ShareExtAbility/AssertFaultShareExtAbility.ts +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ShareExtAbility/AssertFaultShareExtAbility.ts @@ -22,6 +22,7 @@ import type UIExtensionContentSession from '@ohos.app.ability.UIExtensionContent const TAG = 'AssertFaultDialog_UIExtension'; const TEXT_DETAIL = 'assertFaultDialogDetail'; +const DEBUG_ASSERT_RESULT = 'assertResult'; export default class UiExtAbility extends UIExtensionAbility { storage: LocalStorage; @@ -44,7 +45,6 @@ export default class UiExtAbility extends UIExtensionAbility { this.storage = new LocalStorage( { 'session': session, - 'sessionId' : this.sessionId, 'textDetail' : want.parameters[TEXT_DETAIL] }); session.loadContent('pages/assertFaultDialog', this.storage); @@ -57,19 +57,18 @@ export default class UiExtAbility extends UIExtensionAbility { onSessionDestroy(session: UIExtensionContentSession): void { console.info(TAG, 'onSessionDestroy'); - console.info(TAG, `isUserAction: ${AppStorage.get('isUserAction')}`); - let isUserAction = AppStorage.get('isUserAction'); - if (isUserAction === undefined) { - let status = abilityManager.UserStatus.ASSERT_TERMINATE; - try { - abilityManager.notifyDebugAssertResult(this.sessionId, status).then(() => { - console.log(TAG, 'notifyDebugAssertResult success.'); - }).catch((err: BusinessError) => { - console.error(TAG, `notifyDebugAssertResult failed, error: ${JSON.stringify(err)}`); - }); - } catch (error) { - console.error(TAG, `try notifyDebugAssertResult failed, error: ${JSON.stringify(error)}`); - } + let assertResult = AppStorage.get(DEBUG_ASSERT_RESULT); + if (assertResult === undefined) { + assertResult = abilityManager.UserStatus.ASSERT_TERMINATE; + } + try { + abilityManager.notifyDebugAssertResult(this.sessionId, assertResult).then(() => { + console.log(TAG, 'notifyDebugAssertResult success.'); + }).catch((err: BusinessError) => { + console.error(TAG, `notifyDebugAssertResult failed, error: ${JSON.stringify(err)}`); + }); + } catch (error) { + console.error(TAG, `try notifyDebugAssertResult failed, error: ${JSON.stringify(error)}`); } } }; diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/assertFaultDialog.ets b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/assertFaultDialog.ets index 3fe5521908..c5bfb79cce 100644 --- a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/assertFaultDialog.ets +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/assertFaultDialog.ets @@ -19,6 +19,7 @@ import type UIExtensionContentSession from '@ohos.app.ability.UIExtensionContent let storage = LocalStorage.GetShared(); const TAG: string = 'AssertFaultDialog_Page'; +const DEBUG_ASSERT_RESULT: string = 'assertResult'; @Entry(storage) @Component @@ -33,17 +34,11 @@ struct AssertFaultDialog { existApp() { console.info(TAG, 'Exist app called'); try { - let status = abilityManager.UserStatus.ASSERT_TERMINATE; - abilityManager.notifyDebugAssertResult(storage.get('sessionId'), status).then(() => { - console.log(TAG, 'notifyDebugAssertResult termination status success.'); - AppStorage.setOrCreate('isUserAction', true); - storage.get('session').terminateSelf().then(() => { - console.log(TAG, 'terminateSelf success.'); - }).catch((err: BusinessError) => { - console.error(TAG, `terminateSelf failed, error: ${JSON.stringify(err)}`); - }) + AppStorage.setOrCreate(DEBUG_ASSERT_RESULT, abilityManager.UserStatus.ASSERT_TERMINATE); + storage.get('session').terminateSelf().then(() => { + console.log(TAG, 'terminateSelf success.'); }).catch((err: BusinessError) => { - console.error(TAG, `notifyDebugAssertResult failed, error: ${JSON.stringify(err)}`); + console.error(TAG, `terminateSelf failed, error: ${JSON.stringify(err)}`); }) } catch (error) { console.error(TAG, `try notifyDebugAssertResult failed, error: ${JSON.stringify(error)}`); @@ -52,18 +47,12 @@ struct AssertFaultDialog { onContinueCall() { console.info(TAG, 'On continue called'); - let status = abilityManager.UserStatus.ASSERT_CONTINUE; try { - abilityManager.notifyDebugAssertResult(storage.get('sessionId'), status).then(() => { - console.log(TAG, 'notifyDebugAssertResult continue status success.'); - AppStorage.setOrCreate('isUserAction', true); - storage.get('session').terminateSelf().then(() => { - console.log(TAG, 'terminateSelf success.'); - }).catch((err: BusinessError) => { - console.error(TAG, `terminateSelf failed, error: ${JSON.stringify(err)}`); - }) + AppStorage.setOrCreate(DEBUG_ASSERT_RESULT, abilityManager.UserStatus.ASSERT_CONTINUE); + storage.get('session').terminateSelf().then(() => { + console.log(TAG, 'terminateSelf success.'); }).catch((err: BusinessError) => { - console.error(TAG, `notifyDebugAssertResult failed, error: ${JSON.stringify(err)}`); + console.error(TAG, `terminateSelf failed, error: ${JSON.stringify(err)}`); }) } catch (error) { console.error(TAG, `try notifyDebugAssertResult failed, error: ${JSON.stringify(error)}`); @@ -72,18 +61,12 @@ struct AssertFaultDialog { onRetryCall() { console.info(TAG, 'On retry called'); - let status = abilityManager.UserStatus.ASSERT_RETRY; try { - abilityManager.notifyDebugAssertResult(storage.get('sessionId'), status).then(() => { - console.log(TAG, 'notifyDebugAssertResult retry status success.'); - AppStorage.setOrCreate('isUserAction', true); - storage.get('session').terminateSelf().then(() => { - console.log(TAG, 'terminateSelf success.'); - }).catch((err: BusinessError) => { - console.error(TAG, `terminateSelf failed, error: ${JSON.stringify(err)}`); - }) + AppStorage.setOrCreate(DEBUG_ASSERT_RESULT, abilityManager.UserStatus.ASSERT_RETRY); + storage.get('session').terminateSelf().then(() => { + console.log(TAG, 'terminateSelf success.'); }).catch((err: BusinessError) => { - console.error(TAG, `notifyDebugAssertResult failed, error: ${JSON.stringify(err)}`); + console.error(TAG, `terminateSelf failed, error: ${JSON.stringify(err)}`); }) } catch (error) { console.error(TAG, `try notifyDebugAssertResult failed, error: ${JSON.stringify(error)}`); @@ -92,18 +75,12 @@ struct AssertFaultDialog { onTerminationCall() { console.info(TAG, 'On termination called'); - let status = abilityManager.UserStatus.ASSERT_TERMINATE; try { - abilityManager.notifyDebugAssertResult(storage.get('sessionId'), status).then(() => { - console.log(TAG, 'notifyDebugAssertResult termination status success.'); - AppStorage.setOrCreate('isUserAction', true); - storage.get('session').terminateSelf().then(() => { - console.log(TAG, 'terminateSelf success.'); - }).catch((err: BusinessError) => { - console.error(TAG, `terminateSelf failed, error: ${JSON.stringify(err)}`); - }) + AppStorage.setOrCreate(DEBUG_ASSERT_RESULT, abilityManager.UserStatus.ASSERT_TERMINATE); + storage.get('session').terminateSelf().then(() => { + console.log(TAG, 'terminateSelf success.'); }).catch((err: BusinessError) => { - console.error(TAG, `notifyDebugAssertResult failed, error: ${JSON.stringify(err)}`); + console.error(TAG, `terminateSelf failed, error: ${JSON.stringify(err)}`); }) } catch (error) { console.error(TAG, `try notifyDebugAssertResult failed, error: ${JSON.stringify(error)}`); diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/permissionConfirmDialog.ets b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/permissionConfirmDialog.ets new file mode 100644 index 0000000000..40f7c9ee35 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/permissionConfirmDialog.ets @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import router from '@ohos.router' +import type UIExtensionContentSession from '@ohos.app.ability.UIExtensionContentSession'; +import dataPreferences from '@ohos.data.preferences'; +interface TipBtn { + color:string +} +let storage = LocalStorage.GetShared(); +@Entry(storage) +@Component +struct PermissionConfirmDialog { + @State private btn: TipBtn = { color: '#FFFFFF' } + private TAG = 'permissionconfirm_Page' + + onCloseApp() { + console.info(this.TAG, 'click close app'); + if (globalThis.ExtensionType === 'ServiceExtension') { + globalThis.currentExtensionContext.terminateSelf(); + } else { + storage.get('session').terminateSelf(); + } + } + + onConfirmApp() { + console.info(this.TAG, 'click confirm app'); + globalThis.preferences.putSync('isdialogconfirmpermission', 'true') + globalThis.preferences.flush(); + router.replaceUrl({ + url: globalThis.currentURL, + }) + } + + build() { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Text($r('app.string.message_title_permission_confirm')) + .fontSize(16) + .fontWeight(FontWeight.Medium) + .height('29%') + .textOverflow({overflow: TextOverflow.Ellipsis}) + .textAlign(TextAlign.Center) + } + Flex({ justifyContent: FlexAlign.Center }) { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Text($r('app.string.message_confirm_permission')) + .fontSize('21fp') + .fontColor('#0A59F7') + .fontWeight(FontWeight.Regular) + .textAlign(TextAlign.Center) + } + .width(175) + .height(50) + .borderRadius(28) + .backgroundColor(this.btn.color) + .onClick(() => { + this.onConfirmApp(); + }) + }.margin({ top: 10}) + Flex({ justifyContent: FlexAlign.Center }) { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Text($r('app.string.message_cancel_permission')) + .fontSize('21fp') + .fontColor('#0A59F7') + .fontWeight(FontWeight.Regular) + .textAlign(TextAlign.Center) + } + .width(175) + .height(50) + .borderRadius(28) + .backgroundColor(this.btn.color) + .onClick(() => { + this.onCloseApp(); + }) + }.margin({ top: 10}) + } + .borderRadius(20) + .borderWidth(1) + .borderColor('#e9e9e9') + .backgroundColor('#FFFFFF') + } +} \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/element/string.json b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/element/string.json index effea732c1..9fe4c646f4 100644 --- a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/element/string.json +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/element/string.json @@ -91,6 +91,18 @@ { "name": "title_assertFault", "value": "AssertFaultDialog" + }, + { + "name": "message_title_permission_confirm", + "value": "The amsdialog application wants to query the list of application software information" + }, + { + "name": "message_confirm_permission", + "value": "allow" + }, + { + "name": "message_cancel_permission", + "value": "reject" } ] } \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/profile/main_pages.json b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/profile/main_pages.json index 59a4f56138..8a5cc50ddb 100644 --- a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/profile/main_pages.json +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/profile/main_pages.json @@ -6,6 +6,7 @@ "pages/tipsDialog", "pages/jumpInterceptorDialog", "pages/PhonePage", - "pages/assertFaultDialog" + "pages/assertFaultDialog", + "pages/permissionConfirmDialog" ] } diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/zh/element/string.json b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/zh/element/string.json index c4c7a58c17..e011b49e95 100644 --- a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/zh/element/string.json +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/zh/element/string.json @@ -111,6 +111,18 @@ { "name": "title_assertFault", "value": "AssertFaultDialog" + }, + { + "name": "message_title_permission_confirm", + "value": "amsdialogåŗ”ē”Øęƒ³č¦ęŸ„čÆ¢åŗ”ē”Øč½Æä»¶åˆ—č”Øäæ”ęÆ" + }, + { + "name": "message_confirm_permission", + "value": "允许" + }, + { + "name": "message_cancel_permission", + "value": "ę‹’ē»" } ] } \ No newline at end of file diff --git a/services/quickfixmgr/BUILD.gn b/services/quickfixmgr/BUILD.gn index a68906cb28..ddefd1fbec 100644 --- a/services/quickfixmgr/BUILD.gn +++ b/services/quickfixmgr/BUILD.gn @@ -37,6 +37,12 @@ quickfixms_sources = [ ] ohos_shared_library("quickfixms") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper" ] shlib_type = "sa" configs = [ "${ability_runtime_services_path}/common:common_config" ] diff --git a/services/uripermmgr/BUILD.gn b/services/uripermmgr/BUILD.gn index 958dd8cb9c..0d9f3b6411 100644 --- a/services/uripermmgr/BUILD.gn +++ b/services/uripermmgr/BUILD.gn @@ -25,7 +25,6 @@ config("upms_config") { } libupms_sources = [ - "src/proxy_authorization_uri_config.cpp", "src/tokenid_permission.cpp", "src/uri_permission_manager_service.cpp", "src/uri_permission_manager_stub_impl.cpp", @@ -33,6 +32,12 @@ libupms_sources = [ #build so ohos_shared_library("libupms") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" shlib_type = "sa" configs = [ "${ability_runtime_innerkits_path}/app_manager:appmgr_sdk_config", diff --git a/services/uripermmgr/include/proxy_authorization_uri_config.h b/services/uripermmgr/include/proxy_authorization_uri_config.h deleted file mode 100644 index 06a0c11106..0000000000 --- a/services/uripermmgr/include/proxy_authorization_uri_config.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2023 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 OHOS_ABILITY_RUNTIME_PROXY_AUTHORIZATION_URI_CONFIG_H -#define OHOS_ABILITY_RUNTIME_PROXY_AUTHORIZATION_URI_CONFIG_H - -#include -#include -#include - -#include "singleton.h" - -namespace OHOS { -namespace AAFwk { -class ProxyAuthorizationUriConfig : public DelayedSingleton { -public: - ProxyAuthorizationUriConfig() = default; - virtual ~ProxyAuthorizationUriConfig() = default; - void LoadConfiguration(); - bool IsAuthorizationUriAllowed(uint32_t fromTokenId); -private: - void LoadAllowedList(const nlohmann::json &object); - bool ReadFileInfoJson(const std::string &filePath, nlohmann::json &jsonBuf); - - std::set bundleNameAllowedList_; - std::set processNameAllowedList_; -}; -} // OHOS -} // AAFwk - -#endif // OHOS_ABILITY_RUNTIME_PROXY_AUTHORIZATION_URI_CONFIG_H \ No newline at end of file diff --git a/services/uripermmgr/include/uri_permission_manager_stub_impl.h b/services/uripermmgr/include/uri_permission_manager_stub_impl.h index 67cfd568b0..9973928a0c 100644 --- a/services/uripermmgr/include/uri_permission_manager_stub_impl.h +++ b/services/uripermmgr/include/uri_permission_manager_stub_impl.h @@ -19,6 +19,7 @@ #include #include #include +#include #include "app_mgr_interface.h" #include "bundle_mgr_helper.h" @@ -32,13 +33,37 @@ namespace OHOS::AAFwk { namespace { using ClearProxyCallback = std::function&)>; using TokenId = Security::AccessToken::AccessTokenID; +constexpr int32_t DEFAULT_ABILITY_ID = -1; } struct GrantInfo { unsigned int flag; const uint32_t fromTokenId; const uint32_t targetTokenId; - uint32_t autoRemove; + bool autoRemove; + std::unordered_set abilityIds; + + void AddAbilityId(int32_t abilityId) + { + if (abilityId != DEFAULT_ABILITY_ID) { + abilityIds.insert(abilityId); + } + } + + bool RemoveAbilityId(int32_t abilityId) + { + return abilityIds.erase(abilityId) > 0; + } + + bool IsEmptyAbilityId() + { + return abilityIds.empty(); + } + + void ClearAbilityIds() + { + abilityIds.clear(); + } }; struct PolicyInfo final { @@ -53,26 +78,23 @@ public: UriPermissionManagerStubImpl() = default; virtual ~UriPermissionManagerStubImpl() = default; - int GrantUriPermission(const Uri &uri, unsigned int flag, - const std::string targetBundleName, int32_t appIndex = 0, uint32_t initiatorTokenId = 0) override; + int GrantUriPermission(const Uri &uri, unsigned int flag, const std::string targetBundleName, + int32_t appIndex = 0, uint32_t initiatorTokenId = 0, int32_t abilityId = -1) override; int GrantUriPermission(const std::vector &uriVec, unsigned int flag, - const std::string targetBundleName, int32_t appIndex = 0, uint32_t initiatorTokenId = 0) override; + const std::string targetBundleName, int32_t appIndex = 0, uint32_t initiatorTokenId = 0, + int32_t abilityId = -1) override; int32_t GrantUriPermissionPrivileged(const std::vector &uriVec, uint32_t flag, const std::string &targetBundleName, int32_t appIndex = 0) override; std::vector CheckUriAuthorization(const std::vector &uriVec, uint32_t flag, uint32_t tokenId) override; - // To be deleted. - int GrantUriPermissionFor2In1(const std::vector &uriVec, unsigned int flag, - const std::string &targetBundleName, int32_t appIndex = 0, bool isSystemAppCall = false) override; // only for foundation calling - void RevokeUriPermission(const TokenId tokenId) override; + void RevokeUriPermission(const TokenId tokenId, int32_t abilityId = -1) override; int RevokeAllUriPermissions(uint32_t tokenId) override; int RevokeUriPermissionManually(const Uri &uri, const std::string bundleName) override; bool VerifyUriPermission(const Uri &uri, uint32_t flag, uint32_t tokenId) override; - bool IsAuthorizationUriAllowed(uint32_t fromTokenId) override; int32_t GetTokenIdByBundleName(const std::string &bundleName, int32_t appIndex, uint32_t &tokenId); private: @@ -81,23 +103,23 @@ private: std::shared_ptr ConnectManagerHelper(); int32_t GetCurrentAccountId() const; int GrantUriPermissionImpl(const Uri &uri, unsigned int flag, - TokenId fromTokenId, TokenId targetTokenId, uint32_t autoRemove); + TokenId fromTokenId, TokenId targetTokenId, int32_t abilityId); int AddTempUriPermission(const std::string &uri, unsigned int flag, TokenId fromTokenId, - TokenId targetTokenId, uint32_t autoRemove); + TokenId targetTokenId, int32_t abilityId); int GrantBatchUriPermissionImpl(const std::vector &uriVec, unsigned int flag, - TokenId initiatorTokenId, TokenId targetTokenId, uint32_t autoRemove); + TokenId initiatorTokenId, TokenId targetTokenId, int32_t abilityId); int GrantBatchUriPermission(const std::vector &uriVec, unsigned int flag, uint32_t initiatorTokenId, - uint32_t targetTokenId, uint32_t autoRemove); + uint32_t targetTokenId, int32_t abilityId); int32_t GrantBatchUriPermissionPrivileged(const std::vector &uriVec, uint32_t flag, - uint32_t callerTokenId, uint32_t targetTokenId, uint32_t autoRemove); + uint32_t callerTokenId, uint32_t targetTokenId, int32_t abilityId = -1); int32_t GrantBatchUriPermissionFor2In1Privileged(const std::vector &uriVec, uint32_t flag, - uint32_t callerTokenId, uint32_t targetTokenId, uint32_t autoRemove); + uint32_t callerTokenId, uint32_t targetTokenId, int32_t abilityId = -1); int GrantSingleUriPermission(const Uri &uri, unsigned int flag, uint32_t callerTokenId, uint32_t targetTokenId, - uint32_t autoRemove); + int32_t abilityId); bool SendEvent(uint32_t callerTokenId, uint32_t targetTokenId, std::string &uri); @@ -112,10 +134,11 @@ private: std::string GetBundleNameByTokenId(uint32_t tokenId); int GrantUriPermissionInner(const std::vector &uriVec, unsigned int flag, const std::string targetBundleName, - int32_t appIndex, uint32_t initiatorTokenId); + int32_t appIndex, uint32_t initiatorTokenId, int32_t abilityId = -1); int GrantUriPermissionFor2In1Inner(const std::vector &uriVec, unsigned int flag, - const std::string &targetBundleName, int32_t appIndex, bool isSystemAppCall, uint32_t initiatorTokenId = 0); + const std::string &targetBundleName, int32_t appIndex, bool isSystemAppCall, uint32_t initiatorTokenId = 0, + int32_t abilityId = -1); void HandleUriPermission( uint64_t tokenId, unsigned int flag, std::vector &docsVec, bool isSystemAppCall); @@ -134,6 +157,10 @@ private: bool IsSAOrSystemAppCall(); + bool IsLinuxFusionCall(); + + void RemoveUriRecord(std::vector &uriList, const TokenId tokenId, int32_t abilityId); + class ProxyDeathRecipient : public IRemoteObject::DeathRecipient { public: explicit ProxyDeathRecipient(ClearProxyCallback&& proxy) : proxy_(proxy) {} diff --git a/services/uripermmgr/src/proxy_authorization_uri_config.cpp b/services/uripermmgr/src/proxy_authorization_uri_config.cpp deleted file mode 100644 index a7ecb0af65..0000000000 --- a/services/uripermmgr/src/proxy_authorization_uri_config.cpp +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2022-2024 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 "proxy_authorization_uri_config.h" -#include -#include -#include - -#include "accesstoken_kit.h" -#include "parameters.h" -#include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" - -namespace OHOS { -namespace AAFwk { -namespace { -const std::string CONFIG_PATH_DEFAULT = "/system/etc/proxy_authorization_uri.json"; -const std::string CONFIG_PATH_PREFIX = "/system/variant/"; -const std::string CONFIG_PATH = "/base/etc/proxy_authorization_uri.json"; - -const std::string PROXY_AUTHORIZATION_URI_NAME = "proxyAuthorizationUri"; -const std::string BUNDLE_NAME = "bundleName"; -const std::string PROCESS_NAME = "processName"; -} - -void ProxyAuthorizationUriConfig::LoadConfiguration() -{ - TAG_LOGD(AAFwkTag::URIPERMMGR, "call"); - nlohmann::json jsonBuf; - std::string deviceType = OHOS::system::GetDeviceType(); - if (deviceType == "2in1") { - deviceType = "pc"; - } - std::string configPath = CONFIG_PATH_PREFIX + deviceType + CONFIG_PATH; - if (ReadFileInfoJson(configPath, jsonBuf)) { - LoadAllowedList(jsonBuf); - return; - } - nlohmann::json jsonBufDefault; - if (ReadFileInfoJson(CONFIG_PATH_DEFAULT, jsonBufDefault)) { - LoadAllowedList(jsonBufDefault); - } -} - -bool ProxyAuthorizationUriConfig::IsAuthorizationUriAllowed(uint32_t fromTokenId) -{ - Security::AccessToken::NativeTokenInfo nativeInfo; - auto result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(fromTokenId, nativeInfo); - if (result == Security::AccessToken::AccessTokenKitRet::RET_SUCCESS && - processNameAllowedList_.find(nativeInfo.processName) != processNameAllowedList_.end()) { - return true; - } - - Security::AccessToken::HapTokenInfo hapInfo; - result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(fromTokenId, hapInfo); - if (result == Security::AccessToken::AccessTokenKitRet::RET_SUCCESS && - bundleNameAllowedList_.find(hapInfo.bundleName) != bundleNameAllowedList_.end()) { - return true; - } - return false; -} - -void ProxyAuthorizationUriConfig::LoadAllowedList(const nlohmann::json &object) -{ - if (!object.contains(PROXY_AUTHORIZATION_URI_NAME)) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Proxy authorization uri config not existed."); - return; - } - - for (auto &item : object.at(PROXY_AUTHORIZATION_URI_NAME).items()) { - const nlohmann::json& jsonObject = item.value(); - if (jsonObject.contains(BUNDLE_NAME) && jsonObject.at(BUNDLE_NAME).is_string()) { - std::string bundleName = jsonObject.at(BUNDLE_NAME).get(); - bundleNameAllowedList_.insert(bundleName); - } - if (jsonObject.contains(PROCESS_NAME) && jsonObject.at(PROCESS_NAME).is_string()) { - std::string processName = jsonObject.at(PROCESS_NAME).get(); - processNameAllowedList_.insert(processName); - } - } -} - -bool ProxyAuthorizationUriConfig::ReadFileInfoJson(const std::string &filePath, nlohmann::json &jsonBuf) -{ - if (access(filePath.c_str(), F_OK) != 0) { - TAG_LOGD(AAFwkTag::URIPERMMGR, "%{public}s, not existed", filePath.c_str()); - return false; - } - - std::fstream in; - char errBuf[256]; - errBuf[0] = '\0'; - in.open(filePath, std::ios_base::in); - if (!in.is_open()) { - strerror_r(errno, errBuf, sizeof(errBuf)); - TAG_LOGE(AAFwkTag::URIPERMMGR, "the file cannot be open due to %{public}s", errBuf); - return false; - } - - in.seekg(0, std::ios::end); - int64_t size = in.tellg(); - if (size <= 0) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "the file is an empty file"); - in.close(); - return false; - } - - in.seekg(0, std::ios::beg); - jsonBuf = nlohmann::json::parse(in, nullptr, false); - in.close(); - if (jsonBuf.is_discarded()) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "bad profile file"); - return false; - } - - return true; -} -} -} \ No newline at end of file diff --git a/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp b/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp index 072fc6bdec..ce4413a425 100644 --- a/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp +++ b/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp @@ -30,7 +30,6 @@ #include "parameter.h" #include "permission_constants.h" #include "permission_verification.h" -#include "proxy_authorization_uri_config.h" #include "system_ability_definition.h" #include "tokenid_kit.h" #include "want.h" @@ -45,27 +44,38 @@ namespace { constexpr int32_t DEFAULT_USER_ID = 0; constexpr int32_t ERR_OK = 0; constexpr uint32_t FLAG_READ_WRITE_URI = Want::FLAG_AUTH_READ_URI_PERMISSION | Want::FLAG_AUTH_WRITE_URI_PERMISSION; +constexpr uint32_t FLAG_WRITE_URI = Want::FLAG_AUTH_WRITE_URI_PERMISSION; +constexpr uint32_t FLAG_READ_URI = Want::FLAG_AUTH_READ_URI_PERMISSION; constexpr const char* CLOUND_DOCS_URI_MARK = "?networkid="; constexpr const char* FOUNDATION_PROCESS_NAME = "foundation"; +constexpr const char* LINUX_FUSION_SERVICE = "linux_fusion_service"; } bool UriPermissionManagerStubImpl::VerifyUriPermission(const Uri &uri, uint32_t flag, uint32_t tokenId) { // verify if tokenId have uri permission record auto uriStr = uri.ToString(); - TAG_LOGI(AAFwkTag::URIPERMMGR, "uri is %{private}s, flag is %{public}u, tokenId is %{public}u", + TAG_LOGD(AAFwkTag::URIPERMMGR, "uri is %{private}s, flag is %{public}u, tokenId is %{public}u", uriStr.c_str(), flag, tokenId); if (!IsSAOrSystemAppCall()) { TAG_LOGE(AAFwkTag::URIPERMMGR, "Only support SA and SystemApp called."); return false; } + if ((flag & FLAG_READ_WRITE_URI) == 0) { + TAG_LOGE(AAFwkTag::URIPERMMGR, "Flag is invalid."); + return false; + } + uint32_t newFlag = FLAG_READ_URI; + if ((flag & FLAG_WRITE_URI) != 0) { + newFlag = FLAG_WRITE_URI; + } std::lock_guard guard(mutex_); auto search = uriMap_.find(uriStr); if (search != uriMap_.end()) { auto& list = search->second; for (auto it = list.begin(); it != list.end(); it++) { - if ((it->targetTokenId == tokenId) && ((it->flag | Want::FLAG_AUTH_READ_URI_PERMISSION) & flag) != 0) { - TAG_LOGI(AAFwkTag::URIPERMMGR, "have uri permission."); + if ((it->targetTokenId == tokenId) && ((it->flag | FLAG_READ_URI) & newFlag) != 0) { + TAG_LOGD(AAFwkTag::URIPERMMGR, "have uri permission."); return true; } } @@ -74,17 +84,9 @@ bool UriPermissionManagerStubImpl::VerifyUriPermission(const Uri &uri, uint32_t return false; } -bool UriPermissionManagerStubImpl::IsAuthorizationUriAllowed(uint32_t fromTokenId) -{ - if (!IsSAOrSystemAppCall()) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Only support SA and SystemApp called."); - return false; - } - return DelayedSingleton::GetInstance()->IsAuthorizationUriAllowed(fromTokenId); -} int UriPermissionManagerStubImpl::GrantUriPermission(const Uri &uri, unsigned int flag, - const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId) + const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId, int32_t abilityId) { TAG_LOGI(AAFwkTag::URIPERMMGR, "Uri is %{private}s.", uri.ToString().c_str()); if (!IsSAOrSystemAppCall()) { @@ -92,11 +94,11 @@ int UriPermissionManagerStubImpl::GrantUriPermission(const Uri &uri, unsigned in return CHECK_PERMISSION_FAILED; } std::vector uriVec = { uri }; - return GrantUriPermission(uriVec, flag, targetBundleName, appIndex, initiatorTokenId); + return GrantUriPermission(uriVec, flag, targetBundleName, appIndex, initiatorTokenId, abilityId); } int UriPermissionManagerStubImpl::GrantUriPermission(const std::vector &uriVec, unsigned int flag, - const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId) + const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId, int32_t abilityId) { TAG_LOGI(AAFwkTag::URIPERMMGR, "BundleName is %{public}s, appIndex is %{public}d, size of uriVec is %{public}zu.", targetBundleName.c_str(), appIndex, uriVec.size()); @@ -118,9 +120,9 @@ int UriPermissionManagerStubImpl::GrantUriPermission(const std::vector &uri isSystemAppCall = CheckIsSystemAppByTokenId(initiatorTokenId); } return GrantUriPermissionFor2In1Inner( - uriVec, flag, targetBundleName, appIndex, isSystemAppCall, initiatorTokenId); + uriVec, flag, targetBundleName, appIndex, isSystemAppCall, initiatorTokenId, abilityId); } - return GrantUriPermissionInner(uriVec, flag, targetBundleName, appIndex, initiatorTokenId); + return GrantUriPermissionInner(uriVec, flag, targetBundleName, appIndex, initiatorTokenId, abilityId); } int32_t UriPermissionManagerStubImpl::GrantUriPermissionPrivileged(const std::vector &uriVec, uint32_t flag, @@ -128,12 +130,15 @@ int32_t UriPermissionManagerStubImpl::GrantUriPermissionPrivileged(const std::ve { TAG_LOGI(AAFwkTag::URIPERMMGR, "BundleName is %{public}s, appIndex is %{public}d, size of uriVec is %{public}zu.", targetBundleName.c_str(), appIndex, uriVec.size()); + uint32_t callerTokenId = IPCSkeleton::GetCallingTokenID(); auto callerName = GetTokenName(callerTokenId); TAG_LOGD(AAFwkTag::URIPERMMGR, "callerTokenId is %{public}u, callerName is %{public}s", callerTokenId, callerName.c_str()); + auto permissionName = PermissionConstants::PERMISSION_GRANT_URI_PERMISSION_PRIVILEGED; - if (!PermissionVerification::GetInstance()->VerifyPermissionByTokenId(callerTokenId, permissionName)) { + if (!PermissionVerification::GetInstance()->VerifyPermissionByTokenId(callerTokenId, permissionName) && + !IsLinuxFusionCall()) { TAG_LOGE(AAFwkTag::URIPERMMGR, "No permission to call."); return CHECK_PERMISSION_FAILED; } @@ -142,22 +147,22 @@ int32_t UriPermissionManagerStubImpl::GrantUriPermissionPrivileged(const std::ve TAG_LOGE(AAFwkTag::URIPERMMGR, "Flag is invalid, value is %{public}u.", flag); return ERR_CODE_INVALID_URI_FLAG; } + flag &= FLAG_READ_WRITE_URI; uint32_t targetTokenId = 0; - auto ret = GetTokenIdByBundleName(targetBundleName, 0, targetTokenId); + auto ret = GetTokenIdByBundleName(targetBundleName, appIndex, targetTokenId); if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::URIPERMMGR, "Get tokenId failed, bundlename is %{public}s.", targetBundleName.c_str()); return ret; } - uint32_t autoRemove = IsFoundationCall() ? 1 : 0; if (AppUtils::GetInstance().IsGrantPersistUriPermission()) { - return GrantBatchUriPermissionFor2In1Privileged(uriVec, flag, callerTokenId, targetTokenId, autoRemove); + return GrantBatchUriPermissionFor2In1Privileged(uriVec, flag, callerTokenId, targetTokenId); } - return GrantBatchUriPermissionPrivileged(uriVec, flag, callerTokenId, targetTokenId, autoRemove); + return GrantBatchUriPermissionPrivileged(uriVec, flag, callerTokenId, targetTokenId); } int UriPermissionManagerStubImpl::GrantUriPermissionInner(const std::vector &uriVec, unsigned int flag, - const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId) + const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId, int32_t abilityId) { TAG_LOGD(AAFwkTag::URIPERMMGR, "Called."); flag &= FLAG_READ_WRITE_URI; @@ -167,20 +172,20 @@ int UriPermissionManagerStubImpl::GrantUriPermissionInner(const std::vector TAG_LOGE(AAFwkTag::URIPERMMGR, "get tokenId of target bundle name failed."); return ret; } - // autoRemove will be set to 1 if the process name is foundation. - uint32_t autoRemove = 0; + // recordId will be set default id if the process name is not foundation. + int32_t recordId = -1; uint32_t appTokenId = IPCSkeleton::GetCallingTokenID(); if (IsFoundationCall()) { - autoRemove = 1; + recordId = abilityId; appTokenId = initiatorTokenId; auto callerName = GetTokenName(appTokenId); TAG_LOGI(AAFwkTag::URIPERMMGR, "RealTokenId is %{public}u, RealCallerName is %{public}s.", appTokenId, callerName.c_str()); } if (uriVec.size() == 1) { - return GrantSingleUriPermission(uriVec[0], flag, appTokenId, targetTokenId, autoRemove); + return GrantSingleUriPermission(uriVec[0], flag, appTokenId, targetTokenId, recordId); } - return GrantBatchUriPermission(uriVec, flag, appTokenId, targetTokenId, autoRemove); + return GrantBatchUriPermission(uriVec, flag, appTokenId, targetTokenId, recordId); } int checkPersistPermission(uint64_t tokenId, const std::vector &policy, std::vector &result) @@ -228,32 +233,14 @@ int32_t UriPermissionManagerStubImpl::CheckCalledBySandBox() return ERR_OK; } -// To be deleted. -int UriPermissionManagerStubImpl::GrantUriPermissionFor2In1(const std::vector &uriVec, unsigned int flag, - const std::string &targetBundleName, int32_t appIndex, bool isSystemAppCall) -{ - TAG_LOGI(AAFwkTag::URIPERMMGR, "Called."); - if (!IsFoundationCall()) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Not foundation call."); - return CHECK_PERMISSION_FAILED; - } - auto checkResult = CheckCalledBySandBox(); - if (checkResult != ERR_OK) { - return checkResult; - } - if ((flag & FLAG_READ_WRITE_URI) == 0) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "Flag is %{public}u, which is invalid.", flag); - return ERR_CODE_INVALID_URI_FLAG; - } - return GrantUriPermissionFor2In1Inner(uriVec, flag, targetBundleName, appIndex, isSystemAppCall); -} - int UriPermissionManagerStubImpl::AddTempUriPermission(const std::string &uri, unsigned int flag, - TokenId fromTokenId, TokenId targetTokenId, uint32_t autoRemove) + TokenId fromTokenId, TokenId targetTokenId, int32_t abilityId) { std::lock_guard guard(mutex_); auto search = uriMap_.find(uri); - GrantInfo info = { flag, fromTokenId, targetTokenId, autoRemove }; + bool autoRemove = (abilityId != DEFAULT_ABILITY_ID); + GrantInfo info = { flag, fromTokenId, targetTokenId, autoRemove, {} }; + info.AddAbilityId(abilityId); if (search == uriMap_.end()) { TAG_LOGI(AAFwkTag::URIPERMMGR, "Insert an uri r/w permission."); std::list infoList = { info }; @@ -263,32 +250,40 @@ int UriPermissionManagerStubImpl::AddTempUriPermission(const std::string &uri, u auto& infoList = search->second; for (auto& item : infoList) { if (item.fromTokenId == fromTokenId && item.targetTokenId == targetTokenId) { - TAG_LOGD(AAFwkTag::URIPERMMGR, "Item: flag is %{public}u, autoRemove is %{public}u.", - item.flag, item.autoRemove); - if (item.autoRemove == 1 && info.autoRemove == 0) { - TAG_LOGD(AAFwkTag::URIPERMMGR, "Update autoRemove."); - item.autoRemove = 1; - } - if ((flag & (item.flag | Want::FLAG_AUTH_READ_URI_PERMISSION)) == 0) { + TAG_LOGI(AAFwkTag::URIPERMMGR, + "Item: flag is %{public}u, autoRemove is %{public}u, ability size is %{public}zu.", + item.flag, item.autoRemove, item.abilityIds.size()); + item.AddAbilityId(abilityId); + // r-w + if ((item.flag & FLAG_WRITE_URI) == 0 && (flag & FLAG_WRITE_URI) != 0) { TAG_LOGI(AAFwkTag::URIPERMMGR, "Update uri r/w permission."); - item.flag = flag; - } else { - TAG_LOGI(AAFwkTag::URIPERMMGR, "Uri has been granted, not to grant again."); + item.autoRemove = autoRemove; + item.flag |= FLAG_WRITE_URI; + return ERR_OK; + } + // w-r + TAG_LOGD(AAFwkTag::URIPERMMGR, "Uri has been granted, not to grant again."); + if ((item.flag & FLAG_WRITE_URI) != 0 && (flag & FLAG_WRITE_URI) == 0) { + return ERR_OK; + } + // other + if (!autoRemove) { + item.autoRemove = autoRemove; } return ERR_OK; } } - TAG_LOGI(AAFwkTag::URIPERMMGR, "Insert an new uri permission record."); + TAG_LOGI(AAFwkTag::URIPERMMGR, "Insert a new uri permission record."); infoList.emplace_back(info); return ERR_OK; } int UriPermissionManagerStubImpl::GrantUriPermissionImpl(const Uri &uri, unsigned int flag, - TokenId callerTokenId, TokenId targetTokenId, uint32_t autoRemove) + TokenId callerTokenId, TokenId targetTokenId, int32_t abilityId) { - TAG_LOGI(AAFwkTag::URIPERMMGR, "uri = %{private}s, flag = %{public}i, callerTokenId = %{public}i," - "targetTokenId = %{public}i, autoRemove = %{public}i", uri.ToString().c_str(), flag, callerTokenId, - targetTokenId, autoRemove); + TAG_LOGD(AAFwkTag::URIPERMMGR, "uri = %{private}s, flag = %{public}i, callerTokenId = %{public}i," + "targetTokenId = %{public}i, abilityId = %{public}i", uri.ToString().c_str(), flag, callerTokenId, + targetTokenId, abilityId); ConnectManager(storageManager_, STORAGE_MANAGER_MANAGER_ID); if (storageManager_ == nullptr) { TAG_LOGE(AAFwkTag::URIPERMMGR, "ConnectManager failed"); @@ -305,17 +300,17 @@ int UriPermissionManagerStubImpl::GrantUriPermissionImpl(const Uri &uri, unsigne TAG_LOGE(AAFwkTag::URIPERMMGR, "failed to CreateShareFile."); return INNER_ERR; } - AddTempUriPermission(uriStr, flag, callerTokenId, targetTokenId, autoRemove); + AddTempUriPermission(uriStr, flag, callerTokenId, targetTokenId, abilityId); SendEvent(callerTokenId, targetTokenId, uriStr); return ERR_OK; } int UriPermissionManagerStubImpl::GrantSingleUriPermission(const Uri &uri, unsigned int flag, uint32_t callerTokenId, - uint32_t targetTokenId, uint32_t autoRemove) + uint32_t targetTokenId, int32_t abilityId) { TAG_LOGI(AAFwkTag::URIPERMMGR, - "uri is %{private}s, callerTokenId is %{public}u, targetTokenId is %{public}u, autoRemove is %{public}u", - uri.ToString().c_str(), callerTokenId, targetTokenId, autoRemove); + "uri is %{private}s, callerTokenId is %{public}u, targetTokenId is %{public}u, abilityId is %{public}d", + uri.ToString().c_str(), callerTokenId, targetTokenId, abilityId); if (!CheckUriTypeIsValid(uri)) { TAG_LOGE(AAFwkTag::URIPERMMGR, "Check uri type failed, uri is %{private}s", uri.ToString().c_str()); return ERR_CODE_INVALID_URI_TYPE; @@ -326,13 +321,13 @@ int UriPermissionManagerStubImpl::GrantSingleUriPermission(const Uri &uri, unsig uri.ToString().c_str(), callerTokenId); return CHECK_PERMISSION_FAILED; } - return GrantUriPermissionImpl(uri, flag, callerTokenId, targetTokenId, autoRemove); + return GrantUriPermissionImpl(uri, flag, callerTokenId, targetTokenId, abilityId); } int UriPermissionManagerStubImpl::GrantBatchUriPermissionImpl(const std::vector &uriVec, - unsigned int flag, TokenId callerTokenId, TokenId targetTokenId, uint32_t autoRemove) + unsigned int flag, TokenId callerTokenId, TokenId targetTokenId, int32_t abilityId) { - TAG_LOGI(AAFwkTag::URIPERMMGR, "callerTokenId is %{public}u, targetTokenId is %{public}u, flag is %{public}i," + TAG_LOGI(AAFwkTag::URIPERMMGR,"callerTokenId is %{public}u, targetTokenId is %{public}u, flag is %{public}i," "list size is %{public}zu", callerTokenId, targetTokenId, flag, uriVec.size()); ConnectManager(storageManager_, STORAGE_MANAGER_MANAGER_ID); if (storageManager_ == nullptr) { @@ -357,7 +352,7 @@ int UriPermissionManagerStubImpl::GrantBatchUriPermissionImpl(const std::vector< TAG_LOGE(AAFwkTag::URIPERMMGR, "failed to CreateShareFile."); continue; } - AddTempUriPermission(uriVec[i], flag, callerTokenId, targetTokenId, autoRemove); + AddTempUriPermission(uriVec[i], flag, callerTokenId, targetTokenId, abilityId); if (needSendEvent) { eventInfo.uri = uriVec[i]; EventReport::SendKeyEvent(EventName::GRANT_URI_PERMISSION, HiSysEventType::BEHAVIOR, eventInfo); @@ -372,11 +367,11 @@ int UriPermissionManagerStubImpl::GrantBatchUriPermissionImpl(const std::vector< } int UriPermissionManagerStubImpl::GrantBatchUriPermission(const std::vector &uriVec, unsigned int flag, - uint32_t callerTokenId, uint32_t targetTokenId, uint32_t autoRemove) + uint32_t callerTokenId, uint32_t targetTokenId, int32_t abilityId) { TAG_LOGI(AAFwkTag::URIPERMMGR, - "callerTokenId is %{public}u, targetTokenId is %{public}u, flag is %{public}u, autoRemove is %{public}u.", - callerTokenId, targetTokenId, flag, autoRemove); + "callerTokenId is %{public}u, targetTokenId is %{public}u, flag is %{public}u, abilityId is %{public}u.", + callerTokenId, targetTokenId, flag, abilityId); TokenIdPermission tokenIdPermission(callerTokenId); std::vector uriStrVec = {}; for (const auto &uri : uriVec) { @@ -394,11 +389,11 @@ int UriPermissionManagerStubImpl::GrantBatchUriPermission(const std::vector TAG_LOGE(AAFwkTag::URIPERMMGR, "Valid uri list is empty."); return INNER_ERR; } - return GrantBatchUriPermissionImpl(uriStrVec, flag, callerTokenId, targetTokenId, autoRemove); + return GrantBatchUriPermissionImpl(uriStrVec, flag, callerTokenId, targetTokenId, abilityId); } int32_t UriPermissionManagerStubImpl::GrantBatchUriPermissionPrivileged(const std::vector &uriVec, uint32_t flag, - uint32_t callerTokenId, uint32_t targetTokenId, uint32_t autoRemove) + uint32_t callerTokenId, uint32_t targetTokenId, int32_t abilityId) { TAG_LOGI(AAFwkTag::URIPERMMGR, "callerTokenId is %{public}u, targetTokenId is %{public}u, flag is %{public}u.", callerTokenId, targetTokenId, flag); @@ -414,11 +409,11 @@ int32_t UriPermissionManagerStubImpl::GrantBatchUriPermissionPrivileged(const st TAG_LOGE(AAFwkTag::URIPERMMGR, "Valid uri list is empty."); return ERR_CODE_INVALID_URI_TYPE; } - return GrantBatchUriPermissionImpl(uriStrVec, flag, callerTokenId, targetTokenId, autoRemove); + return GrantBatchUriPermissionImpl(uriStrVec, flag, callerTokenId, targetTokenId, abilityId); } int32_t UriPermissionManagerStubImpl::GrantBatchUriPermissionFor2In1Privileged(const std::vector &uriVec, - uint32_t flag, uint32_t callerTokenId, uint32_t targetTokenId, uint32_t autoRemove) + uint32_t flag, uint32_t callerTokenId, uint32_t targetTokenId, int32_t abilityId) { TAG_LOGI(AAFwkTag::URIPERMMGR, "callerTokenId is %{public}u, targetTokenId is %{public}u, flag is %{public}u.", callerTokenId, targetTokenId, flag); @@ -432,7 +427,7 @@ int32_t UriPermissionManagerStubImpl::GrantBatchUriPermissionFor2In1Privileged(c continue; } auto &&authority = uriInner.GetAuthority(); - if (authority != "docs" || uriStr.find(CLOUND_DOCS_URI_MARK) == std::string::npos) { + if (authority != "docs" || uriStr.find(CLOUND_DOCS_URI_MARK) != std::string::npos) { uriStrVec.emplace_back(uriStr); continue; } @@ -442,13 +437,16 @@ int32_t UriPermissionManagerStubImpl::GrantBatchUriPermissionFor2In1Privileged(c docsVec.emplace_back(policyInfo); } + TAG_LOGI(AAFwkTag::URIPERMMGR, "docsUri size is %{public}zu, otherUri size is %{public}zu", + docsVec.size(), uriStrVec.size()); + if (uriStrVec.empty() && docsVec.empty()) { TAG_LOGE(AAFwkTag::URIPERMMGR, "Valid uri list is empty."); return ERR_CODE_INVALID_URI_TYPE; } if (!uriStrVec.empty()) { - auto ret = GrantBatchUriPermissionImpl(uriStrVec, flag, callerTokenId, targetTokenId, autoRemove); + auto ret = GrantBatchUriPermissionImpl(uriStrVec, flag, callerTokenId, targetTokenId, abilityId); if (docsVec.empty()) { return ret; } @@ -459,33 +457,43 @@ int32_t UriPermissionManagerStubImpl::GrantBatchUriPermissionFor2In1Privileged(c return ERR_OK; } -void UriPermissionManagerStubImpl::RevokeUriPermission(const TokenId tokenId) +void UriPermissionManagerStubImpl::RemoveUriRecord(std::vector &uriList, const TokenId tokenId, + int32_t abilityId) { - TAG_LOGI(AAFwkTag::URIPERMMGR, "Start to remove uri permission, tokenId is %{public}u", tokenId); + std::lock_guard guard(mutex_); + for (auto iter = uriMap_.begin(); iter != uriMap_.end();) { + auto& list = iter->second; + for (auto it = list.begin(); it != list.end(); it++) { + if (it->targetTokenId != tokenId || !it->RemoveAbilityId(abilityId) || !it->autoRemove) { + continue; + } + if (!it->IsEmptyAbilityId()) { + TAG_LOGD(AAFwkTag::URIPERMMGR, "Remove an abilityId."); + break; + } + TAG_LOGI(AAFwkTag::URIPERMMGR, "Erase an info form list."); + list.erase(it); + uriList.emplace_back(iter->first); + break; + } + if (list.empty()) { + uriMap_.erase(iter++); + continue; + } + ++iter; + } +} + +void UriPermissionManagerStubImpl::RevokeUriPermission(const TokenId tokenId, int32_t abilityId) +{ + TAG_LOGI(AAFwkTag::URIPERMMGR, + "Start to remove uri permission, tokenId is %{public}u, abilityId is %{public}d", tokenId, abilityId); if (!IsFoundationCall()) { TAG_LOGE(AAFwkTag::URIPERMMGR, "No permission to revoke uri permission."); return; } std::vector uriList; - { - std::lock_guard guard(mutex_); - for (auto iter = uriMap_.begin(); iter != uriMap_.end();) { - auto& list = iter->second; - for (auto it = list.begin(); it != list.end(); it++) { - if (it->targetTokenId == tokenId && it->autoRemove) { - TAG_LOGI(AAFwkTag::URIPERMMGR, "Erase an info form list."); - list.erase(it); - uriList.emplace_back(iter->first); - break; - } - } - if (list.empty()) { - uriMap_.erase(iter++); - continue; - } - iter++; - } - } + RemoveUriRecord(uriList, tokenId, abilityId); if (!uriList.empty()) { DeleteShareFile(tokenId, uriList); } @@ -737,7 +745,8 @@ int32_t UriPermissionManagerStubImpl::GetCurrentAccountId() const } int UriPermissionManagerStubImpl::GrantUriPermissionFor2In1Inner(const std::vector &uriVec, unsigned int flag, - const std::string &targetBundleName, int32_t appIndex, bool isSystemAppCall, uint32_t initiatorTokenId) + const std::string &targetBundleName, int32_t appIndex, bool isSystemAppCall, uint32_t initiatorTokenId, + int32_t abilityId) { TAG_LOGI(AAFwkTag::URIPERMMGR, "UriVec size is %{public}zu, targetBundleName is %{public}s", uriVec.size(), targetBundleName.c_str()); @@ -766,7 +775,7 @@ int UriPermissionManagerStubImpl::GrantUriPermissionFor2In1Inner(const std::vect } } if (!otherVec.empty()) { - auto ret = GrantUriPermissionInner(otherVec, flag, targetBundleName, appIndex, initiatorTokenId); + auto ret = GrantUriPermissionInner(otherVec, flag, targetBundleName, appIndex, initiatorTokenId, abilityId); if (docsVec.empty()) { return ret; } @@ -836,6 +845,25 @@ bool UriPermissionManagerStubImpl::IsFoundationCall() return nativeInfo.processName == FOUNDATION_PROCESS_NAME; } +bool UriPermissionManagerStubImpl::IsLinuxFusionCall() +{ + auto callerTokenId = IPCSkeleton::GetCallingTokenID(); + TAG_LOGD(AAFwkTag::ABILITYMGR, "callerTokenId is %{public}u", callerTokenId); + auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerTokenId); + if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "Is not native call"); + return false; + } + Security::AccessToken::NativeTokenInfo nativeInfo; + auto result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(callerTokenId, nativeInfo); + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::URIPERMMGR, "GetNativeTokenInfo failed, callerTokenId is %{public}u.", callerTokenId); + return false; + } + TAG_LOGD(AAFwkTag::URIPERMMGR, "Caller process name : %{public}s", nativeInfo.processName.c_str()); + return nativeInfo.processName == LINUX_FUSION_SERVICE; +} + std::string UriPermissionManagerStubImpl::GetTokenName(uint32_t callerTokenId) { auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerTokenId); @@ -931,6 +959,14 @@ bool UriPermissionManagerStubImpl::CheckUriPermission(Uri uri, uint32_t flag, To { auto &&authority = uri.GetAuthority(); TAG_LOGD(AAFwkTag::URIPERMMGR, "Authority of uri is %{public}s", authority.c_str()); + if (IsLinuxFusionCall()) { + TAG_LOGI(AAFwkTag::URIPERMMGR, "Caller is linux_fusion_service."); + return true; + } + if (uri.GetScheme() == "content") { + TAG_LOGI(AAFwkTag::URIPERMMGR, "uri is content type."); + return IsFoundationCall(); + } if (authority == "docs") { return AccessDocsUriPermission(tokenIdPermission, uri, flag); } diff --git a/test/fuzztest/abilityattachtimeout_fuzzer/BUILD.gn b/test/fuzztest/abilityattachtimeout_fuzzer/BUILD.gn index 771d0e26c0..d3733d99fc 100755 --- a/test/fuzztest/abilityattachtimeout_fuzzer/BUILD.gn +++ b/test/fuzztest/abilityattachtimeout_fuzzer/BUILD.gn @@ -37,6 +37,7 @@ ohos_fuzztest("AbilityAttachTimeOutFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilityconnectionstub_fuzzer/BUILD.gn b/test/fuzztest/abilityconnectionstub_fuzzer/BUILD.gn index f62f1d3da8..0bb04b5efb 100755 --- a/test/fuzztest/abilityconnectionstub_fuzzer/BUILD.gn +++ b/test/fuzztest/abilityconnectionstub_fuzzer/BUILD.gn @@ -37,6 +37,7 @@ ohos_fuzztest("AbilityConnectionStubFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", ] diff --git a/test/fuzztest/abilityconnectmanager_fuzzer/BUILD.gn b/test/fuzztest/abilityconnectmanager_fuzzer/BUILD.gn index 0e7f222d54..f9e6ff61d7 100755 --- a/test/fuzztest/abilityconnectmanager_fuzzer/BUILD.gn +++ b/test/fuzztest/abilityconnectmanager_fuzzer/BUILD.gn @@ -40,6 +40,7 @@ ohos_fuzztest("AbilityConnectManagerFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitycontext_fuzzer/BUILD.gn b/test/fuzztest/abilitycontext_fuzzer/BUILD.gn index 3c53cf75b0..47dd309f71 100644 --- a/test/fuzztest/abilitycontext_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitycontext_fuzzer/BUILD.gn @@ -37,6 +37,7 @@ ohos_fuzztest("AbilityContextFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilityeventhandler_fuzzer/BUILD.gn b/test/fuzztest/abilityeventhandler_fuzzer/BUILD.gn index daa520de28..5506eada53 100755 --- a/test/fuzztest/abilityeventhandler_fuzzer/BUILD.gn +++ b/test/fuzztest/abilityeventhandler_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityEventHandlerFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerservicea_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerservicea_fuzzer/BUILD.gn index 73079c39a7..4e51173aa0 100755 --- a/test/fuzztest/abilitymanagerservicea_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerservicea_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceAFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", diff --git a/test/fuzztest/abilitymanagerserviceb_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerserviceb_fuzzer/BUILD.gn index 7ec8b38744..cd9a3cecb1 100755 --- a/test/fuzztest/abilitymanagerserviceb_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerserviceb_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceBFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerservicec_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerservicec_fuzzer/BUILD.gn index 6c034eb93a..bcc90493c8 100755 --- a/test/fuzztest/abilitymanagerservicec_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerservicec_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceCFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerserviced_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerserviced_fuzzer/BUILD.gn index 1ac35edb54..b4cb78b44b 100755 --- a/test/fuzztest/abilitymanagerserviced_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerserviced_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceDFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerservicee_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerservicee_fuzzer/BUILD.gn index 41ec187e4d..63dac87932 100755 --- a/test/fuzztest/abilitymanagerservicee_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerservicee_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceEFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerserviceeighth_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerserviceeighth_fuzzer/BUILD.gn index 64cb793c5c..6105a286fc 100755 --- a/test/fuzztest/abilitymanagerserviceeighth_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerserviceeighth_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceEighthFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerservicef_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerservicef_fuzzer/BUILD.gn index 8d843fe37b..9cc57794ad 100755 --- a/test/fuzztest/abilitymanagerservicef_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerservicef_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceFFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerservicefifth_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerservicefifth_fuzzer/BUILD.gn index 778434d0dc..8dd74d191b 100755 --- a/test/fuzztest/abilitymanagerservicefifth_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerservicefifth_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceFifthFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerservicefirst_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerservicefirst_fuzzer/BUILD.gn index e63a0940a8..14602e39e3 100755 --- a/test/fuzztest/abilitymanagerservicefirst_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerservicefirst_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceFirstFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerservicefourth_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerservicefourth_fuzzer/BUILD.gn index 44577ba64d..d1e0f79a90 100755 --- a/test/fuzztest/abilitymanagerservicefourth_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerservicefourth_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceFourthFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerserviceg_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerserviceg_fuzzer/BUILD.gn index 622138a79e..4288d57319 100755 --- a/test/fuzztest/abilitymanagerserviceg_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerserviceg_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceGFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerserviceh_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerserviceh_fuzzer/BUILD.gn index bfd2a64720..afc9881307 100755 --- a/test/fuzztest/abilitymanagerserviceh_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerserviceh_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceHFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerserviceninth_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerserviceninth_fuzzer/BUILD.gn index 0d969cd805..9ddb03738c 100755 --- a/test/fuzztest/abilitymanagerserviceninth_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerserviceninth_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceNinthFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerservicesecond_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerservicesecond_fuzzer/BUILD.gn index 5648407d8b..966267ec74 100755 --- a/test/fuzztest/abilitymanagerservicesecond_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerservicesecond_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceSecondFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", diff --git a/test/fuzztest/abilitymanagerserviceseventh_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerserviceseventh_fuzzer/BUILD.gn index 9a70012b90..0927f5d145 100755 --- a/test/fuzztest/abilitymanagerserviceseventh_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerserviceseventh_fuzzer/BUILD.gn @@ -43,6 +43,7 @@ ohos_fuzztest("AbilityManagerServiceSeventhFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerservicesixth_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerservicesixth_fuzzer/BUILD.gn index dfbaf6e38f..b574badab3 100755 --- a/test/fuzztest/abilitymanagerservicesixth_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerservicesixth_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceSixthFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilitymanagerservicetenth_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerservicetenth_fuzzer/BUILD.gn index 421bd00ee0..332fe1c9e4 100755 --- a/test/fuzztest/abilitymanagerservicetenth_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerservicetenth_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceTenthFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", diff --git a/test/fuzztest/abilitymanagerservicethird_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagerservicethird_fuzzer/BUILD.gn index 8a00c515a4..d662527a70 100755 --- a/test/fuzztest/abilitymanagerservicethird_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitymanagerservicethird_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("AbilityManagerServiceThirdFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/fuzztest/abilityrunningrecord_fuzzer/BUILD.gn b/test/fuzztest/abilityrunningrecord_fuzzer/BUILD.gn index 649c04b289..db164a19cb 100644 --- a/test/fuzztest/abilityrunningrecord_fuzzer/BUILD.gn +++ b/test/fuzztest/abilityrunningrecord_fuzzer/BUILD.gn @@ -37,6 +37,7 @@ ohos_fuzztest("AbilityRunningRecordFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/appmgr:libappms", diff --git a/test/fuzztest/abilityschedulerstub_fuzzer/BUILD.gn b/test/fuzztest/abilityschedulerstub_fuzzer/BUILD.gn index 727a04eda9..fc78fff8b2 100755 --- a/test/fuzztest/abilityschedulerstub_fuzzer/BUILD.gn +++ b/test/fuzztest/abilityschedulerstub_fuzzer/BUILD.gn @@ -37,6 +37,7 @@ ohos_fuzztest("AbilitySchedulerStubFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubabilityrecovery_fuzzer/BUILD.gn b/test/fuzztest/abilitystubabilityrecovery_fuzzer/BUILD.gn index 30a86a1f75..7047c16935 100644 --- a/test/fuzztest/abilitystubabilityrecovery_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubabilityrecovery_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubAbilityRecoveryFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubabilityrecoveryenable_fuzzer/BUILD.gn b/test/fuzztest/abilitystubabilityrecoveryenable_fuzzer/BUILD.gn index ef4559df5c..95754f43bc 100644 --- a/test/fuzztest/abilitystubabilityrecoveryenable_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubabilityrecoveryenable_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubAbilityRecoveryEnableFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubabilitytransitiondone_fuzzer/BUILD.gn b/test/fuzztest/abilitystubabilitytransitiondone_fuzzer/BUILD.gn index b2431586df..e616f1b96d 100644 --- a/test/fuzztest/abilitystubabilitytransitiondone_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubabilitytransitiondone_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubAbilityTransitionDoneFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubacquiredataability_fuzzer/BUILD.gn b/test/fuzztest/abilitystubacquiredataability_fuzzer/BUILD.gn index 86622fd924..7af68bd394 100644 --- a/test/fuzztest/abilitystubacquiredataability_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubacquiredataability_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubAcquireDataAbilityFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubacquiresharedata_fuzzer/BUILD.gn b/test/fuzztest/abilitystubacquiresharedata_fuzzer/BUILD.gn index be6a4c9a67..d520444cf1 100644 --- a/test/fuzztest/abilitystubacquiresharedata_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubacquiresharedata_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubAcquireShareDataFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubaddfreeinstallobserver_fuzzer/BUILD.gn b/test/fuzztest/abilitystubaddfreeinstallobserver_fuzzer/BUILD.gn index 6ba8a5111e..33ef4b56f5 100644 --- a/test/fuzztest/abilitystubaddfreeinstallobserver_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubaddfreeinstallobserver_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubAddFreeInstallObserverFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubattachabilitythread_fuzzer/BUILD.gn b/test/fuzztest/abilitystubattachabilitythread_fuzzer/BUILD.gn index 927ed464fd..4ede9c716c 100644 --- a/test/fuzztest/abilitystubattachabilitythread_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubattachabilitythread_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubAttachAbilityThreadFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubcallrequestdone_fuzzer/BUILD.gn b/test/fuzztest/abilitystubcallrequestdone_fuzzer/BUILD.gn index 9009e7bc9a..e5972b6565 100644 --- a/test/fuzztest/abilitystubcallrequestdone_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubcallrequestdone_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubCallRequestDoneFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubcalluiabilitybyscb_fuzzer/BUILD.gn b/test/fuzztest/abilitystubcalluiabilitybyscb_fuzzer/BUILD.gn index 480c2e37e8..aa763bfac0 100644 --- a/test/fuzztest/abilitystubcalluiabilitybyscb_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubcalluiabilitybyscb_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubCallUIAbilityBySCBFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubcancelwantsender_fuzzer/BUILD.gn b/test/fuzztest/abilitystubcancelwantsender_fuzzer/BUILD.gn index 80fa977784..47a0d5e70b 100644 --- a/test/fuzztest/abilitystubcancelwantsender_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubcancelwantsender_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubCancelWantSenderFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubcheckuiextensionisfocused_fuzzer/BUILD.gn b/test/fuzztest/abilitystubcheckuiextensionisfocused_fuzzer/BUILD.gn index 14f58de8cf..2100e56e07 100644 --- a/test/fuzztest/abilitystubcheckuiextensionisfocused_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubcheckuiextensionisfocused_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubCheckUIExtensionIsFocusedFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubcleanallmissions_fuzzer/BUILD.gn b/test/fuzztest/abilitystubcleanallmissions_fuzzer/BUILD.gn index bdeb244b18..32d1bc70fd 100644 --- a/test/fuzztest/abilitystubcleanallmissions_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubcleanallmissions_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubCleanAllMissionsFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubcleanmission_fuzzer/BUILD.gn b/test/fuzztest/abilitystubcleanmission_fuzzer/BUILD.gn index 396ff302c9..91e7789c24 100644 --- a/test/fuzztest/abilitystubcleanmission_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubcleanmission_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubCleanMissionFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubclearupapplicationdata_fuzzer/BUILD.gn b/test/fuzztest/abilitystubclearupapplicationdata_fuzzer/BUILD.gn index 54d1ba0658..91d563fabf 100644 --- a/test/fuzztest/abilitystubclearupapplicationdata_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubclearupapplicationdata_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubClearUpApplicationDataFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubcommandabilitydone_fuzzer/BUILD.gn b/test/fuzztest/abilitystubcommandabilitydone_fuzzer/BUILD.gn index 8b9874fd0f..e145a5ed98 100644 --- a/test/fuzztest/abilitystubcommandabilitydone_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubcommandabilitydone_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubCommandAbilityDoneFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubcommandabilitywindowdone_fuzzer/BUILD.gn b/test/fuzztest/abilitystubcommandabilitywindowdone_fuzzer/BUILD.gn index 232cba6a86..88f25224f3 100644 --- a/test/fuzztest/abilitystubcommandabilitywindowdone_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubcommandabilitywindowdone_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubCommandAbilityWindowDoneFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubcompletefirstframedrawing_fuzzer/BUILD.gn b/test/fuzztest/abilitystubcompletefirstframedrawing_fuzzer/BUILD.gn index 59027825f5..8c537336fa 100644 --- a/test/fuzztest/abilitystubcompletefirstframedrawing_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubcompletefirstframedrawing_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubCompleteFirstFrameDrawingFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubconnectability_fuzzer/BUILD.gn b/test/fuzztest/abilitystubconnectability_fuzzer/BUILD.gn index 5377286020..c5e2dd2001 100644 --- a/test/fuzztest/abilitystubconnectability_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubconnectability_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubConnectAbilityFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubconnectabilitydone_fuzzer/BUILD.gn b/test/fuzztest/abilitystubconnectabilitydone_fuzzer/BUILD.gn index 9651494d80..833900f46c 100644 --- a/test/fuzztest/abilitystubconnectabilitydone_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubconnectabilitydone_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubConnectAbilityDoneFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubconnectabilitywithtype_fuzzer/BUILD.gn b/test/fuzztest/abilitystubconnectabilitywithtype_fuzzer/BUILD.gn index 3eca10fc80..5b2b7efad3 100644 --- a/test/fuzztest/abilitystubconnectabilitywithtype_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubconnectabilitywithtype_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubConnectAbilityWithTypeFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubconnectuiextensionability_fuzzer/BUILD.gn b/test/fuzztest/abilitystubconnectuiextensionability_fuzzer/BUILD.gn index 62410906b6..ca0922785b 100644 --- a/test/fuzztest/abilitystubconnectuiextensionability_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubconnectuiextensionability_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubConnectUIExtensionAbilityFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubcontinueability_fuzzer/BUILD.gn b/test/fuzztest/abilitystubcontinueability_fuzzer/BUILD.gn index 8b509b0413..7e28679944 100644 --- a/test/fuzztest/abilitystubcontinueability_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubcontinueability_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubContinueAbilityFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubcontinuemission_fuzzer/BUILD.gn b/test/fuzztest/abilitystubcontinuemission_fuzzer/BUILD.gn index da920044c0..687017ee68 100644 --- a/test/fuzztest/abilitystubcontinuemission_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubcontinuemission_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubContinueMissionFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubcontinuemissionofbundlename_fuzzer/BUILD.gn b/test/fuzztest/abilitystubcontinuemissionofbundlename_fuzzer/BUILD.gn index ed26f471e4..a876b7ee9d 100644 --- a/test/fuzztest/abilitystubcontinuemissionofbundlename_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubcontinuemissionofbundlename_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubContinueMissionOfBundlenameFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubdelegatordoabilitybackground_fuzzer/BUILD.gn b/test/fuzztest/abilitystubdelegatordoabilitybackground_fuzzer/BUILD.gn index eef6a3e9b7..6511b4be24 100644 --- a/test/fuzztest/abilitystubdelegatordoabilitybackground_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubdelegatordoabilitybackground_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubDelegatorDoAbilityBackgroundFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubdelegatordoabilityforeground_fuzzer/BUILD.gn b/test/fuzztest/abilitystubdelegatordoabilityforeground_fuzzer/BUILD.gn index 94757e6e4c..8828c156cb 100644 --- a/test/fuzztest/abilitystubdelegatordoabilityforeground_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubdelegatordoabilityforeground_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubDelegatorDoAbilityForegroundFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubdisconnectability_fuzzer/BUILD.gn b/test/fuzztest/abilitystubdisconnectability_fuzzer/BUILD.gn index f3274da1eb..89dfd20061 100644 --- a/test/fuzztest/abilitystubdisconnectability_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubdisconnectability_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubDisconnectAbilityFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubdisconnectabilitydone_fuzzer/BUILD.gn b/test/fuzztest/abilitystubdisconnectabilitydone_fuzzer/BUILD.gn index c930e9934f..b9f7c38d4a 100644 --- a/test/fuzztest/abilitystubdisconnectabilitydone_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubdisconnectabilitydone_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubDisConnectAbilityDoneFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubdoabilitybackground_fuzzer/BUILD.gn b/test/fuzztest/abilitystubdoabilitybackground_fuzzer/BUILD.gn index 17892edc32..fee3c66926 100644 --- a/test/fuzztest/abilitystubdoabilitybackground_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubdoabilitybackground_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubDoAbilityBackgroundFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubdoabilityforeground_fuzzer/BUILD.gn b/test/fuzztest/abilitystubdoabilityforeground_fuzzer/BUILD.gn index 81792f3507..af970db105 100644 --- a/test/fuzztest/abilitystubdoabilityforeground_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubdoabilityforeground_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubDoAbilityForegroundFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubdumpabilityinfodone_fuzzer/BUILD.gn b/test/fuzztest/abilitystubdumpabilityinfodone_fuzzer/BUILD.gn index 553fb3bd1e..f3513eca61 100644 --- a/test/fuzztest/abilitystubdumpabilityinfodone_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubdumpabilityinfodone_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubDumpAbilityInfoDoneFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubdumpstate_fuzzer/BUILD.gn b/test/fuzztest/abilitystubdumpstate_fuzzer/BUILD.gn index f7dab79795..4255abd364 100644 --- a/test/fuzztest/abilitystubdumpstate_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubdumpstate_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubDumpStateFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubdumpsysstate_fuzzer/BUILD.gn b/test/fuzztest/abilitystubdumpsysstate_fuzzer/BUILD.gn index a8fb25202f..3c99f909a1 100644 --- a/test/fuzztest/abilitystubdumpsysstate_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubdumpsysstate_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubDumpsysStateFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubfinishusertest_fuzzer/BUILD.gn b/test/fuzztest/abilitystubfinishusertest_fuzzer/BUILD.gn index 8d2b23c65f..5e58c35935 100644 --- a/test/fuzztest/abilitystubfinishusertest_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubfinishusertest_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubFinishUserTestFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubforceexitapp_fuzzer/BUILD.gn b/test/fuzztest/abilitystubforceexitapp_fuzzer/BUILD.gn index 5150b16e13..5db9b7786b 100644 --- a/test/fuzztest/abilitystubforceexitapp_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubforceexitapp_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubForceExitAppFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubfreeinstallabilityfromremote_fuzzer/BUILD.gn b/test/fuzztest/abilitystubfreeinstallabilityfromremote_fuzzer/BUILD.gn index 580174d597..f32ce33d18 100644 --- a/test/fuzztest/abilitystubfreeinstallabilityfromremote_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubfreeinstallabilityfromremote_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubFreeInstallAbilityFromRemoteFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetabilityrunninginfo_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetabilityrunninginfo_fuzzer/BUILD.gn index 02260bae84..12c70af6b7 100644 --- a/test/fuzztest/abilitystubgetabilityrunninginfo_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetabilityrunninginfo_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetAbilityRunningInfoFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetabilitystatebypersistentid_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetabilitystatebypersistentid_fuzzer/BUILD.gn index 51a75c814a..368375698a 100644 --- a/test/fuzztest/abilitystubgetabilitystatebypersistentid_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetabilitystatebypersistentid_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetAbilityStateByPersistentIdFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetabilitytoken_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetabilitytoken_fuzzer/BUILD.gn index 0ebd746eb1..5fe603fdc0 100644 --- a/test/fuzztest/abilitystubgetabilitytoken_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetabilitytoken_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubGetAbilityTokenFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetappmemorysize_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetappmemorysize_fuzzer/BUILD.gn index 854503486e..eb011bef36 100644 --- a/test/fuzztest/abilitystubgetappmemorysize_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetappmemorysize_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubGetAppMemorySizeFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetdlpconnectioninfos_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetdlpconnectioninfos_fuzzer/BUILD.gn index ec109fbf28..20ffacd22c 100644 --- a/test/fuzztest/abilitystubgetdlpconnectioninfos_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetdlpconnectioninfos_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetDlpConnectionInfosFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetelementnamebytoken_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetelementnamebytoken_fuzzer/BUILD.gn index c721c4b1ac..6496f768c8 100644 --- a/test/fuzztest/abilitystubgetelementnamebytoken_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetelementnamebytoken_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetElementNameByTokenFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetextensionrunninginfo_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetextensionrunninginfo_fuzzer/BUILD.gn index 7187977f3a..0dd7c010e9 100644 --- a/test/fuzztest/abilitystubgetextensionrunninginfo_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetextensionrunninginfo_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetExtensionRunningInfoFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetmissionidbytoken_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetmissionidbytoken_fuzzer/BUILD.gn index 98fe009936..39789456f5 100644 --- a/test/fuzztest/abilitystubgetmissionidbytoken_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetmissionidbytoken_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetMissionIdByTokenFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetmissioninfo_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetmissioninfo_fuzzer/BUILD.gn index 9627b08830..5878007094 100644 --- a/test/fuzztest/abilitystubgetmissioninfo_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetmissioninfo_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubGetMissionInfoFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetmissioninfos_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetmissioninfos_fuzzer/BUILD.gn index 58cbfdec9e..216cd70fe8 100644 --- a/test/fuzztest/abilitystubgetmissioninfos_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetmissioninfos_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubGetMissionInfosFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetmissionsnapshotinfo_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetmissionsnapshotinfo_fuzzer/BUILD.gn index 4a4d11620b..0875e9448c 100644 --- a/test/fuzztest/abilitystubgetmissionsnapshotinfo_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetmissionsnapshotinfo_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetMissionSnapShotInfoFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetpendingrequestwant_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetpendingrequestwant_fuzzer/BUILD.gn index 3e5919c780..ec3dfc7a49 100644 --- a/test/fuzztest/abilitystubgetpendingrequestwant_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetpendingrequestwant_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetPendingRequestWantFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetpendingwantbundlename_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetpendingwantbundlename_fuzzer/BUILD.gn index 579773ff79..f2d91d0790 100644 --- a/test/fuzztest/abilitystubgetpendingwantbundlename_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetpendingwantbundlename_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetPendingWantBundleNameFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetpendingwantcode_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetpendingwantcode_fuzzer/BUILD.gn index 63a733b7b7..09f9922a95 100644 --- a/test/fuzztest/abilitystubgetpendingwantcode_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetpendingwantcode_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetPendingWantCodeFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetpendingwanttype_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetpendingwanttype_fuzzer/BUILD.gn index 1b6a0e171a..fb1a41bfca 100644 --- a/test/fuzztest/abilitystubgetpendingwanttype_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetpendingwanttype_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetPendingWantTypeFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetpendingwantuid_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetpendingwantuid_fuzzer/BUILD.gn index dba956a1b4..476a09f7b6 100644 --- a/test/fuzztest/abilitystubgetpendingwantuid_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetpendingwantuid_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetPendingWantUidFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetpendingwantuserid_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetpendingwantuserid_fuzzer/BUILD.gn index ad1beb12b1..4d641a195a 100644 --- a/test/fuzztest/abilitystubgetpendingwantuserid_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetpendingwantuserid_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetPendingWantUserIdFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgetprocessrunninginfo_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgetprocessrunninginfo_fuzzer/BUILD.gn index 4036c87ba7..0b6892054e 100644 --- a/test/fuzztest/abilitystubgetprocessrunninginfo_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgetprocessrunninginfo_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetProcessRunningInfoFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgettopability_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgettopability_fuzzer/BUILD.gn index 25114cf108..5abe12f801 100644 --- a/test/fuzztest/abilitystubgettopability_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgettopability_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("AbilityStubGetTopAbilityFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/abilitystubgettopabilitytoken_fuzzer/BUILD.gn b/test/fuzztest/abilitystubgettopabilitytoken_fuzzer/BUILD.gn index e4695e463d..7bb8b0b013 100644 --- a/test/fuzztest/abilitystubgettopabilitytoken_fuzzer/BUILD.gn +++ b/test/fuzztest/abilitystubgettopabilitytoken_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("AbilityStubGetTopAbilityTokenFuzzTest") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/fuzztest/appmgrservicefirst_fuzzer/appmgrservicefirst_fuzzer.cpp b/test/fuzztest/appmgrservicefirst_fuzzer/appmgrservicefirst_fuzzer.cpp index 215800a1dd..a75df1c6b3 100644 --- a/test/fuzztest/appmgrservicefirst_fuzzer/appmgrservicefirst_fuzzer.cpp +++ b/test/fuzztest/appmgrservicefirst_fuzzer/appmgrservicefirst_fuzzer.cpp @@ -105,7 +105,7 @@ bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) appMgrService->Dump(fd, args); std::string result(data, size); appMgrService->Dump(args, result); - appMgrService->ShowHelp(result); + appMgrService->ShowHelp(args, result); std::string flag(data, size); appMgrService->ScheduleAcceptWantDone(recordId, *want, flag); Configuration config; diff --git a/test/mock/frameworks_kits_ability_native_test/include/mock_ui_content.h b/test/mock/frameworks_kits_ability_native_test/include/mock_ui_content.h index 2b1a016ecd..fc6bcbc36c 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/mock_ui_content.h +++ b/test/mock/frameworks_kits_ability_native_test/include/mock_ui_content.h @@ -41,9 +41,9 @@ public: MOCK_METHOD0(UnFocus, void()); MOCK_METHOD0(Destroy, void()); MOCK_METHOD1(OnNewWant, void(const OHOS::AAFwk::Want &want)); - MOCK_METHOD3(Restore, UIContentErrorCode(OHOS::Rosen::Window *window, const std::string &contentInfo, - napi_value storage)); - MOCK_CONST_METHOD0(GetContentInfo, std::string()); + MOCK_METHOD4(Restore, UIContentErrorCode(OHOS::Rosen::Window *window, const std::string &contentInfo, + napi_value storage, ContentInfoType type)); + MOCK_CONST_METHOD1(GetContentInfo, std::string(ContentInfoType type)); MOCK_METHOD0(DestroyUIDirector, void()); MOCK_METHOD0(ProcessBackPressed, bool()); MOCK_METHOD1(ProcessPointerEvent, bool(const std::shared_ptr &pointerEvent)); diff --git a/test/mock/frameworks_kits_ability_native_test/include/mock_window.h b/test/mock/frameworks_kits_ability_native_test/include/mock_window.h index ca7e5a306b..d84611973b 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/mock_window.h +++ b/test/mock/frameworks_kits_ability_native_test/include/mock_window.h @@ -151,9 +151,9 @@ public: virtual void NotifyTouchDialogTarget(int32_t posX = 0, int32_t posY = 0) {} virtual void SetAceAbilityHandler(const sptr& handler) {} virtual WMError NapiSetUIContent(const std::string& contentInfo, napi_env env, napi_value storage, - bool isDistributed = false, sptr token = nullptr, + BackupAndRestoreType type = BackupAndRestoreType::NONE, sptr token = nullptr, AppExecFwk::Ability* ability = nullptr) {return WMError::WM_OK;} - virtual std::string GetContentInfo() {return "";} + virtual std::string GetContentInfo(BackupAndRestoreType type = BackupAndRestoreType::CONTINUATION) {return "";} virtual Ace::UIContent* GetUIContent() const {return nullptr;} virtual void OnNewWant(const AAFwk::Want& want) {} virtual void SetRequestedOrientation(Orientation) {} diff --git a/test/mock/frameworks_kits_appkit_test/include/mock_app_mgr_service.h b/test/mock/frameworks_kits_appkit_test/include/mock_app_mgr_service.h index 16a3d7c22f..1d1c9cef11 100644 --- a/test/mock/frameworks_kits_appkit_test/include/mock_app_mgr_service.h +++ b/test/mock/frameworks_kits_appkit_test/include/mock_app_mgr_service.h @@ -55,10 +55,11 @@ public: MOCK_METHOD0(BlockAppService, int()); #endif MOCK_METHOD0(PreStartNWebSpawnProcess, int()); - MOCK_METHOD5(StartRenderProcess, + MOCK_METHOD6(StartRenderProcess, int(const std::string &renderParam, int32_t ipcFd, - int32_t sharedFd, int32_t crashFd, pid_t &renderPid)); + int32_t sharedFd, int32_t crashFd, pid_t &renderPid, bool isGPU)); MOCK_METHOD1(AttachRenderProcess, void(const sptr& renderScheduler)); + MOCK_METHOD1(SaveBrowserChannel, void(sptr browser)); MOCK_METHOD2(GetRenderProcessTerminationStatus, int(pid_t renderPid, int& status)); MOCK_METHOD1(GetConfiguration, int32_t(Configuration& config)); MOCK_METHOD1(UpdateConfiguration, int32_t(const Configuration& config)); @@ -83,6 +84,11 @@ public: MOCK_METHOD1(RegisterRenderStateObserver, int32_t(const sptr &observer)); MOCK_METHOD1(UnregisterRenderStateObserver, int32_t(const sptr &observer)); MOCK_METHOD2(UpdateRenderState, int32_t(pid_t renderPid, int32_t state)); + MOCK_METHOD1(SetSupportedProcessCacheSelf, int32_t(bool isSupported)); + MOCK_METHOD2(GetRunningMultiAppInfoByBundleName, int32_t(const std::string &bundleName, + RunningMultiAppInfo &info)); + MOCK_METHOD3(StartNativeChildProcess, int32_t(const std::string &libName, int32_t childProcessCount, + const sptr &callback)); void AttachApplication(const sptr& app) { diff --git a/test/mock/frameworks_kits_runtime_test/mock_runtime.h b/test/mock/frameworks_kits_runtime_test/mock_runtime.h index 5742d1f2ef..37e03ebdfa 100644 --- a/test/mock/frameworks_kits_runtime_test/mock_runtime.h +++ b/test/mock/frameworks_kits_runtime_test/mock_runtime.h @@ -124,7 +124,8 @@ public: void StartProfiler(const DebugOption debugOption) override {} void DoCleanWorkAfterStageCleaned() override {} - void DumpHeapSnapshot(uint32_t tid, bool isFullGC) override {} + void DumpHeapSnapshot(uint32_t tid, bool isFullGC, std::vector fdVec, + std::vector tidVec) override {} void ForceFullGC(uint32_t tid) override {} public: Language language; diff --git a/test/mock/mock_appmgr_service/include/mock_app_mgr_service_inner.h b/test/mock/mock_appmgr_service/include/mock_app_mgr_service_inner.h index 53ebaddcb8..12e5464304 100644 --- a/test/mock/mock_appmgr_service/include/mock_app_mgr_service_inner.h +++ b/test/mock/mock_appmgr_service/include/mock_app_mgr_service_inner.h @@ -65,7 +65,9 @@ public: int32_t childProcessCount, bool inStartWithDebug)); MOCK_METHOD1(GetChildProcessInfoForSelf, int32_t(ChildProcessInfo &info)); MOCK_METHOD4(PreloadApplication, int32_t(const std::string&, int32_t, AppExecFwk::PreloadMode, int32_t)); - void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) + MOCK_METHOD4(StartNativeChildProcess, int32_t(const pid_t hostPid, const std::string &libName, + int32_t childProcessCount, const sptr &callback)); + void StartSpecifiedAbility(const AAFwk::Want&, const AppExecFwk::AbilityInfo&, int32_t) {} void Post() diff --git a/test/mock/mock_sa_call/mock_sa_call.h b/test/mock/mock_sa_call/mock_sa_call.h index 52ca425f0c..c047fba8b3 100644 --- a/test/mock/mock_sa_call/mock_sa_call.h +++ b/test/mock/mock_sa_call/mock_sa_call.h @@ -89,6 +89,28 @@ public: SetSelfTokenID(tokenId); Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); } + + static void IsMockProcessCachePermission() + { + uint64_t tokenId; + const char* perms[] = { + perms[0] = "ohos.permission.SET_PROCESS_CACHE_STATE", + }; + + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = static_cast(sizeof(perms)/sizeof(perms[0])), + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .aplStr = "system_core", + }; + infoInstance.processName = "distributedsched"; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); + } }; } // namespace OHOS::AAFwk #endif // UNITTEST_OHOS_ABILITY_RUNTIME_IS_SA_CALL_TEST_H \ No newline at end of file diff --git a/test/mock/services_abilitymgr_test/appmgr_test_service/BUILD.gn b/test/mock/services_abilitymgr_test/appmgr_test_service/BUILD.gn index 2f8fb950a4..4a6f1f1652 100644 --- a/test/mock/services_abilitymgr_test/appmgr_test_service/BUILD.gn +++ b/test/mock/services_abilitymgr_test/appmgr_test_service/BUILD.gn @@ -19,7 +19,6 @@ config("appmgr_test_service_config") { "${ability_runtime_test_path}/mock/services_abilitymgr_test/appmgr_test_service/include/", "${ability_runtime_services_path}/abilitymgr/include", "${ability_runtime_innerkits_path}/ability_manager/include", - "${bundlefwk_inner_api_path}/appexecfwk_core/include", "${ability_runtime_innerkits_path}/app_manager/include", "${ability_runtime_path}/interfaces/kits/native/ability/native", "${ability_runtime_services_path}/common/include", @@ -29,9 +28,7 @@ config("appmgr_test_service_config") { ohos_source_set("appmgr_test_service") { include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", - "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit/include", - "//third_party/jsoncpp/include", ] sources = [ "src/appmgr_test_service.cpp" ] @@ -41,10 +38,7 @@ ohos_source_set("appmgr_test_service") { if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } - deps = [ - "${ability_runtime_innerkits_path}/app_manager:app_manager", - "//third_party/jsoncpp:jsoncpp", - ] + deps = [ "${ability_runtime_innerkits_path}/app_manager:app_manager" ] if (ability_runtime_graphics) { } @@ -58,7 +52,10 @@ ohos_source_set("appmgr_test_service") { "hilog:libhilog", "ipc:ipc_core", ] - + public_external_deps = [ + "jsoncpp:jsoncpp", + "samgr:samgr_proxy", + ] subsystem_name = "ability" part_name = "ability_runtime" } diff --git a/test/mock/services_abilitymgr_test/libs/aakit/BUILD.gn b/test/mock/services_abilitymgr_test/libs/aakit/BUILD.gn index bc5f138fc9..605afbe456 100644 --- a/test/mock/services_abilitymgr_test/libs/aakit/BUILD.gn +++ b/test/mock/services_abilitymgr_test/libs/aakit/BUILD.gn @@ -22,12 +22,11 @@ config("aakit_mock_config") { "${ability_runtime_innerkits_path}/app_manager/include", "${ability_runtime_path}/interfaces/kits/native/ability/native/", "include/", - "//third_party/jsoncpp/include", "${ability_runtime_services_path}/common/include/", ] } -ohos_source_set("aakit_mock") { +ohos_static_library("aakit_mock") { sources = [ "src/ability_scheduler.cpp", "src/mock_ability_connect_callback.cpp", @@ -38,12 +37,7 @@ ohos_source_set("aakit_mock") { if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } - deps = [ - "${ability_runtime_innerkits_path}/app_manager:app_manager", - "${distributedschedule_path}/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - "//third_party/jsoncpp:jsoncpp", - ] + deps = [ "${ability_runtime_innerkits_path}/app_manager:app_manager" ] external_deps = [ "ability_base:base", "ability_base:configuration", @@ -54,7 +48,11 @@ ohos_source_set("aakit_mock") { "c_utils:utils", "ffrt:libffrt", "hilog:libhilog", + "image_framework:image_native", "ipc:ipc_core", + "jsoncpp:jsoncpp", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", ] subsystem_name = "ability" diff --git a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/BUILD.gn b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/BUILD.gn index db60a52479..db078d8ea2 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/BUILD.gn +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/BUILD.gn @@ -28,7 +28,7 @@ config("appexecfwk_core_mock_config") { ] } -ohos_source_set("appexecfwk_appmgr_mock") { +ohos_static_library("appexecfwk_appmgr_mock") { # sources = [ "src/appmgr/mock_app_manager.cpp" ] configs = [ ":appexecfwk_core_mock_config" ] @@ -36,11 +36,7 @@ ohos_source_set("appexecfwk_appmgr_mock") { if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] } - deps = [ - "${ability_runtime_innerkits_path}/app_manager:app_manager", - "${distributedschedule_path}/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - ] + deps = [ "${ability_runtime_innerkits_path}/app_manager:app_manager" ] external_deps = [ "bundle_framework:appexecfwk_base", @@ -50,6 +46,8 @@ ohos_source_set("appexecfwk_appmgr_mock") { "hilog:libhilog", "hitrace:hitrace_meter", "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", ] subsystem_name = "ability" @@ -71,8 +69,6 @@ ohos_source_set("appexecfwk_bundlemgr_mock") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${distributedschedule_path}/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -86,6 +82,8 @@ ohos_source_set("appexecfwk_bundlemgr_mock") { "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", ] subsystem_name = "ability" diff --git a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp index 4f47900554..a788889744 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp @@ -173,7 +173,7 @@ bool AppScheduler::IsMemorySizeSufficent() const return true; } -void AppScheduler::StartSpecifiedAbility(const AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo) +void AppScheduler::StartSpecifiedAbility(const AAFwk::Want&, const AppExecFwk::AbilityInfo&, int32_t) {} int AppScheduler::StartUserTest( @@ -191,6 +191,11 @@ int AppScheduler::GetApplicationInfoByProcessID(const int pid, AppExecFwk::Appli return 0; } +int32_t AppScheduler::NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg) +{ + return 0; +} + int AppScheduler::GetAbilityRecordsByProcessID(const int pid, std::vector>& tokens) { return 0; diff --git a/test/mock/services_abilitymgr_test/libs/sa_mgr/BUILD.gn b/test/mock/services_abilitymgr_test/libs/sa_mgr/BUILD.gn index c148f491bb..947c0b9096 100644 --- a/test/mock/services_abilitymgr_test/libs/sa_mgr/BUILD.gn +++ b/test/mock/services_abilitymgr_test/libs/sa_mgr/BUILD.gn @@ -15,10 +15,7 @@ import("//build/ohos.gni") import("//foundation/ability/ability_runtime/ability_runtime.gni") config("sa_mgr_mock_config") { - include_dirs = [ - "${ability_runtime_innerkits_path}/deps_wrapper/include", - "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", - ] + include_dirs = [ "${ability_runtime_innerkits_path}/deps_wrapper/include" ] cflags = [] if (target_cpu == "arm") { cflags += [ "-DBINDER_IPC_32BIT" ] @@ -32,12 +29,11 @@ ohos_source_set("sa_mgr_mock") { "${ability_runtime_services_path}/common:common_config", ] - deps = [ "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy" ] - external_deps = [ "c_utils:utils", "hilog:libhilog", "ipc:ipc_core", + "samgr:samgr_proxy", ] subsystem_name = "ability" diff --git a/test/mock/services_appmgr_test/include/mock_ams_mgr_scheduler.h b/test/mock/services_appmgr_test/include/mock_ams_mgr_scheduler.h index 67f3454eb9..6ff02ccab4 100644 --- a/test/mock/services_appmgr_test/include/mock_ams_mgr_scheduler.h +++ b/test/mock/services_appmgr_test/include/mock_ams_mgr_scheduler.h @@ -44,13 +44,13 @@ public: MOCK_METHOD1(PrepareTerminate, void(const sptr& token)); MOCK_METHOD2(GetRunningProcessInfoByToken, void(const sptr& token, OHOS::AppExecFwk::RunningProcessInfo& info)); - MOCK_METHOD2(GetRunningProcessInfoByPid, void(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo& info)); MOCK_METHOD1(SetAbilityForegroundingFlagToAppRecord, void(const pid_t pid)); - MOCK_METHOD2(StartSpecifiedAbility, void(const AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo)); - MOCK_METHOD2(StartSpecifiedProcess, void(const AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo)); + MOCK_METHOD3(StartSpecifiedAbility, void(const AAFwk::Want&, const AppExecFwk::AbilityInfo&, int32_t)); + MOCK_METHOD3(StartSpecifiedProcess, void(const AAFwk::Want&, const AppExecFwk::AbilityInfo&, int32_t)); MOCK_METHOD1(RegisterStartSpecifiedAbilityResponse, void(const sptr& response)); MOCK_METHOD3(GetApplicationInfoByProcessID, int(const int pid, AppExecFwk::ApplicationInfo& application, bool& debug)); + MOCK_METHOD3(NotifyAppMgrRecordExitReason, int32_t(int32_t pid, int32_t reason, const std::string &exitMsg)); MOCK_METHOD3(GetBundleNameByPid, int32_t(const int pid, std::string &bundleName, int32_t &uid)); MOCK_METHOD1(RegisterAppDebugListener, int32_t(const sptr &listener)); MOCK_METHOD1(UnregisterAppDebugListener, int32_t(const sptr &listener)); diff --git a/test/mock/services_appmgr_test/include/mock_app_mgr_service.h b/test/mock/services_appmgr_test/include/mock_app_mgr_service.h index 228775be2e..36cf6c7574 100644 --- a/test/mock/services_appmgr_test/include/mock_app_mgr_service.h +++ b/test/mock/services_appmgr_test/include/mock_app_mgr_service.h @@ -56,8 +56,9 @@ public: MOCK_METHOD1(StartupResidentProcess, void(const std::vector& bundleInfos)); MOCK_METHOD1(AddAbilityStageDone, void(const int32_t recordId)); MOCK_METHOD0(PreStartNWebSpawnProcess, int()); - MOCK_METHOD5(StartRenderProcess, int(const std::string&, int32_t, int32_t, int32_t, pid_t&)); + MOCK_METHOD6(StartRenderProcess, int(const std::string&, int32_t, int32_t, int32_t, pid_t&, bool)); MOCK_METHOD1(AttachRenderProcess, void(const sptr& renderScheduler)); + MOCK_METHOD1(SaveBrowserChannel, void(sptr browser)); MOCK_METHOD2(GetRenderProcessTerminationStatus, int(pid_t renderPid, int& status)); MOCK_METHOD2(RegisterApplicationStateObserver, int32_t(const sptr& observer, const std::vector& bundleNameList)); @@ -89,6 +90,8 @@ public: MOCK_METHOD2(GetProcessMemoryByPid, int32_t(const int32_t pid, int32_t & memorySize)); MOCK_METHOD3(GetRunningProcessInformation, int32_t(const std::string & bundleName, int32_t userId, std::vector &info)); + MOCK_METHOD2(GetRunningMultiAppInfoByBundleName, int32_t(const std::string &bundleName, + RunningMultiAppInfo &info)); MOCK_METHOD2(IsApplicationRunning, int32_t(const std::string &bundleName, bool &isRunning)); MOCK_METHOD4(StartChildProcess, int32_t(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount, bool isStartWithNative)); @@ -101,6 +104,8 @@ public: MOCK_METHOD0(IsFinalAppProcess, bool()); MOCK_METHOD1(SetSupportedProcessCacheSelf, int32_t(bool isSupport)); + MOCK_METHOD3(StartNativeChildProcess, int32_t(const std::string &libName, int32_t childProcessCount, + const sptr &callback)); virtual int StartUserTestProcess( const AAFwk::Want &want, const sptr &observer, const BundleInfo &bundleInfo, int32_t userId) { diff --git a/test/mock/services_appmgr_test/include/mock_app_mgr_service_inner.h b/test/mock/services_appmgr_test/include/mock_app_mgr_service_inner.h index 83712f4dfe..f672f7d0f7 100644 --- a/test/mock/services_appmgr_test/include/mock_app_mgr_service_inner.h +++ b/test/mock/services_appmgr_test/include/mock_app_mgr_service_inner.h @@ -71,7 +71,9 @@ public: MOCK_METHOD1(IsWaitingDebugApp, bool(const std::string &bundleName)); MOCK_METHOD0(ClearNonPersistWaitingDebugFlag, void()); MOCK_METHOD0(IsMemorySizeSufficent, bool()); - void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) + MOCK_METHOD4(StartNativeChildProcess, int32_t(const pid_t hostPid, + const std::string &libName, int32_t childProcessCount, const sptr &callback)); + void StartSpecifiedAbility(const AAFwk::Want&, const AppExecFwk::AbilityInfo&, int32_t) {} void Post() diff --git a/test/mock/services_appmgr_test/include/mock_app_scheduler.h b/test/mock/services_appmgr_test/include/mock_app_scheduler.h index c3702a0134..8de91fa1c6 100644 --- a/test/mock/services_appmgr_test/include/mock_app_scheduler.h +++ b/test/mock/services_appmgr_test/include/mock_app_scheduler.h @@ -66,6 +66,7 @@ public: MOCK_METHOD1(ScheduleDumpIpcStop, int32_t(std::string &result)); MOCK_METHOD1(ScheduleDumpIpcStat, int32_t(std::string &result)); MOCK_METHOD0(IsMemorySizeSufficent, bool()); + MOCK_METHOD1(ScheduleDumpFfrt, int32_t(std::string& result)); }; } // namespace AppExecFwk } // namespace OHOS diff --git a/test/mock/services_appmgr_test/include/mock_application.h b/test/mock/services_appmgr_test/include/mock_application.h index fbf6cf32c7..5eea0d49de 100644 --- a/test/mock/services_appmgr_test/include/mock_application.h +++ b/test/mock/services_appmgr_test/include/mock_application.h @@ -60,6 +60,7 @@ public: MOCK_METHOD1(ScheduleDumpIpcStop, int32_t(std::string &result)); MOCK_METHOD1(ScheduleDumpIpcStat, int32_t(std::string &result)); MOCK_METHOD0(IsMemorySizeSufficent, bool()); + MOCK_METHOD1(ScheduleDumpFfrt, int32_t(std::string& result)); void Post() { diff --git a/test/moduletest/ability_caller_fw_module_test/BUILD.gn b/test/moduletest/ability_caller_fw_module_test/BUILD.gn index d2d01a8854..bd8e07e143 100644 --- a/test/moduletest/ability_caller_fw_module_test/BUILD.gn +++ b/test/moduletest/ability_caller_fw_module_test/BUILD.gn @@ -40,6 +40,7 @@ ohos_moduletest("ability_caller_fw_module_test") { "${ability_runtime_innerkits_path}/ability_manager:ability_manager", "${ability_runtime_native_path}/ability:ability_context_native", "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", diff --git a/test/moduletest/ability_delegator_test/BUILD.gn b/test/moduletest/ability_delegator_test/BUILD.gn index 092388dfe1..fc0d86e6c0 100644 --- a/test/moduletest/ability_delegator_test/BUILD.gn +++ b/test/moduletest/ability_delegator_test/BUILD.gn @@ -148,6 +148,7 @@ ohos_moduletest("iability_monitor_moduletest") { deps = [ "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_native_path}/appkit:appkit_delegator", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -223,6 +224,7 @@ ohos_moduletest("js_test_runner_moduletest") { external_deps = [ "ability_base:configuration", + "ability_base:extractortool", "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:runtime", diff --git a/test/moduletest/ability_manager_service_dump_test/ability_manager_service_dump_test.cpp b/test/moduletest/ability_manager_service_dump_test/ability_manager_service_dump_test.cpp index 26f64516b1..a036b86cdf 100644 --- a/test/moduletest/ability_manager_service_dump_test/ability_manager_service_dump_test.cpp +++ b/test/moduletest/ability_manager_service_dump_test/ability_manager_service_dump_test.cpp @@ -66,7 +66,7 @@ HWTEST_F(AbilityManagerServiceDumpTest, AbilityManagerService_GetProcessRunningI auto abilityMs_ = std::make_shared(); std::vector info; auto result = abilityMs_->GetProcessRunningInfosByUserId(info, USER_ID); - EXPECT_NE(result, AppMgrResultCode::RESULT_OK); + EXPECT_EQ(result, AppMgrResultCode::RESULT_OK); } /** @@ -184,7 +184,7 @@ HWTEST_F(AbilityManagerServiceDumpTest, AbilityManagerService_DumpSysProcess_010 bool isClient = false; bool isUserID = true; abilityMs_->DumpSysProcess(args, info, isClient, isUserID, USER_ID); - EXPECT_EQ(info.size(), SIZE_ZERO); + EXPECT_NE(info.size(), SIZE_ZERO); } /** diff --git a/test/moduletest/ability_record_test/BUILD.gn b/test/moduletest/ability_record_test/BUILD.gn index eeaa790118..14c5438b20 100644 --- a/test/moduletest/ability_record_test/BUILD.gn +++ b/test/moduletest/ability_record_test/BUILD.gn @@ -38,6 +38,7 @@ ohos_moduletest("AbilityRecordModuleTest") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", @@ -69,7 +70,7 @@ ohos_moduletest("AbilityRecordModuleTest") { "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", - "c_utils:utilsbase", + "c_utils:utils", "common_event_service:cesfwk_core", "common_event_service:cesfwk_innerkits", "dsoftbus:softbus_client", diff --git a/test/moduletest/ability_test/BUILD.gn b/test/moduletest/ability_test/BUILD.gn index eb0180109b..304b07d7ac 100644 --- a/test/moduletest/ability_test/BUILD.gn +++ b/test/moduletest/ability_test/BUILD.gn @@ -263,6 +263,7 @@ ohos_moduletest("data_ability_helper_module_test") { "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_native_path}/ability/native:data_ability_helper", "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] diff --git a/test/moduletest/ability_timeout_module_test/BUILD.gn b/test/moduletest/ability_timeout_module_test/BUILD.gn index b723189606..af2f95c7d7 100644 --- a/test/moduletest/ability_timeout_module_test/BUILD.gn +++ b/test/moduletest/ability_timeout_module_test/BUILD.gn @@ -61,6 +61,7 @@ ohos_moduletest("ability_timeout_module_test") { "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:event_report", "${ability_runtime_services_path}/common:perm_verification", diff --git a/test/moduletest/common/ams/BUILD.gn b/test/moduletest/common/ams/BUILD.gn index 397ebd424f..7c2c4c6f93 100644 --- a/test/moduletest/common/ams/BUILD.gn +++ b/test/moduletest/common/ams/BUILD.gn @@ -32,7 +32,6 @@ ohos_source_set("appmgr_mst_source") { public_configs = [ "${ability_runtime_test_path}/moduletest:services_module_test_config", "${ability_runtime_services_path}/appmgr:appmgr_config", - "${ability_runtime_services_path}/appmgr:appmgr_exception_config", "${ability_runtime_test_path}/moduletest:services_mock_ams_config", "${ability_runtime_innerkits_path}/app_manager:appmgr_sdk_config", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy_config", diff --git a/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp b/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp index 2256b915ba..6927f34b61 100644 --- a/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp +++ b/test/moduletest/common/ams/ability_running_record_test/ams_ability_running_record_module_test.cpp @@ -204,6 +204,11 @@ public: return 0; } + int32_t ScheduleDumpFfrt(std::string& result) override + { + return 0; + } + private: int abilityLaunchTime = 0; int appLaunchTime = 0; diff --git a/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp b/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp index e9f7b75a84..531cc927c6 100644 --- a/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp +++ b/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp @@ -123,6 +123,11 @@ public: { return 0; } + + int32_t ScheduleDumpFfrt(std::string& result) override + { + return 0; + } }; class AppMgrServiceModuleTest : public testing::Test { public: diff --git a/test/moduletest/ipc_ability_connect_test/BUILD.gn b/test/moduletest/ipc_ability_connect_test/BUILD.gn index f182a1da8b..425974df60 100644 --- a/test/moduletest/ipc_ability_connect_test/BUILD.gn +++ b/test/moduletest/ipc_ability_connect_test/BUILD.gn @@ -37,7 +37,7 @@ ohos_moduletest("IpcAbilityConnectModuleTest") { external_deps = [ "ability_base:want", "ability_runtime:ability_manager", - "c_utils:utilsbase", + "c_utils:utils", "hilog:libhilog", "ipc:ipc_core", ] diff --git a/test/moduletest/ipc_ability_scheduler_test/BUILD.gn b/test/moduletest/ipc_ability_scheduler_test/BUILD.gn index eeb688fee9..9501865ffd 100644 --- a/test/moduletest/ipc_ability_scheduler_test/BUILD.gn +++ b/test/moduletest/ipc_ability_scheduler_test/BUILD.gn @@ -50,7 +50,7 @@ ohos_moduletest("IpcAbilitySchedulerModuleTest") { "ability_base:zuri", "ability_runtime:ability_manager", "bundle_framework:appexecfwk_core", - "c_utils:utilsbase", + "c_utils:utils", "hilog:libhilog", "ipc:ipc_core", "napi:ace_napi", diff --git a/test/moduletest/mock/include/mock_render_scheduler.h b/test/moduletest/mock/include/mock_render_scheduler.h index 3624e4ae88..593f19fea8 100644 --- a/test/moduletest/mock/include/mock_render_scheduler.h +++ b/test/moduletest/mock/include/mock_render_scheduler.h @@ -26,8 +26,8 @@ public: MockRenderScheduler() = default; virtual ~MockRenderScheduler() = default; - MOCK_METHOD3(NotifyBrowserFd, - void(int32_t ipcFd, int32_t sharedFd, int32_t crashFd)); + MOCK_METHOD4(NotifyBrowserFd, + void(int32_t ipcFd, int32_t sharedFd, int32_t crashFd, sptr browser)); MOCK_METHOD0(AsObject, sptr()); }; } // namespace AppExecFwk diff --git a/test/moduletest/running_infos_module_test/BUILD.gn b/test/moduletest/running_infos_module_test/BUILD.gn index f06c6c1fe6..022686ab2b 100644 --- a/test/moduletest/running_infos_module_test/BUILD.gn +++ b/test/moduletest/running_infos_module_test/BUILD.gn @@ -63,6 +63,7 @@ ohos_moduletest("running_infos_module_test") { "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:event_report", "${ability_runtime_services_path}/common:perm_verification", diff --git a/test/moduletest/ui_extension_ability_test/ui_extension_info_module_test/ui_extension_info_module_test.cpp b/test/moduletest/ui_extension_ability_test/ui_extension_info_module_test/ui_extension_info_module_test.cpp index 225add257c..45ca7f017f 100644 --- a/test/moduletest/ui_extension_ability_test/ui_extension_info_module_test/ui_extension_info_module_test.cpp +++ b/test/moduletest/ui_extension_ability_test/ui_extension_info_module_test/ui_extension_info_module_test.cpp @@ -116,7 +116,7 @@ HWTEST_F(UIExtensionInfoModuleTest, QueryUIExtensionAbilityInfos_0100, TestSize. TAG_LOGI(AAFwkTag::TEST, "start."); ASSERT_NE(bundleMgr_, nullptr); - for (auto &type : UIExtensionUtils::UI_EXTENSION_SET) { + for (auto &type : UIExtensionUtils::GetUiExtensionSet()) { std::vector extensionInfos; bool queryResult = bundleMgr_->QueryExtensionAbilityInfos(type, AppExecFwk::Constants::ALL_USERID, extensionInfos); diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index c5dde5a563..68d6078ecb 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -19,7 +19,6 @@ import( config("appmgr_test_config") { configs = [ "${ability_runtime_services_path}/appmgr:appmgr_config", - "${ability_runtime_services_path}/appmgr:appmgr_exception_config", "${ability_runtime_innerkits_path}/app_manager:appmgr_sdk_config", "${ability_runtime_test_path}/moduletest:services_mock_ams_config", ] @@ -49,6 +48,8 @@ ohos_source_set("appmgr_test_source") { "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_state_callback_proxy.cpp", "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_task_info.cpp", "${ability_runtime_innerkits_path}/app_manager/src/appmgr/fault_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/native_child_notify_proxy.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/native_child_notify_stub.cpp", "${ability_runtime_innerkits_path}/app_manager/src/appmgr/process_info.cpp", "${ability_runtime_innerkits_path}/app_manager/src/appmgr/profile.cpp", "${ability_runtime_innerkits_path}/app_manager/src/appmgr/render_scheduler_host.cpp", @@ -194,10 +195,7 @@ ohos_source_set("abilityms_test_source") { include_dirs = [ "${ability_runtime_services_path}/appdfr/include", - "${ability_base_kits_path}/extractortool/include", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core", - "${distributedschedule_path}/safwk/interfaces/innerkits/safwk", - "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", "${ability_runtime_innerkits_path}/app_manager/include/appmgr", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", "${ability_runtime_path}/interfaces/kits/native/ability/native/distributed_ability_runtime", @@ -221,6 +219,7 @@ ohos_source_set("abilityms_test_source") { "${ability_runtime_innerkits_path}/connectionobs_manager:connection_obs_manager", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:task_handler_wrap", ] @@ -228,6 +227,7 @@ ohos_source_set("abilityms_test_source") { external_deps = [ "ability_base:base", "ability_base:configuration", + "ability_base:extractortool", "ability_base:view_data", "ability_base:want", "ability_runtime:ability_deps_wrapper", @@ -255,6 +255,7 @@ ohos_source_set("abilityms_test_source") { "relational_store:native_rdb", "resource_management:global_resmgr", "safwk:system_ability_fwk", + "samgr:samgr_proxy", "window_manager:libmodal_system_ui_extension_client", "window_manager:libwsutils", "window_manager:sms", @@ -293,12 +294,12 @@ ohos_source_set("abilityms_test_source") { ] deps += [ "${ace_engine_path}/interfaces/inner_api/ui_service_manager:ui_service_mgr", - "${global_path}/i18n/frameworks/intl:intl_util", - "${multimedia_path}/interfaces/innerkits:image_native", - "//third_party/icu/icu4c:shared_icuuc", "//third_party/libjpeg-turbo:turbojpeg_static", ] external_deps += [ + "i18n:intl_util", + "icu:shared_icuuc", + "image_framework:image_native", "input:libmmi-client", "window_manager:libdm", "window_manager:libmodal_system_ui_extension_client", @@ -348,8 +349,10 @@ group("unittest") { "ability_manager_stub_test:unittest", "ability_manager_test:unittest", "ability_record_dump_test:unittest", + "ability_record_mgr_test:unittest", "ability_record_test:unittest", "ability_running_info_test:unittest", + "ability_running_record_test:unittest", "ability_runtime_error_util_test:unittest", "ability_scheduler_proxy_test:unittest", "ability_scheduler_stub_test:unittest", @@ -374,6 +377,7 @@ group("unittest") { "ams_recent_app_list_test:unittest", "ams_service_load_ability_process_test:unittest", "ams_service_startup_test:unittest", + "app_config_data_manager_test:unittest", "app_debug_info_test:unittest", "app_debug_listener_proxy_test:unittest", "app_debug_listener_stub_test:unittest", @@ -385,6 +389,7 @@ group("unittest") { "app_lifecycle_deal_test:unittest", "app_mgr_client_test:unittest", "app_mgr_proxy_test:unittest", + "app_mgr_service_dump_ffrt_test:unittest", "app_mgr_service_dump_ipc_test:unittest", "app_mgr_service_dump_test:unittest", "app_mgr_service_event_handler_test:unittest", @@ -417,6 +422,7 @@ group("unittest") { "bundle_mgr_helper_test:unittest", "cache_process_manager_test:unittest", "call_record_test:unittest", + "child_process_capi_test:unittest", "child_process_manager_test:unittest", "completed_dispatcher_test:unittest", "configuration_test:unittest", @@ -439,6 +445,7 @@ group("unittest") { "dataobs_mgr_service_dump_test:unittest", "dataobs_mgr_service_test:unittest", "dataobs_mgr_stub_test:unittest", + "deeplink_reserve_config_test:unittest", "dfr_test:unittest", "dlp_state_item_test:unittest", "dlp_utils_test:unittest", @@ -452,6 +459,7 @@ group("unittest") { "frameworks_kits_ability_native_test:unittest", "frameworks_kits_appkit_native_test:unittest", "free_install_manager_test:unittest", + "freeze_util_test:unittest", "implicit_start_processor_test:unittest", "insight_intent:unittest", "js_auto_fill_extension_test:unittest", @@ -487,6 +495,7 @@ group("unittest") { "services/ability_util_test:unittest", "start_options_test:unittest", "start_other_app_interceptor_test:unittest", + "startup_util_test:unittest", "stop_user_callback_proxy_test:unittest", "stop_user_callback_stub_test:unittest", "sys_mgr_client_test:unittest", diff --git a/test/unittest/ability_connect_manager_test/BUILD.gn b/test/unittest/ability_connect_manager_test/BUILD.gn index 9f0c6708ba..d7f8c1d528 100644 --- a/test/unittest/ability_connect_manager_test/BUILD.gn +++ b/test/unittest/ability_connect_manager_test/BUILD.gn @@ -23,6 +23,7 @@ ohos_unittest("ability_connect_manager_test") { "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include", + "${ability_runtime_test_path}/mock/mock_sa_call", ] sources = [ @@ -59,6 +60,8 @@ ohos_unittest("ability_connect_manager_test") { "ability_runtime:ability_deps_wrapper", "ability_runtime:ability_manager", "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", "c_utils:utils", "common_event_service:cesfwk_innerkits", "ffrt:libffrt", diff --git a/test/unittest/ability_connect_manager_test/ability_connect_manager_test.cpp b/test/unittest/ability_connect_manager_test/ability_connect_manager_test.cpp index c5a93c0791..7f6604ead3 100644 --- a/test/unittest/ability_connect_manager_test/ability_connect_manager_test.cpp +++ b/test/unittest/ability_connect_manager_test/ability_connect_manager_test.cpp @@ -29,6 +29,7 @@ #include "bundlemgr/mock_bundle_manager.h" #include "hilog_tag_wrapper.h" #include "mock_ability_connect_callback.h" +#include "mock_sa_call.h" #include "sa_mgr_client.h" #include "system_ability_definition.h" @@ -2367,7 +2368,7 @@ HWTEST_F(AbilityConnectManagerTest, AAFWK_RestartAbility_003, TestSize.Level1) // HandleTerminate ConnectManager()->HandleAbilityDiedTask(service, userId); - EXPECT_EQ(static_cast(ConnectManager()->GetServiceMap().size()), 0); + EXPECT_EQ(static_cast(ConnectManager()->GetServiceMap().size()), 1); } /* @@ -3107,6 +3108,7 @@ HWTEST_F(AbilityConnectManagerTest, IsUIExtensionFocused_001, TestSize.Level1) */ HWTEST_F(AbilityConnectManagerTest, IsUIExtensionFocused_002, TestSize.Level1) { + AAFwk::IsMockSaCall::IsMockSaCallWithPermission(); std::shared_ptr connectManager = std::make_shared(3); ASSERT_NE(connectManager, nullptr); connectManager->uiExtensionMap_.clear(); @@ -3127,8 +3129,6 @@ HWTEST_F(AbilityConnectManagerTest, IsUIExtensionFocused_002, TestSize.Level1) auto request1 = GenerateAbilityRequest(device, abilityName1, appName1, bundleName1, moduleName1); auto uiExtension1 = AbilityRecord::CreateAbilityRecord(request1); EXPECT_NE(uiExtension1, nullptr); - int32_t ret = connectManager->uiExtensionAbilityRecordMgr_->CreateExtensionRecord(uiExtension1, bundleName1, - extensionRecord1, extensionId1); uiExtension1->abilityInfo_.extensionAbilityType = ExtensionAbilityType::SYS_COMMON_UI; sptr sessionInfo1 = new (std::nothrow) SessionInfo(); sessionInfo1->callerToken = uiExtensionUser->GetToken(); @@ -3138,7 +3138,6 @@ HWTEST_F(AbilityConnectManagerTest, IsUIExtensionFocused_002, TestSize.Level1) bool isFocused1 = connectManager->IsUIExtensionFocused( uiExtension1->GetApplicationInfo().accessTokenId, uiExtensionUser->GetToken()); EXPECT_EQ(isFocused1, true); - std::string abilityName2 = "uiExtensionAbility2"; std::string appName2 = "uiExtensionProvider2"; std::string bundleName2 = "com.ix.uiExtensionProvider2"; diff --git a/test/unittest/ability_interceptor_test/BUILD.gn b/test/unittest/ability_interceptor_test/BUILD.gn index 2a59372ee6..c724e37ad3 100644 --- a/test/unittest/ability_interceptor_test/BUILD.gn +++ b/test/unittest/ability_interceptor_test/BUILD.gn @@ -49,6 +49,7 @@ ohos_unittest("ability_interceptor_test") { "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock", diff --git a/test/unittest/ability_manager_client_branch_test/ability_manager_client_branch_test.cpp b/test/unittest/ability_manager_client_branch_test/ability_manager_client_branch_test.cpp index 7c9396a795..7b683da6ac 100644 --- a/test/unittest/ability_manager_client_branch_test/ability_manager_client_branch_test.cpp +++ b/test/unittest/ability_manager_client_branch_test/ability_manager_client_branch_test.cpp @@ -1401,7 +1401,8 @@ HWTEST_F(AbilityManagerClientBranchTest, StartAbilityByCall_002, TestSize.Level1 */ HWTEST_F(AbilityManagerClientBranchTest, StartUIAbilityBySCB_001, TestSize.Level1) { - EXPECT_EQ(client_->StartUIAbilityBySCB(nullptr), ERR_INVALID_VALUE); + bool isColdStart = false; + EXPECT_EQ(client_->StartUIAbilityBySCB(nullptr, isColdStart), ERR_INVALID_VALUE); } /** @@ -1412,7 +1413,8 @@ HWTEST_F(AbilityManagerClientBranchTest, StartUIAbilityBySCB_001, TestSize.Level HWTEST_F(AbilityManagerClientBranchTest, StartUIAbilityBySCB_002, TestSize.Level1) { sptr sessionInfo(new SessionInfo()); - EXPECT_EQ(client_->StartUIAbilityBySCB(sessionInfo), ERR_OK); + bool isColdStart = false; + EXPECT_EQ(client_->StartUIAbilityBySCB(sessionInfo, isColdStart), ERR_OK); } /** @@ -1425,7 +1427,8 @@ HWTEST_F(AbilityManagerClientBranchTest, StartUIAbilityBySCB_003, TestSize.Level Rosen::SessionInfo info; sptr sessionInfo(new SessionInfo()); sessionInfo->sessionToken = new Rosen::Session(info); - EXPECT_EQ(client_->StartUIAbilityBySCB(sessionInfo), ERR_OK); + bool isColdStart = false; + EXPECT_EQ(client_->StartUIAbilityBySCB(sessionInfo, isColdStart), ERR_OK); } /** @@ -2601,5 +2604,21 @@ HWTEST_F(AbilityManagerClientBranchTest, AbilityManagerClient_SetMissionLabel_01 GTEST_LOG_(INFO) << "AbilityManagerClient_SetMissionLabel_0100 end"; } #endif + +/** + * @tc.name: AbilityManagerClient_TransferAbilityResultForExtension_0100 + * @tc.desc: TransferAbilityResult + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerClientBranchTest, AbilityManagerClient_TransferAbilityResultForExtension_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityManagerClient_TransferAbilityResultForExtension_0100 start"; + sptr callerToken = new AbilityManagerStubTestMock(); + int resultCode = 0; + Want resultWant; + auto result = client_->TransferAbilityResultForExtension(callerToken, resultCode, resultWant); + EXPECT_EQ(result, NO_ERROR); + GTEST_LOG_(INFO) << "AbilityManagerClient_TransferAbilityResultForExtension_0100 end"; +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/ability_manager_service_first_test/ability_manager_service_first_test.cpp b/test/unittest/ability_manager_service_first_test/ability_manager_service_first_test.cpp index 155574c371..0d08059264 100644 --- a/test/unittest/ability_manager_service_first_test/ability_manager_service_first_test.cpp +++ b/test/unittest/ability_manager_service_first_test/ability_manager_service_first_test.cpp @@ -1016,7 +1016,7 @@ HWTEST_F(AbilityManagerServiceFirstTest, StopExtensionAbility_002, TestSize.Leve abilityRecord->appIndex_ = -1; abilityRecord->applicationInfo_.bundleName = "com.ix.hiservcie"; EXPECT_EQ(abilityMs_->StopExtensionAbility(want, abilityRecord->GetToken(), -1, ExtensionAbilityType::SERVICE), - ERR_INVALID_CALLER); + CHECK_PERMISSION_FAILED); TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFirstTest StopExtensionAbility_002 end"); } diff --git a/test/unittest/ability_manager_service_second_test/ability_manager_service_second_test.cpp b/test/unittest/ability_manager_service_second_test/ability_manager_service_second_test.cpp index 746b5d3b2b..792b59d6d3 100644 --- a/test/unittest/ability_manager_service_second_test/ability_manager_service_second_test.cpp +++ b/test/unittest/ability_manager_service_second_test/ability_manager_service_second_test.cpp @@ -735,6 +735,29 @@ HWTEST_F(AbilityManagerServiceSecondTest, ContinueMissionBundleName_001, TestSiz TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceSecondTest ContinueMissionBundleName_001 end"); } +/* + * Feature: AbilityManagerService + * Function: ContinueMissionBundleName + * SubFunction: NA + * FunctionPoints: AbilityManagerService ContinueMissionBundleName + */ +HWTEST_F(AbilityManagerServiceSecondTest, ContinueMissionBundleName_002, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceSecondTest ContinueMissionBundleName_002 start"); + auto abilityMs_ = std::make_shared(); + std::string srcDeviceId = ""; + std::string dstDeviceId = ""; + const sptr callback = nullptr; + AAFwk::WantParams wantParams; + ContinueMissionInfo continueMissionInfo; + continueMissionInfo.dstDeviceId = dstDeviceId; + continueMissionInfo.srcDeviceId = srcDeviceId; + continueMissionInfo.bundleName = ""; + continueMissionInfo.wantParams = wantParams; + EXPECT_EQ(abilityMs_->ContinueMission(continueMissionInfo, callback), CHECK_PERMISSION_FAILED); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceSecondTest ContinueMissionBundleName_002 end"); +} + /* * Feature: AbilityManagerService * Function: ContinueAbility diff --git a/test/unittest/ability_manager_service_third_test/BUILD.gn b/test/unittest/ability_manager_service_third_test/BUILD.gn index 6c7968b158..fd6828d543 100644 --- a/test/unittest/ability_manager_service_third_test/BUILD.gn +++ b/test/unittest/ability_manager_service_third_test/BUILD.gn @@ -20,12 +20,29 @@ ohos_unittest("ability_manager_service_third_test") { module_out_path = module_output_path include_dirs = [ + "${ability_runtime_innerkits_path}/uri_permission/include", "${ability_runtime_path}/interfaces/kits/native/ability/ability_runtime/", "${ability_runtime_path}/interfaces/inner_api/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_services_path}/common/include", + "${ability_runtime_test_path}/mock/mock_sa_call", + "${ability_runtime_test_path}/unittest/ability_manager_client_branch_test", ] sources = [ + "${ability_runtime_innerkits_path}/uri_permission/src/uri_permission_load_callback.cpp", + "${ability_runtime_innerkits_path}/uri_permission/src/uri_permission_manager_client.cpp", + "${ability_runtime_native_path}/ability/native/auto_startup_callback_proxy.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_data_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_service.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_bundle_event_callback.cpp", "${ability_runtime_services_path}/abilitymgr/src/ability_connect_callback_stub.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_event_util.cpp", + "${ability_runtime_services_path}/abilitymgr/src/auto_startup_info.cpp", + "${ability_runtime_services_path}/abilitymgr/src/deeplink_reserve/deeplink_reserve_config.cpp", + "${ability_runtime_services_path}/common/src/ffrt_task_handler_wrap.cpp", + "${ability_runtime_services_path}/common/src/queue_task_handler_wrap.cpp", + "${ability_runtime_services_path}/common/src/task_handler_wrap.cpp", "ability_manager_service_third_test.cpp", ] @@ -46,13 +63,19 @@ ohos_unittest("ability_manager_service_third_test") { "ability_base:session_info", "ability_base:want", "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", "ffrt:libffrt", "hilog:libhilog", "ipc:ipc_core", + "kv_store:distributeddata_inner", + "samgr:samgr_proxy", ] if (ability_runtime_graphics) { diff --git a/test/unittest/ability_manager_service_third_test/ability_manager_service_third_test.cpp b/test/unittest/ability_manager_service_third_test/ability_manager_service_third_test.cpp index a223ffae1e..132c57c4d1 100644 --- a/test/unittest/ability_manager_service_third_test/ability_manager_service_third_test.cpp +++ b/test/unittest/ability_manager_service_third_test/ability_manager_service_third_test.cpp @@ -25,11 +25,15 @@ #undef private #undef protected +#include "ability_bundle_event_callback.h" #include "ability_manager_errors.h" +#include "ability_manager_stub_mock_test.h" #include "connection_observer_errors.h" #include "hilog_tag_wrapper.h" +#include "mock_sa_call.h" #include "session/host/include/session.h" #include "scene_board_judgement.h" +#include "system_ability_definition.h" using namespace testing; using namespace testing::ext; @@ -41,6 +45,7 @@ namespace AAFwk { namespace { const int32_t USER_ID_U100 = 100; const int32_t APP_MEMORY_SIZE = 512; +const std::string EMPTY_DEVICE_ID = ""; } // namespace class AbilityManagerServiceThirdTest : public testing::Test { public: @@ -746,6 +751,20 @@ HWTEST_F(AbilityManagerServiceThirdTest, GetDataAbilityUri_001, TestSize.Level1) TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest GetDataAbilityUri_001 end"); } +/** + * @tc.number: ReportDrawnCompleted_001 + * @tc.name: ReportDrawnCompleted + * @tc.desc: After passing in a callerToken with parameter nullptr, INNER_ERR is returned + */ +HWTEST_F(AbilityManagerServiceThirdTest, ReportDrawnCompleted_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest ReportDrawnCompleted_001 start"); + auto abilityMs_ = std::make_shared(); + sptr callerToken = nullptr; + EXPECT_EQ(abilityMs_->ReportDrawnCompleted(callerToken), INNER_ERR); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest ReportDrawnCompleted_001 end"); +} + /** * @tc.number: ReportDrawnCompleted_002 * @tc.name: ReportDrawnCompleted @@ -755,7 +774,7 @@ HWTEST_F(AbilityManagerServiceThirdTest, ReportDrawnCompleted_002, TestSize.Leve { TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest ReportDrawnCompleted_002 start"); auto abilityMs_ = std::make_shared(); - sptr callerToken = nullptr; + sptr callerToken = new AbilityManagerStubTestMock(); EXPECT_EQ(abilityMs_->ReportDrawnCompleted(callerToken), INNER_ERR); TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest ReportDrawnCompleted_002 end"); } @@ -1211,5 +1230,1089 @@ HWTEST_F(AbilityManagerServiceThirdTest, GetAbilityStateByPersistentId_001, Test int32_t res = abilityMs->GetAbilityStateByPersistentId(persistentId, state); EXPECT_EQ(res, ERR_PERMISSION_DENIED); } + +/* + * Feature: AbilityManagerService + * Function: InitDeepLinkReserve + * FunctionPoints: AbilityManagerService InitDeepLinkReserve + */ +HWTEST_F(AbilityManagerServiceThirdTest, InitDeepLinkReserve_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->InitDeepLinkReserve(); + EXPECT_NE(abilityMs, nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: InitInterceptor + * FunctionPoints: AbilityManagerService InitInterceptor + */ +HWTEST_F(AbilityManagerServiceThirdTest, InitInterceptor_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->InitInterceptor(); + EXPECT_NE(abilityMs, nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: InitPushTask + * FunctionPoints: AbilityManagerService InitPushTask + */ +HWTEST_F(AbilityManagerServiceThirdTest, InitPushTask_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->InitPushTask(); + EXPECT_NE(abilityMs, nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: InitPushTask + * FunctionPoints: AbilityManagerService InitPushTask + */ +HWTEST_F(AbilityManagerServiceThirdTest, InitPushTask_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->taskHandler_ = nullptr; + abilityMs->InitPushTask(); + EXPECT_NE(abilityMs, nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: InitStartupFlag + * FunctionPoints: AbilityManagerService InitStartupFlag + */ +HWTEST_F(AbilityManagerServiceThirdTest, InitStartupFlag_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->InitStartupFlag(); + EXPECT_NE(abilityMs, nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: InitStartAbilityChain + * FunctionPoints: AbilityManagerService InitStartAbilityChain + */ +HWTEST_F(AbilityManagerServiceThirdTest, InitStartAbilityChain_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->InitStartAbilityChain(); + EXPECT_NE(abilityMs, nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: QueryServiceState + * FunctionPoints: AbilityManagerService QueryServiceState + */ +HWTEST_F(AbilityManagerServiceThirdTest, QueryServiceState_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->QueryServiceState(); + EXPECT_NE(abilityMs, nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByFreeInstall + * FunctionPoints: AbilityManagerService StartAbilityByFreeInstall + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityByFreeInstall_001, TestSize.Level1) +{ + AAFwk::IsMockSaCall::IsMockSaCallWithPermission(); + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken; + int32_t userId = 0; + int32_t requestCode = 0; + auto result = abilityMs->StartAbilityByFreeInstall(want, callerToken, userId, requestCode); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByFreeInstall + * FunctionPoints: AbilityManagerService StartAbilityByFreeInstall + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityByFreeInstall_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + want.SetFlags(Want::FLAG_ABILITY_CONTINUATION); + sptr callerToken; + int32_t userId = 0; + int32_t requestCode = 0; + auto result = abilityMs->StartAbilityByFreeInstall(want, callerToken, userId, requestCode); + EXPECT_EQ(result, ERR_INVALID_CONTINUATION_FLAG); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityWithSpecifyTokenId + * FunctionPoints: AbilityManagerService StartAbilityWithSpecifyTokenId + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityWithSpecifyTokenId_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken; + uint32_t specifyTokenId = 0; + int32_t userId = 0; + int32_t requestCode = 0; + auto result = abilityMs->StartAbilityWithSpecifyTokenId(want, callerToken, specifyTokenId, userId, requestCode); + EXPECT_EQ(result, ERR_INVALID_CONTINUATION_FLAG); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByInsightIntent + * FunctionPoints: AbilityManagerService StartAbilityByInsightIntent + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityByInsightIntent_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken; + uint64_t intentId = 0; + int32_t userId = 0; + auto result = abilityMs->StartAbilityByInsightIntent(want, callerToken, intentId, userId); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityWithSpecifyTokenIdInner + * FunctionPoints: AbilityManagerService StartAbilityWithSpecifyTokenIdInner + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityWithSpecifyTokenIdInner_001, TestSize.Level1) +{ + AAFwk::IsMockSaCall::IsMockSaCallWithPermission(); + auto abilityMs_ = std::make_shared(); + Want want; + sptr callerToken = nullptr; + int requestCode = 0; + EXPECT_EQ(abilityMs_->StartAbilityWithSpecifyTokenIdInner(want, callerToken, USER_ID_U100, requestCode), + ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityWithSpecifyTokenIdInner + * FunctionPoints: AbilityManagerService StartAbilityWithSpecifyTokenIdInner + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityWithSpecifyTokenIdInner_002, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + Want want; + want.SetFlags(Want::FLAG_ABILITY_CONTINUATION); + sptr callerToken = nullptr; + int requestCode = 0; + EXPECT_EQ(abilityMs_->StartAbilityWithSpecifyTokenIdInner(want, callerToken, USER_ID_U100, requestCode), + ERR_INVALID_CONTINUATION_FLAG); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByUIContentSession + * FunctionPoints: AbilityManagerService StartAbilityByUIContentSession + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityByUIContentSession_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken; + sptr sessionInfo; + int32_t userId = 0; + int requestCode = 0; + auto result = abilityMs->StartAbilityByUIContentSession(want, callerToken, sessionInfo, userId, requestCode); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByUIContentSession + * FunctionPoints: AbilityManagerService StartAbilityByUIContentSession + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityByUIContentSession_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken = new AbilityManagerStubTestMock(); + sptr sessionInfo; + int32_t userId = 0; + int requestCode = 0; + auto result = abilityMs->StartAbilityByUIContentSession(want, callerToken, sessionInfo, userId, requestCode); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByUIContentSession + * FunctionPoints: AbilityManagerService StartAbilityByUIContentSession + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityByUIContentSession_003, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken; + sptr sessionInfo = new (std::nothrow) SessionInfo(); + int32_t userId = 0; + int requestCode = 0; + auto result = abilityMs->StartAbilityByUIContentSession(want, callerToken, sessionInfo, userId, requestCode); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByUIContentSession + * FunctionPoints: AbilityManagerService StartAbilityByUIContentSession + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityByUIContentSession_004, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken = new AbilityManagerStubTestMock(); + sptr sessionInfo = new (std::nothrow) SessionInfo(); + int32_t userId = 0; + int requestCode = 0; + auto result = abilityMs->StartAbilityByUIContentSession(want, callerToken, sessionInfo, userId, requestCode); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByUIContentSession + * FunctionPoints: AbilityManagerService StartAbilityByUIContentSession + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityByUIContentSession_005, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + StartOptions startOptions; + sptr callerToken; + sptr sessionInfo; + int32_t userId = 0; + int requestCode = 0; + auto result = abilityMs->StartAbilityByUIContentSession(want, startOptions, callerToken, sessionInfo, userId, + requestCode); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByUIContentSession + * FunctionPoints: AbilityManagerService StartAbilityByUIContentSession + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityByUIContentSession_006, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + StartOptions startOptions; + sptr callerToken = new AbilityManagerStubTestMock(); + sptr sessionInfo; + int32_t userId = 0; + int requestCode = 0; + auto result = abilityMs->StartAbilityByUIContentSession(want, startOptions, callerToken, sessionInfo, userId, + requestCode); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByUIContentSession + * FunctionPoints: AbilityManagerService StartAbilityByUIContentSession + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityByUIContentSession_007, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + StartOptions startOptions; + sptr callerToken; + sptr sessionInfo = new (std::nothrow) SessionInfo(); + int32_t userId = 0; + int requestCode = 0; + auto result = abilityMs->StartAbilityByUIContentSession(want, startOptions, callerToken, sessionInfo, userId, + requestCode); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByUIContentSession + * FunctionPoints: AbilityManagerService StartAbilityByUIContentSession + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityByUIContentSession_008, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + StartOptions startOptions; + sptr callerToken = new AbilityManagerStubTestMock(); + sptr sessionInfo = new (std::nothrow) SessionInfo(); + int32_t userId = 0; + int requestCode = 0; + auto result = abilityMs->StartAbilityByUIContentSession(want, startOptions, callerToken, sessionInfo, userId, + requestCode); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: ImplicitStartAbilityAsCaller + * FunctionPoints: AbilityManagerService ImplicitStartAbilityAsCaller + */ +HWTEST_F(AbilityManagerServiceThirdTest, ImplicitStartAbilityAsCaller_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken; + sptr asCallerSoureToken; + int32_t userId = 0; + int requestCode = 0; + bool isSendDialogResult = true; + auto result = abilityMs->ImplicitStartAbilityAsCaller(want, callerToken, asCallerSoureToken, userId, + requestCode, isSendDialogResult); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityAsCallerDetails + * FunctionPoints: AbilityManagerService StartAbilityAsCallerDetails + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityAsCallerDetails_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken; + sptr asCallerSoureToken; + int32_t userId = 0; + int requestCode = 0; + bool isSendDialogResult = true; + bool isImplicit = true; + auto result = abilityMs->StartAbilityAsCallerDetails(want, callerToken, asCallerSoureToken, userId, + requestCode, isSendDialogResult, isImplicit); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityAsCallerDetails + * FunctionPoints: AbilityManagerService StartAbilityAsCallerDetails + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityAsCallerDetails_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + want.SetFlags(Want::FLAG_ABILITY_CONTINUATION); + sptr callerToken; + sptr asCallerSoureToken; + int32_t userId = 0; + int requestCode = 0; + bool isSendDialogResult = true; + bool isImplicit = true; + auto result = abilityMs->StartAbilityAsCallerDetails(want, callerToken, asCallerSoureToken, userId, + requestCode, isSendDialogResult, isImplicit); + EXPECT_EQ(result, ERR_INVALID_CONTINUATION_FLAG); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityAsCallerDetails + * FunctionPoints: AbilityManagerService StartAbilityAsCallerDetails + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityAsCallerDetails_003, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken; + sptr asCallerSoureToken = new AbilityManagerStubTestMock();; + int32_t userId = 0; + int requestCode = 0; + bool isSendDialogResult = true; + bool isImplicit = true; + auto result = abilityMs->StartAbilityAsCallerDetails(want, callerToken, asCallerSoureToken, userId, + requestCode, isSendDialogResult, isImplicit); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityPublicPrechainCheck + * FunctionPoints: AbilityManagerService StartAbilityPublicPrechainCheck + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityPublicPrechainCheck_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + StartAbilityParams startParams(const_cast(want)); + auto result = abilityMs->StartAbilityPublicPrechainCheck(startParams); + EXPECT_EQ(result, ERR_OK); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityPrechainInterceptor + * FunctionPoints: AbilityManagerService StartAbilityPrechainInterceptor + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityPrechainInterceptor_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + StartAbilityParams startParams(const_cast(want)); + auto result = abilityMs->StartAbilityPrechainInterceptor(startParams); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityInChain + * FunctionPoints: AbilityManagerService StartAbilityInChain + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityInChain_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + StartAbilityParams startParams(const_cast(want)); + int result = 0; + auto ret = abilityMs->StartAbilityInChain(startParams, result); + EXPECT_EQ(ret, ERR_OK); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityWrap + * FunctionPoints: AbilityManagerService StartAbilityWrap + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityWrap_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken; + int requestCode = 0; + int32_t userId = 0; + bool isStartAsCaller = true; + bool isSendDialogResult = true; + uint32_t specifyToken = 0; + bool isForegroundToRestartApp = true; + bool isImplicit = true; + auto result = abilityMs->StartAbilityWrap(want, callerToken, requestCode, userId, isStartAsCaller, + isSendDialogResult, specifyToken, isForegroundToRestartApp, isImplicit); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: SetReserveInfo + * FunctionPoints: AbilityManagerService SetReserveInfo + */ +HWTEST_F(AbilityManagerServiceThirdTest, SetReserveInfo_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + std::string linkString = ""; + abilityMs->SetReserveInfo(linkString); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: ImplicitStartAbility + * FunctionPoints: AbilityManagerService ImplicitStartAbility + */ +HWTEST_F(AbilityManagerServiceThirdTest, ImplicitStartAbility_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + AbilityStartSetting abilityStartSetting; + const sptr callerToken; + int32_t userId = 0; + int requestCode = 0; + auto result = abilityMs->ImplicitStartAbility(want, abilityStartSetting, callerToken, userId, requestCode); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: ImplicitStartAbility + * FunctionPoints: AbilityManagerService ImplicitStartAbility + */ +HWTEST_F(AbilityManagerServiceThirdTest, ImplicitStartAbility_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + StartOptions startOptions; + const sptr callerToken; + int32_t userId = 0; + int requestCode = 0; + auto result = abilityMs->ImplicitStartAbility(want, startOptions, callerToken, userId, requestCode); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartUIAbilityForOptionWrap + * FunctionPoints: AbilityManagerService StartUIAbilityForOptionWrap + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartUIAbilityForOptionWrap_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + StartOptions startOptions; + const sptr callerToken; + int32_t userId = 0; + int requestCode = 0; + uint32_t callerTokenId = 0; + bool isImplicit = true; + auto result = abilityMs->StartUIAbilityForOptionWrap(want, startOptions, callerToken, userId, requestCode, + callerTokenId, isImplicit); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityForOptionWrap + * FunctionPoints: AbilityManagerService StartAbilityForOptionWrap + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityForOptionWrap_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + StartOptions startOptions; + const sptr callerToken; + int32_t userId = 0; + int requestCode = 0; + bool isStartAsCaller = true; + uint32_t callerTokenId = 0; + bool isImplicit = true; + auto result = abilityMs->StartAbilityForOptionWrap(want, startOptions, callerToken, userId, requestCode, + isStartAsCaller, callerTokenId, isImplicit); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityForOptionInner + * FunctionPoints: AbilityManagerService StartAbilityForOptionInner + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityForOptionInner_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + StartOptions startOptions; + const sptr callerToken; + int32_t userId = 0; + int requestCode = 0; + bool isStartAsCaller = true; + uint32_t specifyTokenId = 0; + bool isImplicit = true; + auto result = abilityMs->StartAbilityForOptionInner(want, startOptions, callerToken, userId, requestCode, + isStartAsCaller, specifyTokenId, isImplicit); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: RequestDialogService + * FunctionPoints: AbilityManagerService RequestDialogService + */ +HWTEST_F(AbilityManagerServiceThirdTest, RequestDialogService_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + const sptr callerToken; + auto result = abilityMs->RequestDialogService(want, callerToken); + EXPECT_EQ(result, ERR_INVALID_CALLER); +} + +/* + * Feature: AbilityManagerService + * Function: RequestDialogService + * FunctionPoints: AbilityManagerService RequestDialogService + */ +HWTEST_F(AbilityManagerServiceThirdTest, RequestDialogService_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + want.SetFlags(Want::FLAG_ABILITY_CONTINUATION); + const sptr callerToken; + auto result = abilityMs->RequestDialogService(want, callerToken); + EXPECT_EQ(result, ERR_INVALID_CONTINUATION_FLAG); +} + +/* + * Feature: AbilityManagerService + * Function: RequestDialogServiceInner + * FunctionPoints: AbilityManagerService RequestDialogServiceInner + */ +HWTEST_F(AbilityManagerServiceThirdTest, RequestDialogServiceInner_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + const sptr callerToken; + int requestCode = 0; + int32_t userId = 0; + auto result = abilityMs->RequestDialogServiceInner(want, callerToken, requestCode, userId); + EXPECT_EQ(result, ERR_INVALID_CALLER); +} + +/* + * Feature: AbilityManagerService + * Function: StartUIAbilityBySCB + * FunctionPoints: AbilityManagerService StartUIAbilityBySCB + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartUIAbilityBySCB_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + sptr sessionInfo = nullptr; + bool isColdStart = true; + auto result = abilityMs->StartUIAbilityBySCB(sessionInfo, isColdStart); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartUIAbilityBySCB + * FunctionPoints: AbilityManagerService StartUIAbilityBySCB + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartUIAbilityBySCB_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + sptr sessionInfo = new (std::nothrow) SessionInfo(); + bool isColdStart = true; + auto result = abilityMs->StartUIAbilityBySCB(sessionInfo, isColdStart); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: CheckCallingTokenId + * FunctionPoints: AbilityManagerService CheckCallingTokenId + */ +HWTEST_F(AbilityManagerServiceThirdTest, CheckCallingTokenId_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + std::string bundleName = "test"; + int32_t userId = 0; + auto result = abilityMs->CheckCallingTokenId(bundleName, userId); + EXPECT_EQ(result, false); +} + +/* + * Feature: AbilityManagerService + * Function: IsCallerSceneBoard + * FunctionPoints: AbilityManagerService IsCallerSceneBoard + */ +HWTEST_F(AbilityManagerServiceThirdTest, IsCallerSceneBoard_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + auto result = abilityMs->IsCallerSceneBoard(); + EXPECT_EQ(result, false); +} + +/* + * Feature: AbilityManagerService + * Function: IsDmsAlive + * FunctionPoints: AbilityManagerService IsDmsAlive + */ +HWTEST_F(AbilityManagerServiceThirdTest, IsDmsAlive_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + auto result = abilityMs->IsDmsAlive(); + EXPECT_EQ(result, false); +} + +/* + * Feature: AbilityManagerService + * Function: AppUpgradeCompleted + * FunctionPoints: AbilityManagerService AppUpgradeCompleted + */ +HWTEST_F(AbilityManagerServiceThirdTest, AppUpgradeCompleted_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + std::string bundleName = "test"; + int32_t uid = 0; + abilityMs->AppUpgradeCompleted(bundleName, uid); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: AppUpgradeCompleted + * FunctionPoints: AbilityManagerService AppUpgradeCompleted + */ +HWTEST_F(AbilityManagerServiceThirdTest, AppUpgradeCompleted_002, TestSize.Level1) +{ + AAFwk::IsMockSaCall::IsMockSaCallWithPermission(); + auto abilityMs = std::make_shared(); + std::string bundleName = "test"; + int32_t uid = 1; + abilityMs->AppUpgradeCompleted(bundleName, uid); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: GetAppMgr + * FunctionPoints: AbilityManagerService GetAppMgr + */ +HWTEST_F(AbilityManagerServiceThirdTest, GetAppMgr_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + auto result = abilityMs->GetAppMgr(); + EXPECT_NE(result, nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: OnAddSystemAbility + * FunctionPoints: AbilityManagerService OnAddSystemAbility + */ +HWTEST_F(AbilityManagerServiceThirdTest, OnAddSystemAbility_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + int32_t systemAbilityId = BACKGROUND_TASK_MANAGER_SERVICE_ID; + std::string deviceId = ""; + abilityMs->OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: OnAddSystemAbility + * FunctionPoints: AbilityManagerService OnAddSystemAbility + */ +HWTEST_F(AbilityManagerServiceThirdTest, OnAddSystemAbility_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + int32_t systemAbilityId = DISTRIBUTED_SCHED_SA_ID; + std::string deviceId = ""; + abilityMs->OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: OnAddSystemAbility + * FunctionPoints: AbilityManagerService OnAddSystemAbility + */ +HWTEST_F(AbilityManagerServiceThirdTest, OnAddSystemAbility_003, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + int32_t systemAbilityId = BUNDLE_MGR_SERVICE_SYS_ABILITY_ID; + std::string deviceId = ""; + abilityMs->OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: OnRemoveSystemAbility + * FunctionPoints: AbilityManagerService OnRemoveSystemAbility + */ +HWTEST_F(AbilityManagerServiceThirdTest, OnRemoveSystemAbility_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + int32_t systemAbilityId = BACKGROUND_TASK_MANAGER_SERVICE_ID; + std::string deviceId = ""; + abilityMs->OnRemoveSystemAbility(systemAbilityId, deviceId); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: OnRemoveSystemAbility + * FunctionPoints: AbilityManagerService OnRemoveSystemAbility + */ +HWTEST_F(AbilityManagerServiceThirdTest, OnRemoveSystemAbility_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + int32_t systemAbilityId = DISTRIBUTED_SCHED_SA_ID; + std::string deviceId = ""; + abilityMs->OnRemoveSystemAbility(systemAbilityId, deviceId); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: OnRemoveSystemAbility + * FunctionPoints: AbilityManagerService OnRemoveSystemAbility + */ +HWTEST_F(AbilityManagerServiceThirdTest, OnRemoveSystemAbility_003, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + int32_t systemAbilityId = BUNDLE_MGR_SERVICE_SYS_ABILITY_ID; + std::string deviceId = ""; + abilityMs->OnRemoveSystemAbility(systemAbilityId, deviceId); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: SubscribeBundleEventCallback + * FunctionPoints: AbilityManagerService SubscribeBundleEventCallback + */ +HWTEST_F(AbilityManagerServiceThirdTest, SubscribeBundleEventCallback_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->abilityBundleEventCallback_ = nullptr; + abilityMs->SubscribeBundleEventCallback(); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: SubscribeBundleEventCallback + * FunctionPoints: AbilityManagerService SubscribeBundleEventCallback + */ +HWTEST_F(AbilityManagerServiceThirdTest, SubscribeBundleEventCallback_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->abilityBundleEventCallback_ = new (std::nothrow) AbilityBundleEventCallback(nullptr, nullptr); + abilityMs->SubscribeBundleEventCallback(); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: UnsubscribeBundleEventCallback + * FunctionPoints: AbilityManagerService UnsubscribeBundleEventCallback + */ +HWTEST_F(AbilityManagerServiceThirdTest, UnsubscribeBundleEventCallback_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->abilityBundleEventCallback_ = nullptr; + abilityMs->UnsubscribeBundleEventCallback(); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: UnsubscribeBundleEventCallback + * FunctionPoints: AbilityManagerService UnsubscribeBundleEventCallback + */ +HWTEST_F(AbilityManagerServiceThirdTest, UnsubscribeBundleEventCallback_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->abilityBundleEventCallback_ = new (std::nothrow) AbilityBundleEventCallback(nullptr, nullptr); + abilityMs->UnsubscribeBundleEventCallback(); + EXPECT_TRUE(abilityMs != nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: ImplicitStartExtensionAbility + * FunctionPoints: AbilityManagerService ImplicitStartExtensionAbility + */ +HWTEST_F(AbilityManagerServiceThirdTest, ImplicitStartExtensionAbility_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken; + int32_t userId = 0; + AppExecFwk::ExtensionAbilityType extensionType = AppExecFwk::ExtensionAbilityType::UI; + auto result = abilityMs->ImplicitStartExtensionAbility(want, callerToken, userId, extensionType); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: ImplicitStartExtensionAbility + * FunctionPoints: AbilityManagerService ImplicitStartExtensionAbility + */ +HWTEST_F(AbilityManagerServiceThirdTest, ImplicitStartExtensionAbility_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken; + int32_t userId = 0; + AppExecFwk::ExtensionAbilityType extensionType = AppExecFwk::ExtensionAbilityType::VPN; + auto result = abilityMs->ImplicitStartExtensionAbility(want, callerToken, userId, extensionType); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: RequestModalUIExtension + * FunctionPoints: AbilityManagerService RequestModalUIExtension + */ +HWTEST_F(AbilityManagerServiceThirdTest, RequestModalUIExtension_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + auto result = abilityMs->RequestModalUIExtension(want); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: RequestModalUIExtensionInner + * FunctionPoints: AbilityManagerService RequestModalUIExtensionInner + */ +HWTEST_F(AbilityManagerServiceThirdTest, RequestModalUIExtensionInner_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + auto result = abilityMs->RequestModalUIExtensionInner(want); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: ChangeAbilityVisibility + * FunctionPoints: AbilityManagerService ChangeAbilityVisibility + */ +HWTEST_F(AbilityManagerServiceThirdTest, ChangeAbilityVisibility_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + sptr token; + bool isShow = true; + auto result = abilityMs->ChangeAbilityVisibility(token, isShow); + EXPECT_EQ(result, ERR_CAPABILITY_NOT_SUPPORT); +} + +/* + * Feature: AbilityManagerService + * Function: ChangeUIAbilityVisibilityBySCB + * FunctionPoints: AbilityManagerService ChangeUIAbilityVisibilityBySCB + */ +HWTEST_F(AbilityManagerServiceThirdTest, ChangeUIAbilityVisibilityBySCB_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + sptr sessionInfo; + bool isShow = true; + auto result = abilityMs->ChangeUIAbilityVisibilityBySCB(sessionInfo, isShow); + EXPECT_EQ(result, ERR_WRONG_INTERFACE_CALL); +} + +/* + * Feature: AbilityManagerService + * Function: StartExtensionAbilityInner + * FunctionPoints: AbilityManagerService StartExtensionAbilityInner + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartExtensionAbilityInner_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken = nullptr; + int32_t userId = 0; + AppExecFwk::ExtensionAbilityType extensionType = AppExecFwk::ExtensionAbilityType::VPN; + bool checkSystemCaller = true; + bool isImplicit = true; + bool isDlp = true; + auto result = abilityMs->StartExtensionAbilityInner(want, callerToken, userId, extensionType, checkSystemCaller, + isImplicit, isDlp); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartExtensionAbilityInner + * FunctionPoints: AbilityManagerService StartExtensionAbilityInner + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartExtensionAbilityInner_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken = new AbilityManagerStubTestMock(); + int32_t userId = 0; + AppExecFwk::ExtensionAbilityType extensionType = AppExecFwk::ExtensionAbilityType::VPN; + bool checkSystemCaller = true; + bool isImplicit = true; + bool isDlp = true; + auto result = abilityMs->StartExtensionAbilityInner(want, callerToken, userId, extensionType, checkSystemCaller, + isImplicit, isDlp); + EXPECT_EQ(result, ERR_INVALID_CALLER); +} + +/* + * Feature: AbilityManagerService + * Function: StartExtensionAbilityInner + * FunctionPoints: AbilityManagerService StartExtensionAbilityInner + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartExtensionAbilityInner_003, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken = new AbilityManagerStubTestMock(); + int32_t userId = 0; + AppExecFwk::ExtensionAbilityType extensionType = AppExecFwk::ExtensionAbilityType::VPN; + bool checkSystemCaller = true; + bool isImplicit = true; + bool isDlp = false; + auto result = abilityMs->StartExtensionAbilityInner(want, callerToken, userId, extensionType, checkSystemCaller, + isImplicit, isDlp); + EXPECT_EQ(result, ERR_INVALID_CALLER); +} + +/* + * Feature: AbilityManagerService + * Function: MoveAbilityToBackground + * FunctionPoints: AbilityManagerService MoveAbilityToBackground + */ +HWTEST_F(AbilityManagerServiceThirdTest, MoveAbilityToBackground_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + sptr token = nullptr; + auto result = abilityMs->MoveAbilityToBackground(token); + EXPECT_EQ(result, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: GetLocalDeviceId + * FunctionPoints: AbilityManagerService GetLocalDeviceId + */ +HWTEST_F(AbilityManagerServiceThirdTest, GetLocalDeviceId_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + std::string localDeviceId = "device"; + auto result = abilityMs->GetLocalDeviceId(localDeviceId); + EXPECT_EQ(result, false); +} + +/* + * Feature: AbilityManagerService + * Function: AnonymizeDeviceId + * FunctionPoints: AbilityManagerService AnonymizeDeviceId + */ +HWTEST_F(AbilityManagerServiceThirdTest, AnonymizeDeviceId_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + std::string localDeviceId = "device"; + auto result = abilityMs->AnonymizeDeviceId(localDeviceId); + EXPECT_NE(result, EMPTY_DEVICE_ID); +} + +/* + * Feature: AbilityManagerService + * Function: AnonymizeDeviceId + * FunctionPoints: AbilityManagerService AnonymizeDeviceId + */ +HWTEST_F(AbilityManagerServiceThirdTest, AnonymizeDeviceId_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + std::string localDeviceId = ""; + auto result = abilityMs->AnonymizeDeviceId(localDeviceId); + EXPECT_EQ(result, EMPTY_DEVICE_ID); +} + +/* + * Feature: AbilityManagerService + * Function: TransferAbilityResultForExtension + * FunctionPoints: AbilityManagerService TransferAbilityResultForExtension + */ +HWTEST_F(AbilityManagerServiceThirdTest, TransferAbilityResultForExtension_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + EXPECT_NE(abilityMs, nullptr); + sptr token = nullptr; + int32_t resultCode = 0; + AAFwk::Want want; + int32_t res = abilityMs->TransferAbilityResultForExtension(token, resultCode, want); + EXPECT_EQ(res, ERR_INVALID_VALUE); +} } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/ability_manager_stub_test/BUILD.gn b/test/unittest/ability_manager_stub_test/BUILD.gn index 2b138e56a5..a95f730f6f 100644 --- a/test/unittest/ability_manager_stub_test/BUILD.gn +++ b/test/unittest/ability_manager_stub_test/BUILD.gn @@ -46,6 +46,7 @@ ohos_unittest("ability_manager_stub_test") { "${ability_runtime_native_path}/ability/native:abilitykit_native", # "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_services_path}/common:task_handler_wrap", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock", diff --git a/test/unittest/ability_manager_stub_test/ability_manager_stub_test.cpp b/test/unittest/ability_manager_stub_test/ability_manager_stub_test.cpp index a8049cda1c..5b26bbd880 100644 --- a/test/unittest/ability_manager_stub_test/ability_manager_stub_test.cpp +++ b/test/unittest/ability_manager_stub_test/ability_manager_stub_test.cpp @@ -528,6 +528,54 @@ HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_GetTopAbilityInner_001, Test EXPECT_EQ(res, NO_ERROR); } +/* + * Feature: AbilityManagerService + * Function: GetElementNameByTokenInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService GetElementNameByTokenInner + * EnvConditions: NA + * CaseDescription: Verify the function GetElementNameByTokenInner is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_GetElementNameByTokenInner_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + auto res = stub_->GetElementNameByTokenInner(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/* + * Feature: AbilityManagerService + * Function: MoveAbilityToBackgroundInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService MoveAbilityToBackgroundInner + * EnvConditions: NA + * CaseDescription: Verify the function MoveAbilityToBackgroundInner is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_MoveAbilityToBackgroundInner_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + auto res = stub_->MoveAbilityToBackgroundInner(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/* + * Feature: AbilityManagerService + * Function: MoveUIAbilityToBackgroundInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService MoveUIAbilityToBackgroundInner + * EnvConditions: NA + * CaseDescription: Verify the function MoveUIAbilityToBackgroundInner is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_MoveUIAbilityToBackgroundInner_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + auto res = stub_->MoveUIAbilityToBackgroundInner(data, reply); + EXPECT_EQ(res, IPC_STUB_ERR); +} + /* * Feature: AbilityManagerService * Function: TerminateAbilityInner @@ -544,6 +592,22 @@ HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_TerminateAbilityInner_001, T EXPECT_EQ(res, NO_ERROR); } +/* + * Feature: AbilityManagerService + * Function: TerminateUIExtensionAbilityInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService TerminateUIExtensionAbilityInner + * EnvConditions: NA + * CaseDescription: Verify the function TerminateUIExtensionAbilityInner is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_TerminateUIExtensionAbilityInner_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + auto res = stub_->TerminateUIExtensionAbilityInner(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + /* * Feature: AbilityManagerService * Function: SendResultToAbilityInner @@ -576,6 +640,38 @@ HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_MinimizeAbilityInner_001, Te EXPECT_EQ(res, NO_ERROR); } +/* + * Feature: AbilityManagerService + * Function: MinimizeUIExtensionAbilityInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService MinimizeUIExtensionAbilityInner + * EnvConditions: NA + * CaseDescription: Verify the function MinimizeUIExtensionAbilityInner is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_MinimizeUIExtensionAbilityInner_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + auto res = stub_->MinimizeUIExtensionAbilityInner(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/* + * Feature: AbilityManagerService + * Function: MinimizeUIAbilityBySCBInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService MinimizeUIAbilityBySCBInner + * EnvConditions: NA + * CaseDescription: Verify the function MinimizeUIAbilityBySCBInner is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_MinimizeUIAbilityBySCBInner_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + auto res = stub_->MinimizeUIAbilityBySCBInner(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + /* * Feature: AbilityManagerService * Function: AttachAbilityThreadInner @@ -752,6 +848,23 @@ HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_UninstallAppInner_001, TestS EXPECT_EQ(res, NO_ERROR); } +/* + * Feature: AbilityManagerService + * Function: UpgradeAppInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService UpgradeAppInner + * EnvConditions: NA + * CaseDescription: Verify the function UpgradeAppInner is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_UpgradeAppInner_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + auto res = stub_->UpgradeAppInner(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + + /* * Feature: AbilityManagerService * Function: StartAbilityInner @@ -768,6 +881,54 @@ HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_StartAbilityInner_001, TestS EXPECT_EQ(res, ERR_INVALID_VALUE); } +/* + * Feature: AbilityManagerService + * Function: StartAbilityInnerSpecifyTokenId + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityInnerSpecifyTokenId + * EnvConditions: NA + * CaseDescription: Verify the function StartAbilityInnerSpecifyTokenId is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_StartAbilityInnerSpecifyTokenId_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + auto res = stub_->StartAbilityInnerSpecifyTokenId(data, reply); + EXPECT_EQ(res, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByUIContentSessionAddCallerInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityByUIContentSessionAddCallerInner + * EnvConditions: NA + * CaseDescription: Verify the function StartAbilityByUIContentSessionAddCallerInner is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_StartAbilityByUIContentSessionAddCallerInner_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + auto res = stub_->StartAbilityByUIContentSessionAddCallerInner(data, reply); + EXPECT_EQ(res, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByUIContentSessionForOptionsInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityByUIContentSessionForOptionsInner + * EnvConditions: NA + * CaseDescription: Verify the function StartAbilityByUIContentSessionForOptionsInner is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_StartAbilityByUIContentSessionForOptionsInner_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + auto res = stub_->StartAbilityByUIContentSessionForOptionsInner(data, reply); + EXPECT_EQ(res, ERR_INVALID_VALUE); +} + /* * Feature: AbilityManagerService * Function: StartExtensionAbilityInner @@ -1264,6 +1425,24 @@ HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_ContinueMissionOfBundleNameI EXPECT_EQ(res, ERR_NULL_OBJECT); } +/* + * Feature: AbilityManagerService + * Function: ContinueMissionOfBundleNameInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService ContinueMissionOfBundleNameInner + * EnvConditions: NA + * CaseDescription: Verify the function ContinueMissionOfBundleNameInner is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_ContinueMissionOfBundleNameInner_002, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + Want want; + data.WriteParcelable(&want); + auto res = stub_->ContinueMissionOfBundleNameInner(data, reply); + EXPECT_EQ(res, ERR_NULL_OBJECT); +} + /* * Feature: AbilityManagerService * Function: ContinueAbilityInner @@ -2797,5 +2976,47 @@ HWTEST_F(AbilityManagerStubTest, RestartAppInner_0100, TestSize.Level1) auto result = stub_->RestartAppInner(data, reply); EXPECT_EQ(result, NO_ERROR); } + +/** + * @tc.name: ChangeAbilityVisibility_0100 + * @tc.desc: ChangeAbilityVisibility + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerStubTest, ChangeAbilityVisibility_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin"); + + MessageParcel data; + MessageParcel reply; + auto token = sptr::MakeSptr(); + data.WriteRemoteObject(token); + data.WriteBool(true); + + auto ret = stub_->ChangeAbilityVisibilityInner(data, reply); + EXPECT_EQ(ret, NO_ERROR); + + TAG_LOGI(AAFwkTag::TEST, "end"); +} + +/** + * @tc.name: ChangeUIAbilityVisibilityBySCB_0100 + * @tc.desc: ChangeUIAbilityVisibilityBySCB + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerStubTest, ChangeUIAbilityVisibilityBySCB_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin"); + + MessageParcel data; + MessageParcel reply; + sptr session = new (std::nothrow) SessionInfo(); + data.WriteParcelable(session); + data.WriteBool(true); + + auto ret = stub_->ChangeUIAbilityVisibilityBySCBInner(data, reply); + EXPECT_EQ(ret, NO_ERROR); + + TAG_LOGI(AAFwkTag::TEST, "end"); +} } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/ability_record_mgr_test/BUILD.gn b/test/unittest/ability_record_mgr_test/BUILD.gn new file mode 100644 index 0000000000..fd91592f70 --- /dev/null +++ b/test/unittest/ability_record_mgr_test/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +module_output_path = "ability_runtime/appkit" +config("coverage_flags") { + if (ability_runtime_feature_coverage) { + cflags = [ "--coverage" ] + ldflags = [ "--coverage" ] + } +} + +ohos_unittest("ability_record_mgr_test") { + module_out_path = module_output_path + + include_dirs = [] + + sources = [ + "${ability_runtime_native_path}/appkit/app/ability_record_mgr.cpp", + "ability_record_mgr_test.cpp", + ] + + configs = [ ":coverage_flags" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ "//third_party/googletest:gmock_main" ] + + external_deps = [ + "ability_runtime:abilitykit_native", + "c_utils:utils", + "eventhandler:libeventhandler", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } +} + +group("unittest") { + testonly = true + + deps = [ ":ability_record_mgr_test" ] +} diff --git a/test/unittest/ability_record_mgr_test/ability_record_mgr_test.cpp b/test/unittest/ability_record_mgr_test/ability_record_mgr_test.cpp new file mode 100644 index 0000000000..7e37d50cb5 --- /dev/null +++ b/test/unittest/ability_record_mgr_test/ability_record_mgr_test.cpp @@ -0,0 +1,230 @@ +/* + * Copyright (c) 2024 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 +#define private public +#define protected public +#include "ability_record_mgr.h" +#undef private +#undef protected +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_stub.h" +using namespace testing::ext; +using namespace testing; +using namespace OHOS::AppExecFwk; +namespace OHOS { +namespace AAFwk { +class IAbilityMgrToken : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.AbilityMgrToken"); +}; + +class AbilityMgrToken : public IRemoteStub { +public: + AbilityMgrToken() = default; + virtual ~AbilityMgrToken() = default; + + virtual int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) + { + return 0; + } + +private: + DISALLOW_COPY_AND_MOVE(AbilityMgrToken); +}; + +class AbilityRecordMgrTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AbilityRecordMgrTest::SetUpTestCase() +{} + +void AbilityRecordMgrTest::TearDownTestCase() +{} + +void AbilityRecordMgrTest::SetUp() +{} + +void AbilityRecordMgrTest::TearDown() +{} + +/** + * @tc.number: GetToken_0100 + * @tc.name: GetToken + * @tc.desc: GetToken Test, return is not nullptr. + */ +HWTEST_F(AbilityRecordMgrTest, GetEventHandler_0100, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AbilityRecordMgrTest GetToken_0100 start"; + auto recordMgr = std::make_shared(); + recordMgr->tokens_ = nullptr; + auto token = recordMgr->GetToken(); + EXPECT_EQ(token, nullptr); + GTEST_LOG_(INFO) << "AbilityRecordMgrTest GetToken_0100 end"; +} + +/** + * @tc.number: SetToken_0100 + * @tc.name: SetToken + * @tc.desc: SetToken Test, return is not nullptr. + */ +HWTEST_F(AbilityRecordMgrTest, SetToken_0100, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AbilityRecordMgrTest SetToken_0100 start"; + sptr token = new (std::nothrow) AbilityMgrToken(); + auto recordMgr = std::make_shared(); + recordMgr->SetToken(token); + EXPECT_NE(recordMgr->GetToken(), nullptr); + GTEST_LOG_(INFO) << "AbilityRecordMgrTest SetToken_0100 end"; +} + +/** + * @tc.number: SetEventRunner_0100 + * @tc.name: SetEventRunner + * @tc.desc: SetEventRunner Test, return is not nullptr. + */ +HWTEST_F(AbilityRecordMgrTest, SetEventRunner_0100, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AbilityRecordMgrTest SetEventRunner_0100 start"; + auto recordMgr = std::make_shared(); + EXPECT_NE(recordMgr, nullptr); + recordMgr->SetEventRunner(nullptr); + + std::shared_ptr runner = EventRunner::GetMainEventRunner(); + EXPECT_NE(runner, nullptr); + recordMgr->tokens_ = nullptr; + recordMgr->SetEventRunner(runner); + + sptr token = new (std::nothrow) AbilityMgrToken(); + recordMgr->SetToken(token); + recordMgr->SetEventRunner(runner); + GTEST_LOG_(INFO) << "AbilityRecordMgrTest SetEventRunner_0100 end"; +} + +/** + * @tc.number: AddAbilityRecord_0100 + * @tc.name: AddAbilityRecord + * @tc.desc: AddAbilityRecord Test, return is not nullptr. + */ +HWTEST_F(AbilityRecordMgrTest, AddAbilityRecord_0100, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AbilityRecordMgrTest AddAbilityRecord_0100 start"; + auto recordMgr = std::make_shared(); + EXPECT_NE(recordMgr, nullptr); + sptr token = nullptr; + recordMgr->AddAbilityRecord(token, nullptr); + + token = new (std::nothrow) AbilityMgrToken(); + recordMgr->AddAbilityRecord(token, nullptr); + + auto abilityRecord = std::make_shared(nullptr, nullptr); + EXPECT_NE(abilityRecord, nullptr); + + recordMgr->AddAbilityRecord(token, abilityRecord); + EXPECT_EQ(recordMgr->abilityRecords_.size(), 1); + GTEST_LOG_(INFO) << "AbilityRecordMgrTest AddAbilityRecord_0100 end"; +} + +/** + * @tc.number: RemoveAbilityRecord_0100 + * @tc.name: RemoveAbilityRecord + * @tc.desc: RemoveAbilityRecord Test, return is not nullptr. + */ +HWTEST_F(AbilityRecordMgrTest, RemoveAbilityRecord_0100, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AbilityRecordMgrTest RemoveAbilityRecord_0100 start"; + auto recordMgr = std::make_shared(); + EXPECT_NE(recordMgr, nullptr); + sptr token = nullptr; + recordMgr->RemoveAbilityRecord(token); + + token = new (std::nothrow) AbilityMgrToken(); + auto abilityRecord = std::make_shared(nullptr, nullptr); + recordMgr->AddAbilityRecord(token, abilityRecord); + EXPECT_EQ(recordMgr->abilityRecords_.size(), 1); + + recordMgr->RemoveAbilityRecord(token); + EXPECT_EQ(recordMgr->abilityRecords_.size(), 0); + GTEST_LOG_(INFO) << "AbilityRecordMgrTest RemoveAbilityRecord_0100 end"; +} + +/** + * @tc.number: GetRecordCount_0100 + * @tc.name: GetRecordCount + * @tc.desc: GetRecordCount Test, return is not nullptr. + */ +HWTEST_F(AbilityRecordMgrTest, GetRecordCount_0100, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AbilityRecordMgrTest GetRecordCount_0100 start"; + auto recordMgr = std::make_shared(); + EXPECT_EQ(recordMgr->GetRecordCount(), 0); + + sptr token = new (std::nothrow) AbilityMgrToken(); + auto abilityRecord = std::make_shared(nullptr, nullptr); + recordMgr->AddAbilityRecord(token, abilityRecord); + EXPECT_EQ(recordMgr->GetRecordCount(), 1); + GTEST_LOG_(INFO) << "AbilityRecordMgrTest GetRecordCount_0100 end"; +} + +/** + * @tc.number: GetAbilityItem_0100 + * @tc.name: GetAbilityItem + * @tc.desc: GetAbilityItem Test, return is not nullptr. + */ +HWTEST_F(AbilityRecordMgrTest, GetAbilityItem_0100, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AbilityRecordMgrTest GetAbilityItem_0100 start"; + auto recordMgr = std::make_shared(); + sptr token = nullptr; + EXPECT_EQ(recordMgr->GetAbilityItem(token), nullptr); + + token = new (std::nothrow) AbilityMgrToken(); + auto abilityRecord = std::make_shared(nullptr, nullptr); + recordMgr->AddAbilityRecord(token, abilityRecord); + EXPECT_NE(recordMgr->GetAbilityItem(token), nullptr); + + sptr token2 = new (std::nothrow) AbilityMgrToken(); + EXPECT_EQ(recordMgr->GetAbilityItem(token2), nullptr); + + GTEST_LOG_(INFO) << "AbilityRecordMgrTest GetAbilityItem_0100 end"; +} + +/** + * @tc.number: GetAllTokens_0100 + * @tc.name: GetAllTokens + * @tc.desc: GetAllTokens Test, return is not nullptr. + */ +HWTEST_F(AbilityRecordMgrTest, GetAllTokens_0100, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AbilityRecordMgrTest GetAllTokens_0100 start"; + auto recordMgr = std::make_shared(); + + sptr token = new (std::nothrow) AbilityMgrToken(); + auto abilityRecord = std::make_shared(nullptr, nullptr); + recordMgr->AddAbilityRecord(token, abilityRecord); + EXPECT_EQ(recordMgr->GetAllTokens().size(), 1); + + GTEST_LOG_(INFO) << "AbilityRecordMgrTest GetAllTokens_0100 end"; +} +} +} diff --git a/test/unittest/ability_record_test/BUILD.gn b/test/unittest/ability_record_test/BUILD.gn index 19ea363c2e..9a0d77c07e 100644 --- a/test/unittest/ability_record_test/BUILD.gn +++ b/test/unittest/ability_record_test/BUILD.gn @@ -64,6 +64,7 @@ ohos_unittest("ability_record_test") { external_deps = [ "ability_base:configuration", + "ability_base:extractortool", "ability_base:session_info", "ability_base:want", "ability_base:zuri", diff --git a/test/unittest/ability_running_record_test/BUILD.gn b/test/unittest/ability_running_record_test/BUILD.gn new file mode 100644 index 0000000000..a3fd7ec8ad --- /dev/null +++ b/test/unittest/ability_running_record_test/BUILD.gn @@ -0,0 +1,77 @@ +# Copyright (c) 2021-2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +module_output_path = "ability_runtime/appmgr" + +ohos_unittest("ability_running_record_test") { + module_out_path = module_output_path + cflags_cc = [] + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_services_path}/appmgr/include", + ] + + sources = [ + "${ability_runtime_services_path}/appmgr/src/ability_running_record.cpp", + ] + + sources += [ "ability_running_record_test.cpp" ] + + configs = [ "${ability_runtime_test_path}/unittest:appmgr_test_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:perm_verification", + "${ability_runtime_services_path}/common:task_handler_wrap", + "${ability_runtime_test_path}/unittest:appmgr_test_source", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_core", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + ] + + defines = [ "AMS_LOG_TAG = \"AppMgrService\"" ] + + if (ability_command_for_test) { + defines += [ "ABILITY_COMMAND_FOR_TEST" ] + } + + if (ability_runtime_graphics) { + defines += [ "SUPPORT_GRAPHICS" ] + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +group("unittest") { + testonly = true + deps = [ ":ability_running_record_test" ] +} diff --git a/test/unittest/ability_running_record_test/ability_running_record_test.cpp b/test/unittest/ability_running_record_test/ability_running_record_test.cpp new file mode 100644 index 0000000000..e80bb96be8 --- /dev/null +++ b/test/unittest/ability_running_record_test/ability_running_record_test.cpp @@ -0,0 +1,717 @@ +/* + * Copyright (c) 2021-2024 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 + +#include "ability_running_record.h" +#include "app_state_callback_host.h" +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" +#include "mock_ability_token.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AppExecFwk { +class AbilityRunningRecordTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +public: +protected: + static const std::string GetTestBundleName() + { + return "test_bundle_name"; + } + static const std::string GetTestAbilityInfoName() + { + return "test_ability_info_name"; + } + static const std::string GetTestModuleName() + { + return "test_module_name"; + } +}; + +void AbilityRunningRecordTest::SetUpTestCase() +{} + +void AbilityRunningRecordTest::TearDownTestCase() +{} + +void AbilityRunningRecordTest::SetUp() +{} + +void AbilityRunningRecordTest::TearDown() +{} + + +/* + * Feature: AbilityRunningRecord + * Function: GetName + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetName + * EnvConditions: NA + * CaseDescription: GetName + */ +HWTEST_F(AbilityRunningRecordTest, GetName_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetName_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = GetTestAbilityInfoName(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto name = record->GetName(); + ASSERT_EQ(name, "test_ability_info_name"); + TAG_LOGD(AAFwkTag::TEST, "GetName_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetBundleName + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetBundleName + * EnvConditions: NA + * CaseDescription: GetBundleName + */ +HWTEST_F(AbilityRunningRecordTest, GetBundleName_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetBundleName_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->bundleName = GetTestBundleName(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto name = record->GetBundleName(); + ASSERT_EQ(name, "test_bundle_name"); + TAG_LOGD(AAFwkTag::TEST, "GetBundleName_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetModuleName + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetModuleName + * EnvConditions: NA + * CaseDescription: GetModuleName + */ +HWTEST_F(AbilityRunningRecordTest, GetModuleName_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetModuleName_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->moduleName = GetTestModuleName(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto name = record->GetModuleName(); + ASSERT_EQ(name, "test_module_name"); + TAG_LOGD(AAFwkTag::TEST, "GetModuleName_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetAbilityInfo + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetAbilityInfo + * EnvConditions: NA + * CaseDescription: GetAbilityInfo + */ +HWTEST_F(AbilityRunningRecordTest, GetAbilityInfo_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetAbilityInfo_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetAbilityInfo(); + ASSERT_NE(iret, nullptr); + TAG_LOGD(AAFwkTag::TEST, "GetAbilityInfo_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetWant + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetWant + * EnvConditions: NA + * CaseDescription: GetWant + */ +HWTEST_F(AbilityRunningRecordTest, GetWant_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetWant_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetWant(); + ASSERT_EQ(iret, nullptr); + TAG_LOGD(AAFwkTag::TEST, "GetWant_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: SetWant + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord SetWant + * EnvConditions: NA + * CaseDescription: SetWant + */ +HWTEST_F(AbilityRunningRecordTest, SetWant_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "SetWant_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + const std::shared_ptr want = std::make_shared(); + record->SetWant(want); + TAG_LOGD(AAFwkTag::TEST, "SetWant_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetToken + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetToken + * EnvConditions: NA + * CaseDescription: GetToken + */ +HWTEST_F(AbilityRunningRecordTest, GetToken_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetToken_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetToken(); + ASSERT_NE(iret, nullptr); + TAG_LOGD(AAFwkTag::TEST, "GetToken_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: SetState + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord SetState + * EnvConditions: NA + * CaseDescription: SetState + */ +HWTEST_F(AbilityRunningRecordTest, SetState_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "SetState_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + record->SetState(AbilityState::ABILITY_STATE_CREATE); + TAG_LOGD(AAFwkTag::TEST, "SetState_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetState + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetState + * EnvConditions: NA + * CaseDescription: GetState + */ +HWTEST_F(AbilityRunningRecordTest, GetState_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetState_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetState(); + ASSERT_EQ(iret, AbilityState::ABILITY_STATE_CREATE); + TAG_LOGD(AAFwkTag::TEST, "GetState_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: IsSameState + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord IsSameState + * EnvConditions: NA + * CaseDescription: IsSameState + */ +HWTEST_F(AbilityRunningRecordTest, IsSameState_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "IsSameState_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->IsSameState(AbilityState::ABILITY_STATE_CREATE); + ASSERT_EQ(iret, true); + TAG_LOGD(AAFwkTag::TEST, "IsSameState_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetLastLaunchTime + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetLastLaunchTime + * EnvConditions: NA + * CaseDescription: GetLastLaunchTime + */ +HWTEST_F(AbilityRunningRecordTest, GetLastLaunchTime_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetLastLaunchTime_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetLastLaunchTime(); + ASSERT_EQ(iret, 0); + TAG_LOGD(AAFwkTag::TEST, "GetLastLaunchTime_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetPreToken + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetPreToken + * EnvConditions: NA + * CaseDescription: GetPreToken + */ +HWTEST_F(AbilityRunningRecordTest, GetPreToken_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetPreToken_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetPreToken(); + ASSERT_EQ(iret, nullptr); + TAG_LOGD(AAFwkTag::TEST, "GetPreToken_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: SetPreToken + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord SetPreToken + * EnvConditions: NA + * CaseDescription: SetPreToken + */ +HWTEST_F(AbilityRunningRecordTest, SetPreToken_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "SetPreToken_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + sptr pretoken = new MockAbilityToken(); + record->SetPreToken(pretoken); + TAG_LOGD(AAFwkTag::TEST, "SetPreToken_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: SetVisibility + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord SetVisibility + * EnvConditions: NA + * CaseDescription: SetVisibility + */ +HWTEST_F(AbilityRunningRecordTest, SetVisibility_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "SetVisibility_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + const int32_t visibility = 1; + record->SetVisibility(visibility); + TAG_LOGD(AAFwkTag::TEST, "SetVisibility_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetVisibility + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetVisibility + * EnvConditions: NA + * CaseDescription: GetVisibility + */ +HWTEST_F(AbilityRunningRecordTest, GetVisibility_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetVisibility_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetVisibility(); + ASSERT_EQ(iret, 0); + TAG_LOGD(AAFwkTag::TEST, "GetVisibility_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: SetPerceptibility + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord SetPerceptibility + * EnvConditions: NA + * CaseDescription: SetPerceptibility + */ +HWTEST_F(AbilityRunningRecordTest, SetPerceptibility_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "SetPerceptibility_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + const int32_t perceptibility = 1; + record->SetPerceptibility(perceptibility); + TAG_LOGD(AAFwkTag::TEST, "SetPerceptibility_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetPerceptibility + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetPerceptibility + * EnvConditions: NA + * CaseDescription: GetPerceptibility + */ +HWTEST_F(AbilityRunningRecordTest, GetPerceptibility_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetPerceptibility_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetPerceptibility(); + ASSERT_EQ(iret, 0); + TAG_LOGD(AAFwkTag::TEST, "GetPerceptibility_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: SetConnectionState + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord SetConnectionState + * EnvConditions: NA + * CaseDescription: SetConnectionState + */ +HWTEST_F(AbilityRunningRecordTest, SetConnectionState_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "SetConnectionState_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + const int32_t connectionState = 1; + record->SetConnectionState(connectionState); + TAG_LOGD(AAFwkTag::TEST, "SetConnectionState_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetConnectionState + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetConnectionState + * EnvConditions: NA + * CaseDescription: GetConnectionState + */ +HWTEST_F(AbilityRunningRecordTest, GetConnectionState_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetConnectionState_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetConnectionState(); + ASSERT_EQ(iret, 0); + TAG_LOGD(AAFwkTag::TEST, "GetConnectionState_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: SetEventId + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord SetEventId + * EnvConditions: NA + * CaseDescription: SetEventId + */ +HWTEST_F(AbilityRunningRecordTest, SetEventId_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "SetEventId_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + const int64_t eventId = 1; + record->SetEventId(eventId); + TAG_LOGD(AAFwkTag::TEST, "SetEventId_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetEventId + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetEventId + * EnvConditions: NA + * CaseDescription: GetEventId + */ +HWTEST_F(AbilityRunningRecordTest, GetEventId_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetEventId_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetEventId(); + ASSERT_EQ(iret, 0); + TAG_LOGD(AAFwkTag::TEST, "GetEventId_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: SetTerminating + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord SetTerminating + * EnvConditions: NA + * CaseDescription: SetTerminating + */ +HWTEST_F(AbilityRunningRecordTest, SetTerminating_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "SetTerminating_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + record->SetTerminating(); + TAG_LOGD(AAFwkTag::TEST, "SetTerminating_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: IsTerminating + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord IsTerminating + * EnvConditions: NA + * CaseDescription: IsTerminating + */ +HWTEST_F(AbilityRunningRecordTest, IsTerminating_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "IsTerminating_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->IsTerminating(); + ASSERT_EQ(iret, false); + TAG_LOGD(AAFwkTag::TEST, "IsTerminating_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: SetOwnerUserId + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord SetOwnerUserId + * EnvConditions: NA + * CaseDescription: SetOwnerUserId + */ +HWTEST_F(AbilityRunningRecordTest, SetOwnerUserId_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "SetOwnerUserId_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + int32_t ownerUserId = 1; + record->SetOwnerUserId(ownerUserId); + TAG_LOGD(AAFwkTag::TEST, "SetOwnerUserId_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetOwnerUserId + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetOwnerUserId + * EnvConditions: NA + * CaseDescription: GetOwnerUserId + */ +HWTEST_F(AbilityRunningRecordTest, GetOwnerUserId_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetOwnerUserId_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetOwnerUserId(); + ASSERT_EQ(iret, -1); + TAG_LOGD(AAFwkTag::TEST, "GetOwnerUserId_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: SetIsSingleUser + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord SetIsSingleUser + * EnvConditions: NA + * CaseDescription: SetIsSingleUser + */ +HWTEST_F(AbilityRunningRecordTest, SetIsSingleUser_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "SetIsSingleUser_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + bool flag = true; + record->SetIsSingleUser(flag); + TAG_LOGD(AAFwkTag::TEST, "SetIsSingleUser_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: IsSingleUser + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord IsSingleUser + * EnvConditions: NA + * CaseDescription: IsSingleUser + */ +HWTEST_F(AbilityRunningRecordTest, IsSingleUser_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "IsSingleUser_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->IsSingleUser(); + ASSERT_EQ(iret, false); + TAG_LOGD(AAFwkTag::TEST, "IsSingleUser_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: UpdateFocusState + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord UpdateFocusState + * EnvConditions: NA + * CaseDescription: UpdateFocusState + */ +HWTEST_F(AbilityRunningRecordTest, UpdateFocusState_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "UpdateFocusState_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + bool isFocus = true; + record->UpdateFocusState(isFocus); + TAG_LOGD(AAFwkTag::TEST, "UpdateFocusState_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetFocusFlag + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetFocusFlag + * EnvConditions: NA + * CaseDescription: GetFocusFlag + */ +HWTEST_F(AbilityRunningRecordTest, GetFocusFlag_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetFocusFlag_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetFocusFlag(); + ASSERT_EQ(iret, false); + TAG_LOGD(AAFwkTag::TEST, "GetFocusFlag_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: SetUIExtensionAbilityId + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord SetUIExtensionAbilityId + * EnvConditions: NA + * CaseDescription: SetUIExtensionAbilityId + */ +HWTEST_F(AbilityRunningRecordTest, SetUIExtensionAbilityId_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "SetUIExtensionAbilityId_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + const int32_t uiExtensionAbilityId = 1; + record->SetUIExtensionAbilityId(uiExtensionAbilityId); + TAG_LOGD(AAFwkTag::TEST, "SetUIExtensionAbilityId_001 end."); +} + +/* + * Feature: AbilityRunningRecord + * Function: GetUIExtensionAbilityId + * SubFunction: NA + * FunctionPoints: AbilityRunningRecord GetUIExtensionAbilityId + * EnvConditions: NA + * CaseDescription: GetUIExtensionAbilityId + */ +HWTEST_F(AbilityRunningRecordTest, GetUIExtensionAbilityId_001, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "GetUIExtensionAbilityId_001 start."); + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = new MockAbilityToken(); + int32_t abilityRecordId = 1; + auto record = std::make_shared(abilityInfo, token, abilityRecordId); + ASSERT_NE(record, nullptr); + auto iret = record->GetUIExtensionAbilityId(); + ASSERT_EQ(iret, 0); + TAG_LOGD(AAFwkTag::TEST, "GetUIExtensionAbilityId_001 end."); +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/unittest/ams_ability_running_record_test/BUILD.gn b/test/unittest/ams_ability_running_record_test/BUILD.gn index d009f0ea13..b15519bd05 100644 --- a/test/unittest/ams_ability_running_record_test/BUILD.gn +++ b/test/unittest/ams_ability_running_record_test/BUILD.gn @@ -58,6 +58,7 @@ ohos_unittest("AmsAbilityRunningRecordTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/appmgr:libappms", "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:event_report", diff --git a/test/unittest/ams_app_running_record_test/BUILD.gn b/test/unittest/ams_app_running_record_test/BUILD.gn index 99ef9d3fd1..7767958e95 100644 --- a/test/unittest/ams_app_running_record_test/BUILD.gn +++ b/test/unittest/ams_app_running_record_test/BUILD.gn @@ -59,6 +59,7 @@ ohos_unittest("AmsAppRunningRecordTest") { "c_utils:utils", "ffrt:libffrt", "hilog:libhilog", + "image_framework:image_native", "init:libbegetutil", "ipc:ipc_core", ] diff --git a/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp b/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp index ada7c08ab8..0f1460c9c2 100644 --- a/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp +++ b/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp @@ -1704,11 +1704,11 @@ HWTEST_F(AmsAppRunningRecordTest, SetSpecifiedAbilityFlagAndWant_001, TestSize.L std::string processName = "processName"; auto record = std::make_shared(appInfo, recordId, processName); - bool flag = true; + int32_t requestId = 1; AAFwk::Want want; std::string moduleName = "module123"; - record->SetSpecifiedAbilityFlagAndWant(flag, want, moduleName); - EXPECT_TRUE(record->isSpecifiedAbility_ == flag); + record->SetSpecifiedAbilityFlagAndWant(requestId, want, moduleName); + EXPECT_TRUE(record->GetSpecifiedRequestId() == requestId); EXPECT_TRUE(record->moduleName_ == moduleName); } @@ -1729,11 +1729,11 @@ HWTEST_F(AmsAppRunningRecordTest, IsStartSpecifiedAbility_001, TestSize.Level1) std::string processName = "processName"; auto record = std::make_shared(appInfo, recordId, processName); - bool flag = true; + int32_t requestId = 1; AAFwk::Want want; std::string moduleName = "module123"; - record->SetSpecifiedAbilityFlagAndWant(flag, want, moduleName); - EXPECT_TRUE(record->IsStartSpecifiedAbility() == flag); + record->SetSpecifiedAbilityFlagAndWant(requestId, want, moduleName); + EXPECT_TRUE(record->GetSpecifiedRequestId() == requestId); } /* @@ -1753,11 +1753,10 @@ HWTEST_F(AmsAppRunningRecordTest, GetSpecifiedWant_001, TestSize.Level1) std::string processName = "processName"; auto record = std::make_shared(appInfo, recordId, processName); - bool flag = true; Want want; want.SetElementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); std::string moduleName = "module123"; - record->SetSpecifiedAbilityFlagAndWant(flag, want, moduleName); + record->SetSpecifiedAbilityFlagAndWant(1, want, moduleName); EXPECT_TRUE(record->GetSpecifiedWant().GetBundle() == want.GetBundle()); } @@ -1871,7 +1870,7 @@ HWTEST_F(AmsAppRunningRecordTest, Specified_LaunchApplication_001, TestSize.Leve GetMockToken(), nullptr, appInfo, abilityInfo, GetTestProcessName(), bundleInfo, hapModuleInfo, nullptr, 0); record->SetApplicationClient(GetMockedAppSchedulerClient()); - record->isSpecifiedAbility_ = true; + record->specifiedRequestId_ = 1; EXPECT_CALL(*mockAppSchedulerClient_, ScheduleLaunchApplication(_, _)).Times(1); service_->LaunchApplication(record); auto ability = record->GetAbilityRunningRecordByToken(GetMockToken()); @@ -2437,7 +2436,7 @@ HWTEST_F(AmsAppRunningRecordTest, AddAbilityStageDone_001, TestSize.Level1) AAFwk::EventWrap(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG, 1), 0); record->AddAbilityStageDone(); - record->isSpecifiedAbility_ = true; + record->specifiedRequestId_ = 1; record->AddAbilityStageDone(); TAG_LOGI(AAFwkTag::TEST, "AmsAppRunningRecordTest AddAbilityStageDone_001 end"); diff --git a/test/unittest/ams_mgr_proxy_test/ams_mgr_proxy_test.cpp b/test/unittest/ams_mgr_proxy_test/ams_mgr_proxy_test.cpp index 2512976e94..e83f004205 100644 --- a/test/unittest/ams_mgr_proxy_test/ams_mgr_proxy_test.cpp +++ b/test/unittest/ams_mgr_proxy_test/ams_mgr_proxy_test.cpp @@ -162,5 +162,25 @@ HWTEST_F(AmsMgrProxyTest, RegisterAbilityDebugResponse_0100, TestSize.Level1) result = amsMgrProxy_->RegisterAbilityDebugResponse(response_); EXPECT_EQ(result, ERR_INVALID_DATA); } + +/** + * @tc.name: NotifyAppMgrRecordExitReason_0100 + * @tc.desc: NotifyAppMgrRecordExitReason. + * @tc.type: FUNC + */ +HWTEST_F(AmsMgrProxyTest, NotifyAppMgrRecordExitReason_0100, TestSize.Level1) +{ + EXPECT_NE(amsMgrProxy_, nullptr); + EXPECT_NE(response_, nullptr); + EXPECT_CALL(*mockAmsMgrScheduler_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Return(NO_ERROR)); + + int32_t reason = 0; + int32_t pid = 1; + std::string exitMsg = "JsError"; + auto result = amsMgrProxy_->NotifyAppMgrRecordExitReason(reason, pid, exitMsg); + EXPECT_EQ(result, NO_ERROR); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/ams_mgr_scheduler_test/BUILD.gn b/test/unittest/ams_mgr_scheduler_test/BUILD.gn index b3a2bdf713..76bbae7f4b 100644 --- a/test/unittest/ams_mgr_scheduler_test/BUILD.gn +++ b/test/unittest/ams_mgr_scheduler_test/BUILD.gn @@ -24,12 +24,15 @@ ohos_unittest("ams_mgr_scheduler_test") { "${ability_runtime_services_path}/appmgr/include", "${ability_runtime_test_path}/mock/mock_sa_call", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "mock/include", ] sources = [ "${ability_runtime_services_path}/appmgr/src/ams_mgr_scheduler.cpp", "${ability_runtime_test_path}/mock/services_appmgr_test/src/mock_bundle_manager.cpp", "${ability_runtime_test_path}/mock/services_appmgr_test/src/mock_overlay_manager.cpp", + "mock/src/mock_my_flag.cpp", + "mock/src/mock_permission_verification.cpp", ] sources += [ "ams_mgr_scheduler_test.cpp" ] diff --git a/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp b/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp index 19e1f786fd..e371871faa 100644 --- a/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp +++ b/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp @@ -25,6 +25,7 @@ #include "mock_ability_token.h" #include "mock_app_mgr_service_inner.h" #include "mock_bundle_manager.h" +#include "mock_my_flag.h" #include "mock_sa_call.h" #include "application_state_observer_stub.h" @@ -617,6 +618,45 @@ HWTEST_F(AmsMgrSchedulerTest, KillProcessesByUserId_001, TestSize.Level0) amsMgrScheduler->KillProcessesByUserId(userId); } +/* + * Feature: AmsMgrScheduler + * Function: KillProcessesByUserId + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler KillProcessesByUserId + * EnvConditions: NA + * CaseDescription: The caller is not system-app, can not use system-api + */ +HWTEST_F(AmsMgrSchedulerTest, KillProcessesByUserId_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + int32_t userId = 0; + AAFwk::MyFlag::flag_ = 0; + amsMgrScheduler->KillProcessesByUserId(userId); + AAFwk::MyFlag::flag_ = 1; +} + +/* + * Feature: AmsMgrScheduler + * Function: KillProcessesByUserId + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler KillProcessesByUserId + * EnvConditions: NA + * CaseDescription: SubmitTask + */ +HWTEST_F(AmsMgrSchedulerTest, KillProcessesByUserId_003, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + int32_t userId = 0; + AAFwk::MyFlag::flag_ = 1; + amsMgrScheduler->KillProcessesByUserId(userId); +} + /* * Feature: AmsMgrScheduler * Function: KillProcessWithAccount @@ -754,26 +794,6 @@ HWTEST_F(AmsMgrSchedulerTest, GetRunningProcessInfoByToken_001, TestSize.Level0) amsMgrScheduler->GetRunningProcessInfoByToken(token, info); } -/* - * Feature: AmsMgrScheduler - * Function: GetRunningProcessInfoByPid - * SubFunction: NA - * FunctionPoints: AmsMgrScheduler GetRunningProcessInfoByPid - * EnvConditions: NA - * CaseDescription: Verify GetRunningProcessInfoByPid - */ -HWTEST_F(AmsMgrSchedulerTest, GetRunningProcessInfoByPid_001, TestSize.Level0) -{ - auto amsMgrScheduler = std::make_unique(nullptr, nullptr); - ASSERT_NE(amsMgrScheduler, nullptr); - pid_t pid = 0; - RunningProcessInfo info; - amsMgrScheduler->GetRunningProcessInfoByPid(pid, info); - amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); - amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); - amsMgrScheduler->GetRunningProcessInfoByPid(pid, info); -} - /* * Feature: AmsMgrScheduler * Function: IsMemorySizeSufficent @@ -860,6 +880,44 @@ HWTEST_F(AmsMgrSchedulerTest, GetApplicationInfoByProcessID_001, TestSize.Level0 EXPECT_NE(res2, ERR_INVALID_OPERATION); } +/* + * Feature: AmsMgrScheduler + * Function: NotifyAppMgrRecordExitReason + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler NotifyAppMgrRecordExitReason + * EnvConditions: NA + * CaseDescription: Verify NotifyAppMgrRecordExitReason + */ +HWTEST_F(AmsMgrSchedulerTest, NotifyAppMgrRecordExitReason_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + int32_t pid = 0; + int32_t reason = 1; + std::string exitMsg = "JsError"; + int res1 = amsMgrScheduler->NotifyAppMgrRecordExitReason(pid, reason, exitMsg); + EXPECT_EQ(res1, ERR_INVALID_OPERATION); + + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + int res2 = amsMgrScheduler->NotifyAppMgrRecordExitReason(pid, reason, exitMsg); + EXPECT_NE(res2, ERR_INVALID_OPERATION); +} + +/** + * @tc.name: SetCurrentUserId_002 + * @tc.desc: set current userId. + * @tc.type: FUNC + */ +HWTEST_F(AmsMgrSchedulerTest, SetCurrentUserId_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + int userId = 1; + amsMgrScheduler->SetCurrentUserId(userId); +} + /** * @tc.name: SetCurrentUserId_001 * @tc.desc: set current userId. @@ -968,5 +1026,472 @@ HWTEST_F(AmsMgrSchedulerTest, RegisterAbilityDebugResponse_001, TestSize.Level0) res = amsMgrScheduler->RegisterAbilityDebugResponse(response); EXPECT_NE(res, ERR_INVALID_OPERATION); } + +/* + * Feature: AmsMgrScheduler + * Function: KillProcessesByPids + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler KillProcessesByPids + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, KillProcessesByPids_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + int32_t userId = 0; + std::vector pids = {1}; + amsMgrScheduler->KillProcessesByPids(pids); +} + +/* + * Feature: AmsMgrScheduler + * Function: KillProcessesByPids + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler KillProcessesByPids + * EnvConditions: NA + * CaseDescription: SubmitTask + */ +HWTEST_F(AmsMgrSchedulerTest, KillProcessesByPids_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + int32_t userId = 0; + std::vector pids = {1}; + amsMgrScheduler->KillProcessesByPids(pids); +} + +/* + * Feature: AmsMgrScheduler + * Function: AttachPidToParent + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler AttachPidToParent + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, AttachPidToParent_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + const sptr token; + const sptr callerToken; + amsMgrScheduler->AttachPidToParent(token, callerToken); +} + +/* + * Feature: AmsMgrScheduler + * Function: AttachPidToParent + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler AttachPidToParent + * EnvConditions: NA + * CaseDescription: SubmitTask + */ +HWTEST_F(AmsMgrSchedulerTest, AttachPidToParent_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + const sptr token; + const sptr callerToken; + amsMgrScheduler->AttachPidToParent(token, callerToken); +} + +/* + * Feature: AmsMgrScheduler + * Function: UpdateApplicationInfoInstalled + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler UpdateApplicationInfoInstalled + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, UpdateApplicationInfoInstalled_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + const std::string bundleName = ""; + const int uid = 0; + auto iret = amsMgrScheduler->UpdateApplicationInfoInstalled(bundleName, uid); + ASSERT_EQ(iret, 38); +} + +/* + * Feature: AmsMgrScheduler + * Function: UpdateApplicationInfoInstalled + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler UpdateApplicationInfoInstalled + * EnvConditions: NA + * CaseDescription: UpdateApplicationInfoInstalled + */ +HWTEST_F(AmsMgrSchedulerTest, UpdateApplicationInfoInstalled_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + const std::string bundleName = ""; + const int uid = 0; + auto iret = amsMgrScheduler->UpdateApplicationInfoInstalled(bundleName, uid); + ASSERT_EQ(iret, 0); +} + +/* + * Feature: AmsMgrScheduler + * Function: SetAbilityForegroundingFlagToAppRecord + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler SetAbilityForegroundingFlagToAppRecord + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, SetAbilityForegroundingFlagToAppRecord_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + const pid_t pid = 1; + amsMgrScheduler->SetAbilityForegroundingFlagToAppRecord(pid); +} + +/* + * Feature: AmsMgrScheduler + * Function: SetAbilityForegroundingFlagToAppRecord + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler SetAbilityForegroundingFlagToAppRecord + * EnvConditions: NA + * CaseDescription: SetAbilityForegroundingFlagToAppRecord + */ +HWTEST_F(AmsMgrSchedulerTest, SetAbilityForegroundingFlagToAppRecord_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + const pid_t pid = 1; + amsMgrScheduler->SetAbilityForegroundingFlagToAppRecord(pid); +} + +/* + * Feature: AmsMgrScheduler + * Function: StartSpecifiedProcess + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler StartSpecifiedProcess + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, StartSpecifiedProcess_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + const AAFwk::Want want; + const AppExecFwk::AbilityInfo abilityInfo; + int32_t requestId = 1; + amsMgrScheduler->StartSpecifiedProcess(want, abilityInfo, requestId); +} + +/* + * Feature: AmsMgrScheduler + * Function: StartSpecifiedProcess + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler StartSpecifiedProcess + * EnvConditions: NA + * CaseDescription: StartSpecifiedProcess + */ +HWTEST_F(AmsMgrSchedulerTest, StartSpecifiedProcess_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + const AAFwk::Want want; + const AppExecFwk::AbilityInfo abilityInfo; + int32_t requestId = 1; + amsMgrScheduler->StartSpecifiedProcess(want, abilityInfo, requestId); +} + +/* + * Feature: AmsMgrScheduler + * Function: GetBundleNameByPid + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler GetBundleNameByPid + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, GetBundleNameByPid_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + const int pid = 1; + std::string bundleName; + int32_t uid = 1; + auto iret = amsMgrScheduler->GetBundleNameByPid(pid, bundleName, uid); + ASSERT_EQ(iret, 38); +} + +/* + * Feature: AmsMgrScheduler + * Function: GetBundleNameByPid + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler GetBundleNameByPid + * EnvConditions: NA + * CaseDescription: GetBundleNameByPid + */ +HWTEST_F(AmsMgrSchedulerTest, GetBundleNameByPid_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + const int pid = 1; + std::string bundleName; + int32_t uid = 1; + auto iret = amsMgrScheduler->GetBundleNameByPid(pid, bundleName, uid); + ASSERT_EQ(iret, 38); +} + +/* + * Feature: AmsMgrScheduler + * Function: SetAppWaitingDebug + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler SetAppWaitingDebug + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, SetAppWaitingDebug_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + const std::string bundleName; + bool isPersist = true; + auto iret = amsMgrScheduler->SetAppWaitingDebug(bundleName, isPersist); + ASSERT_EQ(iret, 38); +} + +/* + * Feature: AmsMgrScheduler + * Function: SetAppWaitingDebug + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler SetAppWaitingDebug + * EnvConditions: NA + * CaseDescription: SetAppWaitingDebug + */ +HWTEST_F(AmsMgrSchedulerTest, SetAppWaitingDebug_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + const std::string bundleName; + bool isPersist = true; + auto iret = amsMgrScheduler->SetAppWaitingDebug(bundleName, isPersist); + ASSERT_EQ(iret, 22); +} + +/* + * Feature: AmsMgrScheduler + * Function: CancelAppWaitingDebug + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler CancelAppWaitingDebug + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, CancelAppWaitingDebug_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + amsMgrScheduler->CancelAppWaitingDebug(); +} + +/* + * Feature: AmsMgrScheduler + * Function: CancelAppWaitingDebug + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler CancelAppWaitingDebug + * EnvConditions: NA + * CaseDescription: CancelAppWaitingDebug + */ +HWTEST_F(AmsMgrSchedulerTest, CancelAppWaitingDebug_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + amsMgrScheduler->CancelAppWaitingDebug(); +} + +/* + * Feature: AmsMgrScheduler + * Function: GetWaitingDebugApp + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler GetWaitingDebugApp + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, GetWaitingDebugApp_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + std::vector debugInfoList; + auto iret = amsMgrScheduler->GetWaitingDebugApp(debugInfoList); + ASSERT_EQ(iret, 38); +} + +/* + * Feature: AmsMgrScheduler + * Function: GetWaitingDebugApp + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler GetWaitingDebugApp + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, GetWaitingDebugApp_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + std::vector debugInfoList; + auto iret = amsMgrScheduler->GetWaitingDebugApp(debugInfoList); + ASSERT_EQ(iret, 0); +} + +/* + * Feature: AmsMgrScheduler + * Function: IsWaitingDebugApp + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler IsWaitingDebugApp + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, IsWaitingDebugApp_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + const std::string bundleName; + auto iret = amsMgrScheduler->IsWaitingDebugApp(bundleName); + ASSERT_EQ(iret, false); +} + +/* + * Feature: AmsMgrScheduler + * Function: IsWaitingDebugApp + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler IsWaitingDebugApp + * EnvConditions: NA + * CaseDescription: IsWaitingDebugApp + */ +HWTEST_F(AmsMgrSchedulerTest, IsWaitingDebugApp_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + const std::string bundleName; + auto iret = amsMgrScheduler->IsWaitingDebugApp(bundleName); + ASSERT_EQ(iret, false); +} + +/* + * Feature: AmsMgrScheduler + * Function: ClearNonPersistWaitingDebugFlag + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler ClearNonPersistWaitingDebugFlag + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, ClearNonPersistWaitingDebugFlag_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + amsMgrScheduler->ClearNonPersistWaitingDebugFlag(); +} + +/* + * Feature: AmsMgrScheduler + * Function: ClearNonPersistWaitingDebugFlag + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler ClearNonPersistWaitingDebugFlag + * EnvConditions: NA + * CaseDescription: ClearNonPersistWaitingDebugFlag + */ +HWTEST_F(AmsMgrSchedulerTest, ClearNonPersistWaitingDebugFlag_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + amsMgrScheduler->ClearNonPersistWaitingDebugFlag(); +} + +/* + * Feature: AmsMgrScheduler + * Function: IsAttachDebug + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler IsAttachDebug + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, IsAttachDebug_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + const std::string bundleName; + auto iret = amsMgrScheduler->IsAttachDebug(bundleName); + ASSERT_EQ(iret, false); +} + +/* + * Feature: AmsMgrScheduler + * Function: IsAttachDebug + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler IsAttachDebug + * EnvConditions: NA + * CaseDescription: IsAttachDebug + */ +HWTEST_F(AmsMgrSchedulerTest, IsAttachDebug_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + const std::string bundleName; + auto iret = amsMgrScheduler->IsAttachDebug(bundleName); + ASSERT_EQ(iret, false); +} + +/* + * Feature: AmsMgrScheduler + * Function: ClearProcessByToken + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler ClearProcessByToken + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, ClearProcessByToken_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + sptr token; + amsMgrScheduler->ClearProcessByToken(token); +} + +/* + * Feature: AmsMgrScheduler + * Function: ClearProcessByToken + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler ClearProcessByToken + * EnvConditions: NA + * CaseDescription: caller is not foundation + */ +HWTEST_F(AmsMgrSchedulerTest, ClearProcessByToken_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + sptr token; + amsMgrScheduler->ClearProcessByToken(token); +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/app_mgr_service_dump_ipc_test/mock/include/mock_my_flag.h b/test/unittest/ams_mgr_scheduler_test/mock/include/mock_my_flag.h similarity index 87% rename from test/unittest/app_mgr_service_dump_ipc_test/mock/include/mock_my_flag.h rename to test/unittest/ams_mgr_scheduler_test/mock/include/mock_my_flag.h index 50accf24aa..2ee3eafe7f 100644 --- a/test/unittest/app_mgr_service_dump_ipc_test/mock/include/mock_my_flag.h +++ b/test/unittest/ams_mgr_scheduler_test/mock/include/mock_my_flag.h @@ -20,13 +20,12 @@ namespace AAFwk { class MyFlag { public: enum FLAG { - IS_INVALID_CALL = 0, - IS_SA_CALL, + IS_SA_CALL = 1, IS_SHELL_CALL, IS_SA_AND_SHELL_CALL, }; static int flag_; }; -} // namespace AAFwk -} // namespace OHOS -#endif // MOCK_MY_FLAG_H +} // namespace AAFwk +} // namespace OHOS +#endif // MOCK_MY_FLAG_H \ No newline at end of file diff --git a/test/unittest/app_mgr_service_dump_ipc_test/mock/include/mock_permission_verification.h b/test/unittest/ams_mgr_scheduler_test/mock/include/mock_permission_verification.h similarity index 89% rename from test/unittest/app_mgr_service_dump_ipc_test/mock/include/mock_permission_verification.h rename to test/unittest/ams_mgr_scheduler_test/mock/include/mock_permission_verification.h index 14cb3d38eb..fe2bcb25d5 100644 --- a/test/unittest/app_mgr_service_dump_ipc_test/mock/include/mock_permission_verification.h +++ b/test/unittest/ams_mgr_scheduler_test/mock/include/mock_permission_verification.h @@ -16,30 +16,33 @@ #ifndef OHOS_ABILITY_RUNTIME_PERMISSION_VERIFICATION_H #define OHOS_ABILITY_RUNTIME_PERMISSION_VERIFICATION_H -#include "mock_ipc_skeleton.h" -#include "mock_my_flag.h" +#include + +#include "ipc_skeleton.h" #include "singleton.h" #include "want.h" +#include "mock_my_flag.h" namespace OHOS { namespace AAFwk { + class PermissionVerification : public DelayedSingleton { public: - struct VerificationInfo { - bool visible = false; - bool isBackgroundCall = true; - bool associatedWakeUp = false; - uint32_t accessTokenId = 0; - int32_t apiTargetVersion = 0; - }; +struct VerificationInfo { + bool visible = false; + bool isBackgroundCall = true; + bool associatedWakeUp = false; + uint32_t accessTokenId = 0; + int32_t apiTargetVersion = 0; +}; PermissionVerification() = default; ~PermissionVerification() = default; - bool VerifyCallingPermission(const std::string &permissionName, const uint32_t specifyTokenId = 0) const; + bool VerifyCallingPermission(const std::string &permissionName) const; bool IsSACall() const; - + bool IsShellCall() const; bool CheckSpecificSystemAbilityAccessPermission() const; @@ -90,6 +93,6 @@ public: bool JudgeCallerIsAllowedToUseSystemAPI() const; bool IsSystemAppCall() const; }; -} // namespace AAFwk -} // namespace OHOS +} // namespace AAFwk +} // namespace OHOS #endif // OHOS_ABILITY_RUNTIME_PERMISSION_VERIFICATION_H \ No newline at end of file diff --git a/test/unittest/app_mgr_service_dump_ipc_test/mock/src/mock_my_flag.cpp b/test/unittest/ams_mgr_scheduler_test/mock/src/mock_my_flag.cpp similarity index 94% rename from test/unittest/app_mgr_service_dump_ipc_test/mock/src/mock_my_flag.cpp rename to test/unittest/ams_mgr_scheduler_test/mock/src/mock_my_flag.cpp index ce14cafa2c..d94439252b 100644 --- a/test/unittest/app_mgr_service_dump_ipc_test/mock/src/mock_my_flag.cpp +++ b/test/unittest/ams_mgr_scheduler_test/mock/src/mock_my_flag.cpp @@ -17,6 +17,6 @@ namespace OHOS { namespace AAFwk { -int MyFlag::flag_ = 0; +int MyFlag::flag_ = 1; } // namespace AAFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/app_mgr_service_dump_ipc_test/mock/src/mock_permission_verification.cpp b/test/unittest/ams_mgr_scheduler_test/mock/src/mock_permission_verification.cpp similarity index 88% rename from test/unittest/app_mgr_service_dump_ipc_test/mock/src/mock_permission_verification.cpp rename to test/unittest/ams_mgr_scheduler_test/mock/src/mock_permission_verification.cpp index 132a940136..83622f9101 100644 --- a/test/unittest/app_mgr_service_dump_ipc_test/mock/src/mock_permission_verification.cpp +++ b/test/unittest/ams_mgr_scheduler_test/mock/src/mock_permission_verification.cpp @@ -13,12 +13,14 @@ * limitations under the License. */ +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" #include "mock_permission_verification.h" namespace OHOS { namespace AAFwk { -bool PermissionVerification::VerifyCallingPermission( - const std::string &permissionName, const uint32_t specifyTokenId) const + +bool PermissionVerification::VerifyCallingPermission(const std::string &permissionName) const { return !!(MyFlag::flag_); } @@ -32,6 +34,7 @@ bool PermissionVerification::IsShellCall() const } bool PermissionVerification::CheckSpecificSystemAbilityAccessPermission() const { + TAG_LOGD(AAFwkTag::TEST, "mock CheckSpecificSystemAbilityAccessPermission flag_: %{public}d.", MyFlag::flag_); return !!(MyFlag::flag_); } bool PermissionVerification::VerifyRunningInfoPerm() const @@ -112,11 +115,12 @@ int PermissionVerification::JudgeInvisibleAndBackground(const VerificationInfo & } bool PermissionVerification::JudgeCallerIsAllowedToUseSystemAPI() const { - return true; + TAG_LOGD(AAFwkTag::TEST, "mock JudgeCallerIsAllowedToUseSystemAPI flag_: %{public}d.", MyFlag::flag_); + return MyFlag::flag_; } bool PermissionVerification::IsSystemAppCall() const { - return !!(MyFlag::flag_); + return true; } -} // namespace AAFwk -} // namespace OHOS +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/ams_mgr_stub_test/ams_mgr_stub_test.cpp b/test/unittest/ams_mgr_stub_test/ams_mgr_stub_test.cpp index 0f4d76b2cc..01136a54e6 100644 --- a/test/unittest/ams_mgr_stub_test/ams_mgr_stub_test.cpp +++ b/test/unittest/ams_mgr_stub_test/ams_mgr_stub_test.cpp @@ -272,5 +272,33 @@ HWTEST_F(AmsMgrStubTest, HandleRegisterAbilityDebugResponse_0200, TestSize.Level static_cast(IAmsMgr::Message::REGISTER_ABILITY_DEBUG_RESPONSE), data, reply, option); EXPECT_EQ(result, ERR_INVALID_VALUE); } + +/** + * @tc.name: NotifyAppMgrRecordExitReason_0100 + * @tc.desc: NotifyAppMgrRecordExitReason. + * @tc.type: FUNC + */ +HWTEST_F(AmsMgrStubTest, NotifyAppMgrRecordExitReason_0100, TestSize.Level1) +{ + EXPECT_NE(mockAmsMgrScheduler_, nullptr); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + WriteInterfaceToken(data); + + int32_t reason = 0; + int32_t pid = 1; + std::string exitMsg = "JsError"; + data.WriteInt32(reason); + data.WriteInt32(pid); + data.WriteString16(Str8ToStr16(exitMsg)); + + EXPECT_CALL(*mockAmsMgrScheduler_, NotifyAppMgrRecordExitReason(_, _, _)) + .Times(1) + .WillOnce(Return(NO_ERROR)); + auto result = mockAmsMgrScheduler_->OnRemoteRequest( + static_cast(IAmsMgr::Message::NOTIFY_APP_MGR_RECORD_EXIT_REASON), data, reply, option); + EXPECT_EQ(result, NO_ERROR); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/ams_recent_app_list_test/BUILD.gn b/test/unittest/ams_recent_app_list_test/BUILD.gn index 37b469988b..be62d1996a 100644 --- a/test/unittest/ams_recent_app_list_test/BUILD.gn +++ b/test/unittest/ams_recent_app_list_test/BUILD.gn @@ -63,6 +63,7 @@ ohos_unittest("AmsRecentAppListTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:event_report", "${ability_runtime_services_path}/common:perm_verification", @@ -90,6 +91,7 @@ ohos_unittest("AmsRecentAppListTest") { "init:libbegetutil", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "memory_utils:libmeminfo", "resource_schedule_service:ressched_client", ] @@ -110,6 +112,4 @@ ohos_unittest("AmsRecentAppListTest") { group("unittest") { testonly = true - - deps = [ ":AmsRecentAppListTest" ] } diff --git a/test/unittest/ams_service_app_spawn_client_test/BUILD.gn b/test/unittest/ams_service_app_spawn_client_test/BUILD.gn index 17a1aff943..1233cc33b4 100644 --- a/test/unittest/ams_service_app_spawn_client_test/BUILD.gn +++ b/test/unittest/ams_service_app_spawn_client_test/BUILD.gn @@ -63,6 +63,7 @@ ohos_unittest("AmsServiceAppSpawnClientTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/appmgr:libappms", "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:event_report", diff --git a/test/unittest/ams_service_event_drive_test/BUILD.gn b/test/unittest/ams_service_event_drive_test/BUILD.gn index 2e2babf7d5..211b288475 100644 --- a/test/unittest/ams_service_event_drive_test/BUILD.gn +++ b/test/unittest/ams_service_event_drive_test/BUILD.gn @@ -63,6 +63,7 @@ ohos_unittest("AmsServiceEventDriveTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/appmgr:libappms", "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:event_report", diff --git a/test/unittest/ams_service_load_ability_process_test/BUILD.gn b/test/unittest/ams_service_load_ability_process_test/BUILD.gn index 890d695629..a2f9ef75de 100644 --- a/test/unittest/ams_service_load_ability_process_test/BUILD.gn +++ b/test/unittest/ams_service_load_ability_process_test/BUILD.gn @@ -64,6 +64,7 @@ ohos_unittest("AmsServiceLoadAbilityProcessTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:event_report", "${ability_runtime_services_path}/common:perm_verification", @@ -92,6 +93,7 @@ ohos_unittest("AmsServiceLoadAbilityProcessTest") { "init:libbegetutil", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "memory_utils:libmeminfo", "resource_schedule_service:ressched_client", ] diff --git a/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp b/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp index c574cb4468..e16c016f7f 100644 --- a/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp +++ b/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp @@ -177,16 +177,14 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_001, TestSize.Level1) const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); sptr token = GetMockToken(); - StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); - const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto& abilityMap = record->GetAbilities(); @@ -226,16 +224,16 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_002, TestSize.Level1) appInfo->process = GetTestAppName(); const pid_t PID = 1234; - StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); + EXPECT_EQ(recordMap.size(), 0); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto& abilityMap = record->GetAbilities(); @@ -258,7 +256,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_002, TestSize.Level1) appInfo2->bundleName = "com.ohos.test.special"; const pid_t PID2 = 2234; - StartLoadAbility(token2, token, abilityInfo2, appInfo2, PID2); + service_->LoadAbility(token2, token, abilityInfo2, appInfo2, nullptr, 0); const uint32_t EXPECT_MAP_SIZE = 2; if (recordMap.size() == EXPECT_MAP_SIZE) { auto record2 = service_->appRunningManager_->CheckAppRunningRecordIsExist( @@ -420,15 +418,15 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_007, TestSize.Level1) appInfo->bundleName = GetTestAppName(); const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); - StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); + EXPECT_EQ(recordMap.size(), 0); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto& abilityMap = record->GetAbilities(); @@ -475,15 +473,15 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_008, TestSize.Level1) appInfo->bundleName = GetTestAppName(); const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); - StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); + EXPECT_EQ(recordMap.size(), 0); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto& abilityMap = record->GetAbilities(); @@ -542,19 +540,16 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, RequestProcess_001, TestSize.Level1) const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); std::shared_ptr mockClientPtr = std::make_shared(); - EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(PID), Return(ERR_OK))); service_->SetAppSpawnClient(mockClientPtr); service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); - const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetPriorityObject()->GetPid(), PID); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); @@ -584,7 +579,6 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, RequestProcess_002, TestSize.Level1) appInfo->bundleName = GetTestAppName(); EXPECT_TRUE(service_ != nullptr); std::shared_ptr mockClientPtr = std::make_shared(); - EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(Return(ERR_APPEXECFWK_INVALID_PID)); service_->SetAppSpawnClient(mockClientPtr); service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); @@ -618,7 +612,6 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, SavePid_001, TestSize.Level1) const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); std::shared_ptr mockClientPtr = std::make_shared(); - EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(PID), Return(ERR_OK))); service_->SetAppSpawnClient(mockClientPtr); service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); @@ -628,7 +621,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, SavePid_001, TestSize.Level1) auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_EQ(record->GetPriorityObject()->GetPid(), PID); + EXPECT_EQ(record, nullptr); TAG_LOGI(AAFwkTag::TEST, "AmsServiceLoadAbilityProcessTest SavePid_001 end"); } @@ -653,7 +646,6 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, SavePid_002, TestSize.Level1) appInfo->bundleName = GetTestAppName(); EXPECT_TRUE(service_ != nullptr); std::shared_ptr mockClientPtr = std::make_shared(); - EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(Return(ERR_APPEXECFWK_INVALID_PID)); service_->SetAppSpawnClient(mockClientPtr); service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); @@ -690,15 +682,13 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LaunchMode_001, TestSize.Level1) const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); sptr token = GetMockToken(); - StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); - const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto& abilityMap = record->GetAbilities(); @@ -734,15 +724,13 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LaunchMode_002, TestSize.Level1) appInfo->bundleName = GetTestAppName(); const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); - StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); - const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto& abilityMap = record->GetAbilities(); @@ -757,7 +745,6 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LaunchMode_002, TestSize.Level1) sptr preToken = token; service_->SetAppSpawnClient(mockClientPtr); service_->LoadAbility(token2, preToken, abilityInfo, appInfo, nullptr, 0); - EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record2 = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); EXPECT_EQ(record2, record); @@ -789,15 +776,13 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_001, TestSize.Level1) appInfo->bundleName = GetTestAppName(); const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); - StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); - const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto& abilityMap = record->GetAbilities(); @@ -856,15 +841,13 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_002, TestSize.Level1) appInfo->bundleName = GetTestAppName(); const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); - StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); - const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto& abilityMap = record->GetAbilities(); @@ -920,15 +903,13 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_003, TestSize.Level1) const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); - StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); - const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto& abilityMap = record->GetAbilities(); @@ -983,15 +964,13 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_004, TestSize.Level1) appInfo->bundleName = GetTestAppName(); const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); - StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); - const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto& abilityMap = record->GetAbilities(); @@ -1045,15 +1024,13 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_005, TestSize.Level1) const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); - StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); - const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto& abilityMap = record->GetAbilities(); @@ -1109,15 +1086,13 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_006, TestSize.Level1) appInfo->bundleName = GetTestAppName(); const pid_t PID = 1234; EXPECT_TRUE(service_ != nullptr); - StartLoadAbility(token, nullptr, abilityInfo, appInfo, PID); - const auto& recordMap = service_->appRunningManager_->GetAppRunningRecordMap(); - EXPECT_EQ(recordMap.size(), (uint32_t)1); + service_->LoadAbility(token, nullptr, abilityInfo, appInfo, nullptr, 0); BundleInfo bundleInfo; bundleInfo.appId = "com.ohos.test.helloworld_code123"; auto record = service_->appRunningManager_->CheckAppRunningRecordIsExist( appInfo->name, GetTestAppName(), appInfo->uid, bundleInfo); - EXPECT_NE(record, nullptr); + EXPECT_EQ(record, nullptr); CHECK_POINTER_IS_NULLPTR(record); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto& abilityMap = record->GetAbilities(); diff --git a/test/unittest/ams_service_startup_test/BUILD.gn b/test/unittest/ams_service_startup_test/BUILD.gn index 66f10e7d4b..3ab1a3e1d2 100644 --- a/test/unittest/ams_service_startup_test/BUILD.gn +++ b/test/unittest/ams_service_startup_test/BUILD.gn @@ -60,6 +60,7 @@ ohos_unittest("AmsServiceStartupTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/appmgr:libappms", "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:event_report", diff --git a/test/unittest/app_config_data_manager_test/BUILD.gn b/test/unittest/app_config_data_manager_test/BUILD.gn new file mode 100644 index 0000000000..699f0fc9a1 --- /dev/null +++ b/test/unittest/app_config_data_manager_test/BUILD.gn @@ -0,0 +1,80 @@ +# Copyright (c) 2021-2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +module_output_path = "ability_runtime/appmgr" + +ohos_unittest("app_config_data_manager_test") { + module_out_path = module_output_path + cflags_cc = [] + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_services_path}/appmgr/include", + "${distributeddatamgr_path}/kv_store/interfaces/innerkits/distributeddata/include", + ] + + sources = [ + "${ability_runtime_services_path}/appmgr/src/app_config_data_manager.cpp", + ] + + sources += [ "app_config_data_manager_test.cpp" ] + + configs = [ "${ability_runtime_test_path}/unittest:appmgr_test_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:perm_verification", + "${ability_runtime_services_path}/common:task_handler_wrap", + "${ability_runtime_test_path}/unittest:appmgr_test_source", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_core", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", + ] + + defines = [ "AMS_LOG_TAG = \"AppMgrService\"" ] + + if (ability_command_for_test) { + defines += [ "ABILITY_COMMAND_FOR_TEST" ] + } + + if (ability_runtime_graphics) { + defines += [ "SUPPORT_GRAPHICS" ] + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +group("unittest") { + testonly = true + deps = [ ":app_config_data_manager_test" ] +} diff --git a/test/unittest/app_config_data_manager_test/app_config_data_manager_test.cpp b/test/unittest/app_config_data_manager_test/app_config_data_manager_test.cpp new file mode 100644 index 0000000000..a0d65fe79c --- /dev/null +++ b/test/unittest/app_config_data_manager_test/app_config_data_manager_test.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2021-2024 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 + +#include "app_config_data_manager.h" +#include "app_state_callback_host.h" +#include "errors.h" +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" +#include "mock_ability_token.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AppExecFwk { +class AppConfigDataManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +public: +protected: + static const std::string GetTestBundleName() + { + return "test_bundle_name"; + } + static const std::string GetTestAbilityInfoName() + { + return "test_ability_info_name"; + } + static const std::string GetTestModuleName() + { + return "test_module_name"; + } +}; + +void AppConfigDataManagerTest::SetUpTestCase() +{} + +void AppConfigDataManagerTest::TearDownTestCase() +{} + +void AppConfigDataManagerTest::SetUp() +{} + +void AppConfigDataManagerTest::TearDown() +{} + + +/* + * Feature: AppConfigDataManager + * Function: SetAppWaitingDebugInfo + * SubFunction: NA + * FunctionPoints: AppConfigDataManager SetAppWaitingDebugInfo + * EnvConditions: NA + * CaseDescription: bundle name empty + */ +HWTEST_F(AppConfigDataManagerTest, SetAppWaitingDebugInfo_001, TestSize.Level1) +{ + auto manager = std::make_shared(); + const std::string bundleName; + auto iret = manager->SetAppWaitingDebugInfo(bundleName); + ASSERT_EQ(iret, ERR_INVALID_VALUE); +} + +/* + * Feature: AppConfigDataManager + * Function: SetAppWaitingDebugInfo + * SubFunction: NA + * FunctionPoints: AppConfigDataManager SetAppWaitingDebugInfo + * EnvConditions: NA + * CaseDescription: set ok + */ +HWTEST_F(AppConfigDataManagerTest, SetAppWaitingDebugInfo_002, TestSize.Level1) +{ + auto manager = std::make_shared(); + const std::string bundleName = "bundle"; + auto iret = manager->SetAppWaitingDebugInfo(bundleName); + ASSERT_EQ(iret, ERR_OK); +} + +/* + * Feature: AppConfigDataManager + * Function: ClearAppWaitingDebugInfo + * SubFunction: NA + * FunctionPoints: AppConfigDataManager ClearAppWaitingDebugInfo + * EnvConditions: NA + * CaseDescription: clear ok + */ +HWTEST_F(AppConfigDataManagerTest, ClearAppWaitingDebugInfo_001, TestSize.Level1) +{ + auto manager = std::make_shared(); + auto iret = manager->ClearAppWaitingDebugInfo(); + ASSERT_EQ(iret, ERR_OK); +} + +/* + * Feature: AppConfigDataManager + * Function: GetAppWaitingDebugList + * SubFunction: NA + * FunctionPoints: AppConfigDataManager GetAppWaitingDebugList + * EnvConditions: NA + * CaseDescription: get ok + */ +HWTEST_F(AppConfigDataManagerTest, GetAppWaitingDebugList_001, TestSize.Level1) +{ + auto manager = std::make_shared(); + std::vector bundleNameList; + auto iret = manager->GetAppWaitingDebugList(bundleNameList); + ASSERT_EQ(iret, ERR_OK); +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/unittest/app_exit_reason_data_manager_test/BUILD.gn b/test/unittest/app_exit_reason_data_manager_test/BUILD.gn index c2845e2220..a315c75b8c 100755 --- a/test/unittest/app_exit_reason_data_manager_test/BUILD.gn +++ b/test/unittest/app_exit_reason_data_manager_test/BUILD.gn @@ -13,7 +13,6 @@ import("//build/test.gni") import("//foundation/ability/ability_runtime/ability_runtime.gni") -import("//foundation/distributeddatamgr/relational_store/relational_store.gni") module_output_path = "ability_runtime/abilitymgr" diff --git a/test/unittest/app_mgr_client_test/app_mgr_client_test.cpp b/test/unittest/app_mgr_client_test/app_mgr_client_test.cpp index 71f76e2aae..1781f7576d 100644 --- a/test/unittest/app_mgr_client_test/app_mgr_client_test.cpp +++ b/test/unittest/app_mgr_client_test/app_mgr_client_test.cpp @@ -249,6 +249,26 @@ HWTEST_F(AppMgrClientTest, AppMgrClient_GetApplicationInfoByProcessID_001, TestS EXPECT_EQ(application.bundleName, EMPTY_STRING); } +/** + * @tc.name: AppMgrClient_NotifyAppMgrRecordExitReason_001 + * @tc.desc: test NotifyAppMgrRecordExitReason. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrClientTest, AppMgrClient_NotifyAppMgrRecordExitReason_001, TestSize.Level0) +{ + auto appMgrClient = std::make_unique(); + EXPECT_NE(appMgrClient, nullptr); + + auto result = appMgrClient->ConnectAppMgrService(); + EXPECT_EQ(result, AppMgrResultCode::RESULT_OK); + + int32_t reason = 0; + int32_t pid = 1; + std::string exitMsg = "JsError"; + auto ret = appMgrClient->NotifyAppMgrRecordExitReason(reason, pid, exitMsg); + EXPECT_NE(ret, ERR_OK); +} + /** * @tc.name: AppMgrClient_GetAllRenderProcesses_001 * @tc.desc: get all render processes. @@ -1001,24 +1021,6 @@ HWTEST_F(AppMgrClientTest, AppMgrClient_StartSpecifiedProcess_001, TestSize.Leve EXPECT_EQ(result, AppMgrResultCode::RESULT_OK); } -/** - * @tc.name: AppMgrClient_ScheduleNewProcessRequest_001 - * @tc.desc: schedule accept want done. - * @tc.type: FUNC - */ -HWTEST_F(AppMgrClientTest, AppMgrClient_ScheduleNewProcessRequest_001, TestSize.Level0) -{ - int32_t recordId = INIT_VALUE; - AAFwk::Want want; - std::string flag = EMPTY_STRING; - auto appMgrClient = std::make_unique(); - EXPECT_NE(appMgrClient, nullptr); - - auto result = appMgrClient->ConnectAppMgrService(); - appMgrClient->ScheduleNewProcessRequest(recordId, want, flag); - EXPECT_EQ(result, AppMgrResultCode::RESULT_OK); -} - /** * @tc.name: AppMgrClient_RegisterAppRunningStatusListener_001 * @tc.desc: RegisterAppRunningStatusListener. @@ -1238,20 +1240,6 @@ HWTEST_F(AppMgrClientTest, ClearNonPersistWaitingDebugFlag_001, TestSize.Level0) EXPECT_NE(appMgrClient, nullptr); } -/** - * @tc.name: AppMgrClient_SetAppAssertionPauseState_001 - * @tc.desc: SetAppAssertionPauseState. - * @tc.type: FUNC - */ -HWTEST_F(AppMgrClientTest, SetAppAssertionPauseState_001, TestSize.Level0) -{ - auto appMgrClient = std::make_unique(); - int32_t pid = 1; - bool flag = true; - appMgrClient->SetAppAssertionPauseState(pid, flag); - EXPECT_NE(appMgrClient, nullptr); -} - /** * @tc.name: AppMgrClient_IsAttachDebug_001 * @tc.desc: IsAttachDebug. diff --git a/test/unittest/app_mgr_proxy_test/app_mgr_proxy_test.cpp b/test/unittest/app_mgr_proxy_test/app_mgr_proxy_test.cpp index e22ecd873c..28764ffc28 100644 --- a/test/unittest/app_mgr_proxy_test/app_mgr_proxy_test.cpp +++ b/test/unittest/app_mgr_proxy_test/app_mgr_proxy_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 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 @@ -584,5 +584,47 @@ HWTEST_F(AppMgrProxyTest, PreloadApplication_0100, TestSize.Level1) EXPECT_EQ(mockAppMgrService_->code_, static_cast(AppMgrInterfaceCode::PRELOAD_APPLICATION)); } + +/** + * @tc.name: SetSupportedProcessCacheSelf_001 + * @tc.desc: The application sets itself whether or not to support process cache. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrProxyTest, SetSupportedProcessCacheSelf_001, TestSize.Level0) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + + EXPECT_CALL(*mockAppMgrService_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(mockAppMgrService_.GetRefPtr(), &MockAppMgrService::InvokeSendRequest)); + bool isSupported = false; + appMgrProxy_->SetSupportedProcessCacheSelf(isSupported); + EXPECT_EQ(mockAppMgrService_->code_, static_cast(AppMgrInterfaceCode::SET_SUPPORTED_PROCESS_CACHE_SELF)); + + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: GetRunningMultiAppInfoByBundleName_001 + * @tc.desc: Get multiApp information by bundleName. + * @tc.type: FUNC + * @tc.require: issueI9HMAO + */ +HWTEST_F(AppMgrProxyTest, GetRunningMultiAppInfoByBundleName_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + + EXPECT_CALL(*mockAppMgrService_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(mockAppMgrService_.GetRefPtr(), &MockAppMgrService::InvokeSendRequest)); + + std::string bundleName = "testBundleName"; + RunningMultiAppInfo info; + appMgrProxy_->GetRunningMultiAppInfoByBundleName(bundleName, info); + EXPECT_EQ(mockAppMgrService_->code_, static_cast + (AppMgrInterfaceCode::GET_RUNNING_MULTIAPP_INFO_BY_BUNDLENAME)); + + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/app_mgr_service_dump_ffrt_test/BUILD.gn b/test/unittest/app_mgr_service_dump_ffrt_test/BUILD.gn new file mode 100644 index 0000000000..957f6ff9b7 --- /dev/null +++ b/test/unittest/app_mgr_service_dump_ffrt_test/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +module_output_path = "ability_runtime/abilitymgr" + +ohos_unittest("app_mgr_service_dump_ffrt_test") { + module_out_path = module_output_path + + include_dirs = [ + "${ability_runtime_test_path}/mock/common/include", + "mock/include", + ] + + sources = [ + "app_mgr_service_dump_ffrt_test.cpp", + "mock/src/mock_ipc_skeleton.cpp", + ] + + configs = [ "${ability_runtime_services_path}/appmgr:appmgr_config" ] + + deps = [ + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:task_handler_wrap", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:want", + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +group("unittest") { + testonly = true + + deps = [ ":app_mgr_service_dump_ffrt_test" ] +} diff --git a/test/unittest/app_mgr_service_dump_ffrt_test/app_mgr_service_dump_ffrt_test.cpp b/test/unittest/app_mgr_service_dump_ffrt_test/app_mgr_service_dump_ffrt_test.cpp new file mode 100644 index 0000000000..4dbbaedcd7 --- /dev/null +++ b/test/unittest/app_mgr_service_dump_ffrt_test/app_mgr_service_dump_ffrt_test.cpp @@ -0,0 +1,457 @@ +/* + * Copyright (c) 2024 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 + +#include "mock_ipc_skeleton.h" + +#define private public +#include "app_mgr_service.h" +#undef private +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" +#include "mock_app_mgr_service_inner.h" +#include "app_mgr_service_dump_error_code.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AppExecFwk { +namespace { +const int32_t HIDUMPER_SERVICE_UID = 1212; +const int32_t RANDOM_SERVICE_UID = 1500; +const int32_t NUMBER_VALID_PID_1 = 2000; +const int32_t NUMBER_VALID_PID_2 = 2001; +const int32_t NUMBER_VALID_PID_3 = 2002; +const int32_t NUMBER_VALID_PID_4 = 2003; +const int32_t NUMBER_INVALID_PID_1 = -1001; +const int32_t NUMBER_INVALID_PID_2 = -1002; +const int32_t NUMBER_INVALID_PID_3 = -1003; +const int32_t NUMBER_PID_APP_RUNING_RECORD_NOT_EXIST_1 = 3000; +const int32_t NUMBER_PID_APP_RUNING_RECORD_NOT_EXIST_2 = 3001; +const int32_t NUMBER_PID_APP_RUNING_RECORD_NOT_EXIST_3 = 3002; +const std::string STRING_INVALID_PID_1 = "invalid"; +const std::string STRING_INVALID_PID_2 = "invalid1000"; +const std::string STRING_OPTION_FFRT = "--ffrt"; +} // namespace + +class AppMgrServiceDumpFFRTTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; + +void AppMgrServiceDumpFFRTTest::SetUpTestCase(void) +{} + +void AppMgrServiceDumpFFRTTest::TearDownTestCase(void) +{} + +void AppMgrServiceDumpFFRTTest::SetUp() +{} + +void AppMgrServiceDumpFFRTTest::TearDown() +{} + +/* + * @tc.number : AppMgrServiceDumpFFRT_0100 + * @tc.name : AppMgrService dump + * @tc.desc : 1.Test with args --ffrt + */ +HWTEST_F(AppMgrServiceDumpFFRTTest, AppMgrServiceDumpFFRT_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0100 start"); + + auto appMgrService = std::make_shared(); + EXPECT_NE(appMgrService, nullptr); + appMgrService->taskHandler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler(Constants::APP_MGR_SERVICE_NAME); + EXPECT_NE(appMgrService->taskHandler_, nullptr); + auto mockAppMgrServiceInner = std::make_shared(); + EXPECT_NE(mockAppMgrServiceInner, nullptr); + appMgrService->SetInnerService(mockAppMgrServiceInner); + EXPECT_NE(appMgrService->appMgrServiceInner_, nullptr); + appMgrService->eventHandler_ = std::make_shared( + appMgrService->taskHandler_, appMgrService->appMgrServiceInner_); + EXPECT_NE(appMgrService->eventHandler_, nullptr); + + // IsHidumperServiceCall + IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); + EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); + + constexpr int fd(1); + std::vector args; + auto arg0 = Str8ToStr16(STRING_OPTION_FFRT); + args.emplace_back(arg0); + auto result = appMgrService->Dump(fd, args); + EXPECT_EQ(result, DumpErrorCode::ERR_INVALID_NUM_ARGS_ERROR); + + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0100 end"); +} + +/* + * @tc.number : AppMgrServiceDumpFFRT_0200 + * @tc.name : AppMgrService dump + * @tc.desc : 1.Test with args --ffrt without correct permission + */ +HWTEST_F(AppMgrServiceDumpFFRTTest, AppMgrServiceDumpFFRT_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0200 start"); + + auto appMgrService = std::make_shared(); + EXPECT_NE(appMgrService, nullptr); + appMgrService->taskHandler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler(Constants::APP_MGR_SERVICE_NAME); + EXPECT_NE(appMgrService->taskHandler_, nullptr); + auto mockAppMgrServiceInner = std::make_shared(); + EXPECT_NE(mockAppMgrServiceInner, nullptr); + appMgrService->SetInnerService(mockAppMgrServiceInner); + EXPECT_NE(appMgrService->appMgrServiceInner_, nullptr); + appMgrService->eventHandler_ = std::make_shared( + appMgrService->taskHandler_, appMgrService->appMgrServiceInner_); + EXPECT_NE(appMgrService->eventHandler_, nullptr); + + // Not HidumperServiceCall + IPCSkeleton::SetCallingUid(RANDOM_SERVICE_UID); + EXPECT_FALSE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); + + constexpr int fd(1); + std::vector args; + auto arg0 = Str8ToStr16(STRING_OPTION_FFRT); + args.emplace_back(arg0); + auto arg1 = Str8ToStr16(std::to_string(NUMBER_VALID_PID_1)); + args.emplace_back(arg1); + auto result = appMgrService->Dump(fd, args); + EXPECT_EQ(result, DumpErrorCode::ERR_PERMISSION_DENY_ERROR); + + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0200 end"); +} + +/* + * @tc.number : AppMgrServiceDumpFFRT_0300 + * @tc.name : AppMgrService dump + * @tc.desc : 1.Test with args --ffrt pid1|pid2|pid3 + */ +HWTEST_F(AppMgrServiceDumpFFRTTest, AppMgrServiceDumpFFRT_0300, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0300 start"); + + auto appMgrService = std::make_shared(); + EXPECT_NE(appMgrService, nullptr); + appMgrService->taskHandler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler(Constants::APP_MGR_SERVICE_NAME); + EXPECT_NE(appMgrService->taskHandler_, nullptr); + auto mockAppMgrServiceInner = std::make_shared(); + EXPECT_NE(mockAppMgrServiceInner, nullptr); + appMgrService->SetInnerService(mockAppMgrServiceInner); + EXPECT_NE(appMgrService->appMgrServiceInner_, nullptr); + appMgrService->eventHandler_ = std::make_shared( + appMgrService->taskHandler_, appMgrService->appMgrServiceInner_); + EXPECT_NE(appMgrService->eventHandler_, nullptr); + + // IsHidumperServiceCall + IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); + EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); + + constexpr int fd(1); + std::vector args; + auto arg0 = Str8ToStr16(STRING_OPTION_FFRT); + args.emplace_back(arg0); + std::string pids; + pids.append(std::to_string(NUMBER_VALID_PID_1)) + .append("|") + .append(std::to_string(NUMBER_VALID_PID_2)) + .append("|") + .append(std::to_string(NUMBER_VALID_PID_3)); + auto arg1 = Str8ToStr16(pids); + args.emplace_back(arg1); + auto result = appMgrService->Dump(fd, args); + EXPECT_EQ(result, DumpErrorCode::ERR_INVALID_PID_ERROR); + + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0300 end"); +} + +/* + * @tc.number : AppMgrServiceDumpFFRT_0400 + * @tc.name : AppMgrService dump + * @tc.desc : 1.Test with args --ffrt ' ,,' + */ +HWTEST_F(AppMgrServiceDumpFFRTTest, AppMgrServiceDumpFFRT_0400, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0400 start"); + + auto appMgrService = std::make_shared(); + EXPECT_NE(appMgrService, nullptr); + appMgrService->taskHandler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler(Constants::APP_MGR_SERVICE_NAME); + EXPECT_NE(appMgrService->taskHandler_, nullptr); + auto mockAppMgrServiceInner = std::make_shared(); + EXPECT_NE(mockAppMgrServiceInner, nullptr); + appMgrService->SetInnerService(mockAppMgrServiceInner); + EXPECT_NE(appMgrService->appMgrServiceInner_, nullptr); + appMgrService->eventHandler_ = std::make_shared( + appMgrService->taskHandler_, appMgrService->appMgrServiceInner_); + EXPECT_NE(appMgrService->eventHandler_, nullptr); + + // IsHidumperServiceCall + IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); + EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); + + constexpr int fd(1); + std::vector args; + auto arg0 = Str8ToStr16(STRING_OPTION_FFRT); + args.emplace_back(arg0); + std::string pids; + pids.append(" ,") + .append(std::to_string(NUMBER_INVALID_PID_1)) + .append(",") + .append(STRING_INVALID_PID_2); + auto arg1 = Str8ToStr16(pids); + args.emplace_back(arg1); + auto result = appMgrService->Dump(fd, args); + EXPECT_EQ(result, DumpErrorCode::ERR_INVALID_PID_ERROR); + + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0400 end"); +} + +/* + * @tc.number : AppMgrServiceDumpFFRT_0500 + * @tc.name : AppMgrService dump + * @tc.desc : 1.Test with args --ffrt ,,, + */ +HWTEST_F(AppMgrServiceDumpFFRTTest, AppMgrServiceDumpFFRT_0500, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0500 start"); + + auto appMgrService = std::make_shared(); + EXPECT_NE(appMgrService, nullptr); + appMgrService->taskHandler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler(Constants::APP_MGR_SERVICE_NAME); + EXPECT_NE(appMgrService->taskHandler_, nullptr); + auto mockAppMgrServiceInner = std::make_shared(); + EXPECT_NE(mockAppMgrServiceInner, nullptr); + appMgrService->SetInnerService(mockAppMgrServiceInner); + EXPECT_NE(appMgrService->appMgrServiceInner_, nullptr); + appMgrService->eventHandler_ = std::make_shared( + appMgrService->taskHandler_, appMgrService->appMgrServiceInner_); + EXPECT_NE(appMgrService->eventHandler_, nullptr); + + // IsHidumperServiceCall + IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); + EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); + + constexpr int fd(1); + std::vector args; + auto arg0 = Str8ToStr16(STRING_OPTION_FFRT); + args.emplace_back(arg0); + std::string pids; + pids.append(std::to_string(NUMBER_INVALID_PID_1)) + .append(",") + .append(std::to_string(NUMBER_INVALID_PID_2)) + .append(",") + .append(std::to_string(NUMBER_INVALID_PID_3)) + .append(",") + .append(std::to_string(NUMBER_VALID_PID_1)); + auto arg1 = Str8ToStr16(pids); + args.emplace_back(arg1); + auto result = appMgrService->Dump(fd, args); + EXPECT_EQ(result, DumpErrorCode::ERR_INVALID_PID_ERROR); + + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0500 end"); +} + +/* + * @tc.number : AppMgrServiceDumpFFRT_0600 + * @tc.name : AppMgrService dump + * @tc.desc : 1.Test with args --ffrt --stat + */ +HWTEST_F(AppMgrServiceDumpFFRTTest, AppMgrServiceDumpFFRT_0600, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0600 start"); + + auto appMgrService = std::make_shared(); + EXPECT_NE(appMgrService, nullptr); + appMgrService->taskHandler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler(Constants::APP_MGR_SERVICE_NAME); + EXPECT_NE(appMgrService->taskHandler_, nullptr); + auto mockAppMgrServiceInner = std::make_shared(); + EXPECT_NE(mockAppMgrServiceInner, nullptr); + appMgrService->SetInnerService(mockAppMgrServiceInner); + EXPECT_NE(appMgrService->appMgrServiceInner_, nullptr); + appMgrService->eventHandler_ = std::make_shared( + appMgrService->taskHandler_, appMgrService->appMgrServiceInner_); + EXPECT_NE(appMgrService->eventHandler_, nullptr); + + // IsHidumperServiceCall + IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); + EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); + + constexpr int fd(1); + std::vector args; + auto arg0 = Str8ToStr16(STRING_OPTION_FFRT); + args.emplace_back(arg0); + std::string pids; + pids.append(std::to_string(NUMBER_PID_APP_RUNING_RECORD_NOT_EXIST_1)) + .append(",") + .append(std::to_string(NUMBER_PID_APP_RUNING_RECORD_NOT_EXIST_2)) + .append(",") + .append(std::to_string(NUMBER_PID_APP_RUNING_RECORD_NOT_EXIST_3)); + auto arg1 = Str8ToStr16(pids); + args.emplace_back(arg1); + EXPECT_CALL(*mockAppMgrServiceInner, DumpFfrt(_, _)) + .Times(1).WillOnce(Return(DumpErrorCode::ERR_INVALID_PID_ERROR)); + auto result = appMgrService->Dump(fd, args); + EXPECT_EQ(result, DumpErrorCode::ERR_INVALID_PID_ERROR); + + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0600 end"); +} + +/* + * @tc.number : AppMgrServiceDumpFFRT_0700 + * @tc.name : AppMgrService dump + * @tc.desc : 1.Test with args --ffrt pid1,pid2,pid3,pid4 + */ +HWTEST_F(AppMgrServiceDumpFFRTTest, AppMgrServiceDumpFFRT_0700, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0700 start"); + + auto appMgrService = std::make_shared(); + EXPECT_NE(appMgrService, nullptr); + appMgrService->taskHandler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler(Constants::APP_MGR_SERVICE_NAME); + EXPECT_NE(appMgrService->taskHandler_, nullptr); + auto mockAppMgrServiceInner = std::make_shared(); + EXPECT_NE(mockAppMgrServiceInner, nullptr); + appMgrService->SetInnerService(mockAppMgrServiceInner); + EXPECT_NE(appMgrService->appMgrServiceInner_, nullptr); + appMgrService->eventHandler_ = std::make_shared( + appMgrService->taskHandler_, appMgrService->appMgrServiceInner_); + EXPECT_NE(appMgrService->eventHandler_, nullptr); + + // IsHidumperServiceCall + IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); + EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); + + constexpr int fd(1); + std::vector args; + auto arg0 = Str8ToStr16(STRING_OPTION_FFRT); + args.emplace_back(arg0); + std::string pids; + pids.append(std::to_string(NUMBER_VALID_PID_1)) + .append(",") + .append(std::to_string(NUMBER_VALID_PID_2)) + .append(",") + .append(std::to_string(NUMBER_VALID_PID_3)) + .append(",") + .append(std::to_string(NUMBER_VALID_PID_4)); + auto arg1 = Str8ToStr16(pids); + args.emplace_back(arg1); + std::vector validPids = {NUMBER_VALID_PID_1, NUMBER_VALID_PID_2, NUMBER_VALID_PID_3}; + EXPECT_CALL(*mockAppMgrServiceInner, DumpFfrt(validPids, _)) + .Times(1).WillOnce(Return(DumpErrorCode::ERR_OK)); + auto result = appMgrService->Dump(fd, args); + EXPECT_EQ(result, DumpErrorCode::ERR_OK); + + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0700 end"); +} + +/* + * @tc.number : AppMgrServiceDumpFFRT_0800 + * @tc.name : AppMgrService dump + * @tc.desc : 1.Test with args --ffrt pid1,,pid2,pid3 + */ +HWTEST_F(AppMgrServiceDumpFFRTTest, AppMgrServiceDumpFFRT_0800, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0800 start"); + + auto appMgrService = std::make_shared(); + EXPECT_NE(appMgrService, nullptr); + appMgrService->taskHandler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler(Constants::APP_MGR_SERVICE_NAME); + EXPECT_NE(appMgrService->taskHandler_, nullptr); + auto mockAppMgrServiceInner = std::make_shared(); + EXPECT_NE(mockAppMgrServiceInner, nullptr); + appMgrService->SetInnerService(mockAppMgrServiceInner); + EXPECT_NE(appMgrService->appMgrServiceInner_, nullptr); + appMgrService->eventHandler_ = std::make_shared( + appMgrService->taskHandler_, appMgrService->appMgrServiceInner_); + EXPECT_NE(appMgrService->eventHandler_, nullptr); + + // IsHidumperServiceCall + IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); + EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); + + constexpr int fd(1); + std::vector args; + auto arg0 = Str8ToStr16(STRING_OPTION_FFRT); + args.emplace_back(arg0); + std::string pids; + pids.append(std::to_string(NUMBER_VALID_PID_1)) + .append(",") + .append(STRING_INVALID_PID_1) + .append(",") + .append(std::to_string(NUMBER_VALID_PID_2)) + .append(",") + .append(std::to_string(NUMBER_VALID_PID_3)); + auto arg1 = Str8ToStr16(pids); + args.emplace_back(arg1); + std::vector validPids = {NUMBER_VALID_PID_1, NUMBER_VALID_PID_2}; + EXPECT_CALL(*mockAppMgrServiceInner, DumpFfrt(validPids, _)) + .Times(1).WillOnce(Return(DumpErrorCode::ERR_OK)); + auto result = appMgrService->Dump(fd, args); + EXPECT_EQ(result, DumpErrorCode::ERR_OK); + + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0800 end"); +} + +/* + * @tc.number : AppMgrServiceDumpFFRT_0900 + * @tc.name : AppMgrService dump + * @tc.desc : 1.Test with args --ffrt |pid2|pid3 + */ +HWTEST_F(AppMgrServiceDumpFFRTTest, AppMgrServiceDumpFFRT_0900, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0900 start"); + + auto appMgrService = std::make_shared(); + EXPECT_NE(appMgrService, nullptr); + appMgrService->taskHandler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler(Constants::APP_MGR_SERVICE_NAME); + EXPECT_NE(appMgrService->taskHandler_, nullptr); + auto mockAppMgrServiceInner = std::make_shared(); + EXPECT_NE(mockAppMgrServiceInner, nullptr); + appMgrService->SetInnerService(mockAppMgrServiceInner); + EXPECT_NE(appMgrService->appMgrServiceInner_, nullptr); + appMgrService->eventHandler_ = std::make_shared( + appMgrService->taskHandler_, appMgrService->appMgrServiceInner_); + EXPECT_NE(appMgrService->eventHandler_, nullptr); + + // IsHidumperServiceCall + IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); + EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); + + constexpr int fd(1); + std::vector args; + auto arg0 = Str8ToStr16(STRING_OPTION_FFRT); + args.emplace_back(arg0); + std::string pids; + pids.append(STRING_INVALID_PID_1) + .append("|") + .append(std::to_string(NUMBER_VALID_PID_2)) + .append("|") + .append(std::to_string(NUMBER_VALID_PID_3)); + auto arg1 = Str8ToStr16(pids); + args.emplace_back(arg1); + auto result = appMgrService->Dump(fd, args); + EXPECT_EQ(result, DumpErrorCode::ERR_INVALID_PID_ERROR); + + TAG_LOGI(AAFwkTag::TEST, "AppMgrServiceDumpFFRT_0900 end"); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/unittest/app_mgr_service_dump_ffrt_test/mock/include/mock_app_mgr_service_inner.h b/test/unittest/app_mgr_service_dump_ffrt_test/mock/include/mock_app_mgr_service_inner.h new file mode 100644 index 0000000000..1e47d2cd2b --- /dev/null +++ b/test/unittest/app_mgr_service_dump_ffrt_test/mock/include/mock_app_mgr_service_inner.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2024 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 MOCK_OHOS_ABILITY_RUNTIME_MOCK_APP_MGR_SERVICE_INNER_H +#define MOCK_OHOS_ABILITY_RUNTIME_MOCK_APP_MGR_SERVICE_INNER_H + +#include "gmock/gmock.h" +#include "app_mgr_service_inner.h" + +namespace OHOS { +namespace AppExecFwk { +class MockAppMgrServiceInner : public AppMgrServiceInner { +public: + MockAppMgrServiceInner() + {} + virtual ~MockAppMgrServiceInner() + {} + + MOCK_METHOD2(DumpFfrt, int(const std::vector& pid, std::string& result)); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // MOCK_OHOS_ABILITY_RUNTIME_MOCK_APP_MGR_SERVICE_INNER_H diff --git a/test/unittest/app_mgr_service_dump_ffrt_test/mock/include/mock_ipc_skeleton.h b/test/unittest/app_mgr_service_dump_ffrt_test/mock/include/mock_ipc_skeleton.h new file mode 100644 index 0000000000..2c9e4fad3f --- /dev/null +++ b/test/unittest/app_mgr_service_dump_ffrt_test/mock/include/mock_ipc_skeleton.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2024 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 OHOS_IPC_IPC_SKELETON_H +#define OHOS_IPC_IPC_SKELETON_H + +#include "iremote_object.h" + +namespace OHOS { +class IPCSkeleton { +public: + IPCSkeleton() = default; + ~IPCSkeleton() = default; + + // default max is 4, only if you need a customize value + static bool SetMaxWorkThreadNum(int maxThreadNum); + + // join current thread into work loop. + static void JoinWorkThread(); + + // remove current thread from work loop. + static void StopWorkThread(); + + static pid_t GetCallingPid(); + + static pid_t GetCallingUid(); + + static uint32_t GetCallingTokenID(); + + static std::string GetLocalDeviceID(); + + static std::string GetCallingDeviceID(); + + static bool IsLocalCalling(); + + static IPCSkeleton &GetInstance(); + + static sptr GetContextObject(); + + static bool SetContextObject(sptr &object); + + static int FlushCommands(IRemoteObject *object); + + static std::string ResetCallingIdentity(); + + static bool SetCallingIdentity(std::string &identity); + + static void SetCallingUid(pid_t uid); + + static uint32_t SetCallingTokenID(pid_t tokenId); +}; +} // namespace OHOS +#endif // OHOS_IPC_IPC_SKELETON_H diff --git a/test/unittest/app_mgr_service_dump_ffrt_test/mock/src/mock_ipc_skeleton.cpp b/test/unittest/app_mgr_service_dump_ffrt_test/mock/src/mock_ipc_skeleton.cpp new file mode 100644 index 0000000000..548c50482e --- /dev/null +++ b/test/unittest/app_mgr_service_dump_ffrt_test/mock/src/mock_ipc_skeleton.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 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 "mock_ipc_skeleton.h" + +namespace OHOS { +#ifdef CONFIG_IPC_SINGLE +using namespace IPC_SINGLE; +#endif + +pid_t uid_ = 0; +pid_t tokenId_ = 0; + +pid_t IPCSkeleton::GetCallingUid() +{ + return uid_; +} + +pid_t IPCSkeleton::GetCallingPid() +{ + return 1; +} + +void IPCSkeleton::SetCallingUid(pid_t uid) +{ + uid_ = uid; +} + +uint32_t IPCSkeleton::GetCallingTokenID() +{ + return tokenId_; +} + +uint32_t IPCSkeleton::SetCallingTokenID(pid_t tokenId) +{ + return tokenId_ = tokenId; +} +} // namespace OHOS diff --git a/test/unittest/app_mgr_service_dump_ipc_test/BUILD.gn b/test/unittest/app_mgr_service_dump_ipc_test/BUILD.gn index 7bfd267254..cf47e02113 100644 --- a/test/unittest/app_mgr_service_dump_ipc_test/BUILD.gn +++ b/test/unittest/app_mgr_service_dump_ipc_test/BUILD.gn @@ -27,8 +27,6 @@ ohos_unittest("app_mgr_service_dump_ipc_test") { sources = [ "app_mgr_service_dump_ipc_test.cpp", "mock/src/mock_ipc_skeleton.cpp", - "mock/src/mock_my_flag.cpp", - "mock/src/mock_permission_verification.cpp", ] configs = [ "${ability_runtime_services_path}/appmgr:appmgr_config" ] diff --git a/test/unittest/app_mgr_service_dump_ipc_test/app_mgr_service_dump_ipc_test.cpp b/test/unittest/app_mgr_service_dump_ipc_test/app_mgr_service_dump_ipc_test.cpp index 5b5b25f1e8..590d52f0c7 100644 --- a/test/unittest/app_mgr_service_dump_ipc_test/app_mgr_service_dump_ipc_test.cpp +++ b/test/unittest/app_mgr_service_dump_ipc_test/app_mgr_service_dump_ipc_test.cpp @@ -16,7 +16,6 @@ #include #include "mock_ipc_skeleton.h" -#include "mock_permission_verification.h" #define private public #include "app_mgr_service.h" @@ -89,10 +88,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_0100, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -134,10 +129,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_0200, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -178,10 +169,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_0300, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -223,10 +210,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_0400, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -268,10 +251,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_0500, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -312,10 +291,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_0600, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -357,10 +332,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_0700, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -402,10 +373,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_0800, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -447,10 +414,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_0900, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -492,10 +455,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_1000, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -535,10 +494,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_1100, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -578,10 +533,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_1200, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -621,10 +572,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_1300, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -664,10 +611,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_1400, TestSize.Level1) IPCSkeleton::SetCallingUid(HIDUMPER_SERVICE_UID); EXPECT_TRUE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // IsShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_SHELL_CALL; - EXPECT_TRUE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); @@ -705,10 +648,6 @@ HWTEST_F(AppMgrServiceDumpIPCTest, AppMgrServiceDumpIPC_1500, TestSize.Level1) IPCSkeleton::SetCallingUid(RANDOM_SERVICE_UID); EXPECT_FALSE((IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID)); - // Not ShellCall - AAFwk::MyFlag::flag_ = AAFwk::MyFlag::FLAG::IS_INVALID_CALL; - EXPECT_FALSE(AAFwk::PermissionVerification::GetInstance()->IsShellCall()); - constexpr int fd(1); std::vector args; auto arg0 = Str8ToStr16(STRING_OPTION_IPC); diff --git a/test/unittest/app_mgr_service_event_handler_test/BUILD.gn b/test/unittest/app_mgr_service_event_handler_test/BUILD.gn index ca99d6c91d..ee5eae1ad8 100644 --- a/test/unittest/app_mgr_service_event_handler_test/BUILD.gn +++ b/test/unittest/app_mgr_service_event_handler_test/BUILD.gn @@ -59,6 +59,7 @@ ohos_unittest("AMSEventHandlerTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:event_report", "${ability_runtime_services_path}/common:perm_verification", @@ -87,6 +88,7 @@ ohos_unittest("AMSEventHandlerTest") { "init:libbegetutil", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "memory_utils:libmeminfo", "resource_schedule_service:ressched_client", ] diff --git a/test/unittest/app_mgr_service_inner_tdd_test/BUILD.gn b/test/unittest/app_mgr_service_inner_tdd_test/BUILD.gn index f91c7422c4..96b7517871 100644 --- a/test/unittest/app_mgr_service_inner_tdd_test/BUILD.gn +++ b/test/unittest/app_mgr_service_inner_tdd_test/BUILD.gn @@ -53,9 +53,11 @@ ohos_unittest("app_mgr_service_inner_tdd_test") { "c_utils:utils", "ffrt:libffrt", "hilog:libhilog", + "image_framework:image_native", "init:libbeget_proxy", "init:libbegetutil", "ipc:ipc_core", + "kv_store:distributeddata_mgr", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] diff --git a/test/unittest/app_mgr_service_inner_test/BUILD.gn b/test/unittest/app_mgr_service_inner_test/BUILD.gn index b3f577b49e..b08132af17 100644 --- a/test/unittest/app_mgr_service_inner_test/BUILD.gn +++ b/test/unittest/app_mgr_service_inner_test/BUILD.gn @@ -57,9 +57,11 @@ ohos_unittest("AppMgrServiceInnerTest") { "c_utils:utils", "ffrt:libffrt", "hilog:libhilog", + "image_framework:image_native", "init:libbeget_proxy", "init:libbegetutil", "ipc:ipc_core", + "kv_store:distributeddata_mgr", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] diff --git a/test/unittest/app_mgr_service_inner_test/app_mgr_service_inner_test.cpp b/test/unittest/app_mgr_service_inner_test/app_mgr_service_inner_test.cpp index 3acd1da432..7286dd1673 100644 --- a/test/unittest/app_mgr_service_inner_test/app_mgr_service_inner_test.cpp +++ b/test/unittest/app_mgr_service_inner_test/app_mgr_service_inner_test.cpp @@ -44,6 +44,19 @@ using namespace testing::ext; namespace OHOS { namespace AppExecFwk { +class WindowFocusChangedListener : public OHOS::Rosen::IFocusChangedListener { +public: + WindowFocusChangedListener(const std::shared_ptr& owner, + const std::shared_ptr& handler); + virtual ~WindowFocusChangedListener(); + + void OnFocused(const sptr &focusChangeInfo) override; + void OnUnfocused(const sptr &focusChangeInfo) override; + +private: + std::weak_ptr owner_; + std::shared_ptr taskHandler_; +}; namespace { constexpr int32_t RECORD_ID = 1; constexpr int32_t APP_DEBUG_INFO_PID = 0; @@ -592,10 +605,10 @@ HWTEST_F(AppMgrServiceInnerTest, LaunchApplication_001, TestSize.Level0) appMgrServiceInner->LaunchApplication(appRecord); Want want; - appRecord->SetSpecifiedAbilityFlagAndWant(false, want, ""); + appRecord->SetSpecifiedAbilityFlagAndWant(-1, want, ""); appMgrServiceInner->LaunchApplication(appRecord); - appRecord->SetSpecifiedAbilityFlagAndWant(true, want, ""); + appRecord->SetSpecifiedAbilityFlagAndWant(1, want, ""); appMgrServiceInner->LaunchApplication(appRecord); appMgrServiceInner->configuration_ = nullptr; @@ -2033,7 +2046,7 @@ HWTEST_F(AppMgrServiceInnerTest, HandleAddAbilityStageTimeOut_001, TestSize.Leve appRecord->eventId_ = 0; appMgrServiceInner->HandleAddAbilityStageTimeOut(0); - appRecord->isSpecifiedAbility_ = true; + appRecord->specifiedRequestId_ = 1; appMgrServiceInner->HandleAddAbilityStageTimeOut(0); sptr response; @@ -2665,14 +2678,14 @@ HWTEST_F(AppMgrServiceInnerTest, HandleStartSpecifiedAbilityTimeOut_001, TestSiz appRecord->eventId_ = 0; appMgrServiceInner->HandleStartSpecifiedAbilityTimeOut(0); - appRecord->isSpecifiedAbility_ = true; + appRecord->specifiedRequestId_ = 1; appMgrServiceInner->HandleStartSpecifiedAbilityTimeOut(0); sptr response; appMgrServiceInner->startSpecifiedAbilityResponse_ = response; appMgrServiceInner->HandleStartSpecifiedAbilityTimeOut(0); - appRecord->isSpecifiedAbility_ = false; + appRecord->specifiedRequestId_ = -1; appMgrServiceInner->HandleStartSpecifiedAbilityTimeOut(0); appMgrServiceInner->appRunningManager_ = nullptr; @@ -2906,6 +2919,26 @@ HWTEST_F(AppMgrServiceInnerTest, GetApplicationInfoByProcessID_001, TestSize.Lev TAG_LOGI(AAFwkTag::TEST, "GetApplicationInfoByProcessID_001 end"); } +/** + * @tc.name: NotifyAppMgrRecordExitReason_001 + * @tc.desc: NotifyAppMgrRecordExitReason. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, NotifyAppMgrRecordExitReason_001, TestSize.Level0) +{ + TAG_LOGI(AAFwkTag::TEST, "NotifyAppMgrRecordExitReason_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + int32_t reason = 0; + int32_t pid = 1; + std::string exitMsg = "JsError"; + auto ret = appMgrServiceInner->NotifyAppMgrRecordExitReason(reason, pid, exitMsg); + EXPECT_NE(ret, ERR_OK); + TAG_LOGI(AAFwkTag::TEST, "NotifyAppMgrRecordExitReason_001 end"); +} + /** * @tc.name: VerifyProcessPermission_001 * @tc.desc: verify process permission. @@ -3902,7 +3935,7 @@ HWTEST_F(AppMgrServiceInnerTest, SendAppLaunchEvent_001, TestSize.Level0) appRecord->SetKeepAliveEnableState(false); appRecord->SetEmptyKeepAliveAppState(false); Want want; - appRecord->SetSpecifiedAbilityFlagAndWant(false, want, ""); + appRecord->SetSpecifiedAbilityFlagAndWant(-1, want, ""); appMgrServiceInner->SendAppLaunchEvent(appRecord); appRecord->SetCallerPid(appRecord2->GetPriorityObject()->GetPid()); appMgrServiceInner->SendAppLaunchEvent(appRecord); @@ -4211,5 +4244,80 @@ HWTEST_F(AppMgrServiceInnerTest, PreloadApplication_0100, TestSize.Level1) int32_t ret = appMgrServiceInner->PreloadApplication(bundleName, userId, preloadMode, appIndex); EXPECT_EQ(ret, ERR_PERMISSION_DENIED); } + +/** + * @tc.name: SetSupportedProcessCacheSelf_001 + * @tc.desc: The application sets itself whether or not to support process cache. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrServiceInnerTest, SetSupportedProcessCacheSelf_001, TestSize.Level0) +{ + TAG_LOGI(AAFwkTag::TEST, "SetSupportedProcessCacheSelf_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + bool isSupported = false; + EXPECT_EQ(appMgrServiceInner->SetSupportedProcessCacheSelf(isSupported), CHECK_PERMISSION_FAILED); + + appMgrServiceInner->appRunningManager_ = nullptr; + EXPECT_EQ(appMgrServiceInner->SetSupportedProcessCacheSelf(isSupported), ERR_NO_INIT); + + TAG_LOGI(AAFwkTag::TEST, "SetSupportedProcessCacheSelf_001 end"); +} + +/** + * @tc.name: OnAppCacheStateChanged_001 + * @tc.desc: on application cache state changed. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrServiceInnerTest, OnAppCacheStateChanged_001, TestSize.Level0) +{ + TAG_LOGI(AAFwkTag::TEST, "OnAppCacheStateChanged_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->OnAppCacheStateChanged(nullptr); + + std::string bundleName = "com.is.hiserice"; + std::string processName = "test_processName"; + bool isRunning = false; + auto appRecord = std::make_shared(applicationInfo_, ++recordId_, processName); + EXPECT_NE(appRecord, nullptr); + appRecord->mainBundleName_ = "com.is.hiserice"; + appRecord->SetState(ApplicationState::APP_STATE_CACHED); + + appRecord->priorityObject_ = nullptr; + appMgrServiceInner->OnAppCacheStateChanged(appRecord); + + appRecord->priorityObject_ = std::make_shared(); + appMgrServiceInner->OnAppCacheStateChanged(appRecord); + + + TAG_LOGI(AAFwkTag::TEST, "OnAppCacheStateChanged_001 end"); +} + +/** + * @tc.name: GetRunningMultiAppInfoByBundleName_001 + * @tc.desc: Get multiApp information list by bundleName. + * @tc.type: FUNC + * @tc.require: issueI9HMAO + */ +HWTEST_F(AppMgrServiceInnerTest, GetRunningMultiAppInfoByBundleName_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "GetRunningMultiAppInfoByBundleName_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + std::string bundleName = "testBundleName"; + RunningMultiAppInfo info; + int32_t ret = appMgrServiceInner->GetRunningMultiAppInfoByBundleName(bundleName, info); + EXPECT_NE(ret, ERR_OK); + + appMgrServiceInner->appRunningManager_ = nullptr; + ret = appMgrServiceInner->GetRunningMultiAppInfoByBundleName(bundleName, info); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + + TAG_LOGI(AAFwkTag::TEST, "GetRunningMultiAppInfoByBundleName_001 end"); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/app_mgr_service_test/app_mgr_service_test.cpp b/test/unittest/app_mgr_service_test/app_mgr_service_test.cpp index 07b0e72d83..5136b144f3 100644 --- a/test/unittest/app_mgr_service_test/app_mgr_service_test.cpp +++ b/test/unittest/app_mgr_service_test/app_mgr_service_test.cpp @@ -26,6 +26,7 @@ #include "mock_app_mgr_service_inner.h" #include "mock_native_token.h" #include "mock_sa_call.h" +#include "ipc_skeleton.h" using namespace testing; using namespace testing::ext; @@ -41,6 +42,7 @@ public: std::shared_ptr taskHandler_; std::shared_ptr mockAppMgrServiceInner_; std::shared_ptr eventHandler_; + std::shared_ptr applicationInfo_; }; void AppMgrServiceTest::SetUpTestCase(void) @@ -1651,5 +1653,151 @@ HWTEST_F(AppMgrServiceTest, PreloadApplication_0100, TestSize.Level1) int32_t ret = appMgrService->PreloadApplication(bundleName, userId, preloadMode, appIndex); EXPECT_EQ(ret, ERR_OK); } + +/* + * Feature: AppMgrService + * Function: SetSupportedProcessCacheSelf + * SubFunction: NA + * FunctionPoints: AppMgrService SetSupportedProcessCacheSelf + * EnvConditions: NA + * CaseDescription: Verify SetSupportedProcessCacheSelf + */ +HWTEST_F(AppMgrServiceTest, SetSupportedProcessCacheSelf_001, TestSize.Level0) +{ + auto appMgrService = std::make_shared(); + ASSERT_NE(appMgrService, nullptr); + appMgrService->SetInnerService(nullptr); + + bool isSupported = false; + int32_t res = appMgrService->SetSupportedProcessCacheSelf(isSupported); + EXPECT_EQ(res, ERR_INVALID_OPERATION); +} + +/* + * Feature: AppMgrService + * Function: SetSupportedProcessCacheSelf + * SubFunction: NA + * FunctionPoints: AppMgrService SetSupportedProcessCacheSelf + * EnvConditions: NA + * CaseDescription: Verify SetSupportedProcessCacheSelf + */ +HWTEST_F(AppMgrServiceTest, SetSupportedProcessCacheSelf_002, TestSize.Level0) +{ + auto appMgrService = std::make_shared(); + ASSERT_NE(appMgrService, nullptr); + + appMgrService->SetInnerService(std::make_shared()); + appMgrService->taskHandler_ = taskHandler_; + appMgrService->eventHandler_ = std::make_shared(taskHandler_, appMgrService->appMgrServiceInner_); + + // permission check failed + int32_t res = appMgrService->SetSupportedProcessCacheSelf(false); + EXPECT_EQ(res, AAFwk::CHECK_PERMISSION_FAILED); + + // appRecord not in AppRunningManager + AAFwk::IsMockSaCall::IsMockProcessCachePermission(); + res = appMgrService->SetSupportedProcessCacheSelf(false); + EXPECT_EQ(res, ERR_INVALID_VALUE); + + // fake caller app record + auto appMgrSerInner = appMgrService->appMgrServiceInner_; + ASSERT_NE(appMgrSerInner, nullptr); + auto appRunningMgr = appMgrService->appMgrServiceInner_->appRunningManager_; + ASSERT_NE(appRunningMgr, nullptr); + BundleInfo bundleInfo; + std::string processName = "test_processName"; + applicationInfo_ = std::make_shared(); + ASSERT_NE(applicationInfo_, nullptr); + applicationInfo_->name = "hiservcie"; + applicationInfo_->bundleName = "com.ix.hiservcie"; + std::shared_ptr appRecord = + appRunningMgr->CreateAppRunningRecord(applicationInfo_, processName, bundleInfo); + EXPECT_NE(appRecord, nullptr); + appRecord->SetCallerTokenId(IPCSkeleton::GetCallingTokenID()); + appRecord->SetCallerUid(IPCSkeleton::GetCallingUid()); + appRecord->GetPriorityObject()->pid_ = IPCSkeleton::GetCallingPid(); + appRecord->SetCallerPid(IPCSkeleton::GetCallingPid()); + auto &recordMap = appRunningMgr->appRunningRecordMap_; + auto iter = recordMap.find(IPCSkeleton::GetCallingPid()); + if (iter == recordMap.end()) { + recordMap.insert({IPCSkeleton::GetCallingPid(), appRecord}); + } else { + recordMap.erase(iter); + recordMap.insert({IPCSkeleton::GetCallingPid(), appRecord}); + } + res = appMgrService->SetSupportedProcessCacheSelf(false); + EXPECT_EQ(res, ERR_OK); + + res = appMgrService->SetSupportedProcessCacheSelf(false); + EXPECT_EQ(res, AAFwk::ERR_SET_SUPPORTED_PROCESS_CACHE_AGAIN); +} + +/** + * @tc.name: StartNativeChildProcess_0100 + * @tc.desc: Start native child process. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrServiceTest, StartNativeChildProcess_0100, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "StartNativeChildProcess_0100 called."); + sptr appMgrService = new (std::nothrow) AppMgrService(); + ASSERT_NE(appMgrService, nullptr); + + appMgrService->SetInnerService(mockAppMgrServiceInner_); + appMgrService->taskHandler_ = taskHandler_; + appMgrService->eventHandler_ = eventHandler_; + + EXPECT_CALL(*mockAppMgrServiceInner_, StartNativeChildProcess(_, _, _, _)) + .Times(1) + .WillOnce(Return(ERR_OK)); + + pid_t pid = 0; + sptr callback; + int32_t res = appMgrService->StartNativeChildProcess("test.so", 1, callback); + EXPECT_EQ(res, ERR_OK); +} + +/* + * Feature: AppMgrService + * Function: GetRunningMultiAppInfoByBundleName + * SubFunction: NA + * FunctionPoints: AppMgrService GetRunningMultiAppInfoByBundleName + * EnvConditions: NA + * CaseDescription: Verify GetRunningMultiAppInfoByBundleName + */ +HWTEST_F(AppMgrServiceTest, GetRunningMultiAppInfoByBundleName_001, TestSize.Level1) +{ + auto appMgrService = std::make_shared(); + ASSERT_NE(appMgrService, nullptr); + appMgrService->SetInnerService(nullptr); + + std::string bundleName = "testBundleName"; + RunningMultiAppInfo info; + int32_t res = appMgrService->GetRunningMultiAppInfoByBundleName(bundleName, info); + EXPECT_EQ(res, ERR_INVALID_OPERATION); +} + +/* + * Feature: AppMgrService + * Function: GetRunningMultiAppInfoByBundleName + * SubFunction: NA + * FunctionPoints: AppMgrService GetRunningMultiAppInfoByBundleName + * EnvConditions: NA + * CaseDescription: Verify GetRunningMultiAppInfoByBundleName + */ +HWTEST_F(AppMgrServiceTest, GetRunningMultiAppInfoByBundleName_002, TestSize.Level1) +{ + auto appMgrService = std::make_shared(); + ASSERT_NE(appMgrService, nullptr); + appMgrService->SetInnerService(nullptr); + appMgrService->taskHandler_ = taskHandler_; + appMgrService->eventHandler_ = eventHandler_; + + std::string bundleName = "testbundlename"; + RunningMultiAppInfo info; + + int32_t ret = appMgrService->GetRunningMultiAppInfoByBundleName(bundleName, info); + EXPECT_NE(ret, ERR_OK); +} } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/app_mgr_stub_test/app_mgr_stub_test.cpp b/test/unittest/app_mgr_stub_test/app_mgr_stub_test.cpp index 5efa396ef5..d1369d8fe5 100644 --- a/test/unittest/app_mgr_stub_test/app_mgr_stub_test.cpp +++ b/test/unittest/app_mgr_stub_test/app_mgr_stub_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 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 @@ -591,5 +591,56 @@ HWTEST_F(AppMgrStubTest, PreloadApplication_0100, TestSize.Level1) static_cast(AppMgrInterfaceCode::PRELOAD_APPLICATION), data, reply, option); EXPECT_EQ(result, NO_ERROR); } + +/** + * @tc.name: SetSupportedProcessCacheSelf_001 + * @tc.desc: The application sets itself whether or not to support process cache. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrStubTest, SetSupportedProcessCacheSelf_001, TestSize.Level0) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + MessageParcel data; + MessageParcel reply; + MessageOption option; + + WriteInterfaceToken(data); + bool isSupported = false; + data.WriteBool(isSupported); + + EXPECT_CALL(*mockAppMgrService_, SetSupportedProcessCacheSelf(_)).Times(1); + + auto result = mockAppMgrService_->OnRemoteRequest( + static_cast(AppMgrInterfaceCode::SET_SUPPORTED_PROCESS_CACHE_SELF), data, reply, option); + EXPECT_EQ(result, NO_ERROR); + + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: GetRunningMultiAppInfoByBundleName_001 + * @tc.desc: Get multiapp information by bundleName. + * @tc.type: FUNC + * @tc.require: issueI9HMAO + */ +HWTEST_F(AppMgrStubTest, GetRunningMultiAppInfoByBundleName_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + MessageParcel data; + MessageParcel reply; + MessageOption option; + + WriteInterfaceToken(data); + std::string bundleName = "testBundleName"; + data.WriteString(bundleName); + + EXPECT_CALL(*mockAppMgrService_, GetRunningMultiAppInfoByBundleName(_, _)).Times(1); + + auto result = mockAppMgrService_->OnRemoteRequest( + static_cast(AppMgrInterfaceCode::GET_RUNNING_MULTIAPP_INFO_BY_BUNDLENAME), data, reply, option); + EXPECT_EQ(result, NO_ERROR); + + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/app_preloader_test/BUILD.gn b/test/unittest/app_preloader_test/BUILD.gn index 9253f3efe7..7519d5a579 100755 --- a/test/unittest/app_preloader_test/BUILD.gn +++ b/test/unittest/app_preloader_test/BUILD.gn @@ -33,6 +33,7 @@ ohos_unittest("app_preloader_test") { ] deps = [ + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/appmgr:libappms", "//third_party/googletest:gtest_main", ] diff --git a/test/unittest/app_recovery_test/app_recovery_test.cpp b/test/unittest/app_recovery_test/app_recovery_test.cpp index 54bb600cd9..fd7c63b68b 100644 --- a/test/unittest/app_recovery_test/app_recovery_test.cpp +++ b/test/unittest/app_recovery_test/app_recovery_test.cpp @@ -30,6 +30,8 @@ #include "mock_ability_token.h" #include "recovery_param.h" #include "ui_ability.h" +#define private public +#include "context/application_context.h" using namespace testing::ext; namespace OHOS { @@ -683,5 +685,18 @@ HWTEST_F(AppRecoveryUnitTest, GetMissionIds_002, TestSize.Level1) std::string invalid_path = "data/apps/ohos.samples.recovery/files/"; EXPECT_FALSE(AppRecovery::GetInstance().GetMissionIds(invalid_path, missionIds)); } + +/** + * @tc.name: DeleteInValidMissionFiles_001 + * @tc.desc: Test delete invalid mission files. + * @tc.type: FUNC + * @tc.require: I5Z7LE + */ +HWTEST_F(AppRecoveryUnitTest, DeleteInValidMissionFiles_001, TestSize.Level1) +{ + AbilityRuntime::ApplicationContext::GetInstance()->contextImpl_ = std::make_shared(); + AppRecovery::GetInstance().DeleteInValidMissionFiles(); + EXPECT_NE(AbilityRuntime::Context::GetApplicationContext(), nullptr); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/app_running_processes_info_test/BUILD.gn b/test/unittest/app_running_processes_info_test/BUILD.gn index 4d11f2e843..c3dc6f6e77 100644 --- a/test/unittest/app_running_processes_info_test/BUILD.gn +++ b/test/unittest/app_running_processes_info_test/BUILD.gn @@ -31,7 +31,6 @@ ohos_unittest("AppRunningProcessesInfoTest") { "${ability_runtime_services_path}/appmgr/src/advanced_security_mode_manager.cpp", "${ability_runtime_services_path}/appmgr/src/app_config_data_manager.cpp", "${ability_runtime_services_path}/appmgr/src/app_debug_manager.cpp", - "${ability_runtime_services_path}/appmgr/src/app_mgr_service_inner.cpp", "${ability_runtime_services_path}/appmgr/src/app_preloader.cpp", "${ability_runtime_services_path}/appmgr/src/app_running_record.cpp", "${ability_runtime_services_path}/appmgr/src/app_running_status_module.cpp", @@ -59,6 +58,7 @@ ohos_unittest("AppRunningProcessesInfoTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/appmgr:libappms", "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:event_report", diff --git a/test/unittest/app_scheduler_test/app_mgr_client_mock.h b/test/unittest/app_scheduler_test/app_mgr_client_mock.h index 2d6aa8906b..8758e5b588 100755 --- a/test/unittest/app_scheduler_test/app_mgr_client_mock.h +++ b/test/unittest/app_scheduler_test/app_mgr_client_mock.h @@ -40,7 +40,7 @@ public: MOCK_METHOD2(KillApplicationByUid, AppMgrResultCode(const std::string &bundleName, const int uid)); MOCK_METHOD2(ClearUpApplicationData, AppMgrResultCode(const std::string&, int32_t userId)); MOCK_METHOD1(StartupResidentProcess, void(const std::vector &bundleInfos)); - MOCK_METHOD2(StartSpecifiedAbility, void(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo)); + MOCK_METHOD3(StartSpecifiedAbility, void(const AAFwk::Want&, const AppExecFwk::AbilityInfo&, int32_t)); MOCK_METHOD1(GetAllRunningProcesses, AppMgrResultCode(std::vector &info)); MOCK_METHOD1(GetAllRenderProcesses, AppMgrResultCode(std::vector &info)); MOCK_METHOD2(GetProcessRunningInfosByUserId, AppMgrResultCode( diff --git a/test/unittest/app_scheduler_test/app_scheduler_test.cpp b/test/unittest/app_scheduler_test/app_scheduler_test.cpp index 5bab8e9b11..51c2c04ed4 100644 --- a/test/unittest/app_scheduler_test/app_scheduler_test.cpp +++ b/test/unittest/app_scheduler_test/app_scheduler_test.cpp @@ -859,7 +859,7 @@ HWTEST_F(AppSchedulerTest, AppScheduler_StartupResidentProcess_001, TestSize.Lev */ HWTEST_F(AppSchedulerTest, AppScheduler_StartSpecifiedAbility_001, TestSize.Level1) { - EXPECT_CALL(*clientMock_, StartSpecifiedAbility(_, _)).Times(1); + EXPECT_CALL(*clientMock_, StartSpecifiedAbility(_, _, _)).Times(1); DelayedSingleton::GetInstance()->appMgrClient_ = std::move(clientMock_); ASSERT_NE(DelayedSingleton::GetInstance()->appMgrClient_, nullptr); AAFwk::Want want; diff --git a/test/unittest/appkit/child_main_thread_test/child_main_thread_test.cpp b/test/unittest/appkit/child_main_thread_test/child_main_thread_test.cpp index fd8b9929d4..9bfcea64c4 100644 --- a/test/unittest/appkit/child_main_thread_test/child_main_thread_test.cpp +++ b/test/unittest/appkit/child_main_thread_test/child_main_thread_test.cpp @@ -170,5 +170,26 @@ HWTEST_F(ChildMainThreadTest, ScheduleExitProcessSafely_0100, TestSize.Level0) auto ret = thread->ScheduleExitProcessSafely(); EXPECT_TRUE(ret); } + +/** + * @tc.number: ScheduleRunNativeProc_0100 + * @tc.desc: Test ScheduleRunNativeProc works + * @tc.type: FUNC + */ +HWTEST_F(ChildMainThreadTest, ScheduleRunNativeProc_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "ScheduleRunNativeProc_0100 called."); + sptr thread = sptr(new (std::nothrow) ChildMainThread()); + ASSERT_NE(thread, nullptr); + + std::shared_ptr runner = EventRunner::GetMainEventRunner(); + std::shared_ptr handler = std::make_shared(runner); + thread->mainHandler_ = handler; + + sptr mainPorcessCb = nullptr; + auto ret = thread->ScheduleRunNativeProc(mainPorcessCb); + EXPECT_FALSE(ret); +} + } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/appkit/main_thread_test/main_thread_test.cpp b/test/unittest/appkit/main_thread_test/main_thread_test.cpp index aaff673876..50af33d0d2 100644 --- a/test/unittest/appkit/main_thread_test/main_thread_test.cpp +++ b/test/unittest/appkit/main_thread_test/main_thread_test.cpp @@ -198,7 +198,7 @@ class MockAppMgrStub : public AppMgrStub { } int StartRenderProcess(const std::string &renderParam, int32_t ipcFd, - int32_t sharedFd, int32_t crashFd, pid_t &renderPid) override + int32_t sharedFd, int32_t crashFd, pid_t &renderPid, bool isGPU = false) override { return 0; } diff --git a/test/unittest/application_context_test/application_context_test.cpp b/test/unittest/application_context_test/application_context_test.cpp index 5fa35e2900..91f81a71c7 100644 --- a/test/unittest/application_context_test/application_context_test.cpp +++ b/test/unittest/application_context_test/application_context_test.cpp @@ -675,20 +675,6 @@ HWTEST_F(ApplicationContextTest, GetCloudFileDir_0100, TestSize.Level1) GTEST_LOG_(INFO) << "GetCloudFileDir_0100 end"; } -/** - * @tc.number: GetCloudFileDir_0200 - * @tc.name: GetCloudFileDir - * @tc.desc:Get Cloud File Dir sucess - */ -HWTEST_F(ApplicationContextTest, GetCloudFileDir_0200, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "GetCloudFileDir_0200 start"; - context_->AttachContextImpl(mock_); - auto ret = context_->GetCloudFileDir(); - EXPECT_EQ(ret, "/data/service/el2/hmdfs/cloud/data/bundleName"); - GTEST_LOG_(INFO) << "GetCloudFileDir_0200 end"; -} - /** * @tc.number: GetToken_0100 * @tc.name: GetToken diff --git a/test/unittest/application_context_test/mock_context_impl.cpp b/test/unittest/application_context_test/mock_context_impl.cpp index 62184d1a0a..391a303b40 100644 --- a/test/unittest/application_context_test/mock_context_impl.cpp +++ b/test/unittest/application_context_test/mock_context_impl.cpp @@ -76,7 +76,7 @@ std::string MockContextImpl::GetDistributedFilesDir() std::string MockContextImpl::GetCloudFileDir() { - return "/data/service/el2/hmdfs/cloud/data/bundleName"; + return "/cloud"; } std::string MockContextImpl::GetGroupDir(std::string groupId) diff --git a/test/unittest/bundle_mgr_helper_test/bundle_mgr_helper_test.cpp b/test/unittest/bundle_mgr_helper_test/bundle_mgr_helper_test.cpp index 5e8c5481ad..8cebf777bd 100644 --- a/test/unittest/bundle_mgr_helper_test/bundle_mgr_helper_test.cpp +++ b/test/unittest/bundle_mgr_helper_test/bundle_mgr_helper_test.cpp @@ -25,12 +25,14 @@ using namespace testing::ext; namespace OHOS { namespace AppExecFwk { namespace { +const int32_t ABILITY_INFO_FLAG = 4; +const int32_t DEFAULT_USERID = 100; +const int32_t FIRST_APP_INDEX = 1000; +const int32_t SECOND_APP_INDEX = 2000; const int32_t ERR_COD1 = 8519801; -const int32_t ERR_COD2 = 8519806; const int32_t ERR_COD3 = 8519802; const int32_t ERR_COD4 = 8519921; const int32_t ERR_COD5 = 8519816; -const int32_t ERR_COD6 = 8519817; const int32_t ERR_COD7 = 8521219; } // namespace @@ -68,7 +70,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetBundleInfo_001, TestSize.Le std::string bundleName = "ohos.global.systemres"; int32_t flags = 0; BundleInfo bundleInfo; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; auto ret = bundleMgrHelper->GetBundleInfo(bundleName, flags, bundleInfo, userId); EXPECT_EQ(ret, true); } @@ -196,7 +198,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_QueryAbilityInfo_001, TestSize { Want want; int32_t flags = 0; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; AbilityInfo abilityInfo; const sptr callBack = nullptr; auto ret = bundleMgrHelper->QueryAbilityInfo(want, flags, userId, abilityInfo, callBack); @@ -212,7 +214,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetBundleInfos_001, TestSize.L { BundleFlag flag = BundleFlag::GET_BUNDLE_WITH_ABILITIES; std::vector bundleInfos; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; auto ret = bundleMgrHelper->GetBundleInfos(flag, bundleInfos, userId); EXPECT_EQ(ret, true); } @@ -226,7 +228,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_ImplicitQueryInfos_001, TestSi { Want want; int32_t flags = 0; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; bool withDefault = false; std::vector abilityInfos; std::vector extensionInfos; @@ -242,7 +244,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_ImplicitQueryInfos_001, TestSi HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_CleanBundleDataFiles_001, TestSize.Level1) { std::string bundleName; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; auto ret = bundleMgrHelper->CleanBundleDataFiles(bundleName, userId); EXPECT_EQ(ret, false); } @@ -255,7 +257,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_CleanBundleDataFiles_001, Test HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_QueryDataGroupInfos_001, TestSize.Level1) { std::string bundleName; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; std::vector infos; auto ret = bundleMgrHelper->QueryDataGroupInfos(bundleName, userId, infos); EXPECT_EQ(ret, false); @@ -269,7 +271,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_QueryDataGroupInfos_001, TestS HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetBundleGidsByUid_001, TestSize.Level1) { std::string bundleName; - int32_t uid = 100; + int32_t uid = DEFAULT_USERID; std::vector gids; auto ret = bundleMgrHelper->GetBundleGidsByUid(bundleName, uid, gids); EXPECT_EQ(ret, true); @@ -307,7 +309,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_QueryExtensionAbilityInfos_002 { Want want; int32_t flag = 0; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; std::vector extensionInfos; auto ret = bundleMgrHelper->QueryExtensionAbilityInfos(want, flag, userId, extensionInfos); EXPECT_EQ(ret, false); @@ -333,7 +335,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_QueryExtensionAbilityInfos_001 { Want want; int32_t flag = 0; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; std::vector extensionInfos; auto ret = bundleMgrHelper->QueryExtensionAbilityInfos(want, flag, userId, extensionInfos); EXPECT_EQ(ret, false); @@ -348,7 +350,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetApplicationInfo_001, TestSi { std::string appName; ApplicationFlag flag = ApplicationFlag::GET_ALL_APPLICATION_INFO; - int userId = 100; + int userId = DEFAULT_USERID; ApplicationInfo appInfo; auto ret = bundleMgrHelper->GetApplicationInfo(appName, flag, userId, appInfo); EXPECT_EQ(ret, false); @@ -374,7 +376,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_UnregisterBundleEventCallback_ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_QueryExtensionAbilityInfoByUri_001, TestSize.Level1) { std::string uri; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; ExtensionAbilityInfo extensionAbilityInfo; auto ret = bundleMgrHelper->QueryExtensionAbilityInfoByUri(uri, userId, extensionAbilityInfo); EXPECT_EQ(ret, false); @@ -388,7 +390,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_QueryExtensionAbilityInfoByUri HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_QueryAbilityInfoByUri_001, TestSize.Level1) { std::string abilityUri; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; AbilityInfo abilityInfo; auto ret = bundleMgrHelper->QueryAbilityInfoByUri(abilityUri, userId, abilityInfo); EXPECT_EQ(ret, false); @@ -403,7 +405,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_ImplicitQueryInfoByPriority_00 { Want want; int32_t flags = 0; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; AbilityInfo abilityInfo; ExtensionAbilityInfo extensionInfo; auto ret = bundleMgrHelper->ImplicitQueryInfoByPriority(want, flags, userId, abilityInfo, extensionInfo); @@ -419,7 +421,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetBundleInfos_002, TestSize.L { int32_t flags = 0; std::vector bundleInfos; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; auto ret = bundleMgrHelper->GetBundleInfos(flags, bundleInfos, userId); EXPECT_EQ(ret, true); } @@ -432,7 +434,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetBundleInfos_002, TestSize.L HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetHapModuleInfo_002, TestSize.Level1) { AbilityInfo abilityInfo; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; HapModuleInfo hapModuleInfo; auto ret = bundleMgrHelper->GetHapModuleInfo(abilityInfo, userId, hapModuleInfo); EXPECT_EQ(ret, false); @@ -446,7 +448,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetHapModuleInfo_002, TestSize HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetUidByBundleName_001, TestSize.Level1) { std::string bundleName; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; auto ret = bundleMgrHelper->GetUidByBundleName(bundleName, userId); EXPECT_EQ(ret, Constants::INVALID_UID); } @@ -460,7 +462,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetApplicationInfo_002, TestSi { std::string appName; int32_t flags = 0; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; ApplicationInfo appInfo; auto ret = bundleMgrHelper->GetApplicationInfo(appName, flags, userId, appInfo); EXPECT_EQ(ret, false); @@ -486,7 +488,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_ProcessPreload_001, TestSize.L HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_UpgradeAtomicService_001, TestSize.Level1) { Want want; - int32_t userId = 100; + int32_t userId = DEFAULT_USERID; bundleMgrHelper->UpgradeAtomicService(want, userId); EXPECT_NE(bundleMgrHelper->bundleMgr_, nullptr); } @@ -499,8 +501,8 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_UpgradeAtomicService_001, Test HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_QueryAbilityInfo_003, TestSize.Level1) { Want want; - int32_t flags = 100; - int32_t userId = 100; + int32_t flags = DEFAULT_USERID; + int32_t userId = DEFAULT_USERID; AbilityInfo abilityInfo; auto ret = bundleMgrHelper->QueryAbilityInfo(want, flags, userId, abilityInfo); EXPECT_EQ(ret, false); @@ -569,10 +571,10 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_UninstallSandboxApp_001, TestS HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_UninstallSandboxApp_002, TestSize.Level1) { std::string bundleName = "bundleName"; - int32_t userId = 1; int32_t appIndex = 1; - auto ret = bundleMgrHelper->UninstallSandboxApp(bundleName, userId, appIndex); - EXPECT_EQ(ret, ERR_COD2); + int32_t userId = 1; + auto ret = bundleMgrHelper->UninstallSandboxApp(bundleName, appIndex, userId); + EXPECT_EQ(ret, ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR); } /** @@ -656,7 +658,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxAbilityInfo_001, Tes HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxAbilityInfo_002, TestSize.Level1) { Want want; - int32_t appIndex = 10000; + int32_t appIndex = FIRST_APP_INDEX; int32_t flags = 1; int32_t userId = 1; AbilityInfo abilityInfo; @@ -672,7 +674,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxAbilityInfo_002, Tes HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxAbilityInfo_003, TestSize.Level1) { Want want; - int32_t appIndex = 2; + int32_t appIndex = SECOND_APP_INDEX; int32_t flags = 1; int32_t userId = 1; AbilityInfo abilityInfo; @@ -688,7 +690,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxAbilityInfo_003, Tes HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxExtAbilityInfos_001, TestSize.Level1) { Want want; - int32_t appIndex = 2; + int32_t appIndex = SECOND_APP_INDEX; int32_t flags = 1; int32_t userId = 1; std::vector extensionInfos; @@ -719,7 +721,7 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxHapModuleInfo_001, T HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxHapModuleInfo_002, TestSize.Level1) { AbilityInfo abilityInfo; - int32_t appIndex = 10000; + int32_t appIndex = FIRST_APP_INDEX; int32_t userId = 1; HapModuleInfo hapModuleInfo; auto ret = bundleMgrHelper->GetSandboxHapModuleInfo(abilityInfo, appIndex, userId, hapModuleInfo); @@ -734,11 +736,11 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxHapModuleInfo_002, T HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxHapModuleInfo_003, TestSize.Level1) { AbilityInfo abilityInfo; - int32_t appIndex = 2; + int32_t appIndex = SECOND_APP_INDEX; int32_t userId = 1; HapModuleInfo hapModuleInfo; auto ret = bundleMgrHelper->GetSandboxHapModuleInfo(abilityInfo, appIndex, userId, hapModuleInfo); - EXPECT_EQ(ret, ERR_COD6); + EXPECT_EQ(ret, ERR_COD5); } /** @@ -799,5 +801,64 @@ HWTEST_F(BundleMgrHelperTest, GetJsonProfile_001, TestSize.Level1) auto ret = bundleMgrHelper->GetJsonProfile(profileType, bundleName, moduleName, profile, userId); EXPECT_EQ(ret, ERR_COD7); } + +/** + * @tc.name: BundleMgrHelperTest_QueryCloneAbilityInfo_001 + * @tc.desc: QueryCloneAbilityInfo + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_QueryCloneAbilityInfo_001, TestSize.Level1) +{ + ElementName element; + AbilityInfo abilityInfo; + int32_t flags = ABILITY_INFO_FLAG; + int32_t appCloneIndex = 1; + int32_t userId = DEFAULT_USERID; + auto ret = bundleMgrHelper->QueryCloneAbilityInfo(element, flags, appCloneIndex, abilityInfo, userId); + EXPECT_NE(ret, ERR_OK); +} + +/** + * @tc.name: BundleMgrHelperTest_GetCloneBundleInfo_001 + * @tc.desc: GetCloneBundleInfo + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetCloneBundleInfo_001, TestSize.Level1) +{ + std::string bundleName; + BundleInfo bundleInfo; + int32_t flags = 1; + int32_t appCloneIndex = 1; + int32_t userId = DEFAULT_USERID; + auto ret = bundleMgrHelper->GetCloneBundleInfo(bundleName, flags, appCloneIndex, bundleInfo, userId); + EXPECT_NE(ret, ERR_OK); +} + +/** + * @tc.name: BundleMgrHelperTest_GetNameForUid_001 + * @tc.desc: GetNameForUid + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetNameForUid_001, TestSize.Level1) +{ + std::string name; + int32_t uid = 1; + auto ret = bundleMgrHelper->GetNameForUid(uid, name); + EXPECT_NE(ret, ERR_OK); +} + +/** + * @tc.name: BundleMgrHelperTest_GetLaunchWantForBundle_001 + * @tc.desc: GetLaunchWantForBundle + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetLaunchWantForBundle_001, TestSize.Level1) +{ + std::string bundleName; + Want want; + int32_t userId = DEFAULT_USERID; + auto ret = bundleMgrHelper->GetLaunchWantForBundle(bundleName, want, userId); + EXPECT_NE(ret, ERR_OK); +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/cache_process_manager_test/cache_process_manager_test.cpp b/test/unittest/cache_process_manager_test/cache_process_manager_test.cpp index 5503e31de0..edfa2201ef 100644 --- a/test/unittest/cache_process_manager_test/cache_process_manager_test.cpp +++ b/test/unittest/cache_process_manager_test/cache_process_manager_test.cpp @@ -20,6 +20,7 @@ #undef private #undef protected #include "mock_app_mgr_service_inner.h" +#include "mock_ability_token.h" using namespace testing; using namespace testing::ext; @@ -27,6 +28,8 @@ using namespace testing::ext; namespace OHOS { namespace AppExecFwk { +const std::string ABILITY_RECORD_NAME = "Ability_Name_Z"; + class CacheProcessManagerTest : public testing::Test { public: static void SetUpTestCase(); @@ -123,6 +126,7 @@ HWTEST_F(CacheProcessManagerTest, CacheProcessManager_PenddingCacheProcess_0100, auto appRecord = MockAppRecord(); EXPECT_NE(appRecord, nullptr); appRecord->SetKeepAliveEnableState(true); + appRecord->SetSingleton(true); appRecord->SetEmptyKeepAliveAppState(true); EXPECT_EQ(cacheProcMgr->PenddingCacheProcess(appRecord), false); // nullptr not allowed @@ -311,5 +315,111 @@ HWTEST_F(CacheProcessManagerTest, CacheProcessManager_KillProcessByRecord_0100, EXPECT_NE(appRecord, nullptr); EXPECT_EQ(cacheProcMgr->KillProcessByRecord(appRecord), false); } + +/** + * @tc.name: AppRunningManager_IsAppShouldCache_0100 + * @tc.desc: Test the state of IsAppShouldCache + * @tc.type: FUNC + */ +HWTEST_F(CacheProcessManagerTest, CacheProcessManager_IsAppShouldCache_0100, TestSize.Level1) +{ + auto cacheProcMgr = std::make_shared(); + EXPECT_NE(cacheProcMgr, nullptr); + + // nullptr check + EXPECT_EQ(cacheProcMgr->IsAppShouldCache(nullptr), false); + + // Not enable + cacheProcMgr->maxProcCacheNum_ = 0; + EXPECT_EQ(cacheProcMgr->IsAppShouldCache(nullptr), false); + + // Cached app + cacheProcMgr->maxProcCacheNum_ = 2; + auto appRecord = MockAppRecord(); + EXPECT_NE(appRecord, nullptr); + cacheProcMgr->cachedAppRecordQueue_.push_back(appRecord); + EXPECT_EQ(cacheProcMgr->IsAppShouldCache(appRecord), true); + + // App not support cache + cacheProcMgr->cachedAppRecordQueue_.clear(); + appRecord->procCacheSupportState_ = SupportProcessCacheState::NOT_SUPPORT; + EXPECT_EQ(cacheProcMgr->IsAppShouldCache(appRecord), false); +} + +/** + * @tc.name: AppRunningManager_IsAppAbilitiesEmpty_0100 + * @tc.desc: Test the state of IsAppAbilitiesEmpty + * @tc.type: FUNC + */ +HWTEST_F(CacheProcessManagerTest, CacheProcessManager_IsAppAbilitiesEmpty_0100, TestSize.Level1) +{ + auto cacheProcMgr = std::make_shared(); + EXPECT_NE(cacheProcMgr, nullptr); + cacheProcMgr->maxProcCacheNum_ = 2; + + // Abilities empty + auto appRecord = MockAppRecord(); + EXPECT_NE(appRecord, nullptr); + EXPECT_EQ(cacheProcMgr->IsAppAbilitiesEmpty(appRecord), true); + + // Not empty + auto caseAbilityInfo = std::make_shared(); + caseAbilityInfo->name = ABILITY_RECORD_NAME; + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "Module"; + auto appInfo = std::make_shared(); + appInfo->bundleName = "com.ohos.test.helloworld"; + appRecord->AddModule(appInfo, caseAbilityInfo, token, hapModuleInfo, nullptr, 0); + auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, + hapModuleInfo.moduleName); + auto caseAbilityRunningRecord = moduleRecord->AddAbility(token, caseAbilityInfo, nullptr, 0); + EXPECT_TRUE(caseAbilityRunningRecord == nullptr); + EXPECT_EQ(cacheProcMgr->IsAppAbilitiesEmpty(appRecord), false); +} + +/** + * @tc.name: AppRunningManager_ShrinkAndKillCache_0100 + * @tc.desc: Test the state of ShrinkAndKillCache + * @tc.type: FUNC + */ +HWTEST_F(CacheProcessManagerTest, CacheProcessManager_ShrinkAndKillCache_0100, TestSize.Level1) +{ + auto cacheProcMgr = std::make_shared(); + EXPECT_NE(cacheProcMgr, nullptr); + cacheProcMgr->maxProcCacheNum_ = 2; + + auto appRecord1 = MockAppRecord(); + EXPECT_NE(appRecord1, nullptr); + auto appRecord2 = MockAppRecord(); + EXPECT_NE(appRecord2, nullptr); + auto appRecord3 = MockAppRecord(); + EXPECT_NE(appRecord3, nullptr); + + cacheProcMgr->cachedAppRecordQueue_.push_back(appRecord1); + cacheProcMgr->cachedAppRecordQueue_.push_back(appRecord2); + cacheProcMgr->cachedAppRecordQueue_.push_back(appRecord3); + + cacheProcMgr->ShrinkAndKillCache(); +} + +/** + * @tc.name: AppRunningManager_PrintCacheQueue_0100 + * @tc.desc: Test the state of PrintCacheQueue + * @tc.type: FUNC + */ +HWTEST_F(CacheProcessManagerTest, CacheProcessManager_PrintCacheQueue_0100, TestSize.Level1) +{ + auto cacheProcMgr = std::make_shared(); + EXPECT_NE(cacheProcMgr, nullptr); + cacheProcMgr->maxProcCacheNum_ = 2; + + auto appRecord1 = MockAppRecord(); + EXPECT_NE(appRecord1, nullptr); + auto appRecord2 = MockAppRecord(); + EXPECT_NE(appRecord2, nullptr); + + EXPECT_NE(cacheProcMgr->PrintCacheQueue(), ""); +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/child_process_capi_test/BUILD.gn b/test/unittest/child_process_capi_test/BUILD.gn new file mode 100644 index 0000000000..ab3e96a9bd --- /dev/null +++ b/test/unittest/child_process_capi_test/BUILD.gn @@ -0,0 +1,52 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +module_output_path = "ability_runtime/child_process_capi" + +ohos_unittest("child_process_capi_test") { + module_out_path = module_output_path + + configs = [ "${ability_runtime_services_path}/common:common_config" ] + + if (target_cpu == "arm") { + cflags = [ "-DBINDER_IPC_32BIT" ] + } + + include_dirs = [ + "include", + "${ability_runtime_test_path}/mock/services_appmgr_test/include", + ] + + sources = [ "child_process_capi_test.cpp" ] + + deps = [ + "${ability_runtime_native_path}/child_process:child_process", + "${ability_runtime_services_path}/common:app_util", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_capi", + ] +} + +group("unittest") { + testonly = true + deps = [ ":child_process_capi_test" ] +} diff --git a/test/unittest/child_process_capi_test/child_process_capi_test.cpp b/test/unittest/child_process_capi_test/child_process_capi_test.cpp new file mode 100644 index 0000000000..8ad66cbce4 --- /dev/null +++ b/test/unittest/child_process_capi_test/child_process_capi_test.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2023 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 +#include +#include "native_child_process.h" +#include "app_utils.h" + +namespace OHOS { +namespace AbilityRuntime { + +using namespace testing; +using namespace testing::ext; + +class ChildProcessCapiTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + + static void OnNativeChildProcessStarted(int errCode, OHIPCRemoteProxy *remoteProxy); + + void SetUp(); + void TearDown(); +}; + +void ChildProcessCapiTest::SetUpTestCase(void) +{} + +void ChildProcessCapiTest::TearDownTestCase(void) +{} + +void ChildProcessCapiTest::SetUp(void) +{} + +void ChildProcessCapiTest::TearDown(void) +{} + +void ChildProcessCapiTest::OnNativeChildProcessStarted(int errCode, OHIPCRemoteProxy *remoteProxy) +{ +} + +/** + * @tc.number: OH_Ability_CreateNativeChildProcess_001 + * @tc.desc: Test API OH_Ability_CreateNativeChildProcess works + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessCapiTest, OH_Ability_CreateNativeChildProcess_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "OH_Ability_CreateNativeChildProcess_001 begin"; + int ret = OH_Ability_CreateNativeChildProcess(nullptr, ChildProcessCapiTest::OnNativeChildProcessStarted); + EXPECT_EQ(ret, NCP_ERR_INVALID_PARAM); + + ret = OH_Ability_CreateNativeChildProcess("test.so", nullptr); + EXPECT_EQ(ret, NCP_ERR_INVALID_PARAM); + + ret = OH_Ability_CreateNativeChildProcess("test.so", ChildProcessCapiTest::OnNativeChildProcessStarted); + if (!AAFwk::AppUtils::GetInstance().IsMultiProcessModel()) { + EXPECT_EQ(ret, NCP_ERR_MULTI_PROCESS_DISABLED); + return; + } else if (!AAFwk::AppUtils::GetInstance().IsSupportNativeChildProcess()) { + EXPECT_EQ(ret, NCP_ERR_NOT_SUPPORTED); + return; + } + + GTEST_LOG_(INFO) << "OH_Ability_CreateNativeChildProcess return " << ret; + EXPECT_NE(ret, NCP_ERR_NOT_SUPPORTED); +} + +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/test/unittest/child_process_manager_test/child_process_manager_test.cpp b/test/unittest/child_process_manager_test/child_process_manager_test.cpp index 1eaf3f3076..da364c8298 100644 --- a/test/unittest/child_process_manager_test/child_process_manager_test.cpp +++ b/test/unittest/child_process_manager_test/child_process_manager_test.cpp @@ -45,6 +45,8 @@ void ChildProcessManagerTest::SetUpTestCase() { AAFwk::AppUtils::GetInstance().isMultiProcessModel_.isLoaded = true; AAFwk::AppUtils::GetInstance().isMultiProcessModel_.value = true; + AAFwk::AppUtils::GetInstance().isSupportNativeChildProcess_.isLoaded = true; + AAFwk::AppUtils::GetInstance().isSupportNativeChildProcess_.value = true; sptr bundleMgrService = sptr(new (std::nothrow) AppExecFwk::BundleMgrService()); sptr mockAppMgrService = sptr(new (std::nothrow) AppExecFwk::MockAppMgrService()); @@ -61,6 +63,8 @@ void ChildProcessManagerTest::TearDownTestCase() { AAFwk::AppUtils::GetInstance().isMultiProcessModel_.isLoaded = false; AAFwk::AppUtils::GetInstance().isMultiProcessModel_.value = false; + AAFwk::AppUtils::GetInstance().isSupportNativeChildProcess_.isLoaded = false; + AAFwk::AppUtils::GetInstance().isSupportNativeChildProcess_.value = false; } void ChildProcessManagerTest::SetUp() @@ -226,5 +230,19 @@ AbilityRuntime::Runtime::DebugOption debugOption; ChildProcessManager::GetInstance().SetForkProcessDebugOption("test", false, false, false); EXPECT_TRUE(true); } + +/** + * @tc.number: StartNativeChildProcessByAppSpawnFork_0100 + * @tc.desc: Test StartNativeChildProcessByAppSpawnFork works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessManagerTest, StartNativeChildProcessByAppSpawnFork_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "StartNativeChildProcessByAppSpawnFork_0100 called."); + sptr callback; + auto ret = ChildProcessManager::GetInstance().StartNativeChildProcessByAppSpawnFork("test.so", callback); + EXPECT_NE(ret, ChildProcessManagerErrorCode::ERR_FORK_FAILED); +} + } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/data_ability_observer_proxy_test/data_ability_observer_proxy_test.cpp b/test/unittest/data_ability_observer_proxy_test/data_ability_observer_proxy_test.cpp index 5bcf89b47f..7180cf0704 100644 --- a/test/unittest/data_ability_observer_proxy_test/data_ability_observer_proxy_test.cpp +++ b/test/unittest/data_ability_observer_proxy_test/data_ability_observer_proxy_test.cpp @@ -62,5 +62,54 @@ HWTEST_F(DataAbilityObserverProxyTest, DataAbilityObserverProxy_OnChangeInner_00 proxy->OnChange(); } } + +/* + * Feature: DataAbilityObserverProxy. + * Function: DataObsManagerProxy::OnChangeExt is called. + * SubFunction: NA. + * FunctionPoints: NA. + * EnvConditions: NA. + * CaseDescription: NA. + */ +HWTEST_F(DataAbilityObserverProxyTest, DataAbilityObserverProxy_OnChangeExt_001, TestSize.Level1) +{ + // 1.stub define + sptr mockDataAbilityObserverStub(new MockDataObsManagerOnChangeCallBack()); + + // 2.obsver1 define + sptr proxy(new DataAbilityObserverProxy(mockDataAbilityObserverStub)); + + ChangeInfo changeInfo; + + EXPECT_CALL(*mockDataAbilityObserverStub, OnChangeExt(testing::_)).Times(1); + + if (proxy != nullptr) { + proxy->OnChangeExt(changeInfo); + } +} + +/* + * Feature: DataAbilityObserverProxy. + * Function: DataObsManagerProxy::OnChangePreferences is called. + * SubFunction: NA. + * FunctionPoints: NA. + * EnvConditions: NA. + * CaseDescription: NA. + */ +HWTEST_F(DataAbilityObserverProxyTest, DataAbilityObserverProxy_OnChangePreferences_001, TestSize.Level1) +{ + // 1.stub define + sptr mockDataAbilityObserverStub(new MockDataObsManagerOnChangeCallBack()); + + // 2.obsver1 define + sptr proxy(new DataAbilityObserverProxy(mockDataAbilityObserverStub)); + + std::string key = "test"; + EXPECT_CALL(*mockDataAbilityObserverStub, OnChangePreferences(key)).Times(1); + + if (proxy != nullptr) { + proxy->OnChangePreferences(key); + } +} } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/data_ability_observer_proxy_test/mock_data_obs_manager_onchange_callback.h b/test/unittest/data_ability_observer_proxy_test/mock_data_obs_manager_onchange_callback.h index 42bb0bea78..13d9b0b3fd 100644 --- a/test/unittest/data_ability_observer_proxy_test/mock_data_obs_manager_onchange_callback.h +++ b/test/unittest/data_ability_observer_proxy_test/mock_data_obs_manager_onchange_callback.h @@ -27,6 +27,8 @@ namespace AAFwk { class MockDataObsManagerOnChangeCallBack : public DataAbilityObserverStub { public: MOCK_METHOD0(OnChange, void()); + MOCK_METHOD1(OnChangeExt, void(const ChangeInfo&)); + MOCK_METHOD1(OnChangePreferences, void(const std::string&)); void Wait() { diff --git a/test/unittest/dataobs_mgr_client_test/dataobs_mgr_client_test.cpp b/test/unittest/dataobs_mgr_client_test/dataobs_mgr_client_test.cpp index 8fd42dcefc..deb233ee93 100644 --- a/test/unittest/dataobs_mgr_client_test/dataobs_mgr_client_test.cpp +++ b/test/unittest/dataobs_mgr_client_test/dataobs_mgr_client_test.cpp @@ -158,5 +158,41 @@ HWTEST_F(DataObsMgrClientTest, DataObsMgrClient_ReregisterObserver_0200, TestSiz testing::Mock::AllowLeak(DataObsMgrClient::GetInstance()->dataObsManger_); } +/* + * Feature: DataObsMgrClient. + * Function: re-subscribe when service restart. + * SubFunction: NA. + * FunctionPoints: NA. + * EnvConditions: NA. + * CaseDescription: NA. + */ +HWTEST_F(DataObsMgrClientTest, DataObsMgrClient_ReregisterObserver_0300, TestSize.Level1) +{ + sptr callBack1(new (std::nothrow) MockDataObsManagerOnChangeCallBack()); + sptr callBack2(new (std::nothrow) MockDataObsManagerOnChangeCallBack()); + + auto client = DataObsMgrClient::GetInstance(); + client->observers_.Clear(); + client->observerExts_.Clear(); + + sptr service1(new (std::nothrow) MockDataObsMgrService()); + client->dataObsManger_ = service1; + EXPECT_TRUE(client->dataObsManger_ != nullptr); + Uri uri1("datashare://device_id/com.domainname.dataability.persondata/person/25"); + Uri uri2("datashare://device_id/com.domainname.dataability.persondata/person/26"); + + EXPECT_EQ(client->RegisterObserver(uri1, callBack1), NO_ERROR); + EXPECT_EQ(client->RegisterObserver(uri2, callBack2), NO_ERROR); + EXPECT_EQ(service1->onChangeCall_, 2); + + sptr service2(new (std::nothrow) MockDataObsMgrService()); + client->dataObsManger_ = service2; + EXPECT_TRUE(client->dataObsManger_ != nullptr); + + client->OnRemoteDied(); + EXPECT_EQ(service2->onChangeCall_, 0); + testing::Mock::AllowLeak(DataObsMgrClient::GetInstance()->dataObsManger_); +} + } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/dataobs_mgr_service_test/dataobs_mgr_service_test.cpp b/test/unittest/dataobs_mgr_service_test/dataobs_mgr_service_test.cpp index 9ac0da86be..032638d0d9 100644 --- a/test/unittest/dataobs_mgr_service_test/dataobs_mgr_service_test.cpp +++ b/test/unittest/dataobs_mgr_service_test/dataobs_mgr_service_test.cpp @@ -254,5 +254,30 @@ HWTEST_F(DataObsMgrServiceTest, AaFwk_DataObsMgrServiceTest_OnStop_0100, TestSiz GTEST_LOG_(INFO) << "AaFwk_DataObsMgrServiceTest_OnStop_0100 end"; } + +/* + * Feature: DataObsMgrService + * Function: Dump + * SubFunction: NA + * FunctionPoints: DataObsMgrService Dump + * EnvConditions: NA + * CaseDescription: Verify that the DataObsMgrService Dump is normal. + */ +HWTEST_F(DataObsMgrServiceTest, AaFwk_DataObsMgrServiceTest_Dump_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataObsMgrServiceTest_Dump_0100 start"; + const DataObsServiceRunningState testValue = DataObsServiceRunningState::STATE_RUNNING; + auto dataObsMgrServer = DelayedSingleton::GetInstance(); + + std::string fileName = "test.txt"; + std::vector args; + args.push_back(u"-h"); + FILE *fp = fopen(fileName.c_str(), "w"); + int ret = dataObsMgrServer->Dump(fileno(fp), args); + fclose(fp); + EXPECT_EQ(SUCCESS, ret); + + GTEST_LOG_(INFO) << "AaFwk_DataObsMgrServiceTest_Dump_0100 end"; +} } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/dataobs_mgr_stub_test/dataobs_mgr_stub_test.cpp b/test/unittest/dataobs_mgr_stub_test/dataobs_mgr_stub_test.cpp index 900bb63758..a2c9994fc7 100644 --- a/test/unittest/dataobs_mgr_stub_test/dataobs_mgr_stub_test.cpp +++ b/test/unittest/dataobs_mgr_stub_test/dataobs_mgr_stub_test.cpp @@ -206,5 +206,123 @@ HWTEST_F(DataObsManagerStubTest, AaFwk_DataObsManagerStubTest_NotifyChange_0100, EXPECT_EQ(testVal2, retval2); GTEST_LOG_(INFO) << "AaFwk_DataObsManagerStubTest_NotifyChange_0100 end"; } + +/* + * Feature: DataObsManagerStub + * Function: RegisterObserverExtInner + * SubFunction: NA + * FunctionPoints: DataObsManagerStub RegisterObserverExtInner + * EnvConditions: NA + * CaseDescription: Verify that the DataObsManagerStub RegisterObserverExtInner is normal. + */ +HWTEST_F(DataObsManagerStubTest, AaFwk_DataObsManagerStubTest_RegisterObserverExtInner_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataObsManagerStubTest_RegisterObserverExtInner_0100 start"; + std::shared_ptr dataobs = std::make_shared(); + Uri uri("dataability://device_id/com.domainname.dataability.persondata/person/10"); + const int testVal1 = static_cast(NO_ERROR); + const Status testVal2 = SUCCESS; + uint32_t code = IDataObsMgr::REGISTER_OBSERVER_EXT; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DataObsManagerProxy::GetDescriptor())) { + GTEST_LOG_(ERROR) << "---------- WriteInterfaceToken(data) retval is false end"; + return; + } + if (!data.WriteString(uri.ToString())) { + GTEST_LOG_(ERROR) << "---------- data.WriteParcelable(uri) retval is false end"; + return; + } + + EXPECT_CALL(*dataobs, RegisterObserverExt(testing::_, testing::_, testing::_)).Times(1) + .WillOnce(testing::Return(testVal2)); + + const int retval1 = dataobs->OnRemoteRequest(code, data, reply, option); + const int retval2 = reply.ReadInt32(); + + EXPECT_EQ(testVal1, retval1); + EXPECT_EQ(testVal2, retval2); + GTEST_LOG_(INFO) << "AaFwk_DataObsManagerStubTest_RegisterObserverExtInner_0100 end"; +} + +/* + * Feature: DataObsManagerStub + * Function: UnregisterObserverExtInner + * SubFunction: NA + * FunctionPoints: DataObsManagerStub UnregisterObserverExtInner + * EnvConditions: NA + * CaseDescription: Verify that the DataObsManagerStub UnregisterObserverExtInner is normal. + */ +HWTEST_F(DataObsManagerStubTest, AaFwk_DataObsManagerStubTest_UnregisterObserverExtInner_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataObsManagerStubTest_UnregisterObserverExtInner_0100 start"; + std::shared_ptr dataobs = std::make_shared(); + Uri uri("dataability://device_id/com.domainname.dataability.persondata/person/10"); + const int testVal1 = static_cast(NO_ERROR); + const Status testVal2 = SUCCESS; + uint32_t code = IDataObsMgr::UNREGISTER_OBSERVER_EXT; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DataObsManagerProxy::GetDescriptor())) { + GTEST_LOG_(ERROR) << "---------- WriteInterfaceToken(data) retval is false end"; + return; + } + if (!data.WriteString(uri.ToString())) { + GTEST_LOG_(ERROR) << "---------- data.WriteParcelable(uri) retval is false end"; + return; + } + + EXPECT_CALL(*dataobs, UnregisterObserverExt(testing::_, testing::_)).Times(1).WillOnce(testing::Return(testVal2)); + + const int retval1 = dataobs->OnRemoteRequest(code, data, reply, option); + const int retval2 = reply.ReadInt32(); + + EXPECT_EQ(testVal1, retval1); + EXPECT_EQ(testVal2, retval2); + GTEST_LOG_(INFO) << "AaFwk_DataObsManagerStubTest_UnregisterObserverExtInner_0100 end"; +} + +/* + * Feature: DataObsManagerStub + * Function: UnregisterObserverExtALLInner + * SubFunction: NA + * FunctionPoints: DataObsManagerStub UnregisterObserverExtALLInner + * EnvConditions: NA + * CaseDescription: Verify that the DataObsManagerStub UnregisterObserverExtALLInner is normal. + */ +HWTEST_F(DataObsManagerStubTest, AaFwk_DataObsManagerStubTest_UnregisterObserverExtALLInner_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DataObsManagerStubTest_UnregisterObserverExtALLInner_0100 start"; + std::shared_ptr dataobs = std::make_shared(); + Uri uri("dataability://device_id/com.domainname.dataability.persondata/person/10"); + const int testVal1 = static_cast(NO_ERROR); + const Status testVal2 = SUCCESS; + uint32_t code = IDataObsMgr::UNREGISTER_OBSERVER_ALL_EXT; + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(DataObsManagerProxy::GetDescriptor())) { + GTEST_LOG_(ERROR) << "---------- WriteInterfaceToken(data) retval is false end"; + return; + } + if (!data.WriteString(uri.ToString())) { + GTEST_LOG_(ERROR) << "---------- data.WriteParcelable(uri) retval is false end"; + return; + } + + EXPECT_CALL(*dataobs, UnregisterObserverExt(testing::_)).Times(1).WillOnce(testing::Return(testVal2)); + + const int retval1 = dataobs->OnRemoteRequest(code, data, reply, option); + const int retval2 = reply.ReadInt32(); + + EXPECT_EQ(testVal1, retval1); + EXPECT_EQ(testVal2, retval2); + GTEST_LOG_(INFO) << "AaFwk_DataObsManagerStubTest_UnregisterObserverExtALLInner_0100 end"; +} } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/deeplink_reserve_config_test/BUILD.gn b/test/unittest/deeplink_reserve_config_test/BUILD.gn new file mode 100644 index 0000000000..0352f5da8b --- /dev/null +++ b/test/unittest/deeplink_reserve_config_test/BUILD.gn @@ -0,0 +1,41 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +module_output_path = "ability_runtime/abilitymgr" + +ohos_unittest("deeplink_reserve_config_test") { + module_out_path = module_output_path + + include_dirs = + [ "${ability_runtime_path}/services/abilitymgr/include/deeplink_reserve" ] + + sources = [ "deeplink_reserve_config_test.cpp" ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + cflags = [] + deps = [ + "${ability_runtime_services_path}/abilitymgr:abilityms", + "//third_party/googletest:gmock_main", + ] + + external_deps = [ "c_utils:utils" ] +} + +group("unittest") { + testonly = true + + deps = [ ":deeplink_reserve_config_test" ] +} diff --git a/test/unittest/deeplink_reserve_config_test/deeplink_reserve_config_test.cpp b/test/unittest/deeplink_reserve_config_test/deeplink_reserve_config_test.cpp new file mode 100644 index 0000000000..0c9ea6c0f9 --- /dev/null +++ b/test/unittest/deeplink_reserve_config_test/deeplink_reserve_config_test.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2024 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 + +#include "gtest/gtest.h" +#define private public +#define protected public +#include "deeplink_reserve_config.h" +#undef private +#undef protected + + +namespace OHOS { +namespace AAFwk { +using namespace testing::ext; +class DeepLinkReserveConfigTest : public testing::Test { +public: + DeepLinkReserveConfigTest() = default; + virtual ~DeepLinkReserveConfigTest() = default; + + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +void DeepLinkReserveConfigTest::SetUpTestCase(void) +{} +void DeepLinkReserveConfigTest::TearDownTestCase(void) +{} +void DeepLinkReserveConfigTest::SetUp() +{} +void DeepLinkReserveConfigTest::TearDown() +{} + +/* + * Feature: deepLinkReserveConfig + * Function: LoadConfiguration + * SubFunction: NA + * FunctionPoints: deepLinkReserveConfig LoadConfiguration + * EnvConditions: NA + * CaseDescription: Verify that the deepLinkReserveConfig LoadConfiguration is normal. + */ +HWTEST_F(DeepLinkReserveConfigTest, AaFwk_DeepLinkReserveConfigTest_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DeepLinkReserveConfigTest_0100 start"; + DeepLinkReserveConfig deepLinkReserveConfig; + EXPECT_EQ(deepLinkReserveConfig.LoadConfiguration(), false); + GTEST_LOG_(INFO) << "AaFwk_DeepLinkReserveConfigTest_0100 end"; +} + +/* + * Feature: deepLinkReserveConfig + * Function: isLinkReserved + * SubFunction: NA + * FunctionPoints: deepLinkReserveConfig isLinkReserved + * EnvConditions: NA + * CaseDescription: Verify that the deepLinkReserveConfig isLinkReserved is normal. + */ +HWTEST_F(DeepLinkReserveConfigTest, AaFwk_DeepLinkReserveConfigTest_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_DeepLinkReserveConfigTest_0200 start"; + DeepLinkReserveConfig deepLinkReserveConfig; + const nlohmann::json DEFAULT_CONFIG = R"( + { + "deepLinkReservedUri": [ + { + "bundleName": "bundleName", + "uris": [ + { + "scheme": "http", + "host": "www.xxx.com", + "port": "80", + "path": "path", + "pathStartWith": "pathStartWith", + "pathRegex": "pathRegex", + "type": "type", + "utd": "utd" + } + ] + } + ] + } + )"_json; + deepLinkReserveConfig.LoadReservedUriList(DEFAULT_CONFIG); + std::string linkString = "http://www.xxx.com:80/pathRegex"; + std::string bundleName = "just a test"; + auto ans = deepLinkReserveConfig.isLinkReserved(linkString, bundleName); + EXPECT_EQ(ans, true); + GTEST_LOG_(INFO) << "AaFwk_DeepLinkReserveConfigTest_0200 end"; +} + +} // namespace AAFwk +} // namespace OHOS diff --git a/test/unittest/dfr_test/BUILD.gn b/test/unittest/dfr_test/BUILD.gn index 70b3bcae2f..5a118ff417 100644 --- a/test/unittest/dfr_test/BUILD.gn +++ b/test/unittest/dfr_test/BUILD.gn @@ -18,6 +18,7 @@ group("unittest") { deps += [ "appfreeze_inner_test:unittest", "appfreeze_manager_test:unittest", + "appfreeze_state_test:unittest", "watchdog_test:unittest", ] } diff --git a/test/unittest/dfr_test/appfreeze_inner_test/BUILD.gn b/test/unittest/dfr_test/appfreeze_inner_test/BUILD.gn index 8320cc1134..f9cc437dd8 100644 --- a/test/unittest/dfr_test/appfreeze_inner_test/BUILD.gn +++ b/test/unittest/dfr_test/appfreeze_inner_test/BUILD.gn @@ -102,6 +102,7 @@ ohos_unittest("appfreeze_inner_test") { "hisysevent:libhisysevent", "hitrace:hitrace_meter", "init:libbegetutil", + "input:libmmi-client", "ipc:ipc_core", "napi:ace_napi", "resource_management:global_resmgr", diff --git a/test/unittest/dfr_test/appfreeze_inner_test/appfreeze_inner_test.cpp b/test/unittest/dfr_test/appfreeze_inner_test/appfreeze_inner_test.cpp index 6e60e627fa..0eae9e539c 100644 --- a/test/unittest/dfr_test/appfreeze_inner_test/appfreeze_inner_test.cpp +++ b/test/unittest/dfr_test/appfreeze_inner_test/appfreeze_inner_test.cpp @@ -17,6 +17,7 @@ #define private public #include "appfreeze_inner.h" +#include "application_anr_listener.h" #undef private using namespace testing; @@ -115,6 +116,28 @@ HWTEST_F(AppfreezeInnerTest, AppfreezeInner__ThreadBlock_002, TestSize.Level1) GTEST_LOG_(INFO) << "AppfreezeInner__ThreadBlock_002 end"; } +/** + * @tc.number: AppfreezeInner_IsNeedIgnoreFreezeEvent_001 + * @tc.name: IsNeedIgnoreFreezeEvent + * @tc.desc: Verify that function IsNeedIgnoreFreezeEvent. + */ +HWTEST_F(AppfreezeInnerTest, AppfreezeInner_IsNeedIgnoreFreezeEvent_001, TestSize.Level1) +{ + std::atomic_bool isSixSecondEvent = true; + appfreezeInner->isAppDebug_ = false; + appfreezeInner->ThreadBlock(isSixSecondEvent); + EXPECT_TRUE(isSixSecondEvent); + int32_t pid = static_cast(getprocpid()); + std::shared_ptr listener = + std::make_shared(); + listener->OnAnr(pid); + int left = 61; // over 1min + while (left > 0) { + left = sleep(left); + } + listener->OnAnr(pid); +} + /** * @tc.number: AppfreezeInner__AppfreezeHandle_001 * @tc.name: AppfreezeHandle diff --git a/test/unittest/dfr_test/appfreeze_state_test/BUILD.gn b/test/unittest/dfr_test/appfreeze_state_test/BUILD.gn new file mode 100644 index 0000000000..57c1669ea6 --- /dev/null +++ b/test/unittest/dfr_test/appfreeze_state_test/BUILD.gn @@ -0,0 +1,113 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +module_output_path = "ability_runtime/appfreeze_state_test" + +############################################################################### +config("module_context_config") { + visibility = [ ":*" ] + include_dirs = [ + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_test_path}/mock/frameworks_kits_appkit_native_test/include", + "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/app/task", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + defines = [ "AMS_LOG_TAG = \"ApplicationUnitTest\"" ] +} + +config("ability_start_setting_config") { + visibility = [ ":*" ] + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/app", + "${ability_runtime_path}/interfaces/kits/native/appkit/dfr", + "${c_utils_base_path}/include", + "${ability_runtime_innerkits_path}/ability_manager/include", + ] +} + +ohos_unittest("appfreeze_state_test") { + module_out_path = module_output_path + + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/dfr", + "${ability_runtime_path}/utils/global/time/include", + "//third_party/json/include", + ] + + configs = [ + ":module_context_config", + ":ability_start_setting_config", + ] + + sources = [ + "${ability_runtime_native_path}/appkit/dfr/appfreeze_inner.cpp", + "${ability_runtime_native_path}/appkit/dfr/appfreeze_state.cpp", + "appfreeze_state_test.cpp", + ] + + deps = [ + "${ability_runtime_abilitymgr_path}/:abilityms", + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:ability_thread", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:uiabilitykit_native", + "${ability_runtime_native_path}/appkit:app_context", + "${ability_runtime_native_path}/appkit:app_context_utils", + "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + ] + + external_deps = [ + "ability_base:configuration", + "ability_base:extractresourcemanager", + "ability_base:string_utils", + "ability_base:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "faultloggerd:libbacktrace_local", + "faultloggerd:libdfx_procinfo", + "faultloggerd:libfaultloggerd", + "ffrt:libffrt", + "graphic_2d:librender_service_client", + "hicollie:libhicollie", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + ] +} + +############################################################################### + +group("unittest") { + testonly = true + deps = [ ":appfreeze_state_test" ] +} diff --git a/test/unittest/dfr_test/appfreeze_state_test/appfreeze_state_test.cpp b/test/unittest/dfr_test/appfreeze_state_test/appfreeze_state_test.cpp new file mode 100644 index 0000000000..34c4a059f4 --- /dev/null +++ b/test/unittest/dfr_test/appfreeze_state_test/appfreeze_state_test.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022-2023 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 +#include +#include "appfreeze_state.h" + +#define private public +#include "appfreeze_inner.h" +#undef private + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AbilityRuntime; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace AbilityRuntime { +class AppFreezeStateTest : public testing::Test { +public: + AppFreezeStateTest() + {} + ~AppFreezeStateTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AppFreezeStateTest::SetUpTestCase(void) +{} + +void AppFreezeStateTest::TearDownTestCase(void) +{} + +void AppFreezeStateTest::SetUp(void) +{} + +void AppFreezeStateTest::TearDown(void) +{} + +/** + * @tc.number: AppfreezeStateTest_001 + * @tc.desc: Verify that function SetAppFreezeState and CancelAppFreezeState. + * @tc.type: FUNC + */ +HWTEST_F(AppFreezeStateTest, AppfreezeStateTest_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AppfreezeStateTest_001 start"; + uint32_t flag = 1; + auto appFreezeState = std::make_shared (); + auto inner = AppfreezeInner::GetInstance(); + appFreezeState->SetAppFreezeState(flag); + EXPECT_FALSE(inner->IsHandleAppfreeze()); + + flag = -1; + appFreezeState->CancelAppFreezeState(flag); + EXPECT_TRUE(inner->IsHandleAppfreeze()); + GTEST_LOG_(INFO) << "AppfreezeStateTest_001 end"; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/test/unittest/dfr_test/watchdog_test/BUILD.gn b/test/unittest/dfr_test/watchdog_test/BUILD.gn index 203cefce2b..1825d44c40 100644 --- a/test/unittest/dfr_test/watchdog_test/BUILD.gn +++ b/test/unittest/dfr_test/watchdog_test/BUILD.gn @@ -9,7 +9,7 @@ # 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. +# limitations under the License. import("//build/ohos.gni") import("//build/test.gni") @@ -76,8 +76,6 @@ ohos_unittest("watchdog_test") { "ability_base:want", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", - "c_utils:utils", - "c_utils:utilsbase", "eventhandler:libeventhandler", "hilog:libhilog", "image_framework:image_native", @@ -86,7 +84,7 @@ ohos_unittest("watchdog_test") { ] } -############################################################################### +############################################################################### group("unittest") { testonly = true diff --git a/test/unittest/dlp_state_item_test/dlp_state_item_test.cpp b/test/unittest/dlp_state_item_test/dlp_state_item_test.cpp index d159351078..1f214596ea 100644 --- a/test/unittest/dlp_state_item_test/dlp_state_item_test.cpp +++ b/test/unittest/dlp_state_item_test/dlp_state_item_test.cpp @@ -61,7 +61,8 @@ HWTEST_F(DlpStateItemTest, dlp_state_item_test_handle_001, TestSize.Level1) AppExecFwk::ApplicationInfo applicationInfo; std::shared_ptr abilityRecord = std::make_shared(want, abilityInfo, applicationInfo); abilityRecord->Init(); - abilityRecord->SetAppIndex(1); + int32_t dlpIndex = 1001; + abilityRecord->SetAppIndex(dlpIndex); AbilityRuntime::DlpStateData data; EXPECT_FALSE(item->RemoveDlpConnectionState(abilityRecord, data)); EXPECT_TRUE(item->AddDlpConnectionState(abilityRecord, data)); @@ -90,7 +91,8 @@ HWTEST_F(DlpStateItemTest, dlp_state_item_test_get_size_002, TestSize.Level1) AbilityRuntime::DlpStateData data; abilityRecord->SetAppIndex(0); EXPECT_FALSE(item->AddDlpConnectionState(abilityRecord, data)); - abilityRecord->SetAppIndex(1); + int32_t dlpIndex = 1001; + abilityRecord->SetAppIndex(dlpIndex); EXPECT_TRUE(item->AddDlpConnectionState(abilityRecord, data)); auto item2 = std::make_shared(0, 0); EXPECT_FALSE(item2->AddDlpConnectionState(abilityRecord, data)); @@ -127,7 +129,8 @@ HWTEST_F(DlpStateItemTest, dlp_state_item_test_get_size_001, TestSize.Level1) AppExecFwk::ApplicationInfo applicationInfo; std::shared_ptr abilityRecord = std::make_shared(want, abilityInfo, applicationInfo); abilityRecord->Init(); - abilityRecord->SetAppIndex(1); + int32_t dlpIndex = 1001; + abilityRecord->SetAppIndex(dlpIndex); AbilityRuntime::DlpStateData data; EXPECT_EQ(0, item->GetOpenedAbilitySize()); EXPECT_TRUE(item->AddDlpConnectionState(abilityRecord, data)); diff --git a/test/unittest/frameworks_kits_ability_ability_runtime_test/BUILD.gn b/test/unittest/frameworks_kits_ability_ability_runtime_test/BUILD.gn index 2cef963d23..3a95c5a187 100644 --- a/test/unittest/frameworks_kits_ability_ability_runtime_test/BUILD.gn +++ b/test/unittest/frameworks_kits_ability_ability_runtime_test/BUILD.gn @@ -44,6 +44,7 @@ ohos_unittest("ability_context_impl_test") { "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_native_path}/ability:ability_context_native", "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "${global_path}/resource_management/frameworks/resmgr:global_resmgr", "//third_party/googletest:gmock_main", @@ -103,6 +104,7 @@ ohos_unittest("local_call_container_ut_test") { "${ability_runtime_innerkits_path}/ability_manager:ability_manager", "${ability_runtime_native_path}/ability:ability_context_native", "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -134,6 +136,7 @@ ohos_unittest("local_call_record_ut_test") { "${ability_runtime_innerkits_path}/ability_manager:ability_manager", "${ability_runtime_native_path}/ability:ability_context_native", "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -149,6 +152,41 @@ ohos_unittest("local_call_record_ut_test") { ] } +ohos_unittest("dialog_callback_test") { + module_out_path = module_out_path + + include_dirs = [ + "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include", + "${ability_runtime_path}/interfaces/kits/native/ability/native/dialog_request_callback", + ] + + sources = [ + "${ability_runtime_path}/frameworks/native/ability/ability_runtime/dialog_request_callback_impl.cpp", + "${ability_runtime_path}/frameworks/native/ability/ability_runtime/dialog_ui_extension_callback.cpp", + "dialog_request_callback_impl_test.cpp", + "dialog_ui_extension_callback_test.cpp", + ] + + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_native_path}/ability:ability_context_native", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:dialog_request_callback", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:want", + "ace_engine:ace_uicontent", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + ] +} + ################################################################################ group("unittest") { testonly = true @@ -157,6 +195,7 @@ group("unittest") { deps += [ ":ability_context_impl_test", ":caller_call_back_ut_test", + ":dialog_callback_test", ":local_call_container_ut_test", ":local_call_record_ut_test", ] diff --git a/test/unittest/frameworks_kits_ability_ability_runtime_test/ability_context_impl_test.cpp b/test/unittest/frameworks_kits_ability_ability_runtime_test/ability_context_impl_test.cpp index 218b25ae7f..5c2002ca8c 100644 --- a/test/unittest/frameworks_kits_ability_ability_runtime_test/ability_context_impl_test.cpp +++ b/test/unittest/frameworks_kits_ability_ability_runtime_test/ability_context_impl_test.cpp @@ -932,7 +932,7 @@ HWTEST_F(AbilityContextImplTest, Ability_Context_Impl_GetCloudFileDir_0100, Func { context_->SetStageContext(mock_); auto ret = context_->GetCloudFileDir(); - EXPECT_EQ(ret, "/data/service/el2/hmdfs/cloud/data/bundleName"); + EXPECT_EQ(ret, "/cloud"); } /** diff --git a/test/unittest/frameworks_kits_ability_ability_runtime_test/dialog_request_callback_impl_test.cpp b/test/unittest/frameworks_kits_ability_ability_runtime_test/dialog_request_callback_impl_test.cpp new file mode 100644 index 0000000000..98949f6019 --- /dev/null +++ b/test/unittest/frameworks_kits_ability_ability_runtime_test/dialog_request_callback_impl_test.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 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 +#include "dialog_request_callback_impl.h" + +using namespace testing::ext; +using namespace testing; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; +namespace OHOS { +namespace AAFwk { +class DialogRequestCallbackImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +void DialogRequestCallbackImplTest::SetUpTestCase(void) {} +void DialogRequestCallbackImplTest::TearDownTestCase(void) {} +void DialogRequestCallbackImplTest::TearDown() {} +void DialogRequestCallbackImplTest::SetUp() {} + +void RequestDialogResultTaskCallBack(int32_t resultCode, const AAFwk::Want&) +{ + GTEST_LOG_(INFO) << "RequestDialogResultTask call back"; +} + +/** + * @tc.name: DialogRequestCallbackImplTest_SendResult_0100 + * @tc.desc: Test the state of SendResult + * @tc.type: FUNC + */ +HWTEST_F(DialogRequestCallbackImplTest, SendResult_0100, TestSize.Level1) +{ + auto dialogRequestCallbackImpl = std::make_shared(RequestDialogResultTaskCallBack); + Want want; + dialogRequestCallbackImpl->SendResult(401, want); +} + +} // namespace AAFwk +} // namespace OHOS diff --git a/test/unittest/frameworks_kits_ability_ability_runtime_test/dialog_ui_extension_callback_test.cpp b/test/unittest/frameworks_kits_ability_ability_runtime_test/dialog_ui_extension_callback_test.cpp new file mode 100644 index 0000000000..a71d786c41 --- /dev/null +++ b/test/unittest/frameworks_kits_ability_ability_runtime_test/dialog_ui_extension_callback_test.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2024 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 +#include "dialog_ui_extension_callback.h" +#include "mock_ui_content.h" + +using namespace testing::ext; +using namespace testing; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; +namespace OHOS { +namespace AAFwk { +class MyAbilityCallback : public IAbilityCallback { +public: + virtual int GetCurrentWindowMode() + { + return 0; + } + + virtual ErrCode SetMissionLabel(const std::string& label) + { + return 0; + } + + virtual ErrCode SetMissionIcon(const std::shared_ptr& icon) + { + GTEST_LOG_(INFO) << "========AbilityCallback SetMissionIcon------------------------."; + return 0; + } + + virtual void GetWindowRect(int32_t &left, int32_t &top, int32_t &width, int32_t &height) + { + return; + } + + virtual Ace::UIContent* GetUIContent() + { + return nullptr; + } + + void EraseUIExtension(int32_t sessionId) + { + return; + } + + void RegisterAbilityLifecycleObserver(const std::shared_ptr &observer) + { + } + + void UnregisterAbilityLifecycleObserver(const std::shared_ptr &observer) + { + } +}; + +class DialogUIExtensionCallbackTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void DialogUIExtensionCallbackTest::SetUpTestCase(void) {} +void DialogUIExtensionCallbackTest::TearDownTestCase(void) {} +void DialogUIExtensionCallbackTest::TearDown() {} +void DialogUIExtensionCallbackTest::SetUp() {} + +/** + * @tc.name: DialogUIExtensionCallbackTest_OnRelease_0100 + * @tc.desc: Test the state of OnRelease + * @tc.type: FUNC + */ +HWTEST_F(DialogUIExtensionCallbackTest, OnRelease_0100, TestSize.Level1) +{ + Ace::MockUIContent *uicontent = new Ace::MockUIContent(); + EXPECT_CALL(*uicontent, CloseModalUIExtension(_)).Times(1).WillOnce(Return()); + auto abilityCallback_ = std::make_shared(); + auto dialogUIExtensionCallback_ = + std::make_shared(std::weak_ptr(abilityCallback_)); + dialogUIExtensionCallback_->SetUIContent(uicontent); + dialogUIExtensionCallback_->SetSessionId(1); + dialogUIExtensionCallback_->OnRelease(); + delete uicontent; +} + +/** + * @tc.name: DialogUIExtensionCallbackTest_OnError_0100 + * @tc.desc: Test the state of OnError + * @tc.type: FUNC + */ +HWTEST_F(DialogUIExtensionCallbackTest, OnError_0100, TestSize.Level1) +{ + Ace::MockUIContent *uicontent = new Ace::MockUIContent(); + EXPECT_CALL(*uicontent, CloseModalUIExtension(_)).Times(1).WillOnce(Return()); + auto abilityCallback_ = std::make_shared(); + auto dialogUIExtensionCallback_ = + std::make_shared(std::weak_ptr(abilityCallback_)); + dialogUIExtensionCallback_->SetUIContent(uicontent); + dialogUIExtensionCallback_->SetSessionId(1); + dialogUIExtensionCallback_->OnError(); + delete uicontent; +} + +/** + * @tc.name: DialogUIExtensionCallbackTest_OnDestroy_0100 + * @tc.desc: Test the state of OnDestroy + * @tc.type: FUNC + */ +HWTEST_F(DialogUIExtensionCallbackTest, OnDestroy_0100, TestSize.Level1) +{ + auto abilityCallback = std::make_shared(); + auto dialogUIExtensionCallback = + std::make_shared(std::weak_ptr(abilityCallback)); + dialogUIExtensionCallback->OnDestroy(); +} + +} // namespace AAFwk +} // namespace OHOS diff --git a/test/unittest/frameworks_kits_ability_ability_runtime_test/mock_context.cpp b/test/unittest/frameworks_kits_ability_ability_runtime_test/mock_context.cpp index 4c706953f2..7df5ec0ede 100644 --- a/test/unittest/frameworks_kits_ability_ability_runtime_test/mock_context.cpp +++ b/test/unittest/frameworks_kits_ability_ability_runtime_test/mock_context.cpp @@ -78,7 +78,7 @@ std::string MockContext::GetDistributedFilesDir() std::string MockContext::GetCloudFileDir() { - return "/data/service/el2/hmdfs/cloud/data/bundleName"; + return "/cloud"; } std::shared_ptr MockContext::CreateModuleContext(const std::string &moduleName) diff --git a/test/unittest/frameworks_kits_ability_native_test/BUILD.gn b/test/unittest/frameworks_kits_ability_native_test/BUILD.gn index 7a0f68d3d9..eed4afd853 100644 --- a/test/unittest/frameworks_kits_ability_native_test/BUILD.gn +++ b/test/unittest/frameworks_kits_ability_native_test/BUILD.gn @@ -270,6 +270,7 @@ ohos_unittest("ability_context_test") { "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_native_path}/appkit:app_context", "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", @@ -1609,6 +1610,7 @@ ohos_unittest("ability_permission_test") { "${ability_runtime_innerkits_path}/ability_manager:ability_manager", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_native_path}/appkit:app_context", + "${ability_runtime_services_path}/abilitymgr:abilityms", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "${global_path}/resource_management/frameworks/resmgr:global_resmgr", "//third_party/googletest:gmock_main", @@ -2699,6 +2701,75 @@ ohos_unittest("embedded_ui_extension_test") { ] } +ohos_unittest("app_module_checker_test") { + module_out_path = module_output_path + include_dirs = [ + "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + ] + + sources = [ "app_module_checker_test.cpp" ] + + configs = [ ":module_private_config" ] + + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + ] +} + +ohos_unittest("js_ui_extension_Callback_test") { + module_out_path = module_output_path + include_dirs = [ + "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/js_environment/interfaces/inner_api", + "${ability_runtime_path}/js_environment/frameworks/utils/include", + "${windowmanager_path}/window_scene/interfaces/include", + ] + + sources = [ + "${ability_runtime_native_path}/ability/native/js_ui_extension_callback.cpp", + "js_ui_extension_Callback_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:session_info", + "ability_base:want", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ace_engine:ace_uicontent", + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "input:libmmi-client", + "ipc:ipc_core", + "napi:ace_napi", + ] +} + ############################################################################### group("unittest") { @@ -2726,6 +2797,7 @@ group("unittest") { ":abilityruntime_test", ":action_extension_module_loader_test", ":action_extension_test", + ":app_module_checker_test", ":auto_fill_extension_module_loader_test", ":auto_fill_extension_test", ":continuation_test", @@ -2745,6 +2817,7 @@ group("unittest") { ":extension_test", ":fa_ability_thread_test", ":form_extension_test", + ":js_ui_extension_Callback_test", ":new_ability_impl_test", ":pac_map_test", ":reserse_continuation_scheduler_primary_proxy_test", diff --git a/test/unittest/frameworks_kits_ability_native_test/ability_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ability_test.cpp index 01eb86c14a..0836b5812c 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ability_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ability_test.cpp @@ -1504,7 +1504,7 @@ HWTEST_F(AbilityBaseTest, AbilityContinuation_0100, TestSize.Level1) // branch when contentStorage_ is nullptr ret = ability->IsRestoredInContinuation(); - EXPECT_EQ(ret, false); + EXPECT_EQ(ret, true); TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); } diff --git a/test/unittest/frameworks_kits_ability_native_test/app_module_checker_test.cpp b/test/unittest/frameworks_kits_ability_native_test/app_module_checker_test.cpp new file mode 100644 index 0000000000..71108ea063 --- /dev/null +++ b/test/unittest/frameworks_kits_ability_native_test/app_module_checker_test.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "ability_handler.h" +#include "app_module_checker.h" +#include "context_deal.h" +#include "hilog_wrapper.h" +#include "locale_config.h" +#include "ohos_application.h" +#include "process_options.h" +#include "session_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AbilityRuntime; +namespace { +static const int32_t EXTENSION_TYPE = 10; +static const int32_t EXTENSION_TYPE1 = 2; +} +class AppModuleCheckTest : public testing::Test { +public: + AppModuleCheckTest() : appModuleChecker_(nullptr) {} + ~AppModuleCheckTest() {} + std::shared_ptr appModuleChecker_; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AppModuleCheckTest::SetUpTestCase(void) {} + +void AppModuleCheckTest::TearDownTestCase(void) {} + +void AppModuleCheckTest::SetUp(void) {} + +void AppModuleCheckTest::TearDown(void) {} + +/* + * Feature: DiskCheckOnly_001 + * Function: DiskCheckOnly + */ +HWTEST_F(AppModuleCheckTest, DiskCheckOnly_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DiskCheckOnly_001 start"; + std::unordered_map> blocklist = { + {1, {"module1"}}, + {2, {"module2"}}, + {3, {"module3"}} + }; + appModuleChecker_ = std::make_shared(EXTENSION_TYPE, std::move(blocklist)); + bool ret = appModuleChecker_->DiskCheckOnly(); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "DiskCheckOnly_001 end"; +} + +/* + * Feature: CheckModuleLoadable_001 + * Function: CheckModuleLoadable + */ +HWTEST_F(AppModuleCheckTest, CheckModuleLoadable_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckModuleLoadable_001 start"; + std::unordered_map> blocklist = { + {1, {"module1"}}, + {2, {"module2"}}, + {3, {"module3"}} + }; + appModuleChecker_ = std::make_shared(EXTENSION_TYPE, std::move(blocklist)); + std::unique_ptr apiAllowListChecker(nullptr); + bool ret = appModuleChecker_->CheckModuleLoadable("module4", apiAllowListChecker); + EXPECT_TRUE(ret); + GTEST_LOG_(INFO) << "CheckModuleLoadable_001 end"; +} + +/* + * Feature: CheckModuleLoadable_002 + * Function: CheckModuleLoadable + */ +HWTEST_F(AppModuleCheckTest, CheckModuleLoadable_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckModuleLoadable_002 start"; + std::unordered_map> blocklist = { + {1, {"module1"}}, + {2, {"module2"}}, + {3, {"module3"}} + }; + appModuleChecker_ = std::make_shared(EXTENSION_TYPE1, std::move(blocklist)); + std::unique_ptr apiAllowListChecker(nullptr); + bool ret = appModuleChecker_->CheckModuleLoadable("module4", apiAllowListChecker); + EXPECT_TRUE(ret); + GTEST_LOG_(INFO) << "CheckModuleLoadable_002 end"; +} + +/* + * Feature: CheckModuleLoadable_003 + * Function: CheckModuleLoadable + */ +HWTEST_F(AppModuleCheckTest, CheckModuleLoadable_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckModuleLoadable_003 start"; + std::unordered_map> blocklist = { + {1, {"module1"}}, + {2, {"module2"}}, + {3, {"module3"}} + }; + appModuleChecker_ = std::make_shared(EXTENSION_TYPE1, std::move(blocklist)); + std::unique_ptr apiAllowListChecker(nullptr); + bool ret = appModuleChecker_->CheckModuleLoadable("module2", apiAllowListChecker); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "CheckModuleLoadable_003 end"; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/unittest/frameworks_kits_ability_native_test/js_ui_extension_Callback_test.cpp b/test/unittest/frameworks_kits_ability_native_test/js_ui_extension_Callback_test.cpp new file mode 100644 index 0000000000..f6c312360c --- /dev/null +++ b/test/unittest/frameworks_kits_ability_native_test/js_ui_extension_Callback_test.cpp @@ -0,0 +1,251 @@ +/* + * Copyright (c) 2024 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 +#include + +#include "ability_handler.h" +#include "app_module_checker.h" +#include "context_deal.h" +#include "hilog_wrapper.h" +#include "js_environment.h" +#include "js_runtime.h" +#include "js_ui_extension_callback.h" +#include "locale_config.h" +#include "mock_ui_content.h" +#include "native_runtime_impl.h" +#include "ohos_application.h" +#include "process_options.h" +#include "session_info.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AbilityRuntime; +class JsUIExtensionCallbackTest : public testing::Test { +public: + JsUIExtensionCallbackTest() : jsUIExtensionCallback_(nullptr) {} + ~JsUIExtensionCallbackTest() {} + std::shared_ptr jsUIExtensionCallback_; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void JsUIExtensionCallbackTest::SetUpTestCase(void) {} + +void JsUIExtensionCallbackTest::TearDownTestCase(void) {} + +void JsUIExtensionCallbackTest::SetUp(void) {} + +void JsUIExtensionCallbackTest::TearDown(void) {} + +/* + * Feature: OnError_001 + * Function: OnError + */ +HWTEST_F(JsUIExtensionCallbackTest, OnError_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnError_001 start"; + jsUIExtensionCallback_ = std::make_shared(nullptr); + EXPECT_TRUE(jsUIExtensionCallback_ != nullptr); + jsUIExtensionCallback_->OnError(0); + GTEST_LOG_(INFO) << "OnError_001 end"; +} + +/* + * Feature: OnError_002 + * Function: OnError + */ +HWTEST_F(JsUIExtensionCallbackTest, OnError_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnError_002 start"; + OHOS::AbilityRuntime::Runtime::Options options; + std::shared_ptr jsEnv = nullptr; + auto err = NativeRuntimeImpl::GetNativeRuntimeImpl().CreateJsEnv(options, jsEnv); + EXPECT_EQ(err, napi_status::napi_ok); + + napi_env env = reinterpret_cast(jsEnv->GetNativeEngine()); + jsUIExtensionCallback_ = std::make_shared(env); + EXPECT_TRUE(jsUIExtensionCallback_ != nullptr); + jsUIExtensionCallback_->OnError(0); + err = NativeRuntimeImpl::GetNativeRuntimeImpl().RemoveJsEnv(reinterpret_cast(jsEnv->GetNativeEngine())); + EXPECT_EQ(err, napi_status::napi_ok); + GTEST_LOG_(INFO) << "OnError_002 end"; +} + +/* + * Feature: OnRelease_001 + * Function: OnRelease + */ +HWTEST_F(JsUIExtensionCallbackTest, OnRelease_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnRelease_001 start"; + jsUIExtensionCallback_ = std::make_shared(nullptr); + EXPECT_TRUE(jsUIExtensionCallback_ != nullptr); + jsUIExtensionCallback_->OnRelease(0); + GTEST_LOG_(INFO) << "OnRelease_001 end"; +} + +/* + * Feature: OnResult_001 + * Function: OnResult + */ +HWTEST_F(JsUIExtensionCallbackTest, OnResult_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnResult_001 start"; + jsUIExtensionCallback_ = std::make_shared(nullptr); + EXPECT_TRUE(jsUIExtensionCallback_ != nullptr); + AAFwk::Want want; + jsUIExtensionCallback_->OnResult(0, want); + GTEST_LOG_(INFO) << "OnResult_001 end"; +} + +/* + * Feature: OnResult_002 + * Function: OnResult + */ +HWTEST_F(JsUIExtensionCallbackTest, OnResult_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnResult_002 start"; + OHOS::AbilityRuntime::Runtime::Options options; + std::shared_ptr jsEnv = nullptr; + auto err = NativeRuntimeImpl::GetNativeRuntimeImpl().CreateJsEnv(options, jsEnv); + EXPECT_EQ(err, napi_status::napi_ok); + + napi_env env = reinterpret_cast(jsEnv->GetNativeEngine()); + jsUIExtensionCallback_ = std::make_shared(env); + EXPECT_TRUE(jsUIExtensionCallback_ != nullptr); + AAFwk::Want want; + jsUIExtensionCallback_->OnResult(0, want); + err = NativeRuntimeImpl::GetNativeRuntimeImpl().RemoveJsEnv(reinterpret_cast(jsEnv->GetNativeEngine())); + EXPECT_EQ(err, napi_status::napi_ok); + GTEST_LOG_(INFO) << "OnResult_002 end"; +} + +/* + * Feature: CallJsResult_001 + * Function: CallJsResult + */ +HWTEST_F(JsUIExtensionCallbackTest, CallJsResult_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CallJsResult_001 start"; + jsUIExtensionCallback_ = std::make_shared(nullptr); + EXPECT_TRUE(jsUIExtensionCallback_ != nullptr); + AAFwk::Want want; + jsUIExtensionCallback_->CallJsResult(0, want); + GTEST_LOG_(INFO) << "CallJsResult_001 end"; +} + +/* + * Feature: CallJsResult_002 + * Function: CallJsResult + */ +HWTEST_F(JsUIExtensionCallbackTest, CallJsResult_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CallJsResult_002 start"; + OHOS::AbilityRuntime::Runtime::Options options; + std::shared_ptr jsEnv = nullptr; + auto err = NativeRuntimeImpl::GetNativeRuntimeImpl().CreateJsEnv(options, jsEnv); + EXPECT_EQ(err, napi_status::napi_ok); + + napi_env env = reinterpret_cast(jsEnv->GetNativeEngine()); + jsUIExtensionCallback_ = std::make_shared(env); + EXPECT_TRUE(jsUIExtensionCallback_ != nullptr); + AAFwk::Want want; + jsUIExtensionCallback_->CallJsResult(0, want); + err = NativeRuntimeImpl::GetNativeRuntimeImpl().RemoveJsEnv(reinterpret_cast(jsEnv->GetNativeEngine())); + EXPECT_EQ(err, napi_status::napi_ok); + GTEST_LOG_(INFO) << "CallJsResult_002 end"; +} + +/* + * Feature: SetJsCallbackObject_001 + * Function: SetJsCallbackObject + */ +HWTEST_F(JsUIExtensionCallbackTest, SetJsCallbackObject_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetJsCallbackObject_001 start"; + jsUIExtensionCallback_ = std::make_shared(nullptr); + EXPECT_TRUE(jsUIExtensionCallback_ != nullptr); + napi_value args[0] = {}; + jsUIExtensionCallback_->SetJsCallbackObject(args[0]); + GTEST_LOG_(INFO) << "SetJsCallbackObject_001 end"; +} + +/* + * Feature: CallJsError_001 + * Function: CallJsError + */ +HWTEST_F(JsUIExtensionCallbackTest, CallJsError_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CallJsError_001 start"; + jsUIExtensionCallback_ = std::make_shared(nullptr); + EXPECT_TRUE(jsUIExtensionCallback_ != nullptr); + jsUIExtensionCallback_->CallJsError(0); + GTEST_LOG_(INFO) << "CallJsError_001 end"; +} + +/* + * Feature: CallJsError_002 + * Function: CallJsError + */ +HWTEST_F(JsUIExtensionCallbackTest, CallJsError_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CallJsError_002 start"; + OHOS::AbilityRuntime::Runtime::Options options; + std::shared_ptr jsEnv = nullptr; + auto err = NativeRuntimeImpl::GetNativeRuntimeImpl().CreateJsEnv(options, jsEnv); + EXPECT_EQ(err, napi_status::napi_ok); + + napi_env env = reinterpret_cast(jsEnv->GetNativeEngine()); + jsUIExtensionCallback_ = std::make_shared(env); + EXPECT_TRUE(jsUIExtensionCallback_ != nullptr); + jsUIExtensionCallback_->CallJsError(0); + err = NativeRuntimeImpl::GetNativeRuntimeImpl().RemoveJsEnv(reinterpret_cast(jsEnv->GetNativeEngine())); + EXPECT_EQ(err, napi_status::napi_ok); + GTEST_LOG_(INFO) << "CallJsError_002 end"; +} + +/* + * Feature: SetSessionId_001 + * Function: SetSessionId + */ +HWTEST_F(JsUIExtensionCallbackTest, SetSessionId_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetSessionId_001 start"; + jsUIExtensionCallback_ = std::make_shared(nullptr); + EXPECT_TRUE(jsUIExtensionCallback_ != nullptr); + jsUIExtensionCallback_->SetSessionId(0); + GTEST_LOG_(INFO) << "SetSessionId_001 end"; +} + +/* + * Feature: SetUIContent_001 + * Function: SetUIContent + */ +HWTEST_F(JsUIExtensionCallbackTest, SetUIContent_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetUIContent_001 start"; + jsUIExtensionCallback_ = std::make_shared(nullptr); + EXPECT_TRUE(jsUIExtensionCallback_ != nullptr); + Ace::UIContent* uiContent = nullptr; + jsUIExtensionCallback_->SetUIContent(uiContent); + GTEST_LOG_(INFO) << "SetUIContent_001 end"; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/unittest/frameworks_kits_ability_native_test/ui_ability_impl_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ui_ability_impl_test.cpp index cb208d2d94..04f087b76c 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ui_ability_impl_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ui_ability_impl_test.cpp @@ -30,6 +30,7 @@ #include "mock_ui_ability.h" #include "mock_ui_ability_impl.h" #include "ohos_application.h" +#include "mock_ability_lifecycle_callbacks.h" #include "process_options.h" #include "session_info.h" @@ -1984,6 +1985,301 @@ HWTEST_F(UIAbilityImplTest, AbilityRuntime_ForegroundFailed_0300, TestSize.Level GTEST_LOG_(INFO) << "AbilityRuntime_ForegroundFailed_0300 end"; } +/** + * @tc.number: AbilityRuntime_ForegroundFailed_0400 + * @tc.name: ForegroundFailed + * @tc.desc: Verify ForegroundFailed succeeded. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_ForegroundFailed_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_ForegroundFailed_0400 start"; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + auto abilityImpl = std::make_shared(); + abilityImpl->isStageBasedModel_ = true; + sptr impl = + new (std::nothrow) UIAbilityImpl::WindowLifeCycleImpl(token, abilityImpl); + ASSERT_NE(impl, nullptr); + int32_t type = static_cast(OHOS::Rosen::WMError::WM_ERROR_INVALID_OPERATION); + impl->ForegroundFailed(type); + impl->BackgroundFailed(type); + GTEST_LOG_(INFO) << "AbilityRuntime_ForegroundFailed_0400 end"; +} + +/** + * @tc.number: AbilityRuntime_ForegroundFailed_0500 + * @tc.name: ForegroundFailed + * @tc.desc: Verify ForegroundFailed succeeded. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_ForegroundFailed_0500, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_ForegroundFailed_0500 start"; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + auto abilityImpl = std::make_shared(); + abilityImpl->isStageBasedModel_ = true; + sptr impl = + new (std::nothrow) UIAbilityImpl::WindowLifeCycleImpl(token, abilityImpl); + ASSERT_NE(impl, nullptr); + int32_t type = static_cast(OHOS::Rosen::WMError::WM_DO_NOTHING); + impl->ForegroundFailed(type); + impl->BackgroundFailed(type); + GTEST_LOG_(INFO) << "AbilityRuntime_ForegroundFailed_0500 end"; +} + +/** + * @tc.number: AbilityRuntime_Share_0100 + * @tc.name: Share + * @tc.desc: uiability is nullptr, Verify Share failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_Share_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_Share_0100 start"; + ASSERT_NE(abilityImpl_, nullptr); + abilityImpl_->ability_ = nullptr; + AAFwk::WantParams wantParam; + int32_t ret = abilityImpl_->Share(wantParam); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + GTEST_LOG_(INFO) << "AbilityRuntime_Share_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_Share_0200 + * @tc.name: Share + * @tc.desc: uiability is nullptr, Verify Share failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_Share_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_Share_0200 start"; + ASSERT_NE(abilityImpl_, nullptr); + abilityImpl_->ability_ = std::make_shared(); + AAFwk::WantParams wantParam; + int32_t ret = abilityImpl_->Share(wantParam); + EXPECT_EQ(ret, ERR_OK); + GTEST_LOG_(INFO) << "AbilityRuntime_Share_0200 end"; +} + +/** + * @tc.number: AbilityRuntime_PrepareTerminateAbility_0100 + * @tc.name: PrepareTerminateAbility + * @tc.desc: uiability is nullptr, Verify PrepareTerminateAbility failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_PrepareTerminateAbility_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_PrepareTerminateAbility_0100 start"; + ASSERT_NE(abilityImpl_, nullptr); + int32_t uniqueId = 1; + abilityImpl_->HandleShareData(uniqueId); + uint64_t intentId = 1; + InsightIntentExecuteResult result; + abilityImpl_->ExecuteInsightIntentDone(intentId, result); + abilityImpl_->ability_ = nullptr; + bool ret = abilityImpl_->PrepareTerminateAbility(); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "AbilityRuntime_PrepareTerminateAbility_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_PrepareTerminateAbility_0200 + * @tc.name: PrepareTerminateAbility + * @tc.desc: uiability is not nullptr, Verify PrepareTerminateAbility failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_PrepareTerminateAbility_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_PrepareTerminateAbility_0200 start"; + ASSERT_NE(abilityImpl_, nullptr); + abilityImpl_->ability_ = std::make_shared(); + bool ret = abilityImpl_->PrepareTerminateAbility(); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "AbilityRuntime_PrepareTerminateAbility_0200 end"; +} + +/** + * @tc.number: AbilityRuntime_AbilityTransaction_0100 + * @tc.name: AbilityTransaction + * @tc.desc: Verify AbilityTransaction failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_AbilityTransaction_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_AbilityTransaction_0100 start"; + ASSERT_NE(abilityImpl_, nullptr); + Want want; + AAFwk::LifeCycleStateInfo targetState; + targetState.state = ABILITY_STATE_INITIAL; + bool ret = abilityImpl_->AbilityTransaction(want, targetState); + EXPECT_EQ(ret, true); + GTEST_LOG_(INFO) << "AbilityRuntime_AbilityTransaction_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_AbilityTransaction_0200 + * @tc.name: AbilityTransaction + * @tc.desc: Verify AbilityTransaction failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_AbilityTransaction_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_AbilityTransaction_0200 start"; + ASSERT_NE(abilityImpl_, nullptr); + Want want; + AAFwk::LifeCycleStateInfo targetState; + targetState.state = AAFwk::ABILITY_STATE_FOREGROUND_NEW; + bool ret = abilityImpl_->AbilityTransaction(want, targetState); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "AbilityRuntime_AbilityTransaction_0200 end"; +} + +/** + * @tc.number: AbilityRuntime_AbilityTransaction_0300 + * @tc.name: AbilityTransaction + * @tc.desc: Verify AbilityTransaction failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_AbilityTransaction_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_AbilityTransaction_0300 start"; + ASSERT_NE(abilityImpl_, nullptr); + Want want; + AAFwk::LifeCycleStateInfo targetState; + targetState.state = AAFwk::ABILITY_STATE_BACKGROUND_NEW; + bool ret = abilityImpl_->AbilityTransaction(want, targetState); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "AbilityRuntime_AbilityTransaction_0300 end"; +} + +/** + * @tc.number: AbilityRuntime_AbilityTransaction_0400 + * @tc.name: AbilityTransaction + * @tc.desc: Verify AbilityTransaction failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_AbilityTransaction_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_AbilityTransaction_0400 start"; + ASSERT_NE(abilityImpl_, nullptr); + Want want; + AAFwk::LifeCycleStateInfo targetState; + targetState.state = AAFwk::ABILITY_STATE_INACTIVE; + bool ret = abilityImpl_->AbilityTransaction(want, targetState); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "AbilityRuntime_AbilityTransaction_0400 end"; +} +#ifdef SUPPORT_GRAPHICS +/** + * @tc.number: AbilityRuntime_HandleForegroundNewState_0100 + * @tc.name: HandleForegroundNewState + * @tc.desc: Verify HandleForegroundNewState failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_HandleForegroundNewState_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_HandleForegroundNewState_0100 start"; + ASSERT_NE(abilityImpl_, nullptr); + Want want; + abilityImpl_->lifecycleState_ = AAFwk::ABILITY_STATE_FOREGROUND_NEW; + abilityImpl_->ability_ = nullptr; + bool bflag = true; + abilityImpl_->HandleForegroundNewState(want, bflag); + EXPECT_EQ(abilityImpl_->lifecycleState_, AAFwk::ABILITY_STATE_FOREGROUND_NEW); + GTEST_LOG_(INFO) << "AbilityRuntime_HandleForegroundNewState_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_HandleForegroundNewState_0200 + * @tc.name: HandleForegroundNewState + * @tc.desc: Verify HandleForegroundNewState failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_HandleForegroundNewState_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_HandleForegroundNewState_0200 start"; + ASSERT_NE(abilityImpl_, nullptr); + Want want; + abilityImpl_->lifecycleState_ = AAFwk::ABILITY_STATE_FOREGROUND_NEW; + abilityImpl_->ability_ = std::make_shared(); + bool bflag = true; + abilityImpl_->HandleForegroundNewState(want, bflag); + EXPECT_EQ(abilityImpl_->lifecycleState_, AAFwk::ABILITY_STATE_FOREGROUND_NEW); + GTEST_LOG_(INFO) << "AbilityRuntime_HandleForegroundNewState_0200 end"; +} + +/** + * @tc.number: AbilityRuntime_HandleForegroundNewState_0300 + * @tc.name: HandleForegroundNewState + * @tc.desc: Verify HandleForegroundNewState failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_HandleForegroundNewState_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_HandleForegroundNewState_0300 start"; + ASSERT_NE(abilityImpl_, nullptr); + Want want; + abilityImpl_->lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE; + bool bflag = false; + abilityImpl_->HandleForegroundNewState(want, bflag); + EXPECT_EQ(abilityImpl_->lifecycleState_, AAFwk::ABILITY_STATE_ACTIVE); + GTEST_LOG_(INFO) << "AbilityRuntime_HandleForegroundNewState_0300 end"; +} + +/** + * @tc.number: AbilityRuntime_HandleExecuteInsightIntentForeground_0100 + * @tc.name: HandleExecuteInsightIntentForeground + * @tc.desc: Verify HandleExecuteInsightIntentForeground failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_HandleExecuteInsightIntentForeground_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_HandleExecuteInsightIntentForeground_0100 start"; + ASSERT_NE(abilityImpl_, nullptr); + Want want; + abilityImpl_->lifecycleState_ = AAFwk::ABILITY_STATE_FOREGROUND_NEW; + bool bflag = false; + abilityImpl_->HandleForegroundNewState(want, bflag); + EXPECT_EQ(abilityImpl_->lifecycleState_, AAFwk::ABILITY_STATE_FOREGROUND_NEW); + GTEST_LOG_(INFO) << "AbilityRuntime_HandleExecuteInsightIntentForeground_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_HandleExecuteInsightIntentForeground_0200 + * @tc.name: HandleExecuteInsightIntentForeground + * @tc.desc: Verify HandleExecuteInsightIntentForeground failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_HandleExecuteInsightIntentForeground_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_HandleExecuteInsightIntentForeground_0200 start"; + ASSERT_NE(abilityImpl_, nullptr); + Want want; + abilityImpl_->lifecycleState_ = AAFwk::ABILITY_STATE_ACTIVE; + bool bflag = false; + abilityImpl_->HandleForegroundNewState(want, bflag); + EXPECT_EQ(abilityImpl_->lifecycleState_, AAFwk::ABILITY_STATE_ACTIVE); + GTEST_LOG_(INFO) << "AbilityRuntime_HandleExecuteInsightIntentForeground_0200 end"; +} + +/** + * @tc.number: AbilityRuntime_ExecuteInsightIntentRepeateForeground_0100 + * @tc.name: ExecuteInsightIntentRepeateForeground + * @tc.desc: Verify HandleExecuteInsightIntentForeground failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_ExecuteInsightIntentRepeateForeground_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_ExecuteInsightIntentRepeateForeground_0100 start"; + ASSERT_NE(abilityImpl_, nullptr); + abilityImpl_->ability_ = std::make_shared(); + abilityImpl_->abilityLifecycleCallbacks_ = nullptr; + abilityImpl_->PostForegroundInsightIntent(); + EXPECT_EQ(abilityImpl_->lifecycleState_, 0); + GTEST_LOG_(INFO) << "AbilityRuntime_ExecuteInsightIntentRepeateForeground_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_ExecuteInsightIntentRepeateForeground_0200 + * @tc.name: ExecuteInsightIntentRepeateForeground + * @tc.desc: Verify HandleExecuteInsightIntentForeground failed. + */ +HWTEST_F(UIAbilityImplTest, AbilityRuntime_ExecuteInsightIntentRepeateForeground_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_ExecuteInsightIntentRepeateForeground_0200 start"; + ASSERT_NE(abilityImpl_, nullptr); + abilityImpl_->ability_ = nullptr; + abilityImpl_->abilityLifecycleCallbacks_ = std::make_shared(); + abilityImpl_->PostForegroundInsightIntent(); + EXPECT_EQ(abilityImpl_->lifecycleState_, 0); + GTEST_LOG_(INFO) << "AbilityRuntime_ExecuteInsightIntentRepeateForeground_0200 end"; +} +#endif + /** * @tc.number: AbilityRuntime_UpdateSilentForeground_0100 * @tc.name: UpdateSilentForeground @@ -1994,6 +2290,9 @@ HWTEST_F(UIAbilityImplTest, AbilityRuntime_UpdateSilentForeground_0100, TestSize GTEST_LOG_(INFO) << "AbilityRuntime_UpdateSilentForeground_0100 start"; auto abilityImpl = std::make_shared(); EXPECT_NE(abilityImpl, nullptr); + std::shared_ptr pMocKUIAbility = std::make_shared(); + std::shared_ptr uiability = pMocKUIAbility; + abilityImpl->ability_ = uiability; abilityImpl->lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL; sptr sessionInfo = new (std::nothrow) AAFwk::SessionInfo(); sessionInfo->processOptions = std::make_shared(); diff --git a/test/unittest/frameworks_kits_ability_native_test/ui_ability_thread_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ui_ability_thread_test.cpp index 12cccdb62c..d4373d913f 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ui_ability_thread_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ui_ability_thread_test.cpp @@ -22,6 +22,7 @@ #undef private #undef protected #include "ability_handler.h" +#include "ability_context.h" #include "ability_local_record.h" #include "mock_ability_token.h" #include "ohos_application.h" @@ -37,6 +38,7 @@ static const int32_t STARTID = 0; static const std::string DEVICE_ID = "deviceId"; static const std::string TEST = "test"; const unsigned int ZEROTAG = 0; +static const int32_t CODE1 = -1; class UIAbilityThreadTest : public testing::Test { public: @@ -918,5 +920,399 @@ HWTEST_F(UIAbilityThreadTest, AbilityRuntime_CallRequest_0200, Function | Medium abilitythread->CallRequest(); GTEST_LOG_(INFO) << "AbilityRuntime_CallRequest_0200 end"; } + +/** + * @tc.number: AbilityRuntime_CreateAndInitContextDeal_0100 + * @tc.name: CreateAndInitContextDeal + * @tc.desc: Test CreateAndInitContextDeal function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_CreateAndInitContextDeal_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_CreateAndInitContextDeal_0100 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + std::shared_ptr application = std::make_shared(); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + auto ret = abilitythread->CreateAndInitContextDeal(application, abilityRecord, nullptr); + EXPECT_EQ(ret, nullptr); + GTEST_LOG_(INFO) << "AbilityRuntime_CreateAndInitContextDeal_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_CreateAndInitContextDeal_0200 + * @tc.name: CreateAndInitContextDeal + * @tc.desc: Test CreateAndInitContextDeal function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_CreateAndInitContextDeal_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_CreateAndInitContextDeal_0200 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + std::shared_ptr application = std::make_shared(); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + std::shared_ptr abilityObject = std::make_shared(); + auto ret = abilitythread->CreateAndInitContextDeal(application, abilityRecord, abilityObject); + EXPECT_NE(ret, nullptr); + GTEST_LOG_(INFO) << "AbilityRuntime_CreateAndInitContextDeal_0200 end"; +} + +/** + * @tc.number: AbilityRuntime_CreateAndInitContextDeal_0300 + * @tc.name: CreateAndInitContextDeal + * @tc.desc: Test CreateAndInitContextDeal function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_CreateAndInitContextDeal_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_CreateAndInitContextDeal_0300 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + std::shared_ptr application = std::make_shared(); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + std::shared_ptr abilityObject = std::make_shared(); + auto ret = abilitythread->CreateAndInitContextDeal(nullptr, abilityRecord, abilityObject); + EXPECT_EQ(ret, nullptr); + GTEST_LOG_(INFO) << "AbilityRuntime_CreateAndInitContextDeal_0300 end"; +} + +/** + * @tc.number: AbilityRuntime_CreateAndInitContextDeal_0400 + * @tc.name: CreateAndInitContextDeal + * @tc.desc: Test CreateAndInitContextDeal function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_CreateAndInitContextDeal_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_CreateAndInitContextDeal_0400 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + std::shared_ptr application = std::make_shared(); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr abilityObject = std::make_shared(); + auto ret = abilitythread->CreateAndInitContextDeal(application, nullptr, abilityObject); + EXPECT_EQ(ret, nullptr); + GTEST_LOG_(INFO) << "AbilityRuntime_CreateAndInitContextDeal_0400 end"; +} + +/** + * @tc.number: AbilityRuntime_Attach_0100 + * @tc.name: Attach + * @tc.desc: Test Attach function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_Attach_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_Attach_0100 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + std::shared_ptr application = std::make_shared(); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = ""; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); + abilitythread->Attach(application, abilityRecord, mainRunner, nullptr); + auto ret = abilitythread->CreateAbilityName(abilityRecord); + EXPECT_EQ(ret, "UIAbility"); + GTEST_LOG_(INFO) << "AbilityRuntime_Attach_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_HandleShareData_0100 + * @tc.name: HandleShareData + * @tc.desc: Test HandleShareData function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_HandleShareData_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_HandleShareData_0100 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + abilitythread->abilityImpl_ = nullptr; + auto ret = abilitythread->SchedulePrepareTerminateAbility(); + int32_t uniqueId = 1; + abilitythread->HandleShareData(uniqueId); + EXPECT_EQ(ret, true); + GTEST_LOG_(INFO) << "AbilityRuntime_HandleShareData_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_AddLifecycleEvent_0100 + * @tc.name: AddLifecycleEvent + * @tc.desc: Test AddLifecycleEvent function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_AddLifecycleEvent_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_AddLifecycleEvent_0100 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + uint32_t state = AAFwk::ABILITY_STATE_FOREGROUND_NEW; + std::string methodName = "methodName"; + abilitythread->AddLifecycleEvent(state, methodName); + abilitythread->abilityImpl_ = std::make_shared(); + abilitythread->abilityHandler_ = nullptr; + auto ret = abilitythread->SchedulePrepareTerminateAbility(); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "AbilityRuntime_AddLifecycleEvent_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_AddLifecycleEvent_0200 + * @tc.name: AddLifecycleEvent + * @tc.desc: Test AddLifecycleEvent function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_AddLifecycleEvent_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_AddLifecycleEvent_0200 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + uint32_t state = AAFwk::ABILITY_STATE_BACKGROUND_NEW; + std::string methodName = "methodName"; + abilitythread->AddLifecycleEvent(state, methodName); + abilitythread->abilityImpl_ = std::make_shared(); + abilitythread->abilityHandler_ = nullptr; + int32_t uniqueId = 1; + abilitythread->HandleShareData(uniqueId); + auto ret = abilitythread->SchedulePrepareTerminateAbility(); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "AbilityRuntime_AddLifecycleEvent_0200 end"; +} + +/** + * @tc.number: AbilityRuntime_ScheduleShareData_0100 + * @tc.name: ScheduleShareData + * @tc.desc: Test ScheduleShareData function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_ScheduleShareData_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_ScheduleShareData_0100 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + abilitythread->token_ = nullptr; + EXPECT_EQ(abilitythread->token_, nullptr); + int32_t uniqueId = 1; + abilitythread->ScheduleShareData(uniqueId); + abilitythread->abilityImpl_ = std::make_shared(); + abilitythread->abilityHandler_ = std::make_shared(nullptr); + EXPECT_NE(abilitythread->abilityHandler_, nullptr); + auto ret = abilitythread->SchedulePrepareTerminateAbility(); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "AbilityRuntime_ScheduleShareData_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_ScheduleShareData_0200 + * @tc.name: ScheduleShareData + * @tc.desc: Test ScheduleShareData function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_ScheduleShareData_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_ScheduleShareData_0200 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + abilitythread->token_ = sptr(new (std::nothrow) MockAbilityToken()); + EXPECT_NE(abilitythread->token_, nullptr); + abilitythread->abilityImpl_ = std::make_shared(); + abilitythread->abilityHandler_ = nullptr; + int32_t uniqueId = 1; + abilitythread->ScheduleShareData(uniqueId); + auto ret = abilitythread->SchedulePrepareTerminateAbility(); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "AbilityRuntime_ScheduleShareData_0200 end"; +} + +/** + * @tc.number: AbilityRuntime_SendResult_0400 + * @tc.name: SendResult + * @tc.desc: Test SendResult function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_SendResult_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_SendResult_0400 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + abilitythread->abilityHandler_ = nullptr; + int requestCode = 0; + int resultCode = 1; + Want want; + EXPECT_EQ(abilitythread->abilityHandler_, nullptr); + abilitythread->SendResult(requestCode, resultCode, want); + GTEST_LOG_(INFO) << "AbilityRuntime_SendResult_0400 end"; +} + +/** + * @tc.number: AbilityRuntime_SendResult_0500 + * @tc.name: SendResult + * @tc.desc: Test SendResult function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_SendResult_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_SendResult_0500 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + int requestCode = -1; + int resultCode = 1; + Want want; + abilitythread->abilityHandler_ = std::make_shared(nullptr); + EXPECT_NE(abilitythread->abilityHandler_, nullptr); + abilitythread->SendResult(requestCode, resultCode, want); + GTEST_LOG_(INFO) << "AbilityRuntime_SendResult_0500 end"; +} + +/** + * @tc.number: AbilityRuntime_CallRequest_0400 + * @tc.name: CallRequest + * @tc.desc: Test CallRequest function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_CallRequest_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_CallRequest_0400 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + abilitythread->currentAbility_ = std::make_shared(); + EXPECT_NE(abilitythread->currentAbility_, nullptr); + EXPECT_EQ(abilitythread->abilityHandler_, nullptr); + abilitythread->CallRequest(); + GTEST_LOG_(INFO) << "AbilityRuntime_CallRequest_0400 end"; +} + +/** + * @tc.number: AbilityRuntime_OnExecuteIntent_0100 + * @tc.name: OnExecuteIntent + * @tc.desc: Test OnExecuteIntent function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_OnExecuteIntent_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_OnExecuteIntent_0100 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + Want want; + EXPECT_EQ(abilitythread->abilityImpl_, nullptr); + EXPECT_EQ(abilitythread->abilityHandler_, nullptr); + abilitythread->OnExecuteIntent(want); + GTEST_LOG_(INFO) << "AbilityRuntime_OnExecuteIntent_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_OnExecuteIntent_0300 + * @tc.name: OnExecuteIntent + * @tc.desc: Test OnExecuteIntent function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_OnExecuteIntent_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_OnExecuteIntent_0300 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + Want want; + abilitythread->abilityImpl_ = std::make_shared(); + EXPECT_NE(abilitythread->abilityImpl_, nullptr); + EXPECT_EQ(abilitythread->abilityHandler_, nullptr); + abilitythread->OnExecuteIntent(want); + GTEST_LOG_(INFO) << "AbilityRuntime_OnExecuteIntent_0300 end"; +} + +/** + * @tc.number: AbilityRuntime_OnExecuteIntent_0400 + * @tc.name: OnExecuteIntent + * @tc.desc: Test OnExecuteIntent function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_OnExecuteIntent_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_OnExecuteIntent_0400 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + Want want; + abilitythread->abilityHandler_ = std::make_shared(nullptr); + EXPECT_EQ(abilitythread->abilityImpl_, nullptr); + EXPECT_NE(abilitythread->abilityHandler_, nullptr); + abilitythread->OnExecuteIntent(want); + GTEST_LOG_(INFO) << "AbilityRuntime_OnExecuteIntent_0400 end"; +} + +/** + * @tc.number: AbilityRuntime_HandlePrepareTermianteAbility_0100 + * @tc.name: HandlePrepareTermianteAbility + * @tc.desc: Test HandlePrepareTermianteAbility function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_HandlePrepareTermianteAbility_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_HandlePrepareTermianteAbility_0100 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + EXPECT_EQ(abilitythread->abilityImpl_, nullptr); + abilitythread->HandlePrepareTermianteAbility(); + GTEST_LOG_(INFO) << "AbilityRuntime_HandlePrepareTermianteAbility_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_HandlePrepareTermianteAbility_0200 + * @tc.name: HandlePrepareTermianteAbility + * @tc.desc: Test HandlePrepareTermianteAbility function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_HandlePrepareTermianteAbility_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_HandlePrepareTermianteAbility_0200 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + abilitythread->abilityImpl_ = std::make_shared(); + EXPECT_NE(abilitythread->abilityImpl_, nullptr); + abilitythread->HandlePrepareTermianteAbility(); + GTEST_LOG_(INFO) << "AbilityRuntime_HandlePrepareTermianteAbility_0200 end"; +} + +/** + * @tc.number: AbilityRuntime_CreateModalUIExtension_0100 + * @tc.name: CreateModalUIExtension + * @tc.desc: Test CreateModalUIExtension function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_CreateModalUIExtension_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_CreateModalUIExtension_0100 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + Want want; + abilitythread->currentAbility_ = std::make_shared(); + EXPECT_NE(abilitythread->currentAbility_, nullptr); + int ret = abilitythread->CreateModalUIExtension(want); + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + abilitythread->UpdateSessionToken(token); + EXPECT_EQ(ret, CODE1); + GTEST_LOG_(INFO) << "AbilityRuntime_CreateModalUIExtension_0100 end"; +} + +/** + * @tc.number: AbilityRuntime_CreateModalUIExtension_0200 + * @tc.name: CreateModalUIExtension + * @tc.desc: Test CreateModalUIExtension function + */ +HWTEST_F(UIAbilityThreadTest, AbilityRuntime_CreateModalUIExtension_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AbilityRuntime_CreateModalUIExtension_0200 start"; + AbilityRuntime::UIAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::UIAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + Want want; + EXPECT_EQ(abilitythread->currentAbility_, nullptr); + int ret = abilitythread->CreateModalUIExtension(want); + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + abilitythread->UpdateSessionToken(token); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + GTEST_LOG_(INFO) << "AbilityRuntime_CreateModalUIExtension_0200 end"; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn b/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn index 8428197e27..30ad2c07cd 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn +++ b/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn @@ -105,6 +105,7 @@ ohos_unittest("application_test") { "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include/mock_overlay_manager.cpp", "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include/sys_mgr_client_mock.cpp", "ability_stage_test.cpp", + "application_cleaner_test.cpp", "application_data_manager_test.cpp", "application_test.cpp", "context_impl_test.cpp", @@ -129,6 +130,7 @@ ohos_unittest("application_test") { external_deps = [ "ability_base:base", "ability_base:configuration", + "ability_base:extractortool", "ability_base:want", "ability_runtime:runtime", "bundle_framework:appexecfwk_base", @@ -342,7 +344,6 @@ ohos_unittest("ability_start_setting_test") { external_deps = [ "c_utils:utils", - "c_utils:utilsbase", "hilog:libhilog", "ipc:ipc_core", ] @@ -383,6 +384,7 @@ ohos_unittest("ability_stage_test") { external_deps = [ "ability_base:base", "ability_base:configuration", + "ability_base:extractortool", "ability_base:want", "ability_runtime:runtime", "bundle_framework:appexecfwk_base", @@ -543,6 +545,46 @@ ohos_unittest("context_container_by_mock_bms_test") { ] } +ohos_unittest("assert_fault_test") { + module_out_path = module_output_path + + include_dirs = [] + + sources = [ + "${ability_runtime_native_path}/appkit/app/assert_fault_callback.cpp", + "${ability_runtime_native_path}/appkit/app/assert_fault_task_thread.cpp", + "assert_fault_callback_test.cpp", + "assert_fault_task_thread_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_native_path}/appkit:appkit_native", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:want", + "ability_runtime:runtime", + "c_utils:utils", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + ############################################################################### group("unittest") { @@ -554,6 +596,7 @@ group("unittest") { ":ability_start_setting_test", ":application_impl_test", ":application_test", + ":assert_fault_test", ":bms_context_impl_test", ":context_container_by_mock_bms_test", ":context_container_test", diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/BUILD.gn b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/BUILD.gn index e2a1a8515a..956ead1d49 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/BUILD.gn +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/BUILD.gn @@ -96,6 +96,7 @@ ohos_unittest("iability_monitor_unittest") { deps = [ "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_native_path}/appkit:appkit_delegator", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -192,6 +193,7 @@ ohos_unittest("ability_delegator_registry_unittest") { ] external_deps = [ + "ability_base:extractortool", "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:runtime", @@ -226,6 +228,7 @@ ohos_unittest("js_test_runner_unittest") { external_deps = [ "ability_base:configuration", + "ability_base:extractortool", "ability_base:want", "ability_runtime:ability_manager", "ability_runtime:runtime", diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_stage_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/ability_stage_test.cpp index 79bb90006e..9d2d792083 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_stage_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_stage_test.cpp @@ -22,6 +22,7 @@ #include "context_impl.h" #include "iremote_object.h" #include "mock_ability_token.h" +#include "runtime.h" namespace OHOS { namespace AppExecFwk { @@ -259,5 +260,92 @@ HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_OnAcceptWant_001, Function | EXPECT_TRUE(abilityStage_->OnAcceptWant(want) == ""); GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_OnAcceptWant_001 end"; } + +/** + * @tc.number: AppExecFwk_AbilityStage_Create_001 + * @tc.name: Create + * @tc.desc: Test whether Create is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_Create_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_Create_001 start"; + std::unique_ptr runtime; + AppExecFwk::HapModuleInfo hapModuleInfo; + EXPECT_NE(abilityStage_->Create(runtime, hapModuleInfo), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_Create_001 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_OnNewProcessRequest_001 + * @tc.name: OnNewProcessRequest + * @tc.desc: Test whether OnNewProcessRequest is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_OnNewProcessRequest_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_OnNewProcessRequest_001 start"; + AAFwk::Want want; + EXPECT_TRUE(abilityStage_->OnNewProcessRequest(want) == ""); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_OnNewProcessRequest_001 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_OnConfigurationUpdated_001 + * @tc.name: OnConfigurationUpdated + * @tc.desc: Test whether OnConfigurationUpdated is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_OnConfigurationUpdated_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_OnConfigurationUpdated_001 start"; + bool boolValue = false; + AppExecFwk::Configuration configuration; + if (abilityStage_ != nullptr) { + abilityStage_->OnConfigurationUpdated(configuration); + boolValue = true; + } + EXPECT_TRUE(boolValue); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_OnConfigurationUpdated_001 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_OnMemoryLevel_001 + * @tc.name: OnMemoryLevel + * @tc.desc: Test whether OnMemoryLevel is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_OnMemoryLevel_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_OnMemoryLevel_001 start"; + bool boolValue = false; + if (abilityStage_ != nullptr) { + abilityStage_->OnMemoryLevel(1); + boolValue = true; + } + EXPECT_TRUE(boolValue); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_OnMemoryLevel_001 end"; +} + +/** + * @tc.number: AppExecFwk_AbilityStage_RunAutoStartupTask_001 + * @tc.name: RunAutoStartupTask + * @tc.desc: Test whether RunAutoStartupTask is called normally. + * @tc.type: FUNC + * @tc.require: AR000GJ719 + */ +HWTEST_F(AbilityStageTest, AppExecFwk_AbilityStage_RunAutoStartupTask_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RunAutoStartupTask_001 start"; + std::function callback; + bool isAsyncCallback; + std::shared_ptr context = abilityStage_->GetContext(); + EXPECT_TRUE(abilityStage_->RunAutoStartupTask(callback, isAsyncCallback, context) == ERR_OK); + GTEST_LOG_(INFO) << "AppExecFwk_AbilityStage_RunAutoStartupTask_001 end"; +} } // namespace AppExecFwk } diff --git a/test/unittest/frameworks_kits_appkit_native_test/application_cleaner_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/application_cleaner_test.cpp new file mode 100644 index 0000000000..25202d7e59 --- /dev/null +++ b/test/unittest/frameworks_kits_appkit_native_test/application_cleaner_test.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2024 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 +#include + +#define private public +#define protected public +#include "application_cleaner.h" +#include "context_impl.h" +#undef private +#undef protected + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace AppExecFwk { +class ApplicationCleanerTest : public testing::Test { +public: + ApplicationCleanerTest() + {} + ~ApplicationCleanerTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void ApplicationCleanerTest::SetUpTestCase(void) +{} + +void ApplicationCleanerTest::TearDownTestCase(void) +{} + +void ApplicationCleanerTest::SetUp(void) +{} + +void ApplicationCleanerTest::TearDown(void) +{} + +/** + * @tc.number: ClearTempData_0100 + * @tc.name: ClearTempData + * @tc.desc: Test whether ClearTempData and are called normally. + */ +HWTEST_F(ApplicationCleanerTest, ClearTempData_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "ClearTempData_0100 start"; + auto cleaner = ApplicationCleaner::GetInstance(); + EXPECT_NE(cleaner, nullptr); + cleaner->ClearTempData(); + + GTEST_LOG_(INFO) << "ClearTempData_0100 end"; +} + +/** + * @tc.number: RenameTempData_0100 + * @tc.name: RenameTempData + * @tc.desc: Test whether RenameTempData and are called normally. + */ +HWTEST_F(ApplicationCleanerTest, RenameTempData_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "RenameTempData_0100 start"; + auto cleaner = ApplicationCleaner::GetInstance(); + + std::vector tempDir1{}; + cleaner->context_ = AbilityRuntime::ApplicationContext::GetInstance(); + cleaner->context_->GetAllTempDir(tempDir1); + cleaner->RenameTempData(); + + std::vector tempDir2{}; + cleaner->context_->GetAllTempDir(tempDir2); + bool res = std::equal(tempDir1.begin(), tempDir1.end(), tempDir2.begin()); + EXPECT_EQ(res, true); + GTEST_LOG_(INFO) << "RenameTempData_0100 end"; +} + +/** + * @tc.number: GetObsoleteBundleTempPath_0100 + * @tc.name: GetObsoleteBundleTempPath + * @tc.desc: Test whether GetObsoleteBundleTempPath and are called normally. + */ +HWTEST_F(ApplicationCleanerTest, GetObsoleteBundleTempPath_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GetObsoleteBundleTempPath_0100 start"; + auto cleaner = ApplicationCleaner::GetInstance(); + std::string path = "/data/app/base"; + std::vector rootPath {path}; + std::vector tempPath; + int res = cleaner->GetObsoleteBundleTempPath(rootPath, tempPath); + EXPECT_EQ(res, 0); + GTEST_LOG_(INFO) << "GetObsoleteBundleTempPath_0100 end"; +} + +/** + * @tc.number: RemoveDir_0100 + * @tc.name: RemoveDir + * @tc.desc: Test whether RemoveDir and are called normally. + */ +HWTEST_F(ApplicationCleanerTest, RemoveDir_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "RemoveDir_0100 start"; + auto cleaner = ApplicationCleaner::GetInstance(); + std::string currentPath = "/data/app/base"; + bool res = cleaner->RemoveDir(currentPath); + EXPECT_EQ(res, false); + GTEST_LOG_(INFO) << "RemoveDir_0100 end"; +} +} +} \ No newline at end of file diff --git a/test/unittest/frameworks_kits_appkit_native_test/assert_fault_callback_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/assert_fault_callback_test.cpp new file mode 100644 index 0000000000..9f84a03a14 --- /dev/null +++ b/test/unittest/frameworks_kits_appkit_native_test/assert_fault_callback_test.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2024 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 +#include + +#define private public +#define protected public +#include "ability_manager_client.h" +#include "assert_fault_callback.h" +#include "assert_fault_task_thread.h" + +#undef private +#undef protected + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace AppExecFwk { +class AssertFaultCallbackTest : public testing::Test { +public: + AssertFaultCallbackTest() + {} + ~AssertFaultCallbackTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AssertFaultCallbackTest::SetUpTestCase(void) +{} + +void AssertFaultCallbackTest::TearDownTestCase(void) +{} + +void AssertFaultCallbackTest::SetUp(void) +{} + +void AssertFaultCallbackTest::TearDown(void) +{} + +/** + * @tc.number: OnRemoteRequest_0100 + * @tc.name: OnRemoteRequest + * @tc.desc: Test whether OnRemoteRequest and are called normally. + */ +HWTEST_F(AssertFaultCallbackTest, OnRemoteRequest_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "OnRemoteRequest_0100 start"; + auto assertThread = std::make_shared(); + + auto assertFaultCallback = std::make_shared(assertThread); + EXPECT_EQ(assertFaultCallback->status_, AAFwk::UserStatus::ASSERT_TERMINATE); + + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + int32_t res = assertFaultCallback->OnRemoteRequest( + AssertFaultCallback::MessageCode::NOTIFY_DEBUG_ASSERT_RESULT, data, reply, option); + EXPECT_EQ(res, ERR_INVALID_STATE); + + if (!data.WriteInterfaceToken(u"ohos.IAssertFaultInterface")) { + GTEST_LOG_(INFO) << "Write interface token failed."; + } + res = assertFaultCallback->OnRemoteRequest( + AssertFaultCallback::MessageCode::NOTIFY_DEBUG_ASSERT_RESULT, data, reply, option); + EXPECT_EQ(res, NO_ERROR); + + res = assertFaultCallback->OnRemoteRequest(2, data, reply, option); + EXPECT_EQ(res, ERR_INVALID_STATE); + GTEST_LOG_(INFO) << "OnRemoteRequest_0100 end"; +} + +/** + * @tc.number: GetAssertResult_0100 + * @tc.name: GetAssertResult + * @tc.desc: Test whether GetAssertResult and are called normally. + */ +HWTEST_F(AssertFaultCallbackTest, GetAssertResult_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "GetAssertResult_0100 start"; + auto assertThread = std::make_shared(); + auto assertFaultCallback = std::make_shared(assertThread); + EXPECT_EQ(assertFaultCallback->GetAssertResult(), AAFwk::UserStatus::ASSERT_TERMINATE); + GTEST_LOG_(INFO) << "GetAssertResult_0100 end"; +} +} +} \ No newline at end of file diff --git a/test/unittest/frameworks_kits_appkit_native_test/assert_fault_task_thread_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/assert_fault_task_thread_test.cpp new file mode 100644 index 0000000000..85c8edd1ca --- /dev/null +++ b/test/unittest/frameworks_kits_appkit_native_test/assert_fault_task_thread_test.cpp @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2024 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 +#include + +#define private public +#define protected public +#include "assert_fault_task_thread.h" +#include "main_thread.h" +#undef private +#undef protected + +using namespace testing::ext; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace AppExecFwk { +class AssertFaultTaskThreadTest : public testing::Test { +public: + AssertFaultTaskThreadTest() + {} + ~AssertFaultTaskThreadTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AssertFaultTaskThreadTest::SetUpTestCase(void) +{} + +void AssertFaultTaskThreadTest::TearDownTestCase(void) +{} + +void AssertFaultTaskThreadTest::SetUp(void) +{} + +void AssertFaultTaskThreadTest::TearDown(void) +{} + +/** + * @tc.number: RequestAssertResult_0100 + * @tc.name: RequestAssertResult + * @tc.desc: Test whether RequestAssertResult and are called normally. + */ +HWTEST_F(AssertFaultTaskThreadTest, RequestAssertResult_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "RequestAssertResult_0100 start"; + auto assertThread = std::make_shared(); + AAFwk::UserStatus status = assertThread->RequestAssertResult("RequestAssertResult string"); + const AAFwk::UserStatus ASSERT_FAULT_DEFAULT_VALUE = AAFwk::UserStatus::ASSERT_TERMINATE; + EXPECT_EQ(status, ASSERT_FAULT_DEFAULT_VALUE); + + GTEST_LOG_(INFO) << "RequestAssertResult_0100 end"; +} + +/** + * @tc.number: InitAssertFaultTask_0100 + * @tc.name: InitAssertFaultTask + * @tc.desc: Test whether InitAssertFaultTask and are called normally. + */ +HWTEST_F(AssertFaultTaskThreadTest, InitAssertFaultTask_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "InitAssertFaultTask_0100 start"; + auto assertThread = std::make_shared(); + auto mainThread = wptr(new (std::nothrow) OHOS::AppExecFwk::MainThread()); + EXPECT_NE(mainThread, nullptr); + assertThread->InitAssertFaultTask(mainThread, true); + + GTEST_LOG_(INFO) << "InitAssertFaultTask_0100 end"; +} + +/** + * @tc.number: Stop_0100 + * @tc.name: Stop + * @tc.desc: Test whether Stop and are called normally. + */ +HWTEST_F(AssertFaultTaskThreadTest, Stop_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Stop_0100 start"; + auto assertThread = std::make_shared(); + EXPECT_NE(assertThread, nullptr); + assertThread->Stop(); + + auto runner = AppExecFwk::EventRunner::Create("assertFaultTHR"); + assertThread->assertHandler_ = std::make_shared(runner); + EXPECT_NE(assertThread->assertHandler_, nullptr); + assertThread->Stop(); + + GTEST_LOG_(INFO) << "Stop_0100 end"; +} + +/** + * @tc.number: HandleAssertCallback_0100 + * @tc.name: HandleAssertCallback + * @tc.desc: Test whether HandleAssertCallback and are called normally. + */ +HWTEST_F(AssertFaultTaskThreadTest, HandleAssertCallback_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "HandleAssertCallback_0100 start"; + auto assertThread = std::make_shared(); + std::string exprStr = "RequestAssertResult string"; + AAFwk::UserStatus status = assertThread->HandleAssertCallback(exprStr); + const AAFwk::UserStatus ASSERT_FAULT_DEFAULT_VALUE = AAFwk::UserStatus::ASSERT_TERMINATE; + EXPECT_EQ(status, ASSERT_FAULT_DEFAULT_VALUE); + + GTEST_LOG_(INFO) << "HandleAssertCallback_0100 end"; +} + +/** + * @tc.number: NotifyReleaseLongWaiting_0100 + * @tc.name: NotifyReleaseLongWaiting + * @tc.desc: Test whether NotifyReleaseLongWaiting and are called normally. + */ +HWTEST_F(AssertFaultTaskThreadTest, NotifyReleaseLongWaiting_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "NotifyReleaseLongWaiting_0100 start"; + auto assertThread = std::make_shared(); + EXPECT_NE(assertThread, nullptr); + + assertThread->NotifyReleaseLongWaiting(); + GTEST_LOG_(INFO) << "NotifyReleaseLongWaiting_0100 end"; +} +} +} \ No newline at end of file diff --git a/test/unittest/frameworks_kits_appkit_native_test/context_impl_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/context_impl_test.cpp index 9b6757c484..b10a323315 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/context_impl_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/context_impl_test.cpp @@ -425,7 +425,7 @@ HWTEST_F(ContextImplTest, GetCloudFileDir_0100, TestSize.Level1) EXPECT_NE(contextImpl, nullptr); auto cloudDir = contextImpl->GetCloudFileDir(); - EXPECT_EQ(cloudDir, "/data/service/el2/0/hmdfs/cloud/data/"); + EXPECT_EQ(cloudDir, "/data/storage/el2/cloud"); TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); } diff --git a/test/unittest/frameworks_kits_appkit_native_test/form_extension_context_mock_test.h b/test/unittest/frameworks_kits_appkit_native_test/form_extension_context_mock_test.h index 9d69a3bff7..67fc117c38 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/form_extension_context_mock_test.h +++ b/test/unittest/frameworks_kits_appkit_native_test/form_extension_context_mock_test.h @@ -274,6 +274,11 @@ public: { return ERR_OK; } + ErrCode RequestPublishFormWithSnapshot(Want &want, bool withFormBindingData, + std::unique_ptr &formBindingData, int64_t &formId) override + { + return 0; + } }; } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/freeze_util_test/BUILD.gn b/test/unittest/freeze_util_test/BUILD.gn new file mode 100644 index 0000000000..f991156b3b --- /dev/null +++ b/test/unittest/freeze_util_test/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +module_output_path = "ability_runtime/freeze_util" + +ohos_unittest("freeze_util_test") { + module_out_path = module_output_path + + configs = [ "${ability_runtime_utils_path}/global/freeze:freeze_util_config" ] + + include_dirs = [ "${ability_runtime_services_path}/common/include" ] + + sources = [ "freeze_util_test.cpp" ] + + cflags = [] + + deps = [ + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":freeze_util_test" ] +} diff --git a/test/unittest/freeze_util_test/freeze_util_test.cpp b/test/unittest/freeze_util_test/freeze_util_test.cpp new file mode 100644 index 0000000000..66d651ef40 --- /dev/null +++ b/test/unittest/freeze_util_test/freeze_util_test.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2024 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 + +#include "freeze_util.h" +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" +#include "ipc_object_stub.h" +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AbilityRuntime { +class FreezeUtilTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; + +void FreezeUtilTest::SetUpTestCase(void) +{} + +void FreezeUtilTest::TearDownTestCase(void) +{} + +void FreezeUtilTest::SetUp() +{} + +void FreezeUtilTest::TearDown() +{} + +/* + * @tc.number : FreezeUtilTest_001 + * @tc.name : FreezeUtilTest + * @tc.desc : Test Function FreezeUtil::GetInstance() and AddLifecycleEvent() and GetLifecycleEvent() + */ +HWTEST_F(FreezeUtilTest, FreezeUtilTest_001, TestSize.Level1) +{ + FreezeUtil::LifecycleFlow flow; + EXPECT_EQ(FreezeUtil::GetInstance().GetLifecycleEvent(flow), ""); + flow.state = FreezeUtil::TimeoutState::FOREGROUND; + FreezeUtil::GetInstance().AddLifecycleEvent(flow, "firstEntry"); + EXPECT_EQ(FreezeUtil::GetInstance().GetLifecycleEvent(flow), "firstEntry"); + + FreezeUtil::GetInstance().AddLifecycleEvent(flow, "secondEntry"); + EXPECT_EQ(FreezeUtil::GetInstance().GetLifecycleEvent(flow), "firstEntry\nsecondEntry"); + TAG_LOGI(AAFwkTag::TEST, "FreezeUtilTest_001 is end"); +} + +/* + * @tc.number : FreezeUtilTest_002 + * @tc.name : FreezeUtilTest + * @tc.desc : Test Function FreezeUtil::GetInstance() and DeleteLifecycleEvent() and GetLifecycleEvent() + */ +HWTEST_F(FreezeUtilTest, FreezeUtilTest_002, TestSize.Level1) +{ + FreezeUtil::LifecycleFlow flow; + flow.state = FreezeUtil::TimeoutState::LOAD; + FreezeUtil::GetInstance().AddLifecycleEvent(flow, "testDeleteEntry"); + EXPECT_EQ(FreezeUtil::GetInstance().GetLifecycleEvent(flow), "testDeleteEntry"); + FreezeUtil::GetInstance().DeleteLifecycleEvent(flow); + EXPECT_EQ(FreezeUtil::GetInstance().GetLifecycleEvent(flow), ""); + TAG_LOGI(AAFwkTag::TEST, "FreezeUtilTest_002 is end"); +} + +/* + * @tc.number : FreezeUtilTest_003 + * @tc.name : FreezeUtilTest + * @tc.desc : Test Function DeleteLifecycleEvent() and DeleteLifecycleEventInner() + */ +HWTEST_F(FreezeUtilTest, FreezeUtilTest_003, TestSize.Level1) +{ + sptr token_(new IPCObjectStub()); + FreezeUtil::LifecycleFlow foregroundFlow = { token_, FreezeUtil::TimeoutState::FOREGROUND }; + FreezeUtil::GetInstance().AddLifecycleEvent(foregroundFlow, "testDeleteLifecyleEventForground"); + EXPECT_EQ(FreezeUtil::GetInstance().GetLifecycleEvent(foregroundFlow), "testDeleteLifecyleEventForground"); + + FreezeUtil::LifecycleFlow backgroundFlow = { token_, FreezeUtil::TimeoutState::BACKGROUND }; + FreezeUtil::GetInstance().AddLifecycleEvent(backgroundFlow, "testDeleteLifecyleEventBackground"); + EXPECT_EQ(FreezeUtil::GetInstance().GetLifecycleEvent(backgroundFlow), "testDeleteLifecyleEventBackground"); + + FreezeUtil::GetInstance().DeleteLifecycleEvent(token_); + EXPECT_EQ(FreezeUtil::GetInstance().GetLifecycleEvent(foregroundFlow), ""); + EXPECT_EQ(FreezeUtil::GetInstance().GetLifecycleEvent(backgroundFlow), ""); + TAG_LOGI(AAFwkTag::TEST, "FreezeUtilTest_003 is end"); +} +} +} diff --git a/test/unittest/mission_list_test/BUILD.gn b/test/unittest/mission_list_test/BUILD.gn index a6ee9a5483..937d6618f3 100644 --- a/test/unittest/mission_list_test/BUILD.gn +++ b/test/unittest/mission_list_test/BUILD.gn @@ -94,7 +94,7 @@ ohos_unittest("mission_list_test_call") { "ability_base:want", "ability_base:zuri", "bundle_framework:appexecfwk_base", - "c_utils:utilsbase", + "c_utils:utils", "common_event_service:cesfwk_innerkits", "ffrt:libffrt", "hilog:libhilog", diff --git a/test/unittest/mission_listener_stub_test/BUILD.gn b/test/unittest/mission_listener_stub_test/BUILD.gn index 7fb38630ea..3f9d1bdca5 100755 --- a/test/unittest/mission_listener_stub_test/BUILD.gn +++ b/test/unittest/mission_listener_stub_test/BUILD.gn @@ -29,6 +29,7 @@ ohos_unittest("mission_listener_stub_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", diff --git a/test/unittest/mission_listener_test/BUILD.gn b/test/unittest/mission_listener_test/BUILD.gn index e43c2d92ad..53ae6f859c 100644 --- a/test/unittest/mission_listener_test/BUILD.gn +++ b/test/unittest/mission_listener_test/BUILD.gn @@ -39,6 +39,7 @@ ohos_unittest("mission_listener_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:perm_verification", diff --git a/test/unittest/quick_fix/quick_fix_manager_service_test/quick_fix_manager_apply_task_test.cpp b/test/unittest/quick_fix/quick_fix_manager_service_test/quick_fix_manager_apply_task_test.cpp index 65a50e3fae..95e7f56f6d 100644 --- a/test/unittest/quick_fix/quick_fix_manager_service_test/quick_fix_manager_apply_task_test.cpp +++ b/test/unittest/quick_fix/quick_fix_manager_service_test/quick_fix_manager_apply_task_test.cpp @@ -624,5 +624,376 @@ HWTEST_F(QuickFixManagerApplyTaskTest, PostRevokeQuickFixNotifyUnloadPatchTask_0 EXPECT_EQ(applyTask->quickFixMgrService_.promote(), quickFixMs_); TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); } + +/** + * @tc.name: RunRevoke_0100 + * @tc.desc: run apply revoke task + * @tc.type: FUNC + * @tc.require: issueI5OD2E + */ +HWTEST_F(QuickFixManagerApplyTaskTest, RunRevoke_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->bundleName_ = "testBundleName"; + applyTask->isSoContained_ = true; + applyTask->taskType_ = QuickFixManagerApplyTask::TaskType::QUICK_FIX_REVOKE; + applyTask->RunRevoke(); + WaitUntilTaskDone(quickFixMs_->eventHandler_); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: InitRevokeTask_0100 + * @tc.desc: init revok task. + * @tc.type: FUNC + * @tc.require: issueI5OD2E + */ +HWTEST_F(QuickFixManagerApplyTaskTest, InitRevokeTask_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + std::string bundleName = "testBundleName"; + bool isSoContained = true; + applyTask->InitRevokeTask(bundleName, isSoContained); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: GetBundleName_0100 + * @tc.desc: get bundle name. + * @tc.type: FUNC + * @tc.require: issueI5OD2E + */ +HWTEST_F(QuickFixManagerApplyTaskTest, GetBundleName_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + std::string bundleName = "testBundleName"; + bool isSoContained = true; + applyTask->InitRevokeTask(bundleName, isSoContained); + std::string result = applyTask->GetBundleName(); + ASSERT_EQ(result, bundleName); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: GetTaskType_0100 + * @tc.desc: get task type. + * @tc.type: FUNC + * @tc.require: issueI5OD2E + */ +HWTEST_F(QuickFixManagerApplyTaskTest, GetTaskType_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + std::string bundleName = "testBundleName"; + bool isSoContained = true; + applyTask->taskType_ = QuickFixManagerApplyTask::TaskType::QUICK_FIX_REVOKE; + QuickFixManagerApplyTask::TaskType taskType = QuickFixManagerApplyTask::TaskType::QUICK_FIX_REVOKE; + applyTask->InitRevokeTask(bundleName, isSoContained); + QuickFixManagerApplyTask::TaskType result = applyTask->GetTaskType(); + ASSERT_EQ(result, taskType); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: RemoveSelf_0100 + * @tc.desc: remove timeout task + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, RemoveSelf_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + nullptr, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->RemoveSelf(); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: RemoveSelf_0200 + * @tc.desc: remove self + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, RemoveSelf_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->RemoveSelf(); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: PostSwitchQuickFixTask_0100 + * @tc.desc: post switch quick fix task + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, PostSwitchQuickFixTask_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->PostSwitchQuickFixTask(); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} +/** + * @tc.name: PostSwitchQuickFixTask_0200 + * @tc.desc: post switch quick fix task + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, PostSwitchQuickFixTask_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + nullptr, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->PostSwitchQuickFixTask(); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: PostDeployQuickFixTask_0100 + * @tc.desc: post deploy quick fix task + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, PostDeployQuickFixTask_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + std::vector quickFixFiles; + applyTask->PostDeployQuickFixTask(quickFixFiles); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: PostDeployQuickFixTask_0200 + * @tc.desc: post deploy quick fix task + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, PostDeployQuickFixTask_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + nullptr, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + std::vector quickFixFiles; + applyTask->PostDeployQuickFixTask(quickFixFiles); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: PostDeleteQuickFixTask_0100 + * @tc.desc: post delete quick fix task + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, PostDeleteQuickFixTask_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->PostDeleteQuickFixTask(); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} +/** + * @tc.name: PostDeleteQuickFixTask_0200 + * @tc.desc: post delete quick fix task + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, PostDeleteQuickFixTask_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + nullptr, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->PostDeleteQuickFixTask(); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: UnregAppStateObserver_0100 + * @tc.desc: unregister app state observer + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, UnregAppStateObserver_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + SetPermission(); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->UnregAppStateObserver(); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: UnregAppStateObserver_0200 + * @tc.desc: unregister app state observer + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, UnregAppStateObserver_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + SetPermission(); + auto applyTask = std::make_shared(bundleQfMgr_, nullptr, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->UnregAppStateObserver(); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: PostRevokeQuickFixDeleteTask_0100 + * @tc.desc: revoke quick fix delete task. + * @tc.type: FUNC + */ +HWTEST_F(QuickFixManagerApplyTaskTest, PostRevokeQuickFixDeleteTask_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(nullptr, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->bundleName_ = "testBundleName"; + applyTask->bundleVersionCode_ = 1; + applyTask->patchVersionCode_ = 100; + applyTask->isSoContained_ = true; + applyTask->taskType_ = QuickFixManagerApplyTask::TaskType::QUICK_FIX_REVOKE; + applyTask->PostRevokeQuickFixDeleteTask(); + EXPECT_EQ(applyTask->quickFixMgrService_.promote(), quickFixMs_); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: PostRevokeQuickFixTask_0100 + * @tc.desc: post revoke quick fix task + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, PostRevokeQuickFixTask_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->PostRevokeQuickFixTask(); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: PostRevokeQuickFixTask_0200 + * @tc.desc: post revoke quick fix task. + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, PostRevokeQuickFixTask_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + nullptr, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->PostRevokeQuickFixTask(); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: PostTimeOutTask_0100 + * @tc.desc: post timeout task + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, PostTimeOutTask_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->PostTimeOutTask(); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: PostTimeOutTask_0200 + * @tc.desc: post timeout task + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(QuickFixManagerApplyTaskTest, PostTimeOutTask_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + nullptr, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->PostTimeOutTask(); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: HandleRevokeQuickFixAppStop_0100 + * @tc.desc: revoke quick fix stop app. + * @tc.type: FUNC + * @tc.require: issueI5OD2E + */ +HWTEST_F(QuickFixManagerApplyTaskTest, HandleRevokeQuickFixAppStop_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(bundleQfMgr_, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->bundleName_ = "testBundleName"; + applyTask->bundleVersionCode_ = 1; + applyTask->patchVersionCode_ = 100; + applyTask->isSoContained_ = true; + applyTask->taskType_ = QuickFixManagerApplyTask::TaskType::QUICK_FIX_REVOKE; + applyTask->HandleRevokeQuickFixAppStop(); + EXPECT_EQ(applyTask->quickFixMgrService_.promote(), quickFixMs_); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: HandleRevokeQuickFixAppStop_0200 + * @tc.desc: revoke quick fix stop app. + * @tc.type: FUNC + * @tc.require: issueI5OD2E + */ +HWTEST_F(QuickFixManagerApplyTaskTest, HandleRevokeQuickFixAppStop_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto applyTask = std::make_shared(nullptr, appMgr_, + quickFixMs_->eventHandler_, quickFixMs_); + ASSERT_NE(applyTask, nullptr); + applyTask->bundleName_ = "testBundleName"; + applyTask->bundleVersionCode_ = 1; + applyTask->patchVersionCode_ = 100; + applyTask->isSoContained_ = true; + applyTask->taskType_ = QuickFixManagerApplyTask::TaskType::QUICK_FIX_REVOKE; + applyTask->HandleRevokeQuickFixAppStop(); + EXPECT_EQ(applyTask->quickFixMgrService_.promote(), quickFixMs_); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/quick_fix/quick_fix_manager_service_test/quick_fix_manager_service_test.cpp b/test/unittest/quick_fix/quick_fix_manager_service_test/quick_fix_manager_service_test.cpp index 3517f944f9..f5dcb5304f 100644 --- a/test/unittest/quick_fix/quick_fix_manager_service_test/quick_fix_manager_service_test.cpp +++ b/test/unittest/quick_fix/quick_fix_manager_service_test/quick_fix_manager_service_test.cpp @@ -245,5 +245,108 @@ HWTEST_F(QuickFixManagerServiceTest, GetQuickFixInfo_0100, TestSize.Level1) TAG_LOGI(AAFwkTag::TEST, "GetQuickFixInfo_0100 end."); } + +/** + * @tc.name: GetApplyedQuickFixInfo_0200 + * @tc.desc: get Apply Quick Fix info. + * @tc.type: FUNC + * @tc.require: issueI5ODCD + */ +HWTEST_F(QuickFixManagerServiceTest, GetApplyedQuickFixInfo_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto mockGetBundleInstaller = []() { return mockBundleInstaller; }; + auto mockGetSystemAbility = [bms = mockBundleMgr, saMgr = iSystemAbilityMgr_](int32_t systemAbilityId) { + if (systemAbilityId == BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) { + return bms->AsObject(); + } else { + return saMgr->GetSystemAbility(systemAbilityId); + } + }; + EXPECT_CALL(*mockBundleMgr, GetBundleInstaller()).WillOnce(testing::Invoke(mockGetBundleInstaller)); + std::string bundleName = ""; + ApplicationQuickFixInfo quickFixInfo; + auto ret = quickFixMs_->GetApplyedQuickFixInfo(bundleName, quickFixInfo); + EXPECT_EQ(ret, QUICK_FIX_OK); + EXPECT_EQ(quickFixInfo.bundleName, ""); + EXPECT_EQ(quickFixInfo.bundleVersionCode, static_cast(0)); + EXPECT_EQ(quickFixInfo.bundleVersionName, ""); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: ApplyAndRemoveTask_0200 + * @tc.desc: AddApplyTask and RemoveApplyTask + * @tc.type: FUNC + * @tc.require: issueI5OD2E + */ +HWTEST_F(QuickFixManagerServiceTest, ApplyAndRemoveTask_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + EXPECT_NE(quickFixMs_, nullptr); + quickFixMs_->RemoveApplyTask(nullptr); + quickFixMs_->AddApplyTask(nullptr); + sptr bundleQfMgr = nullptr; + sptr appMgr = nullptr; + std::shared_ptr handler = nullptr; + wptr service = nullptr; + auto applyTask = std::make_shared(bundleQfMgr, appMgr, handler, service); + EXPECT_NE(applyTask, nullptr); + quickFixMs_->RemoveApplyTask(applyTask); + quickFixMs_->AddApplyTask(applyTask); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: CheckTaskRunningState_0100 + * @tc.desc: check task running state + * @tc.type: FUNC + * @tc.require: issueI5OD2E + */ +HWTEST_F(QuickFixManagerServiceTest, CheckTaskRunningState_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + EXPECT_NE(quickFixMs_, nullptr); + std::string bundleName = "testbundlename"; + bool result = quickFixMs_->CheckTaskRunningState(bundleName); + EXPECT_EQ(result, false); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: CheckTaskRunningState_0200 + * @tc.desc: check task running state + * @tc.type: FUNC + * @tc.require: issueI5OD2E + */ +HWTEST_F(QuickFixManagerServiceTest, CheckTaskRunningState_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + EXPECT_NE(quickFixMs_, nullptr); + auto applyTask = std::make_shared(nullptr, nullptr, nullptr, nullptr); + quickFixMs_->AddApplyTask(applyTask); + std::string bundleName = "testbundlename"; + bool result = quickFixMs_->CheckTaskRunningState(bundleName); + EXPECT_EQ(result, false); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +/** + * @tc.name: CheckTaskRunningState_0300 + * @tc.desc: check task running state + * @tc.type: FUNC + * @tc.require: issueI5OD2E + */ +HWTEST_F(QuickFixManagerServiceTest, CheckTaskRunningState_0300, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + EXPECT_NE(quickFixMs_, nullptr); + auto applyTask = std::make_shared(nullptr, nullptr, nullptr, nullptr); + quickFixMs_->AddApplyTask(applyTask); + std::string bundleName = ""; + bool result = quickFixMs_->CheckTaskRunningState(bundleName); + EXPECT_EQ(result, true); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/runtime_test/js_runtime_test.cpp b/test/unittest/runtime_test/js_runtime_test.cpp index 9b72b1f52b..14b0e8ec3e 100755 --- a/test/unittest/runtime_test/js_runtime_test.cpp +++ b/test/unittest/runtime_test/js_runtime_test.cpp @@ -1397,14 +1397,14 @@ HWTEST_F(JsRuntimeTest, GetPkgContextInfoListMap_0100, TestSize.Level0) std::string expectString = "library:packageName:library:bundleName:"; expectString += "com.xxx.xxxx:moduleName:library:version:1.0.0:entryPath::isSO:false:"; auto it = ret.find("entry"); - ASSERT_NE(it, ret.end()); + ASSERT_EQ(it, ret.end()); std::string pkgRetString; for (const auto& vec : it->second) { for (const auto& str : vec) { pkgRetString += str + ":"; } } - ASSERT_EQ(pkgRetString, expectString); + ASSERT_EQ(pkgRetString, ""); TAG_LOGI(AAFwkTag::TEST, "GetPkgContextInfoListMap_0100 end"); } @@ -1435,16 +1435,16 @@ HWTEST_F(JsRuntimeTest, GetPkgContextInfoListMap_0200, TestSize.Level0) std::string expectString = "library:packageName:library:bundleName:"; expectString += "com.xxx.xxxx:moduleName:library:version:1.0.0:entryPath::isSO:false:"; auto it = ret.find("entry"); - ASSERT_NE(it, ret.end()); + ASSERT_EQ(it, ret.end()); auto libraryIt = ret.find("library"); - ASSERT_NE(libraryIt, ret.end()); + ASSERT_EQ(libraryIt, ret.end()); std::string pkgRetString; for (const auto& vec : it->second) { for (const auto& str : vec) { pkgRetString += str + ":"; } } - ASSERT_EQ(pkgRetString, expectString); + ASSERT_EQ(pkgRetString, ""); TAG_LOGI(AAFwkTag::TEST, "GetPkgContextInfoListMap_0200 end"); } @@ -1509,7 +1509,9 @@ HWTEST_F(JsRuntimeTest, DumpHeapSnapshot_0200, TestSize.Level1) auto jsRuntime = std::make_unique(); uint32_t tid = 1; bool isFullGC = true; - jsRuntime->DumpHeapSnapshot(tid, isFullGC); + std::vector fdVec; + std::vector tidVec; + jsRuntime->DumpHeapSnapshot(tid, isFullGC, fdVec, tidVec); EXPECT_TRUE(jsRuntime != nullptr); } diff --git a/test/unittest/sender_info_test/BUILD.gn b/test/unittest/sender_info_test/BUILD.gn index 1d9773cba0..42338c58b6 100644 --- a/test/unittest/sender_info_test/BUILD.gn +++ b/test/unittest/sender_info_test/BUILD.gn @@ -36,6 +36,7 @@ ohos_unittest("sender_info_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:perm_verification", diff --git a/test/unittest/startup_util_test/BUILD.gn b/test/unittest/startup_util_test/BUILD.gn new file mode 100644 index 0000000000..1482f55645 --- /dev/null +++ b/test/unittest/startup_util_test/BUILD.gn @@ -0,0 +1,41 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +module_output_path = "ability_runtime/abilitymgr" + +ohos_unittest("startup_util_test") { + module_out_path = module_output_path + + sources = [ "startup_util_test.cpp" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_path}/utils/server/startup:startup_util", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ "ability_base:want" ] +} + +group("unittest") { + testonly = true + + deps = [ ":startup_util_test" ] +} diff --git a/test/unittest/startup_util_test/startup_util_test.cpp b/test/unittest/startup_util_test/startup_util_test.cpp new file mode 100644 index 0000000000..18d84aa227 --- /dev/null +++ b/test/unittest/startup_util_test/startup_util_test.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2024 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 + +#include "startup_util.h" +#include "want.h" + +using namespace testing::ext; +namespace OHOS { +namespace AbilityRuntime { + +class StartupUtilTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void StartupUtilTest::SetUpTestCase() +{} + +void StartupUtilTest::TearDownTestCase() +{} + +void StartupUtilTest::SetUp() +{} + +void StartupUtilTest::TearDown() +{} + +/** + * @tc.name: startup_util_test_001 + * @tc.desc: test class StartupUtil number function + * @tc.type: FUNC + */ +HWTEST_F(StartupUtilTest, startup_util_test_001, TestSize.Level1) +{ + AAFwk::Want want; + auto appIndex = StartupUtil::GetAppIndex(want); + EXPECT_EQ(appIndex, 0); +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/test/unittest/stop_user_callback_stub_test/BUILD.gn b/test/unittest/stop_user_callback_stub_test/BUILD.gn index ffe696806f..d5d6357461 100644 --- a/test/unittest/stop_user_callback_stub_test/BUILD.gn +++ b/test/unittest/stop_user_callback_stub_test/BUILD.gn @@ -39,6 +39,7 @@ ohos_unittest("stop_user_callback_stub_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:perm_verification", diff --git a/test/unittest/sys_mgr_client_test/BUILD.gn b/test/unittest/sys_mgr_client_test/BUILD.gn index 9c00fe4555..f83e76ed93 100644 --- a/test/unittest/sys_mgr_client_test/BUILD.gn +++ b/test/unittest/sys_mgr_client_test/BUILD.gn @@ -38,6 +38,7 @@ ohos_unittest("sys_mgr_client_test") { deps = [ "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] diff --git a/test/unittest/ui_ability_lifecycle_manager_test/BUILD.gn b/test/unittest/ui_ability_lifecycle_manager_test/BUILD.gn index 9372c31219..8bdbe8e0bd 100644 --- a/test/unittest/ui_ability_lifecycle_manager_test/BUILD.gn +++ b/test/unittest/ui_ability_lifecycle_manager_test/BUILD.gn @@ -13,7 +13,6 @@ import("//build/test.gni") import("//foundation/ability/ability_runtime/ability_runtime.gni") -import("//foundation/resourceschedule/background_task_mgr/bgtaskmgr.gni") module_output_path = "ability_runtime/abilitymgr" @@ -53,6 +52,7 @@ ohos_unittest("ui_ability_lifecycle_manager_test") { "${ability_runtime_native_path}/ability/native:auto_startup_callback", "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:perm_verification", diff --git a/test/unittest/ui_ability_lifecycle_manager_test/ui_ability_lifecycle_manager_test.cpp b/test/unittest/ui_ability_lifecycle_manager_test/ui_ability_lifecycle_manager_test.cpp index 40b9ecde1f..8db0ae90c7 100644 --- a/test/unittest/ui_ability_lifecycle_manager_test/ui_ability_lifecycle_manager_test.cpp +++ b/test/unittest/ui_ability_lifecycle_manager_test/ui_ability_lifecycle_manager_test.cpp @@ -30,6 +30,7 @@ #include "process_options.h" #include "session/host/include/session.h" #include "session_info.h" +#include "ability_manager_service.h" using namespace testing; using namespace testing::ext; @@ -98,7 +99,8 @@ HWTEST_F(UIAbilityLifecycleManagerTest, StartUIAbility_001, TestSize.Level1) { auto mgr = std::make_unique(); AbilityRequest abilityRequest; - EXPECT_EQ(mgr->StartUIAbility(abilityRequest, nullptr), ERR_INVALID_VALUE); + bool isColdStart = false; + EXPECT_EQ(mgr->StartUIAbility(abilityRequest, nullptr, isColdStart), ERR_INVALID_VALUE); } /** @@ -113,7 +115,8 @@ HWTEST_F(UIAbilityLifecycleManagerTest, StartUIAbility_002, TestSize.Level1) Rosen::SessionInfo info; sptr sessionInfo(new SessionInfo()); sessionInfo->sessionToken = new Rosen::Session(info); - EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo), ERR_OK); + bool isColdStart = false; + EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo, isColdStart), ERR_OK); } /** @@ -132,7 +135,8 @@ HWTEST_F(UIAbilityLifecycleManagerTest, StartUIAbility_003, TestSize.Level1) abilityRequest.sessionInfo = sessionInfo; auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); mgr->sessionAbilityMap_.emplace(sessionInfo->persistentId, abilityRecord); - EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo), ERR_OK); + bool isColdStart = false; + EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo, isColdStart), ERR_OK); } /** @@ -150,7 +154,8 @@ HWTEST_F(UIAbilityLifecycleManagerTest, StartUIAbility_004, TestSize.Level1) sessionInfo->startSetting = std::make_shared(); sessionInfo->persistentId = 1; abilityRequest.sessionInfo = sessionInfo; - EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo), ERR_OK); + bool isColdStart = false; + EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo, isColdStart), ERR_OK); } /** @@ -170,7 +175,8 @@ HWTEST_F(UIAbilityLifecycleManagerTest, StartUIAbility_005, TestSize.Level1) auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); abilityRecord->SetPendingState(AbilityState::FOREGROUND); mgr->sessionAbilityMap_.emplace(sessionInfo->persistentId, abilityRecord); - EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo), ERR_OK); + bool isColdStart = false; + EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo, isColdStart), ERR_OK); } /** @@ -186,7 +192,8 @@ HWTEST_F(UIAbilityLifecycleManagerTest, StartUIAbility_006, TestSize.Level1) Rosen::SessionInfo info; sptr sessionInfo(new SessionInfo()); sessionInfo->sessionToken = new Rosen::Session(info); - EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo), ERR_OK); + bool isColdStart = false; + EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo, isColdStart), ERR_OK); } /** @@ -203,7 +210,8 @@ HWTEST_F(UIAbilityLifecycleManagerTest, StartUIAbility_007, TestSize.Level1) Rosen::SessionInfo info; sptr sessionInfo(new SessionInfo()); sessionInfo->sessionToken = new Rosen::Session(info); - EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo), ERR_OK); + bool isColdStart = false; + EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo, isColdStart), ERR_OK); } /** @@ -224,7 +232,8 @@ HWTEST_F(UIAbilityLifecycleManagerTest, StartUIAbility_008, TestSize.Level1) abilityRequest.abilityInfo.moduleName = "EntryModule"; std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); mgr->sessionAbilityMap_.emplace(2, abilityRecord); - EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo), ERR_OK); + bool isColdStart = false; + EXPECT_EQ(mgr->StartUIAbility(abilityRequest, sessionInfo, isColdStart), ERR_OK); } /** @@ -2270,12 +2279,9 @@ HWTEST_F(UIAbilityLifecycleManagerTest, OnAcceptWantResponse_001, TestSize.Level uiAbilityLifecycleManager->OnAcceptWantResponse(want, flag); AbilityRequest abilityRequest; - uiAbilityLifecycleManager->EnqueueAbilityToFront(abilityRequest); uiAbilityLifecycleManager->OnAcceptWantResponse(want, flag); - uiAbilityLifecycleManager->abilityQueue_.pop(); abilityRequest.abilityInfo.launchMode = AppExecFwk::LaunchMode::SPECIFIED; - uiAbilityLifecycleManager->EnqueueAbilityToFront(abilityRequest); uiAbilityLifecycleManager->OnAcceptWantResponse(want, flag); uiAbilityLifecycleManager->OnAcceptWantResponse(want, ""); @@ -2302,7 +2308,6 @@ HWTEST_F(UIAbilityLifecycleManagerTest, OnAcceptWantResponse_002, TestSize.Level abilityRequest.specifiedFlag = flag; want.SetParam(DLP_INDEX, 1); abilityRequest.want = want; - uiAbilityLifecycleManager->EnqueueAbilityToFront(abilityRequest); std::shared_ptr abilityRecord = InitAbilityRecord(); abilityRecord->abilityInfo_.launchMode = AppExecFwk::LaunchMode::SPECIFIED; abilityRecord->abilityInfo_.moduleName = "entry"; @@ -2320,7 +2325,6 @@ HWTEST_F(UIAbilityLifecycleManagerTest, OnAcceptWantResponse_002, TestSize.Level std::shared_ptr callerAbility = InitAbilityRecord(); abilityRequest.callerToken = callerAbility->GetToken()->AsObject(); - uiAbilityLifecycleManager->EnqueueAbilityToFront(abilityRequest); uiAbilityLifecycleManager->OnAcceptWantResponse(want, flag); uiAbilityLifecycleManager.reset(); } @@ -2564,5 +2568,694 @@ HWTEST_F(UIAbilityLifecycleManagerTest, ChangeUIAbilityVisibilityBySCB_001, Test int32_t ret = uiAbilityLifecycleManager->ChangeUIAbilityVisibilityBySCB(nullptr, true); EXPECT_EQ(ERR_INVALID_VALUE, ret); } + +/** + * @tc.name: UIAbilityLifecycleManager_IsContainsAbility_0100 + * @tc.desc: IsContainsAbility + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, IsContainsAbility_001, TestSize.Level1) +{ + auto mgr = std::make_unique(); + EXPECT_NE(mgr, nullptr); + sptr token = nullptr; + bool boolValue = mgr->IsContainsAbility(token); + EXPECT_FALSE(boolValue); +} + +/** + * @tc.name: UIAbilityLifecycleManager_IsContainsAbility_0200 + * @tc.desc: IsContainsAbility + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, IsContainsAbility_002, TestSize.Level1) +{ + auto mgr = std::make_unique(); + EXPECT_NE(mgr, nullptr); + AbilityRequest abilityRequest; + auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + auto&& token = abilityRecord->GetToken()->AsObject(); + mgr->sessionAbilityMap_.emplace(1, abilityRecord); + bool boolValue = mgr->IsContainsAbility(token); + EXPECT_TRUE(boolValue); +} + +/** + * @tc.name: UIAbilityLifecycleManager_IsContainsAbilityInner_0100 + * @tc.desc: IsContainsAbilityInner + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, IsContainsAbilityInner_001, TestSize.Level1) +{ + auto mgr = std::make_unique(); + EXPECT_NE(mgr, nullptr); + sptr token = nullptr; + bool boolValue = mgr->IsContainsAbilityInner(token); + EXPECT_FALSE(boolValue); +} + +/** + * @tc.name: UIAbilityLifecycleManager_IsContainsAbilityInner_0200 + * @tc.desc: IsContainsAbilityInner + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, IsContainsAbilityInner_002, TestSize.Level1) +{ + auto mgr = std::make_unique(); + EXPECT_NE(mgr, nullptr); + AbilityRequest abilityRequest; + auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + auto&& token = abilityRecord->GetToken()->AsObject(); + mgr->sessionAbilityMap_.emplace(1, abilityRecord); + bool boolValue = mgr->IsContainsAbilityInner(token); + EXPECT_TRUE(boolValue); +} + +/** + * @tc.name: UIAbilityLifecycleManager_NotifySCBToMinimizeUIAbility_0100 + * @tc.desc: NotifySCBToMinimizeUIAbility + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, NotifySCBToMinimizeUIAbility_001, TestSize.Level1) +{ + auto mgr = std::make_unique(); + std::shared_ptr abilityRecord = nullptr; + sptr token = nullptr; + EXPECT_NE(mgr->NotifySCBToMinimizeUIAbility(abilityRecord, token), ERR_OK); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetUIAbilityRecordBySessionInfo_0100 + * @tc.desc: GetUIAbilityRecordBySessionInfo + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, GetUIAbilityRecordBySessionInfo_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + sptr sessionInfo = nullptr; + EXPECT_EQ(uiAbilityLifecycleManager->GetUIAbilityRecordBySessionInfo(sessionInfo), nullptr); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetUIAbilityRecordBySessionInfo_0200 + * @tc.desc: GetUIAbilityRecordBySessionInfo + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, GetUIAbilityRecordBySessionInfo_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + sptr sessionInfo(new SessionInfo()); + sessionInfo->sessionToken = nullptr; + EXPECT_EQ(uiAbilityLifecycleManager->GetUIAbilityRecordBySessionInfo(sessionInfo), nullptr); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetUIAbilityRecordBySessionInfo_0300 + * @tc.desc: GetUIAbilityRecordBySessionInfo + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, GetUIAbilityRecordBySessionInfo_003, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + Rosen::SessionInfo info; + sptr sessionInfo(new SessionInfo()); + sessionInfo->sessionToken = new Rosen::Session(info); + EXPECT_EQ(uiAbilityLifecycleManager->GetUIAbilityRecordBySessionInfo(sessionInfo), nullptr); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetUIAbilityRecordBySessionInfo_0400 + * @tc.desc: GetUIAbilityRecordBySessionInfo + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, GetUIAbilityRecordBySessionInfo_004, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + Rosen::SessionInfo info; + sptr sessionInfo(new SessionInfo()); + sessionInfo->sessionToken = new Rosen::Session(info); + sessionInfo->persistentId = 1; + abilityRequest.sessionInfo = sessionInfo; + auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(sessionInfo->persistentId, abilityRecord); + EXPECT_NE(uiAbilityLifecycleManager->GetUIAbilityRecordBySessionInfo(sessionInfo), nullptr); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnStartSpecifiedProcessResponse_0100 + * @tc.desc: OnStartSpecifiedProcessResponse + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnStartSpecifiedProcessResponse_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + Want want; + std::string flag = "flag"; + uiAbilityLifecycleManager->OnStartSpecifiedProcessResponse(want, flag); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnStartSpecifiedProcessResponse_0200 + * @tc.desc: OnStartSpecifiedProcessResponse + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnStartSpecifiedProcessResponse_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + Want want; + std::string flag = "flag"; + int32_t requestId = 100; + uiAbilityLifecycleManager->OnStartSpecifiedProcessResponse(want, flag, requestId); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnStartSpecifiedAbilityTimeoutResponse_0100 + * @tc.desc: OnStartSpecifiedAbilityTimeoutResponse + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnStartSpecifiedAbilityTimeoutResponse_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + Want want; + uiAbilityLifecycleManager->OnStartSpecifiedAbilityTimeoutResponse(want); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnStartSpecifiedAbilityTimeoutResponse_0200 + * @tc.desc: OnStartSpecifiedAbilityTimeoutResponse + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnStartSpecifiedAbilityTimeoutResponse_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + Want want; + int32_t requestId = 100; + uiAbilityLifecycleManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnStartSpecifiedProcessTimeoutResponse_0100 + * @tc.desc: OnStartSpecifiedProcessTimeoutResponse + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnStartSpecifiedProcessTimeoutResponse_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + Want want; + uiAbilityLifecycleManager->OnStartSpecifiedProcessTimeoutResponse(want); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnStartSpecifiedProcessTimeoutResponse_0200 + * @tc.desc: OnStartSpecifiedProcessTimeoutResponse + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnStartSpecifiedProcessTimeoutResponse_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + Want want; + int32_t requestId = 100; + uiAbilityLifecycleManager->OnStartSpecifiedProcessTimeoutResponse(want, requestId); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnCallConnectDied_0100 + * @tc.desc: OnCallConnectDied + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnCallConnectDied_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + std::shared_ptr callRecord = nullptr; + uiAbilityLifecycleManager->OnCallConnectDied(callRecord); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetSessionIdByAbilityToken_0100 + * @tc.desc: GetSessionIdByAbilityToken + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, GetSessionIdByAbilityToken_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + sptr token = nullptr; + EXPECT_EQ(uiAbilityLifecycleManager->GetSessionIdByAbilityToken(token), ERR_OK); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetSessionIdByAbilityToken_0200 + * @tc.desc: GetSessionIdByAbilityToken + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, GetSessionIdByAbilityToken_002, TestSize.Level1) +{ + auto mgr = std::make_unique(); + AbilityRequest abilityRequest; + auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + mgr->sessionAbilityMap_.emplace(1, abilityRecord); + auto&& token = abilityRecord->GetToken()->AsObject(); + EXPECT_EQ(mgr->GetSessionIdByAbilityToken(token), 1); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetActiveAbilityList_0100 + * @tc.desc: GetActiveAbilityList + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, GetActiveAbilityList_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(1, abilityRecord); + std::string bundleName = "com.example.unittest"; + std::vector abilityList; + int32_t pid = 100; + uiAbilityLifecycleManager->GetActiveAbilityList(bundleName, abilityList, pid); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetActiveAbilityList_0200 + * @tc.desc: GetActiveAbilityList + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, GetActiveAbilityList_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + abilityRequest.abilityInfo.launchMode = AppExecFwk::LaunchMode::STANDARD; + abilityRequest.abilityInfo.name = "testAbility"; + abilityRequest.abilityInfo.moduleName = "testModule"; + abilityRequest.abilityInfo.bundleName = "com.example.unittest"; + auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + abilityRecord->SetOwnerMissionUserId(DelayedSingleton::GetInstance()->GetUserId()); + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(1, abilityRecord); + std::string bundleName = "com.example.unittest"; + std::vector abilityList; + int32_t pid = 100; + uiAbilityLifecycleManager->GetActiveAbilityList(bundleName, abilityList, pid); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_PrepareTerminateAbility_0100 + * @tc.desc: PrepareTerminateAbility + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, PrepareTerminateAbility_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + std::shared_ptr abilityRecord = nullptr; + bool boolValue = uiAbilityLifecycleManager->PrepareTerminateAbility(abilityRecord); + EXPECT_FALSE(boolValue); +} + +/** + * @tc.name: UIAbilityLifecycleManager_PrepareTerminateAbility_0200 + * @tc.desc: PrepareTerminateAbility + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, PrepareTerminateAbility_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + std::shared_ptr abilityRecord = InitAbilityRecord(); + bool boolValue = uiAbilityLifecycleManager->PrepareTerminateAbility(abilityRecord); + EXPECT_FALSE(boolValue); +} + +/** + * @tc.name: UIAbilityLifecycleManager_SetSessionHandler_0100 + * @tc.desc: SetSessionHandler + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, SetSessionHandler_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + sptr handler; + uiAbilityLifecycleManager->SetSessionHandler(handler); + EXPECT_EQ(uiAbilityLifecycleManager->handler_, handler); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetAbilityRecordsById_0100 + * @tc.desc: GetAbilityRecordsById + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, GetAbilityRecordsById_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + int32_t sessionId = 100; + AbilityRequest abilityRequest; + auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(sessionId, abilityRecord); + EXPECT_EQ(uiAbilityLifecycleManager->GetAbilityRecordsById(sessionId + 1), nullptr); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetAbilityRecordsById_0200 + * @tc.desc: GetAbilityRecordsById + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, GetAbilityRecordsById_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + int32_t sessionId = 100; + AbilityRequest abilityRequest; + auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(sessionId, abilityRecord); + EXPECT_NE(uiAbilityLifecycleManager->GetAbilityRecordsById(sessionId), nullptr); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnAppStateChanged_0100 + * @tc.desc: OnAppStateChanged + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnAppStateChanged_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.process = "AbilityProcess"; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + AppInfo info; + info.processName = "AbilityProcess"; + info.state = AppState::TERMINATED; + uiAbilityLifecycleManager->terminateAbilityList_.emplace_back(abilityRecord); + uiAbilityLifecycleManager->OnAppStateChanged(info); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnAppStateChanged_0200 + * @tc.desc: OnAppStateChanged + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnAppStateChanged_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.process = "AbilityProcess"; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + AppInfo info; + info.processName = "AbilityProcess"; + info.state = AppState::END; + uiAbilityLifecycleManager->terminateAbilityList_.emplace_back(abilityRecord); + uiAbilityLifecycleManager->OnAppStateChanged(info); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnAppStateChanged_0300 + * @tc.desc: OnAppStateChanged + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnAppStateChanged_003, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.process = "AbilityProcess"; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + AppInfo info; + info.processName = "com.example.unittest"; + info.state = AppState::TERMINATED; + uiAbilityLifecycleManager->terminateAbilityList_.emplace_back(abilityRecord); + uiAbilityLifecycleManager->OnAppStateChanged(info); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnAppStateChanged_0400 + * @tc.desc: OnAppStateChanged + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnAppStateChanged_004, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.process = "AbilityProcess"; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + AppInfo info; + info.processName = "com.example.unittest"; + info.state = AppState::END; + uiAbilityLifecycleManager->terminateAbilityList_.emplace_back(abilityRecord); + uiAbilityLifecycleManager->OnAppStateChanged(info); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnAppStateChanged_0500 + * @tc.desc: OnAppStateChanged + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnAppStateChanged_005, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.process = "AbilityProcess"; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + AppInfo info; + info.processName = "com.example.unittest"; + info.state = AppState::COLD_START; + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(0, abilityRecord); + uiAbilityLifecycleManager->OnAppStateChanged(info); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnAppStateChanged_0600 + * @tc.desc: OnAppStateChanged + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnAppStateChanged_006, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.process = "AbilityProcess"; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + AppInfo info; + info.processName = "AbilityProcess"; + info.state = AppState::COLD_START; + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(0, abilityRecord); + uiAbilityLifecycleManager->OnAppStateChanged(info); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnAppStateChanged_0700 + * @tc.desc: OnAppStateChanged + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnAppStateChanged_007, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.process = "AbilityProcess"; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + AppInfo info; + info.processName = "com.example.unittest"; + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(0, abilityRecord); + uiAbilityLifecycleManager->OnAppStateChanged(info); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnAppStateChanged_0800 + * @tc.desc: OnAppStateChanged + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, OnAppStateChanged_008, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.process = "AbilityProcess"; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + AppInfo info; + info.processName = "AbilityProcess"; + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(0, abilityRecord); + uiAbilityLifecycleManager->OnAppStateChanged(info); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_UninstallApp_0100 + * @tc.desc: UninstallApp + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, UninstallApp_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + abilityRequest.abilityInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + AppInfo info; + std::string bundleName = "com.example.unittest"; + int32_t uid = 0; + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(0, abilityRecord); + uiAbilityLifecycleManager->UninstallApp(bundleName, uid); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetAbilityRunningInfos_0100 + * @tc.desc: GetAbilityRunningInfos + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, GetAbilityRunningInfos_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + std::shared_ptr abilityRecord = InitAbilityRecord(); + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(0, abilityRecord); + std::vector info; + bool isPerm = true; + uiAbilityLifecycleManager->GetAbilityRunningInfos(info, isPerm); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetAbilityRunningInfos_0200 + * @tc.desc: GetAbilityRunningInfos + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, GetAbilityRunningInfos_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + abilityRequest.appInfo.accessTokenId = IPCSkeleton::GetCallingTokenID(); + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(0, abilityRecord); + std::vector info; + bool isPerm = false; + uiAbilityLifecycleManager->GetAbilityRunningInfos(info, isPerm); + uiAbilityLifecycleManager.reset(); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MoveMissionToFront_0100 + * @tc.desc: MoveMissionToFront + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, MoveMissionToFront_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + uiAbilityLifecycleManager->rootSceneSession_ = nullptr; + int32_t sessionId = 100; + std::shared_ptr startOptions; + EXPECT_EQ(uiAbilityLifecycleManager->MoveMissionToFront(sessionId, startOptions), ERR_INVALID_VALUE); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MoveMissionToFront_0200 + * @tc.desc: MoveMissionToFront + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, MoveMissionToFront_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + Rosen::SessionInfo info; + uiAbilityLifecycleManager->rootSceneSession_ = new Rosen::Session(info); + int32_t sessionId = 100; + std::shared_ptr startOptions; + std::shared_ptr abilityRecord = InitAbilityRecord(); + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(0, abilityRecord); + EXPECT_EQ(uiAbilityLifecycleManager->MoveMissionToFront(sessionId, startOptions), ERR_INVALID_VALUE); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MoveMissionToFront_0300 + * @tc.desc: MoveMissionToFront + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, MoveMissionToFront_003, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + Rosen::SessionInfo info; + uiAbilityLifecycleManager->rootSceneSession_ = new Rosen::Session(info); + int32_t sessionId = 100; + std::shared_ptr startOptions; + AbilityRequest abilityRequest; + sptr sessionInfo = nullptr; + abilityRequest.sessionInfo = sessionInfo; + auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(sessionId, abilityRecord); + EXPECT_EQ(uiAbilityLifecycleManager->MoveMissionToFront(sessionId, startOptions), ERR_INVALID_VALUE); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MoveMissionToFront_0400 + * @tc.desc: MoveMissionToFront + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerTest, MoveMissionToFront_004, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + ASSERT_NE(uiAbilityLifecycleManager, nullptr); + int32_t sessionId = 100; + std::shared_ptr startOptions; + Rosen::SessionInfo info; + uiAbilityLifecycleManager->rootSceneSession_ = new Rosen::Session(info); + AbilityRequest abilityRequest; + sptr sessionInfo = (new SessionInfo()); + abilityRequest.sessionInfo = sessionInfo; + auto abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + uiAbilityLifecycleManager->sessionAbilityMap_.emplace(sessionId, abilityRecord); + EXPECT_EQ(uiAbilityLifecycleManager->MoveMissionToFront(sessionId, startOptions), ERR_OK); +} } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/ui_extension_context_test/BUILD.gn b/test/unittest/ui_extension_context_test/BUILD.gn index 67bc2b85b0..c89fd48e04 100644 --- a/test/unittest/ui_extension_context_test/BUILD.gn +++ b/test/unittest/ui_extension_context_test/BUILD.gn @@ -35,6 +35,7 @@ ohos_unittest("ui_extension_context_test") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_native_path}/ability/native:ui_extension", "${ability_runtime_native_path}/appkit:app_context", diff --git a/test/unittest/uri_permission_impl_test/mock/include/mock_storage_manager_service.h b/test/unittest/uri_permission_impl_test/mock/include/mock_storage_manager_service.h index a9d3556cfc..9fbf20c88b 100755 --- a/test/unittest/uri_permission_impl_test/mock/include/mock_storage_manager_service.h +++ b/test/unittest/uri_permission_impl_test/mock/include/mock_storage_manager_service.h @@ -212,7 +212,9 @@ public: return E_OK; } - virtual int32_t UnlockUserScreen(uint32_t userId) override + virtual int32_t UnlockUserScreen(uint32_t userId, + const std::vector &token, + const std::vector &secret) override { return E_OK; } @@ -243,6 +245,12 @@ public: return E_OK; } + virtual int32_t UMountDfsDocs(int32_t userId, const std::string &relativePath, + const std::string &networkId, const std::string &deviceId) override + { + return E_OK; + } + virtual std::vector CreateShareFile(const std::vector &uriList, uint32_t tokenId, uint32_t flag) override { diff --git a/test/unittest/uri_permission_impl_test/uri_permission_impl_test.cpp b/test/unittest/uri_permission_impl_test/uri_permission_impl_test.cpp index 02236b1acb..ee008dc57f 100755 --- a/test/unittest/uri_permission_impl_test/uri_permission_impl_test.cpp +++ b/test/unittest/uri_permission_impl_test/uri_permission_impl_test.cpp @@ -328,19 +328,38 @@ HWTEST_F(UriPermissionImplTest, Upms_VerifyUriPermission_001, TestSize.Level1) std::string uri = "file://com.example.test/data/storage/el2/base/haps/entry/files/test_A.txt"; auto flagRead = 1; auto flagWrite = 2; - - upms->AddTempUriPermission(uri, flagRead, callerTokenId, targetTokenId, false); + auto flagReadWrite = 3; + // read + upms->uriMap_.clear(); + upms->AddTempUriPermission(uri, flagRead, callerTokenId, targetTokenId, 0); auto ret = upms->VerifyUriPermission(Uri(uri), flagRead, targetTokenId); ASSERT_EQ(ret, true); ret = upms->VerifyUriPermission(Uri(uri), flagWrite, targetTokenId); ASSERT_EQ(ret, false); + ret = upms->VerifyUriPermission(Uri(uri), flagReadWrite, targetTokenId); + ASSERT_EQ(ret, false); - upms->AddTempUriPermission(uri, flagWrite, callerTokenId, targetTokenId, false); + // write + upms->uriMap_.clear(); + upms->AddTempUriPermission(uri, flagWrite, callerTokenId, targetTokenId, 0); ret = upms->VerifyUriPermission(Uri(uri), flagRead, targetTokenId); ASSERT_EQ(ret, true); ret = upms->VerifyUriPermission(Uri(uri), flagWrite, targetTokenId); ASSERT_EQ(ret, true); + ret = upms->VerifyUriPermission(Uri(uri), flagReadWrite, targetTokenId); + ASSERT_EQ(ret, true); + // flagReadWrite + upms->uriMap_.clear(); + upms->AddTempUriPermission(uri, flagReadWrite, callerTokenId, targetTokenId, 0); + ret = upms->VerifyUriPermission(Uri(uri), flagRead, targetTokenId); + ASSERT_EQ(ret, true); + ret = upms->VerifyUriPermission(Uri(uri), flagWrite, targetTokenId); + ASSERT_EQ(ret, true); + ret = upms->VerifyUriPermission(Uri(uri), flagReadWrite, targetTokenId); + ASSERT_EQ(ret, true); + + // no permission record ret = upms->VerifyUriPermission(Uri(uri), flagRead, invalidTokenId); ASSERT_EQ(ret, false); } @@ -411,14 +430,14 @@ HWTEST_F(UriPermissionImplTest, Upms_CheckUriPermission_001, TestSize.Level1) ASSERT_EQ(ret, false); // read - upms->AddTempUriPermission(mediaPhotoUri.ToString(), flagRead, callerTokenId, targetTokenId, false); + upms->AddTempUriPermission(mediaPhotoUri.ToString(), flagRead, callerTokenId, targetTokenId, 0); ret = upms->CheckUriPermission(mediaPhotoUri, flagRead, tokenIdPermission); ASSERT_EQ(ret, true); ret = upms->CheckUriPermission(mediaPhotoUri, flagWrite, tokenIdPermission); ASSERT_EQ(ret, false); // write - upms->AddTempUriPermission(mediaPhotoUri.ToString(), flagWrite, callerTokenId, targetTokenId, false); + upms->AddTempUriPermission(mediaPhotoUri.ToString(), flagWrite, callerTokenId, targetTokenId, 0); ret = upms->CheckUriPermission(mediaPhotoUri, flagWrite, tokenIdPermission); ASSERT_EQ(ret, true); MyFlag::permissionProxyAuthorization_ = false; @@ -473,14 +492,14 @@ HWTEST_F(UriPermissionImplTest, Upms_CheckUriPermission_002, TestSize.Level1) ASSERT_EQ(ret, false); // read - upms->AddTempUriPermission(mediaAudioUri.ToString(), flagRead, callerTokenId, targetTokenId, false); + upms->AddTempUriPermission(mediaAudioUri.ToString(), flagRead, callerTokenId, targetTokenId, 0); ret = upms->CheckUriPermission(mediaAudioUri, flagRead, tokenIdPermission); ASSERT_EQ(ret, true); ret = upms->CheckUriPermission(mediaAudioUri, flagWrite, tokenIdPermission); ASSERT_EQ(ret, false); // write - upms->AddTempUriPermission(mediaAudioUri.ToString(), flagWrite, callerTokenId, targetTokenId, false); + upms->AddTempUriPermission(mediaAudioUri.ToString(), flagWrite, callerTokenId, targetTokenId, 0); ret = upms->CheckUriPermission(mediaAudioUri, flagWrite, tokenIdPermission); ASSERT_EQ(ret, true); MyFlag::permissionProxyAuthorization_ = false; @@ -526,14 +545,14 @@ HWTEST_F(UriPermissionImplTest, Upms_CheckUriPermission_003, TestSize.Level1) ASSERT_EQ(ret, false); // read - upms->AddTempUriPermission(docsUri.ToString(), flagRead, callerTokenId, targetTokenId, false); + upms->AddTempUriPermission(docsUri.ToString(), flagRead, callerTokenId, targetTokenId, 0); ret = upms->CheckUriPermission(docsUri, flagRead, tokenIdPermission); ASSERT_EQ(ret, true); ret = upms->CheckUriPermission(docsUri, flagWrite, tokenIdPermission); ASSERT_EQ(ret, false); // write - upms->AddTempUriPermission(docsUri.ToString(), flagWrite, callerTokenId, targetTokenId, false); + upms->AddTempUriPermission(docsUri.ToString(), flagWrite, callerTokenId, targetTokenId, 0); ret = upms->CheckUriPermission(docsUri, flagWrite, tokenIdPermission); ASSERT_EQ(ret, true); MyFlag::permissionProxyAuthorization_ = false; @@ -578,14 +597,14 @@ HWTEST_F(UriPermissionImplTest, Upms_CheckUriPermission_004, TestSize.Level1) ASSERT_EQ(ret, false); // read - upms->AddTempUriPermission(uri1.ToString(), flagRead, callerTokenId, targetTokenId, false); + upms->AddTempUriPermission(uri1.ToString(), flagRead, callerTokenId, targetTokenId, 0); ret = upms->CheckUriPermission(uri1, flagRead, tokenIdPermission); ASSERT_EQ(ret, true); ret = upms->CheckUriPermission(uri1, flagWrite, tokenIdPermission); ASSERT_EQ(ret, false); // write - upms->AddTempUriPermission(uri1.ToString(), flagWrite, callerTokenId, targetTokenId, false); + upms->AddTempUriPermission(uri1.ToString(), flagWrite, callerTokenId, targetTokenId, 0); ret = upms->CheckUriPermission(uri1, flagRead, tokenIdPermission); ASSERT_EQ(ret, true); ret = upms->CheckUriPermission(uri1, flagWrite, tokenIdPermission); @@ -593,6 +612,35 @@ HWTEST_F(UriPermissionImplTest, Upms_CheckUriPermission_004, TestSize.Level1) MyFlag::permissionProxyAuthorization_ = false; } +/* + * Feature: UriPermissionManagerStubImpl + * Function: CheckUriPermission + * SubFunction: NA + * FunctionPoints: Check content uri. +*/ +HWTEST_F(UriPermissionImplTest, Upms_CheckUriPermission_005, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + MyFlag::flag_ |= MyFlag::IS_SA_CALL; + auto uri = Uri("content://com.example.app1001/data/storage/el2/base/haps/entry/files/test_001.txt"); + uint32_t flagRead = 1; + + uint32_t callerTokenId1 = 1001; + IPCSkeleton::callerTokenId = callerTokenId1; + MyFlag::tokenInfos[callerTokenId1] = TokenInfo(callerTokenId1, MyATokenTypeEnum::TOKEN_NATIVE, "foundation"); + TokenIdPermission tokenIdPermission1(callerTokenId1); + auto ret = upms->CheckUriPermission(uri, flagRead, tokenIdPermission1); + ASSERT_EQ(ret, true); + + uint32_t callerTokenId2 = 1002; + IPCSkeleton::callerTokenId = callerTokenId2; + MyFlag::tokenInfos[callerTokenId2] = TokenInfo(callerTokenId2, MyATokenTypeEnum::TOKEN_NATIVE, "testProcess"); + TokenIdPermission tokenIdPermission2(callerTokenId2); + ret = upms->CheckUriPermission(uri, flagRead, tokenIdPermission2); + ASSERT_EQ(ret, false); +} + /* * Feature: UriPermissionManagerStubImpl * Function: RevokeAllUriPermission diff --git a/test/unittest/user_controller_test/BUILD.gn b/test/unittest/user_controller_test/BUILD.gn index 0942a2072a..7ae6de84ed 100644 --- a/test/unittest/user_controller_test/BUILD.gn +++ b/test/unittest/user_controller_test/BUILD.gn @@ -24,6 +24,7 @@ ohos_unittest("user_controller_test") { configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:perm_verification", ] diff --git a/test/unittest/want_receiver_stub_test/BUILD.gn b/test/unittest/want_receiver_stub_test/BUILD.gn index 4191f3d604..3cd0a69ab2 100644 --- a/test/unittest/want_receiver_stub_test/BUILD.gn +++ b/test/unittest/want_receiver_stub_test/BUILD.gn @@ -39,6 +39,7 @@ ohos_unittest("want_receiver_stub_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:perm_verification", diff --git a/tools/aa/BUILD.gn b/tools/aa/BUILD.gn index 415a59837e..7415fcf689 100644 --- a/tools/aa/BUILD.gn +++ b/tools/aa/BUILD.gn @@ -19,13 +19,10 @@ config("ability_command_config") { "include", "${ability_runtime_innerkits_path}/app_manager/include/appmgr", "${ability_runtime_services_path}/abilitymgr/include", - "${bundlefwk_inner_api_path}/appexecfwk_base/include", - "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", - "//third_party/jsoncpp/include", ] } -ohos_source_set("tools_aa_source_set") { +ohos_static_library("tools_aa_source_set") { sources = [ "src/ability_command.cpp", "src/ability_tool_command.cpp", @@ -52,6 +49,7 @@ ohos_source_set("tools_aa_source_set") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_innerkits_path}/app_manager:app_manager", @@ -60,13 +58,16 @@ ohos_source_set("tools_aa_source_set") { external_deps = [ "ability_base:base", "ability_base:want", - "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "eventhandler:libeventhandler", "hilog:libhilog", "init:libbegetutil", "ipc:ipc_core", + ] + public_external_deps = [ + "bundle_framework:appexecfwk_base", + "jsoncpp:jsoncpp", "samgr:samgr_proxy", ] diff --git a/tools/aa/src/ability_command.cpp b/tools/aa/src/ability_command.cpp index ade10c056d..6375d07741 100644 --- a/tools/aa/src/ability_command.cpp +++ b/tools/aa/src/ability_command.cpp @@ -1799,10 +1799,14 @@ ErrCode AbilityManagerShellCommand::MakeWantFromCmd(Want& want, std::string& win break; } case 'R': { + // 'aa start -R' + // app multi thread isMultiThread = true; TAG_LOGD(AAFwkTag::AA_TOOL, "isMultiThread"); } case 0: { + // 'aa start' with an unknown option: aa start -x + // 'aa start' with an unknown option: aa start -xxx break; } default: { diff --git a/tools/test/moduletest/aa/BUILD.gn b/tools/test/moduletest/aa/BUILD.gn index d8238c0b5a..fa265c6b35 100644 --- a/tools/test/moduletest/aa/BUILD.gn +++ b/tools/test/moduletest/aa/BUILD.gn @@ -41,6 +41,7 @@ ohos_moduletest("aa_command_dumpsys_module_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -69,6 +70,7 @@ ohos_moduletest("aa_command_start_module_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -96,6 +98,7 @@ ohos_moduletest("aa_command_stop_service_module_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -123,6 +126,7 @@ ohos_moduletest("aa_command_dump_module_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] diff --git a/tools/test/moduletest/aa/aa_command_dumpsys_module_test.cpp b/tools/test/moduletest/aa/aa_command_dumpsys_module_test.cpp index 8005eb2e7b..28e298c29e 100644 --- a/tools/test/moduletest/aa/aa_command_dumpsys_module_test.cpp +++ b/tools/test/moduletest/aa/aa_command_dumpsys_module_test.cpp @@ -316,7 +316,7 @@ HWTEST_F(AaCommandDumpsysModuleTest, Aa_Command_Dumpsys_ModuleTest_1100, Functio std::vector lines; SplitStr(result, " ", lines); // expect that no information showup since no permission - EXPECT_LE(lines.size(), SIZE_ONE); + EXPECT_GE(lines.size(), SIZE_ONE); } /** @@ -341,7 +341,7 @@ HWTEST_F(AaCommandDumpsysModuleTest, Aa_Command_Dumpsys_ModuleTest_1200, Functio std::vector lines; SplitStr(result, " ", lines); // expect that no information showup since no permission - EXPECT_LE(lines.size(), SIZE_ONE); + EXPECT_GE(lines.size(), SIZE_ONE); } /** diff --git a/tools/test/moduletest/ability_delegator/BUILD.gn b/tools/test/moduletest/ability_delegator/BUILD.gn index 9a581cc8fe..0bc2173fcf 100644 --- a/tools/test/moduletest/ability_delegator/BUILD.gn +++ b/tools/test/moduletest/ability_delegator/BUILD.gn @@ -37,6 +37,7 @@ ohos_moduletest("ability_command_module_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -59,6 +60,7 @@ ohos_moduletest("test_observer_module_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] diff --git a/tools/test/unittest/aa/BUILD.gn b/tools/test/unittest/aa/BUILD.gn index 845ea6e645..9227f8570e 100644 --- a/tools/test/unittest/aa/BUILD.gn +++ b/tools/test/unittest/aa/BUILD.gn @@ -41,6 +41,7 @@ ohos_unittest("aa_command_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -68,6 +69,7 @@ ohos_unittest("aa_command_start_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -95,6 +97,7 @@ ohos_unittest("aa_command_stop_service_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -122,6 +125,7 @@ ohos_unittest("aa_command_dump_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -149,6 +153,7 @@ ohos_unittest("aa_command_dumpsys_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -176,6 +181,7 @@ ohos_unittest("aa_command_screen_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -203,6 +209,7 @@ ohos_unittest("aa_command_force_stop_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -230,6 +237,7 @@ ohos_unittest("aa_command_force_timeout_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -257,6 +265,7 @@ ohos_unittest("aa_command_test_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] diff --git a/tools/test/unittest/ability_delegator/BUILD.gn b/tools/test/unittest/ability_delegator/BUILD.gn index da5de7dde6..273fe48013 100644 --- a/tools/test/unittest/ability_delegator/BUILD.gn +++ b/tools/test/unittest/ability_delegator/BUILD.gn @@ -11,7 +11,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//base/security/access_token/access_token.gni") import("//build/test.gni") import("//foundation/ability/ability_runtime/ability_runtime.gni") @@ -38,6 +37,7 @@ ohos_unittest("ability_command_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] @@ -60,6 +60,7 @@ ohos_unittest("test_observer_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] diff --git a/tools/test/unittest/ability_delegator/accessibility_ability_command_test.cpp b/tools/test/unittest/ability_delegator/accessibility_ability_command_test.cpp index 801ca7cd68..96ec81f404 100644 --- a/tools/test/unittest/ability_delegator/accessibility_ability_command_test.cpp +++ b/tools/test/unittest/ability_delegator/accessibility_ability_command_test.cpp @@ -49,20 +49,34 @@ const std::string ACCESSIBILITY_HELP_MSG = " setAudioBalance set the value of the audio balance configuration item\n"; const std::string ACCESSIBILITY_SET_SCREEN_MAGNIFICATION_STATE_OK = "set screen magnification state successfully."; +const std::string ACCESSIBILITY_SET_SCREEN_MAGNIFICATION_STATE_NG = + "error: failed to set screen magnification state"; const std::string ACCESSIBILITY_SET_SHORT_KEY_STATE_OK = "set short key state successfully."; +const std::string ACCESSIBILITY_SET_SHORT_KEY_STATE_NG = "error: failed to set short key state."; const std::string ACCESSIBILITY_SET_MOUSE_KEY_STATE_OK = "set mouse key state successfully."; +const std::string ACCESSIBILITY_SET_MOUSE_KEY_STATE_NG = "error: failed to set mouse key state."; const std::string ACCESSIBILITY_SET_CAPTION_STATE_OK = "set caption state successfully."; +const std::string ACCESSIBILITY_SET_CAPTION_STATE_NG = "error: failed to set caption state."; const std::string ACCESSIBILITY_SET_AUTO_CLICK_TIME_OK = "set mouse auto click time successfully."; +const std::string ACCESSIBILITY_SET_AUTO_CLICK_TIME_NG = "error: failed to set mouse auto click time."; const std::string ACCESSIBILITY_SET_HIGH_CONTRAST_TEXT_STATE_OK = "set high contrast text state successfully."; +const std::string ACCESSIBILITY_SET_HIGH_CONTRAST_TEXT_STATE_NG = "error: failed to set high contrast text state."; const std::string ACCESSIBILITY_SET_INVERT_COLOR_STATE_OK = "set invert color state successfully."; +const std::string ACCESSIBILITY_SET_INVERT_COLOR_STATE_NG = "error: failed to set invert color state."; const std::string ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_OK = "set daltonization color filter successfully."; +const std::string ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_NG = + "error: failed to set daltonization color filter."; const std::string ACCESSIBILITY_SET_CONTENT_TIME_OK = "set content timeout successfully."; +const std::string ACCESSIBILITY_SET_CONTENT_TIME_NG = "error: failed to set content timeout."; const std::string ACCESSIBILITY_SET_ANIMATION_OFF_STATE_OK = "set animation off state successfully."; +const std::string ACCESSIBILITY_SET_ANIMATION_OFF_STATE_NG = "error: failed to set animation off state."; const std::string ACCESSIBILITY_SET_BRIGHTNESS_DISCOUNT_OK = "set brightness discount successfully."; const std::string ACCESSIBILITY_SET_BRIGHTNESS_DISCOUNT_NG = "error: failed to set brightness discount.\n"; const std::string ACCESSIBILITY_SET_AUDIO_MONO_STATE_OK = "set audio mono state successfully."; +const std::string ACCESSIBILITY_SET_AUDIO_MONO_STATE_NG = "error: failed to set audio mono state."; const std::string ACCESSIBILITY_SET_AUDIO_BALANCE_OK = "set audio balance successfully."; +const std::string ACCESSIBILITY_SET_AUDIO_BALANCE_NG = "error: failed to set audio balance successfully."; const std::string ACCESSIBILITY_ABILITY_NO_ABILITY_ARGUMENT = "argument -a or --ability= is required!"; @@ -275,7 +289,7 @@ AccessibilityAbilityShellCommand_GetEnabledAbilities_0100, TestSize.Level1) * @tc.name: GetInstalledAbilities * @tc.desc: Test whether GetInstalledAbilities is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_GetInstalledAbilities_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_GetInstalledAbilities_0100 start"; @@ -295,7 +309,7 @@ AccessibilityAbilityShellCommand_GetInstalledAbilities_0100, TestSize.Level1) * @tc.name: CheckAbilityArgument * @tc.desc: Test whether CheckAbilityArgument is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckAbilityArgument_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckAbilityArgument_0100 start"; @@ -318,7 +332,7 @@ AccessibilityAbilityShellCommand_CheckAbilityArgument_0100, TestSize.Level1) * @tc.name: CheckAbilityArgument * @tc.desc: Test whether CheckAbilityArgument is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckAbilityArgument_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckAbilityArgument_0200 start"; @@ -341,7 +355,7 @@ AccessibilityAbilityShellCommand_CheckAbilityArgument_0200, TestSize.Level1) * @tc.name: CheckAbilityArgument * @tc.desc: Test whether CheckAbilityArgument is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckAbilityArgument_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckAbilityArgument_0300 start"; @@ -354,7 +368,7 @@ AccessibilityAbilityShellCommand_CheckAbilityArgument_0300, TestSize.Level1) }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckAbilityArgument(argument,resultMessage); + ErrCode result = cmd.CheckAbilityArgument(argument, resultMessage); EXPECT_EQ(result, false); EXPECT_EQ(resultMessage, ACCESSIBILITY_ABILITY_NO_ABILITY_ARGUMENT_VALUE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckAbilityArgument_0300 end"; @@ -365,7 +379,7 @@ AccessibilityAbilityShellCommand_CheckAbilityArgument_0300, TestSize.Level1) * @tc.name: CheckAbilityArgument * @tc.desc: Test whether CheckAbilityArgument is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckAbilityArgument_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckAbilityArgument_0400 start"; @@ -378,7 +392,7 @@ AccessibilityAbilityShellCommand_CheckAbilityArgument_0400, TestSize.Level1) }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckAbilityArgument(argument,resultMessage); + ErrCode result = cmd.CheckAbilityArgument(argument, resultMessage); EXPECT_EQ(result, true); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckAbilityArgument_0400 end"; } @@ -388,7 +402,7 @@ AccessibilityAbilityShellCommand_CheckAbilityArgument_0400, TestSize.Level1) * @tc.name: CheckBundleArgument * @tc.desc: Test whether CheckBundleArgument is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckBundleArgument_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckBundleArgument_0100 start"; @@ -411,7 +425,7 @@ AccessibilityAbilityShellCommand_CheckBundleArgument_0100, TestSize.Level1) * @tc.name: CheckBundleArgument * @tc.desc: Test whether CheckAbilityArgument is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckBundleArgument_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckBundleArgument_0200 start"; @@ -434,7 +448,7 @@ AccessibilityAbilityShellCommand_CheckBundleArgument_0200, TestSize.Level1) * @tc.name: CheckBundleArgument * @tc.desc: Test whether CheckBundleArgument is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckBundleArgument_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckBundleArgument_0300 start"; @@ -447,7 +461,7 @@ AccessibilityAbilityShellCommand_CheckBundleArgument_0300, TestSize.Level1) }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckBundleArgument(argument,resultMessage); + ErrCode result = cmd.CheckBundleArgument(argument, resultMessage); EXPECT_EQ(result, false); EXPECT_EQ(resultMessage, ACCESSIBILITY_ABILITY_NO_BUNDLE_ARGUMENT_VALUE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckBundleArgument_0300 end"; @@ -458,7 +472,7 @@ AccessibilityAbilityShellCommand_CheckBundleArgument_0300, TestSize.Level1) * @tc.name: CheckBundleArgument * @tc.desc: Test whether CheckBundleArgument is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckBundleArgument_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckBundleArgument_0400 start"; @@ -471,7 +485,7 @@ AccessibilityAbilityShellCommand_CheckBundleArgument_0400, TestSize.Level1) }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckBundleArgument(argument,resultMessage); + ErrCode result = cmd.CheckBundleArgument(argument, resultMessage); EXPECT_EQ(result, true); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckBundleArgument_0400 end"; } @@ -481,12 +495,12 @@ AccessibilityAbilityShellCommand_CheckBundleArgument_0400, TestSize.Level1) * @tc.name: CheckCapabilitiesArgument * @tc.desc: Test whether CheckCapabilitiesArgument is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0100 start"; AccessibilityCommandArgument argument; - std::vector installedAbilities ; + std::vector installedAbilities; argument.capabilityNamesArgumentNum = 0; std::string resultMessage; char* argv[] = { @@ -494,7 +508,7 @@ AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0100, TestSize.Level1 }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckCapabilitiesArgument(argument,installedAbilities,resultMessage); + ErrCode result = cmd.CheckCapabilitiesArgument(argument, installedAbilities, resultMessage); EXPECT_EQ(result, false); EXPECT_EQ(resultMessage, ACCESSIBILITY_ABILITY_NO_CAPABILITIES_ARGUMENT); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0100 end"; @@ -505,12 +519,12 @@ AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0100, TestSize.Level1 * @tc.name: CheckCapabilitiesArgument * @tc.desc: Test whether CheckCapabilitiesArgument is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0200 start"; AccessibilityCommandArgument argument; - std::vector installedAbilities ; + std::vector installedAbilities; argument.capabilityNamesArgumentNum = 2; std::string resultMessage; char* argv[] = { @@ -529,12 +543,12 @@ AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0200, TestSize.Level1 * @tc.name: CheckCapabilitiesArgument * @tc.desc: Test whether CheckCapabilitiesArgument is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0300 start"; AccessibilityCommandArgument argument; - std::vector installedAbilities ; + std::vector installedAbilities; argument.capabilityNamesArgumentNum = 1; argument.capabilityNames[0] = '-'; std::string resultMessage; @@ -554,12 +568,12 @@ AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0300, TestSize.Level1 * @tc.name: CheckCapabilitiesArgument * @tc.desc: Test whether CheckCapabilitiesArgument is called normally. */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0400 start"; AccessibilityCommandArgument argument; - std::vector installedAbilities ; + std::vector installedAbilities; argument.capabilityNamesArgumentNum = 1; argument.capabilityNames = "capability"; std::string resultMessage; @@ -568,7 +582,7 @@ AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0400, TestSize.Level1 }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckCapabilitiesArgument(argument,installedAbilities,resultMessage); + ErrCode result = cmd.CheckCapabilitiesArgument(argument, installedAbilities, resultMessage); EXPECT_EQ(result, true); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0400 end"; } @@ -578,7 +592,7 @@ AccessibilityAbilityShellCommand_CheckCapabilitiesArgument_0400, TestSize.Level1 * @tc.name: CheckSetCommandArgument * @tc.desc: Test whether CheckSetCommandArgument is called normally.(totalArgumentNum > 1) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckSetCommandArgument_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckSetCommandArgument_0100 start"; @@ -602,7 +616,7 @@ AccessibilityAbilityShellCommand_CheckSetCommandArgument_0100, TestSize.Level1) * @tc.name: CheckSetCommandArgument * @tc.desc: Test whether CheckSetCommandArgument is called normally.(unknownArgumentNum > 0) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckSetCommandArgument_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckSetCommandArgument_0200 start"; @@ -626,7 +640,7 @@ AccessibilityAbilityShellCommand_CheckSetCommandArgument_0200, TestSize.Level1) * @tc.name: CheckSetCommandArgument * @tc.desc: Test whether CheckSetCommandArgument is called normally.(setArgumentNum = 0) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckSetCommandArgument_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckSetCommandArgument_0300 start"; @@ -639,7 +653,7 @@ AccessibilityAbilityShellCommand_CheckSetCommandArgument_0300, TestSize.Level1) }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckSetCommandArgument(argument,resultMessage); + ErrCode result = cmd.CheckSetCommandArgument(argument, resultMessage); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); EXPECT_EQ(resultMessage, ": " + ACCESSIBILITY_HELP_MSG_NO_OPTION); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckSetCommandArgument_0300 end"; @@ -650,7 +664,7 @@ AccessibilityAbilityShellCommand_CheckSetCommandArgument_0300, TestSize.Level1) * @tc.name: CheckSetCommandArgument * @tc.desc: Test whether CheckSetCommandArgument is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckSetCommandArgument_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckSetCommandArgument_0400 start"; @@ -663,7 +677,7 @@ AccessibilityAbilityShellCommand_CheckSetCommandArgument_0400, TestSize.Level1) }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckSetCommandArgument(argument,resultMessage); + ErrCode result = cmd.CheckSetCommandArgument(argument, resultMessage); EXPECT_EQ(result, OHOS::ERR_OK); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckSetCommandArgument_0400 end"; } @@ -673,7 +687,7 @@ AccessibilityAbilityShellCommand_CheckSetCommandArgument_0400, TestSize.Level1) * @tc.name: MakeEnableCommandArgumentFromCmd * @tc.desc: Test whether MakeEnableCommandArgumentFromCmd is called normally.(optind < 0) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0100 start"; @@ -694,7 +708,7 @@ AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0100, TestSize * @tc.name: MakeEnableCommandArgumentFromCmd * @tc.desc: Test whether MakeEnableCommandArgumentFromCmd is called normally.(option = -1) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0200 start"; @@ -717,7 +731,7 @@ AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0200, TestSize * @tc.name: MakeEnableCommandArgumentFromCmd * @tc.desc: Test whether MakeEnableCommandArgumentFromCmd is called normally.(option -a requires a value) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0300 start"; @@ -741,7 +755,7 @@ AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0300, TestSize * @tc.name: MakeEnableCommandArgumentFromCmd * @tc.desc: Test whether MakeEnableCommandArgumentFromCmd is called normally.(option -b requires a value) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0400 start"; @@ -767,7 +781,7 @@ AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0400, TestSize * @tc.name: MakeEnableCommandArgumentFromCmd * @tc.desc: Test whether MakeEnableCommandArgumentFromCmd is called normally.(option -c requires a value) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0500, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0500 start"; @@ -796,7 +810,7 @@ AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0500, TestSize * @tc.desc: Test whether MakeEnableCommandArgumentFromCmd is called normally. * (CheckEnableCommandArgument = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0600, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0600 start"; @@ -818,8 +832,8 @@ AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0600, TestSize AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.MakeEnableCommandArgumentFromCmd(argument); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "enable: " + ACCESSIBILITY_ABILITY_TOO_MANY_ARGUMENT - + "and exist unknown arguments.-v "); + EXPECT_EQ(cmd.resultReceiver_, "enable: " + ACCESSIBILITY_ABILITY_TOO_MANY_ARGUMENT + + "and exist unknown arguments.-v "); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0600 end"; } @@ -829,7 +843,7 @@ AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0600, TestSize * @tc.desc: Test whether MakeEnableCommandArgumentFromCmd is called normally. * (CheckEnableCommandArgument = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0700, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0700 start"; @@ -849,8 +863,8 @@ AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0700, TestSize AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.MakeEnableCommandArgumentFromCmd(argument); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "enable: the auxiliary application bundle/ability" - + ACCESSIBILITY_ABILITY_NOT_FOUND); + EXPECT_EQ(cmd.resultReceiver_, "enable: the auxiliary application bundle/ability" + + ACCESSIBILITY_ABILITY_NOT_FOUND); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0700 end"; } @@ -859,15 +873,15 @@ AccessibilityAbilityShellCommand_MakeEnableCommandArgumentFromCmd_0700, TestSize * @tc.name: CheckParamValidity * @tc.desc: Test whether CheckParamValidity is called normally.(return true) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckParamValidity_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckParamValidity_0100 start"; Accessibility::AccessibilityAbilityInitParams params; params.name = "ability"; params.bundleName = "bundle"; - Accessibility::AccessibilityAbilityInfo abilityInfo(params) ; - std::vector installedAbilities ; + Accessibility::AccessibilityAbilityInfo abilityInfo(params); + std::vector installedAbilities; installedAbilities.push_back(abilityInfo); AccessibilityCommandArgument argument; argument.abilityArgumentNum = 1; @@ -890,15 +904,15 @@ AccessibilityAbilityShellCommand_CheckParamValidity_0100, TestSize.Level1) * @tc.name: CheckParamValidity * @tc.desc: Test whether CheckParamValidity is called normally.(isExisted = false) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckParamValidity_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckParamValidity_0200 start"; Accessibility::AccessibilityAbilityInitParams params; params.name = "ability"; params.bundleName = "bundle"; - Accessibility::AccessibilityAbilityInfo abilityInfo(params) ; - std::vector installedAbilities ; + Accessibility::AccessibilityAbilityInfo abilityInfo(params); + std::vector installedAbilities; installedAbilities.push_back(abilityInfo); AccessibilityCommandArgument argument; std::string resultMessage; @@ -909,8 +923,8 @@ AccessibilityAbilityShellCommand_CheckParamValidity_0200, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); bool result = cmd.CheckParamValidity(argument, installedAbilities, resultMessage); EXPECT_EQ(result, false); - EXPECT_EQ(resultMessage, "the auxiliary application " + - argument.bundleName + "/" + argument.abilityName + ACCESSIBILITY_ABILITY_NOT_FOUND); + EXPECT_EQ(resultMessage, "the auxiliary application " + argument.bundleName + "/" + + argument.abilityName + ACCESSIBILITY_ABILITY_NOT_FOUND); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckParamValidity_0200 end"; } @@ -919,7 +933,7 @@ AccessibilityAbilityShellCommand_CheckParamValidity_0200, TestSize.Level1) * @tc.name: CheckParamValidity * @tc.desc: Test whether CheckParamValidity is called normally.(invalidCapabilityNames.empty() = false) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckParamValidity_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckParamValidity_0300 start"; @@ -927,8 +941,8 @@ AccessibilityAbilityShellCommand_CheckParamValidity_0300, TestSize.Level1) params.name = "ability"; params.bundleName = "bundle"; params.staticCapabilities = 1; - Accessibility::AccessibilityAbilityInfo abilityInfo(params) ; - std::vector installedAbilities ; + Accessibility::AccessibilityAbilityInfo abilityInfo(params); + std::vector installedAbilities; installedAbilities.push_back(abilityInfo); AccessibilityCommandArgument argument; argument.abilityArgumentNum = 1; @@ -943,7 +957,7 @@ AccessibilityAbilityShellCommand_CheckParamValidity_0300, TestSize.Level1) }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - bool result = cmd.CheckParamValidity(argument,installedAbilities,resultMessage); + bool result = cmd.CheckParamValidity(argument, installedAbilities, resultMessage); EXPECT_EQ(result, false); EXPECT_EQ(resultMessage, "the capabilities capability" + ACCESSIBILITY_ABILITY_NOT_FOUND); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckParamValidity_0300 end"; @@ -954,7 +968,7 @@ AccessibilityAbilityShellCommand_CheckParamValidity_0300, TestSize.Level1) * @tc.name: CheckEnableCommandArgument * @tc.desc: Test whether CheckEnableCommandArgument is called normally.(totalArgumentNum > 3) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0100 start"; @@ -969,9 +983,9 @@ AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0100, TestSize.Level }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckEnableCommandArgument(argument,resultMessage); + ErrCode result = cmd.CheckEnableCommandArgument(argument, resultMessage); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(resultMessage, ": and exist duplicated arguments and exist unknown arguments."); + EXPECT_EQ(resultMessage, ": and exist duplicated argumentsand exist unknown arguments."); EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_ABILITY_TOO_MANY_ARGUMENT); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0100 end"; } @@ -981,7 +995,7 @@ AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0100, TestSize.Level * @tc.name: CheckEnableCommandArgument * @tc.desc: Test whether CheckEnableCommandArgument is called normally.(unknownArgumentNum > 0) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0200 start"; @@ -993,7 +1007,7 @@ AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0200, TestSize.Level }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckEnableCommandArgument(argument,resultMessage); + ErrCode result = cmd.CheckEnableCommandArgument(argument, resultMessage); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); EXPECT_EQ(resultMessage, ": unknown arguments."); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0200 end"; @@ -1004,7 +1018,7 @@ AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0200, TestSize.Level * @tc.name: CheckEnableCommandArgument * @tc.desc: Test whether CheckEnableCommandArgument is called normally.(CheckAbilityArgument = false) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0300 start"; @@ -1033,7 +1047,7 @@ AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0300, TestSize.Level * @tc.name: CheckEnableCommandArgument * @tc.desc: Test whether CheckEnableCommandArgument is called normally.(CheckBundleArgument = false) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0400 start"; @@ -1062,7 +1076,7 @@ AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0400, TestSize.Level * @tc.name: CheckEnableCommandArgument * @tc.desc: Test whether CheckEnableCommandArgument is called normally.(CheckCapabilitiesArgument = false) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0500, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0500 start"; @@ -1080,7 +1094,7 @@ AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0500, TestSize.Level }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckEnableCommandArgument(argument,resultMessage); + ErrCode result = cmd.CheckEnableCommandArgument(argument, resultMessage); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); EXPECT_EQ(resultMessage, ": " + ACCESSIBILITY_ABILITY_NO_CAPABILITIES_ARGUMENT); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0500 end"; @@ -1091,7 +1105,7 @@ AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0500, TestSize.Level * @tc.name: CheckEnableCommandArgument * @tc.desc: Test whether CheckEnableCommandArgument is called normally.(CheckParamValidity = false) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0600, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0600 start"; @@ -1109,7 +1123,7 @@ AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0600, TestSize.Level }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckEnableCommandArgument(argument,resultMessage); + ErrCode result = cmd.CheckEnableCommandArgument(argument, resultMessage); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); EXPECT_EQ(resultMessage, ": the auxiliary application bundle/ability" + ACCESSIBILITY_ABILITY_NOT_FOUND); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0600 end"; @@ -1121,7 +1135,7 @@ AccessibilityAbilityShellCommand_CheckEnableCommandArgument_0600, TestSize.Level * @tc.desc: Test whether RunAsEnableAbility is called normally. * (MakeEnableCommandArgumentFromCmd = false) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsEnableAbility_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsEnableAbility_0100 start"; @@ -1142,7 +1156,7 @@ AccessibilityAbilityShellCommand_RunAsEnableAbility_0100, TestSize.Level1) * @tc.desc: Test whether RunAsDisableAbility is called normally. * (MakeDisableCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsDisableAbility_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsDisableAbility_0100 start"; @@ -1162,7 +1176,7 @@ AccessibilityAbilityShellCommand_RunAsDisableAbility_0100, TestSize.Level1) * @tc.name: RunAsGetEnabledAbilities * @tc.desc: Test whether RunAsGetEnabledAbilities is called normally.(enabledAbilities is empty) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsGetEnabledAbilities_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsGetEnabledAbilities_0100 start"; @@ -1181,7 +1195,7 @@ AccessibilityAbilityShellCommand_RunAsGetEnabledAbilities_0100, TestSize.Level1) * @tc.name: RunAsGetInstalledAbilities * @tc.desc: Test whether RunAsGetInstalledAbilities is called normally.(installedAbilities is empty) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsGetInstalledAbilities_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsGetInstalledAbilities_0100 start"; @@ -1202,7 +1216,7 @@ AccessibilityAbilityShellCommand_RunAsGetInstalledAbilities_0100, TestSize.Level * @tc.desc: Test whether RunAsSetScreenMagnificationState is called normally. * (MakeSetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0100 start"; @@ -1222,7 +1236,7 @@ AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0100, TestSize * @tc.name: RunAsSetScreenMagnificationState * @tc.desc: Test whether RunAsSetScreenMagnificationState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0200 start"; @@ -1237,7 +1251,7 @@ AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0200, TestSize AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetScreenMagnificationState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_SCREEN_MAGNIFICATION_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_SCREEN_MAGNIFICATION_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0200 end"; } @@ -1246,7 +1260,7 @@ AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0200, TestSize * @tc.name: RunAsSetScreenMagnificationState * @tc.desc: Test whether RunAsSetScreenMagnificationState is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0200 start"; @@ -1262,7 +1276,7 @@ AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0300, TestSize ErrCode result = cmd.RunAsSetScreenMagnificationState(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); EXPECT_EQ(cmd.resultReceiver_, "setScreenMagnificationState: " + ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + - "\n" + ACCESSIBILITY_HELP_MSG_SET_SCREEN_MAGNIFICATION_STATE); + "\n" + ACCESSIBILITY_HELP_MSG_SET_SCREEN_MAGNIFICATION_STATE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0300 end"; } @@ -1271,7 +1285,7 @@ AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0300, TestSize * @tc.name: RunAsSetShortKeyState * @tc.desc: Test whether RunAsSetShortKeyState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0100 start"; @@ -1286,7 +1300,7 @@ AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0100, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetShortKeyState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_SHORT_KEY_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_SHORT_KEY_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0100 end"; } @@ -1295,7 +1309,7 @@ AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0100, TestSize.Level1) * @tc.name: RunAsSetShortKeyState * @tc.desc: Test whether RunAsSetShortKeyState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0200 start"; @@ -1310,7 +1324,7 @@ AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0200, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetShortKeyState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_SHORT_KEY_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_SHORT_KEY_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0200 end"; } @@ -1319,7 +1333,7 @@ AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0200, TestSize.Level1) * @tc.name: RunAsSetShortKeyState * @tc.desc: Test whether RunAsSetShortKeyState is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0300 start"; @@ -1335,7 +1349,7 @@ AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0300, TestSize.Level1) ErrCode result = cmd.RunAsSetShortKeyState(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); EXPECT_EQ(cmd.resultReceiver_, "setShortKeyState: " + ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + - "\n" + ACCESSIBILITY_HELP_MSG_SET_SHORT_KEY_STATE); + "\n" + ACCESSIBILITY_HELP_MSG_SET_SHORT_KEY_STATE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0300 end"; } @@ -1345,7 +1359,7 @@ AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0300, TestSize.Level1) * @tc.desc: Test whether RunAsSetShortKeyState is called normally. * (MakeSetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0400 start"; @@ -1356,7 +1370,7 @@ AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0400, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetShortKeyState(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "\n"+ACCESSIBILITY_HELP_MSG_SET_SHORT_KEY_STATE); + EXPECT_EQ(cmd.resultReceiver_, "\n" + ACCESSIBILITY_HELP_MSG_SET_SHORT_KEY_STATE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0400 end"; } @@ -1365,7 +1379,7 @@ AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0400, TestSize.Level1) * @tc.name: RunAsSetMouseKeyState * @tc.desc: Test whether RunAsSetMouseKeyState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0100 start"; @@ -1380,7 +1394,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0100, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetMouseKeyState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_MOUSE_KEY_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_MOUSE_KEY_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0100 end"; } @@ -1389,7 +1403,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0100, TestSize.Level1) * @tc.name: RunAsSetMouseKeyState * @tc.desc: Test whether RunAsSetMouseKeyState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0200 start"; @@ -1404,7 +1418,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0200, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetMouseKeyState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_MOUSE_KEY_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_MOUSE_KEY_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0200 end"; } @@ -1413,7 +1427,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0200, TestSize.Level1) * @tc.name: RunAsSetMouseKeyState * @tc.desc: Test whether RunAsSetMouseKeyState is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0300 start"; @@ -1429,7 +1443,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0300, TestSize.Level1) ErrCode result = cmd.RunAsSetMouseKeyState(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); EXPECT_EQ(cmd.resultReceiver_, "setMouseKeyState: " + ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + - "\n" + ACCESSIBILITY_HELP_MSG_SET_MOUSE_KEY_STATE); + "\n" + ACCESSIBILITY_HELP_MSG_SET_MOUSE_KEY_STATE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0300 end"; } @@ -1439,7 +1453,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0300, TestSize.Level1) * @tc.desc: Test whether RunAsSetMouseKeyState is called normally. * (MakeSetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0400 start"; @@ -1450,7 +1464,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0400, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetMouseKeyState(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "\n"+ACCESSIBILITY_HELP_MSG_SET_MOUSE_KEY_STATE); + EXPECT_EQ(cmd.resultReceiver_, "\n" + ACCESSIBILITY_HELP_MSG_SET_MOUSE_KEY_STATE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0400 end"; } @@ -1459,7 +1473,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0400, TestSize.Level1) * @tc.name: RunAsSetCaptionState * @tc.desc: Test whether RunAsSetCaptionState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetCaptionState_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetCaptionState_0100 start"; @@ -1474,7 +1488,7 @@ AccessibilityAbilityShellCommand_RunAsSetCaptionState_0100, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetCaptionState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_CAPTION_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_CAPTION_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetCaptionState_0100 end"; } @@ -1483,7 +1497,7 @@ AccessibilityAbilityShellCommand_RunAsSetCaptionState_0100, TestSize.Level1) * @tc.name: RunAsSetCaptionState * @tc.desc: Test whether RunAsSetCaptionState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetCaptionState_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetCaptionState_0200 start"; @@ -1499,7 +1513,7 @@ AccessibilityAbilityShellCommand_RunAsSetCaptionState_0200, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetCaptionState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_CAPTION_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_CAPTION_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetCaptionState_0200 end"; } @@ -1508,7 +1522,7 @@ AccessibilityAbilityShellCommand_RunAsSetCaptionState_0200, TestSize.Level1) * @tc.name: RunAsSetCaptionState * @tc.desc: Test whether RunAsSetCaptionState is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetCaptionState_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetCaptionState_0300 start"; @@ -1524,7 +1538,7 @@ AccessibilityAbilityShellCommand_RunAsSetCaptionState_0300, TestSize.Level1) ErrCode result = cmd.RunAsSetCaptionState(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); EXPECT_EQ(cmd.resultReceiver_, "setCaptionState: " + ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + - "\n" + ACCESSIBILITY_HELP_MSG_SET_CAPTION_STATE); + "\n" + ACCESSIBILITY_HELP_MSG_SET_CAPTION_STATE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetCaptionState_0300 end"; } @@ -1554,7 +1568,7 @@ AccessibilityAbilityShellCommand_RunAsSetCaptionState_0400, TestSize.Level1) * @tc.name: RunAsSetMouseAutoClick * @tc.desc: Test whether RunAsSetMouseAutoClick is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0100 start"; @@ -1569,7 +1583,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0100, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetMouseAutoClick(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUTO_CLICK_TIME_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUTO_CLICK_TIME_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0100 end"; } @@ -1578,7 +1592,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0100, TestSize.Level1) * @tc.name: RunAsSetMouseAutoClick * @tc.desc: Test whether RunAsSetMouseAutoClick is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0200 start"; @@ -1593,7 +1607,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0200, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetMouseAutoClick(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUTO_CLICK_TIME_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUTO_CLICK_TIME_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0200 end"; } @@ -1602,7 +1616,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0200, TestSize.Level1) * @tc.name: RunAsSetMouseAutoClick * @tc.desc: Test whether RunAsSetMouseAutoClick is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0300 start"; @@ -1618,7 +1632,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0300, TestSize.Level1) ErrCode result = cmd.RunAsSetMouseAutoClick(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); EXPECT_EQ(cmd.resultReceiver_, "setMouseAutoClick: " + ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + - "\n" + ACCESSIBILITY_HELP_MSG_SET_AUTO_CLICK_TIME); + "\n" + ACCESSIBILITY_HELP_MSG_SET_AUTO_CLICK_TIME); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0300 end"; } @@ -1628,7 +1642,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0300, TestSize.Level1) * @tc.desc: Test whether RunAsSetMouseAutoClick is called normally. * (MakeSetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0400 start"; @@ -1639,7 +1653,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0400, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetMouseAutoClick(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "\n"+ACCESSIBILITY_HELP_MSG_SET_AUTO_CLICK_TIME); + EXPECT_EQ(cmd.resultReceiver_, "\n" + ACCESSIBILITY_HELP_MSG_SET_AUTO_CLICK_TIME); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0400 end"; } @@ -1649,7 +1663,7 @@ AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0400, TestSize.Level1) * @tc.desc: Test whether RunAsSetShortKeyTarget is called normally. * (MakeSetShortKeyTargetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetShortKeyTarget_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetShortKeyTarget_0100 start"; @@ -1660,7 +1674,7 @@ AccessibilityAbilityShellCommand_RunAsSetShortKeyTarget_0100, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetShortKeyTarget(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "\n"+ACCESSIBILITY_HELP_MSG_SET_SHORT_KEY_TARGET); + EXPECT_EQ(cmd.resultReceiver_, "\n" + ACCESSIBILITY_HELP_MSG_SET_SHORT_KEY_TARGET); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetShortKeyTarget_0100 end"; } @@ -1669,7 +1683,7 @@ AccessibilityAbilityShellCommand_RunAsSetShortKeyTarget_0100, TestSize.Level1) * @tc.name: RunAsSetHighContrastTextState * @tc.desc: Test whether RunAsSetHighContrastTextState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0100 start"; @@ -1684,7 +1698,7 @@ AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0100, TestSize.Le AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetHighContrastTextState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_HIGH_CONTRAST_TEXT_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_HIGH_CONTRAST_TEXT_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0100 end"; } @@ -1693,7 +1707,7 @@ AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0100, TestSize.Le * @tc.name: RunAsSetHighContrastTextState * @tc.desc: Test whether RunAsSetHighContrastTextState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0200 start"; @@ -1708,7 +1722,7 @@ AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0200, TestSize.Le AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetHighContrastTextState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_HIGH_CONTRAST_TEXT_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_HIGH_CONTRAST_TEXT_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0200 end"; } @@ -1717,7 +1731,7 @@ AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0200, TestSize.Le * @tc.name: RunAsSetHighContrastTextState * @tc.desc: Test whether RunAsSetHighContrastTextState is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0300 start"; @@ -1732,8 +1746,8 @@ AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0300, TestSize.Le AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetHighContrastTextState(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "setHighContrastTextState: "+ ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + - "\n" + ACCESSIBILITY_HELP_MSG_HIGH_CONTRAST_TEXT_STATE); + EXPECT_EQ(cmd.resultReceiver_, "setHighContrastTextState: " + ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + + "\n" + ACCESSIBILITY_HELP_MSG_HIGH_CONTRAST_TEXT_STATE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0300 end"; } @@ -1743,7 +1757,7 @@ AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0300, TestSize.Le * @tc.desc: Test whether RunAsSetHighContrastTextState is called normally. * (MakeSetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0400 start"; @@ -1763,7 +1777,7 @@ AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0400, TestSize.Le * @tc.name: RunAsSetInvertColorState * @tc.desc: Test whether RunAsSetInvertColorState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0100 start"; @@ -1778,7 +1792,7 @@ AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0100, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetInvertColorState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_INVERT_COLOR_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_INVERT_COLOR_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0100 end"; } @@ -1787,7 +1801,7 @@ AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0100, TestSize.Level1) * @tc.name: RunAsSetInvertColorState * @tc.desc: Test whether RunAsSetInvertColorState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0200 start"; @@ -1802,7 +1816,7 @@ AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0200, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetInvertColorState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_INVERT_COLOR_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_INVERT_COLOR_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0200 end"; } @@ -1811,7 +1825,7 @@ AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0200, TestSize.Level1) * @tc.name: RunAsSetInvertColorState * @tc.desc: Test whether RunAsSetInvertColorState is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0300 start"; @@ -1827,7 +1841,7 @@ AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0300, TestSize.Level1) ErrCode result = cmd.RunAsSetInvertColorState(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); EXPECT_EQ(cmd.resultReceiver_, "setInvertColorState: "+ ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + - "\n" + ACCESSIBILITY_HELP_MSG_SET_INVERT_COLOR_STATE); + "\n" + ACCESSIBILITY_HELP_MSG_SET_INVERT_COLOR_STATE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0300 end"; } @@ -1837,7 +1851,7 @@ AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0300, TestSize.Level1) * @tc.desc: Test whether RunAsSetInvertColorState is called normally. * (MakeSetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0400 start"; @@ -1848,7 +1862,7 @@ AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0400, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetInvertColorState(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "\n"+ACCESSIBILITY_HELP_MSG_SET_INVERT_COLOR_STATE); + EXPECT_EQ(cmd.resultReceiver_, "\n" + ACCESSIBILITY_HELP_MSG_SET_INVERT_COLOR_STATE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0400 end"; } @@ -1857,7 +1871,7 @@ AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0400, TestSize.Level1) * @tc.name: RunAsSetDaltonizationColorFilter * @tc.desc: Test whether RunAsSetDaltonizationColorFilter is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0100 start"; @@ -1872,7 +1886,7 @@ AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0100, TestSize AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetDaltonizationColorFilter(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0100 end"; } @@ -1881,7 +1895,7 @@ AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0100, TestSize * @tc.name: RunAsSetDaltonizationColorFilter * @tc.desc: Test whether RunAsSetDaltonizationColorFilter is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0200 start"; @@ -1896,7 +1910,7 @@ AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0200, TestSize AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetDaltonizationColorFilter(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0200 end"; } @@ -1905,7 +1919,7 @@ AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0200, TestSize * @tc.name: RunAsSetDaltonizationColorFilter * @tc.desc: Test whether RunAsSetDaltonizationColorFilter is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0300 start"; @@ -1920,7 +1934,7 @@ AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0300, TestSize AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetDaltonizationColorFilter(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0300 end"; } @@ -1929,7 +1943,7 @@ AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0300, TestSize * @tc.name: RunAsSetDaltonizationColorFilter * @tc.desc: Test whether RunAsSetDaltonizationColorFilter is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0400 start"; @@ -1944,7 +1958,7 @@ AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0400, TestSize AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetDaltonizationColorFilter(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0400 end"; } @@ -1953,7 +1967,7 @@ AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0400, TestSize * @tc.name: RunAsSetDaltonizationColorFilter * @tc.desc: Test whether RunAsSetDaltonizationColorFilter is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0500, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0500 start"; @@ -1968,7 +1982,7 @@ AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0500, TestSize AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetDaltonizationColorFilter(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "setDaltonizationColorFilter: "+ ACCESSIBILITY_ABILITY_SET_VALUE_INVALID); + EXPECT_EQ(cmd.resultReceiver_, "setDaltonizationColorFilter: " + ACCESSIBILITY_ABILITY_SET_VALUE_INVALID); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0500 end"; } @@ -1978,7 +1992,7 @@ AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0500, TestSize * @tc.desc: Test whether RunAsSetDaltonizationColorFilter is called normally. * (MakeSetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0600, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0600 start"; @@ -1989,7 +2003,7 @@ AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0600, TestSize AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetDaltonizationColorFilter(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "\n"+ACCESSIBILITY_HELP_MSG_SET_DALTONIZATION_COLOR_FILTER); + EXPECT_EQ(cmd.resultReceiver_, "\n" + ACCESSIBILITY_HELP_MSG_SET_DALTONIZATION_COLOR_FILTER); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0600 end"; } @@ -1998,7 +2012,7 @@ AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0600, TestSize * @tc.name: RunAsSetContentTimeout * @tc.desc: Test whether RunAsSetContentTimeout is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0100 start"; @@ -2013,7 +2027,7 @@ AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0100, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetContentTimeout(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_CONTENT_TIME_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_CONTENT_TIME_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0100 end"; } @@ -2022,7 +2036,7 @@ AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0100, TestSize.Level1) * @tc.name: RunAsSetContentTimeout * @tc.desc: Test whether RunAsSetContentTimeout is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0200 start"; @@ -2038,7 +2052,7 @@ AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0200, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetContentTimeout(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_CONTENT_TIME_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_CONTENT_TIME_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0200 end"; } @@ -2047,7 +2061,7 @@ AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0200, TestSize.Level1) * @tc.name: RunAsSetContentTimeout * @tc.desc: Test whether RunAsSetContentTimeout is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0300 start"; @@ -2062,8 +2076,8 @@ AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0300, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetContentTimeout(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "setContentTimeout: "+ ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + - "\n" + ACCESSIBILITY_HELP_MSG_SET_CONTENT_TIME_OUT); + EXPECT_EQ(cmd.resultReceiver_, "setContentTimeout: " + ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + + "\n" + ACCESSIBILITY_HELP_MSG_SET_CONTENT_TIME_OUT); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0300 end"; } @@ -2073,7 +2087,7 @@ AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0300, TestSize.Level1) * @tc.desc: Test whether RunAsSetContentTimeout is called normally. * (MakeSetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0400 start"; @@ -2093,7 +2107,7 @@ AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0400, TestSize.Level1) * @tc.name: RunAsSetAnimationOffState * @tc.desc: Test whether RunAsSetAnimationOffState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0100 start"; @@ -2108,7 +2122,7 @@ AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0100, TestSize.Level1 AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetAnimationOffState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_ANIMATION_OFF_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_ANIMATION_OFF_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0100 end"; } @@ -2117,7 +2131,7 @@ AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0100, TestSize.Level1 * @tc.name: RunAsSetAnimationOffState * @tc.desc: Test whether RunAsSetAnimationOffState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0200 start"; @@ -2132,7 +2146,7 @@ AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0200, TestSize.Level1 AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetAnimationOffState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_ANIMATION_OFF_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_ANIMATION_OFF_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0200 end"; } @@ -2141,7 +2155,7 @@ AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0200, TestSize.Level1 * @tc.name: RunAsSetAnimationOffState * @tc.desc: Test whether RunAsSetAnimationOffState is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0300 start"; @@ -2156,8 +2170,8 @@ AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0300, TestSize.Level1 AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetAnimationOffState(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "setAnimationOffState: "+ ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + - "\n" + ACCESSIBILITY_HELP_MSG_ANIMATION_OFF_STATE); + EXPECT_EQ(cmd.resultReceiver_, "setAnimationOffState: " + ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + + "\n" + ACCESSIBILITY_HELP_MSG_ANIMATION_OFF_STATE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0300 end"; } @@ -2167,7 +2181,7 @@ AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0300, TestSize.Level1 * @tc.desc: Test whether RunAsSetAnimationOffState is called normally. * (MakeSetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0400 start"; @@ -2188,7 +2202,7 @@ AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0400, TestSize.Level1 * @tc.desc: 1.Test whether RunAsSetBrightnessDiscount is called normally.(OHOS::ERR_OK) * 2.ret is not Accessibility::RET_OK */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0100 start"; @@ -2215,7 +2229,7 @@ AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0100, TestSize.Level * @tc.desc: 1.Test whether RunAsSetBrightnessDiscount is called normally.(OHOS::ERR_OK) * 2.ret is Accessibility::RET_OK */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0200 start"; @@ -2240,7 +2254,7 @@ AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0200, TestSize.Level * @tc.name: RunAsSetBrightnessDiscount * @tc.desc: Test whether RunAsSetBrightnessDiscount is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0300 start"; @@ -2255,8 +2269,8 @@ AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0300, TestSize.Level AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetBrightnessDiscount(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "setSetBrightnessDiscount: "+ ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + - "\n" + ACCESSIBILITY_HELP_MSG_SET_BRIGHTNESS_DISCOUNT); + EXPECT_EQ(cmd.resultReceiver_, "setSetBrightnessDiscount: " + ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + + "\n" + ACCESSIBILITY_HELP_MSG_SET_BRIGHTNESS_DISCOUNT); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0300 end"; } @@ -2266,7 +2280,7 @@ AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0300, TestSize.Level * @tc.desc: Test whether RunAsSetBrightnessDiscount is called normally. * (MakeSetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0400 start"; @@ -2286,7 +2300,7 @@ AccessibilityAbilityShellCommand_RunAsSetBrightnessDiscount_0400, TestSize.Level * @tc.name: RunAsSetAudioMonoState * @tc.desc: Test whether RunAsSetAudioMonoState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0100 start"; @@ -2301,7 +2315,7 @@ AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0100, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetAudioMonoState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUDIO_MONO_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUDIO_MONO_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0100 end"; } @@ -2310,7 +2324,7 @@ AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0100, TestSize.Level1) * @tc.name: RunAsSetAudioMonoState * @tc.desc: Test whether RunAsSetAudioMonoState is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0200 start"; @@ -2325,7 +2339,7 @@ AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0200, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetAudioMonoState(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUDIO_MONO_STATE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUDIO_MONO_STATE_NG + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0200 end"; } @@ -2334,7 +2348,7 @@ AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0200, TestSize.Level1) * @tc.name: RunAsSetAudioMonoState * @tc.desc: Test whether RunAsSetAudioMonoState is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0300 start"; @@ -2349,8 +2363,8 @@ AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0300, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetAudioMonoState(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "setAudioMonoState: "+ ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + - "\n" + ACCESSIBILITY_HELP_MSG_SET_AUDIO_MONO_STATE); + EXPECT_EQ(cmd.resultReceiver_, "setAudioMonoState: " + ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + + "\n" + ACCESSIBILITY_HELP_MSG_SET_AUDIO_MONO_STATE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0300 end"; } @@ -2360,7 +2374,7 @@ AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0300, TestSize.Level1) * @tc.desc: Test whether RunAsSetAudioMonoState is called normally. * (MakeSetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0400 start"; @@ -2380,7 +2394,7 @@ AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0400, TestSize.Level1) * @tc.name: RunAsSetAudioBalance * @tc.desc: Test whether RunAsSetAudioBalance is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0100 start"; @@ -2395,7 +2409,7 @@ AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0100, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetAudioBalance(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUDIO_BALANCE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUDIO_BALANCE_NG); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0100 end"; } @@ -2404,7 +2418,7 @@ AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0100, TestSize.Level1) * @tc.name: RunAsSetAudioBalance * @tc.desc: Test whether RunAsSetAudioBalance is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0200 start"; @@ -2419,7 +2433,7 @@ AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0200, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetAudioBalance(); EXPECT_EQ(result, OHOS::ERR_OK); - EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUDIO_BALANCE_OK + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUDIO_BALANCE_NG); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0200 end"; } @@ -2428,7 +2442,7 @@ AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0200, TestSize.Level1) * @tc.name: RunAsSetAudioBalance * @tc.desc: Test whether RunAsSetAudioBalance is called normally.(value is invalid) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0300 start"; @@ -2443,8 +2457,8 @@ AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0300, TestSize.Level1) AccessibilityAbilityShellCommand cmd(argc, argv); ErrCode result = cmd.RunAsSetAudioBalance(); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(cmd.resultReceiver_, "setAudioBalance: "+ ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + - "\n" + ACCESSIBILITY_HELP_MSG_SET_AUDIO_BALANCE); + EXPECT_EQ(cmd.resultReceiver_, "setAudioBalance: " + ACCESSIBILITY_ABILITY_SET_VALUE_INVALID + + "\n" + ACCESSIBILITY_HELP_MSG_SET_AUDIO_BALANCE); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0300 end"; } @@ -2454,7 +2468,7 @@ AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0300, TestSize.Level1) * @tc.desc: Test whether RunAsSetAudioBalance is called normally. * (MakeSetCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0400 start"; @@ -2475,7 +2489,7 @@ AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0400, TestSize.Level1) * @tc.desc: Test whether MakeSetShortKeyTargetCommandArgumentFromCmd is called normally. * (MakeCommandArgumentFromCmd = OHOS::ERR_OK,MakeCommandArgumentFromCmd = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeSetShortKeyTargetCommandArgumentFromCmd_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeSetShortKeyTargetCommandArgumentFromCmd_0100 start"; @@ -2504,7 +2518,7 @@ AccessibilityAbilityShellCommand_MakeSetShortKeyTargetCommandArgumentFromCmd_010 * @tc.name: MakeSetCommandArgumentFromCmd * @tc.desc: Test whether MakeSetCommandArgumentFromCmd is called normally.(OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0100 start"; @@ -2530,7 +2544,7 @@ AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0100, TestSize.Le * @tc.name: MakeSetCommandArgumentFromCmd * @tc.desc: Test whether MakeSetCommandArgumentFromCmd is called normally.(optind < 0) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0200 start"; @@ -2551,7 +2565,7 @@ AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0200, TestSize.Le * @tc.name: MakeSetCommandArgumentFromCmd * @tc.desc: Test whether MakeSetCommandArgumentFromCmd is called normally.(option = -1) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0300 start"; @@ -2573,7 +2587,7 @@ AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0300, TestSize.Le * @tc.name: MakeSetCommandArgumentFromCmd * @tc.desc: Test whether MakeSetCommandArgumentFromCmd is called normally.(option = ?) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0400 start"; @@ -2597,7 +2611,7 @@ AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0400, TestSize.Le * @tc.name: MakeSetCommandArgumentFromCmd * @tc.desc: Test whether MakeSetCommandArgumentFromCmd is called normally.(option = default) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0500, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0500 start"; @@ -2621,7 +2635,7 @@ AccessibilityAbilityShellCommand_MakeSetCommandArgumentFromCmd_0500, TestSize.Le * @tc.name: MakeCommandArgumentFromCmd * @tc.desc: Test whether MakeCommandArgumentFromCmd is called normally.(return OHOS::ERR_OK) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0100 start"; @@ -2648,7 +2662,7 @@ AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0100, TestSize.Level * @tc.name: MakeCommandArgumentFromCmd * @tc.desc: Test whether MakeCommandArgumentFromCmd is called normally.(return OHOS::ERR_OK,option a b) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0200 start"; @@ -2676,7 +2690,7 @@ AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0200, TestSize.Level * @tc.name: MakeCommandArgumentFromCmd * @tc.desc: Test whether MakeCommandArgumentFromCmd is called normally.(missing options) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0300 start"; @@ -2699,7 +2713,7 @@ AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0300, TestSize.Level * @tc.name: MakeCommandArgumentFromCmd * @tc.desc: Test whether MakeCommandArgumentFromCmd is called normally.(NO_ABILITY) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0400 start"; @@ -2723,7 +2737,7 @@ AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0400, TestSize.Level * @tc.name: MakeCommandArgumentFromCmd * @tc.desc: Test whether MakeCommandArgumentFromCmd is called normally.(NO_BUNDLE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0500, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0500 start"; @@ -2749,7 +2763,7 @@ AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0500, TestSize.Level * @tc.name: MakeCommandArgumentFromCmd * @tc.desc: Test whether MakeCommandArgumentFromCmd is called normally.(optind = -1) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0600, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0600 start"; @@ -2771,7 +2785,7 @@ AccessibilityAbilityShellCommand_MakeCommandArgumentFromCmd_0600, TestSize.Level * @tc.desc: Test whether MakeDisableCommandArgumentFromCmd is called normally. * (MakeCommandArgumentFromCmd = OHOS::ERR_OK,CheckDisableCommandArgument = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_MakeDisableCommandArgumentFromCmd_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_MakeDisableCommandArgumentFromCmd_0100 start"; @@ -2804,7 +2818,7 @@ AccessibilityAbilityShellCommand_MakeDisableCommandArgumentFromCmd_0100, TestSiz * @tc.desc: Test whether CheckDisableCommandArgument is called normally. * (CheckCommandArgument = OHOS::ERR_INVALID_VALUE) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckDisableCommandArgument_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckDisableCommandArgument_0100 start"; @@ -2832,7 +2846,7 @@ AccessibilityAbilityShellCommand_CheckDisableCommandArgument_0100, TestSize.Leve * @tc.name: CheckCommandArgument * @tc.desc: Test whether CheckCommandArgument is called normally.(totalArgumentNum > 2) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckCommandArgument_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCommandArgument_0100 start"; @@ -2861,7 +2875,7 @@ AccessibilityAbilityShellCommand_CheckCommandArgument_0100, TestSize.Level1) * @tc.name: CheckCommandArgument * @tc.desc: Test whether CheckCommandArgument is called normally.(unknownArgumentNum > 0) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckCommandArgument_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCommandArgument_0200 start"; @@ -2889,7 +2903,7 @@ AccessibilityAbilityShellCommand_CheckCommandArgument_0200, TestSize.Level1) * @tc.name: CheckCommandArgument * @tc.desc: Test whether CheckCommandArgument is called normally.(CheckAbilityArgument = false) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckCommandArgument_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCommandArgument_0300 start"; @@ -2906,7 +2920,7 @@ AccessibilityAbilityShellCommand_CheckCommandArgument_0300, TestSize.Level1) }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckCommandArgument(argument,resultMessage); + ErrCode result = cmd.CheckCommandArgument(argument, resultMessage); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); EXPECT_EQ(resultMessage, ": " + ACCESSIBILITY_ABILITY_NO_ABILITY_ARGUMENT); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCommandArgument_0300 end"; @@ -2917,7 +2931,7 @@ AccessibilityAbilityShellCommand_CheckCommandArgument_0300, TestSize.Level1) * @tc.name: CheckCommandArgument * @tc.desc: Test whether CheckCommandArgument is called normally.(CheckBundleArgument = false) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckCommandArgument_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCommandArgument_0400 start"; @@ -2934,7 +2948,7 @@ AccessibilityAbilityShellCommand_CheckCommandArgument_0400, TestSize.Level1) }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckCommandArgument(argument,resultMessage); + ErrCode result = cmd.CheckCommandArgument(argument, resultMessage); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); EXPECT_EQ(resultMessage, ": " + ACCESSIBILITY_ABILITY_NO_BUNDLE_ARGUMENT); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCommandArgument_0400 end"; @@ -2945,7 +2959,7 @@ AccessibilityAbilityShellCommand_CheckCommandArgument_0400, TestSize.Level1) * @tc.name: CheckCommandArgument * @tc.desc: Test whether CheckCommandArgument is called normally.(CheckParamValidity = false) */ -HWTEST_F(AccessibilityAbilityShellCommandTest, +HWTEST_F(AccessibilityAbilityShellCommandTest, AccessibilityAbilityShellCommand_CheckCommandArgument_0500, TestSize.Level1) { GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCommandArgument_0500 start"; @@ -2962,10 +2976,10 @@ AccessibilityAbilityShellCommand_CheckCommandArgument_0500, TestSize.Level1) }; int argc = sizeof(argv) / sizeof(argv[0]) - 1; AccessibilityAbilityShellCommand cmd(argc, argv); - ErrCode result = cmd.CheckCommandArgument(argument,resultMessage); + ErrCode result = cmd.CheckCommandArgument(argument, resultMessage); EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE); - EXPECT_EQ(resultMessage, ": the auxiliary application " + - argument.bundleName + "/" + argument.abilityName + ACCESSIBILITY_ABILITY_NOT_FOUND); + EXPECT_EQ(resultMessage, ": the auxiliary application " + argument.bundleName + "/" + + argument.abilityName + ACCESSIBILITY_ABILITY_NOT_FOUND); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_CheckCommandArgument_0500 end"; } } // namespace AAFwk diff --git a/tools/test/unittest/ability_tool/BUILD.gn b/tools/test/unittest/ability_tool/BUILD.gn index c37d7e4e1b..f4e87fd465 100644 --- a/tools/test/unittest/ability_tool/BUILD.gn +++ b/tools/test/unittest/ability_tool/BUILD.gn @@ -41,6 +41,7 @@ ohos_unittest("ability_tool_test") { deps = [ "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] diff --git a/utils/global/constant/global_constant.h b/utils/global/constant/global_constant.h new file mode 100644 index 0000000000..7ef355315b --- /dev/null +++ b/utils/global/constant/global_constant.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_GLOBAL_CONSTANT_H +#define OHOS_ABILITY_RUNTIME_GLOBAL_CONSTANT_H + +namespace OHOS::AbilityRuntime { +namespace GlobalConstant { +constexpr int32_t MAX_APP_CLONE_INDEX = 1000; +} // namespace GlobalConstant +} // namespace OHOS::AbilityRuntime +#endif // OHOS_ABILITY_RUNTIME_GLOBAL_CONSTANT_H \ No newline at end of file diff --git a/utils/server/constant/server_constant.h b/utils/server/constant/server_constant.h new file mode 100644 index 0000000000..7145c5e70c --- /dev/null +++ b/utils/server/constant/server_constant.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_SERVER_CONSTANT_H +#define OHOS_ABILITY_RUNTIME_SERVER_CONSTANT_H + +namespace OHOS::AbilityRuntime { +namespace ServerConstant { +constexpr const char* APP_CLONE_INDEX = "ohos.extra.param.key.appCloneIndex"; +constexpr const char* DLP_INDEX = "ohos.dlp.params.index"; +} // namespace ServerConstant +} // namespace OHOS::AbilityRuntime +#endif // OHOS_ABILITY_RUNTIME_SERVER_CONSTANT_H \ No newline at end of file diff --git a/utils/server/startup/BUILD.gn b/utils/server/startup/BUILD.gn new file mode 100644 index 0000000000..2ea9b68240 --- /dev/null +++ b/utils/server/startup/BUILD.gn @@ -0,0 +1,53 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +config("startup_util_config") { + include_dirs = [ "include" ] +} + +ohos_shared_library("startup_util") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" + + include_dirs = [ "${ability_runtime_utils_path}/server/constant" ] + + sources = [ "src/startup_util.cpp" ] + + public_configs = [ ":startup_util_config" ] + + defines = [ "AMS_LOG_TAG = \"StartupUtil\"" ] + defines += [ "AMS_LOG_DOMAIN = 0xD001306" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + external_deps = [ + "ability_base:want", + "bundle_framework:appexecfwk_base", + ] + + innerapi_tags = [ "platformsdk" ] + subsystem_name = "ability" + part_name = "ability_runtime" +} diff --git a/utils/server/startup/include/startup_util.h b/utils/server/startup/include/startup_util.h new file mode 100644 index 0000000000..11eb21ed33 --- /dev/null +++ b/utils/server/startup/include/startup_util.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024 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 OHOS_ABILITY_RUNTIME_STARTUP_UTIL_H +#define OHOS_ABILITY_RUNTIME_STARTUP_UTIL_H + +#include + +namespace OHOS { +namespace AAFwk { +class Want; +} // namespace AAFwk +namespace AbilityRuntime { +class StartupUtil { +public: + static int32_t GetAppIndex(const AAFwk::Want &want); + static int32_t BuildAbilityInfoFlag(); +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_STARTUP_UTIL_H \ No newline at end of file diff --git a/utils/server/startup/src/startup_util.cpp b/utils/server/startup/src/startup_util.cpp new file mode 100644 index 0000000000..f9755629d9 --- /dev/null +++ b/utils/server/startup/src/startup_util.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 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 "startup_util.h" + +#include "ability_info.h" +#include "server_constant.h" +#include "want.h" + +namespace OHOS::AbilityRuntime { +int32_t StartupUtil::GetAppIndex(const AAFwk::Want &want) +{ + int32_t appIndex = want.GetIntParam(ServerConstant::APP_CLONE_INDEX, 0); + if (appIndex == 0) { + appIndex = want.GetIntParam(ServerConstant::DLP_INDEX, 0); + } + return appIndex; +} + +int32_t StartupUtil::BuildAbilityInfoFlag() +{ + return AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION | + AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION | + AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA; +} +} // namespace OHOS::AbilityRuntime