diff --git a/ability_runtime.gni b/ability_runtime.gni index 87e2c1d0ae..4858303cf6 100644 --- a/ability_runtime.gni +++ b/ability_runtime.gni @@ -93,6 +93,7 @@ declare_args() { background_task_mgr_continuous_task_enable = true resource_schedule_service_enable = true ability_runtime_power = true + ability_runtime_feature_sandboxmanager = true ability_runtime_relational = true ability_runtime_ces = true ability_runtime_resource = true @@ -106,6 +107,7 @@ declare_args() { "com.ohos.textautofill/entry/TextAutoFillAbility" cj_frontend = true ability_runtime_app_no_response_dialog = false + include_app_domain_verify = true if (!defined(global_parts_info) || defined(global_parts_info.account_os_account)) { @@ -170,6 +172,11 @@ declare_args() { hichecker_enabled = false } + if (defined(global_parts_info) && + !defined(global_parts_info.bundlemanager_app_domain_verify)) { + include_app_domain_verify = false + } + if (!defined(global_parts_info) || defined(global_parts_info.ability_form_fwk)) { form_fwk_enable = true diff --git a/bundle.json b/bundle.json index da4a0f7565..684d70d648 100644 --- a/bundle.json +++ b/bundle.json @@ -19,7 +19,8 @@ "SystemCapability.Ability.AbilityRuntime.Mission", "SystemCapability.Ability.AbilityRuntime.QuickFix", "SystemCapability.Ability.AbilityTools.AbilityAssistant", - "SystemCapability.Ability.AppStartup" + "SystemCapability.Ability.AppStartup", + "SystemCapability.Ability.AppExtension.PhotoEditorExtension" ], "features": [ "ability_runtime_auto_fill_ability", @@ -41,6 +42,8 @@ "accessibility", "access_token", "ace_engine", + "app_domain_verify", + "app_file_service", "appspawn", "background_task_mgr", "bundle_framework", @@ -84,6 +87,7 @@ "resource_management", "resource_schedule_service", "safwk", + "sandbox_manager", "samgr", "screenlock_mgr", "storage_service", @@ -457,14 +461,6 @@ ] }, "name": "//foundation/ability/ability_runtime/frameworks/native/ability/native:dialog_request_callback" - }, - { - "header": { - "header_base": "//foundation/ability/ability_runtime/interfaces/inner_api/ability_manager/include", - "header_files": [ - ] - }, - "name": "//foundation/ability/ability_runtime/interfaces/inner_api/ability_manager:ability_manager_base" } ], "test": [ @@ -475,6 +471,7 @@ "//foundation/ability/ability_runtime/tools/test:moduletest", "//foundation/ability/ability_runtime/tools/test:systemtest", "//foundation/ability/ability_runtime/tools/test:unittest", + "//foundation/ability/ability_runtime/cj_environment/test/unittest:unittest", "//foundation/ability/ability_runtime/js_environment/test/unittest:unittest", "//foundation/ability/ability_runtime/service_router_framework:test_target" ] diff --git a/cj_environment/frameworks/cj_environment/src/cj_environment.cpp b/cj_environment/frameworks/cj_environment/src/cj_environment.cpp index 434b456286..d2c79a56a7 100644 --- a/cj_environment/frameworks/cj_environment/src/cj_environment.cpp +++ b/cj_environment/frameworks/cj_environment/src/cj_environment.cpp @@ -15,7 +15,6 @@ #include "cj_environment.h" -#include #include #include "cj_hilog.h" @@ -177,7 +176,16 @@ bool CJEnvironment::LoadRuntimeApis() #ifdef __OHOS__ Dl_namespace ns; dlns_get(CJEnvironment::cjSDKNSName, &ns); - auto dso = DynamicLoadLibrary(&ns, RTLIB_NAME, 1); + std::string runtimeLibName = "libcangjie-runtime"; + if (sanitizerKind_ == SanitizerKind::ASAN) { + runtimeLibName += "_asan"; + } else if (sanitizerKind_ == SanitizerKind::TSAN) { + runtimeLibName += "_tsan"; + } else if (sanitizerKind_ == SanitizerKind::HWASAN) { + runtimeLibName += "_hwasan"; + } + runtimeLibName += ".so"; + auto dso = DynamicLoadLibrary(&ns, runtimeLibName.c_str(), 1); #else auto dso = DynamicLoadLibrary(RTLIB_NAME, 1); #endif @@ -467,10 +475,49 @@ bool CJEnvironment::StartDebugger() return true; } -bool IsCJAbility(const std::string& info) +CJ_EXPORT extern "C" CJEnvMethods* OHOS_GetCJEnvInstance() { - // in cj application, the srcEntry format should be packageName.AbilityClassName. - std::string pattern = "^([a-zA-Z0-9_]+\\.)+[a-zA-Z0-9_]+$"; - return std::regex_match(info, std::regex(pattern)); + static CJEnvMethods gCJEnvMethods { + .initCJAppNS = [](const std::string& path) { + CJEnvironment::GetInstance()->InitCJAppNS(path); + }, + .initCJSDKNS = [](const std::string& path) { + CJEnvironment::GetInstance()->InitCJSDKNS(path); + }, + .initCJSysNS = [](const std::string& path) { + CJEnvironment::GetInstance()->InitCJSysNS(path); + }, + .initCJChipSDKNS = [](const std::string& path) { + CJEnvironment::GetInstance()->InitCJChipSDKNS(path); + }, + .startRuntime = [] { + return CJEnvironment::GetInstance()->StartRuntime(); + }, + .startUIScheduler = [] { + return CJEnvironment::GetInstance()->StartUIScheduler(); + }, + .loadCJModule = [](const char* dllName) { + return CJEnvironment::GetInstance()->LoadCJLibrary(dllName); + }, + .loadLibrary = [](uint32_t kind, const char* dllName) { + return CJEnvironment::GetInstance()->LoadCJLibrary(static_cast(kind), dllName); + }, + .getSymbol = [](void* handle, const char* dllName) { + return CJEnvironment::GetInstance()->GetSymbol(handle, dllName); + }, + .loadCJLibrary = [](const char* dllName) { + return CJEnvironment::GetInstance()->LoadCJLibrary(dllName); + }, + .startDebugger = []() { + return CJEnvironment::GetInstance()->StartDebugger(); + }, + .registerCJUncaughtExceptionHandler = [](const CJUncaughtExceptionInfo& handle) { + return CJEnvironment::GetInstance()->RegisterCJUncaughtExceptionHandler(handle); + }, + .setSanitizerKindRuntimeVersion = [](SanitizerKind kind) { + return CJEnvironment::GetInstance()->SetSanitizerKindRuntimeVersion(kind); + } + }; + return &gCJEnvMethods; } } diff --git a/cj_environment/interfaces/inner_api/cj_environment.h b/cj_environment/interfaces/inner_api/cj_environment.h index 2df6085c0e..9ba9163634 100644 --- a/cj_environment/interfaces/inner_api/cj_environment.h +++ b/cj_environment/interfaces/inner_api/cj_environment.h @@ -16,6 +16,9 @@ #ifndef OHOS_ABILITY_RUNTIME_CJ_ENVIRONMENT_H #define OHOS_ABILITY_RUNTIME_CJ_ENVIRONMENT_H +#include "cj_envsetup.h" + +#include #include #ifdef WINDOWS_PLATFORM @@ -27,17 +30,6 @@ 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 { @@ -48,6 +40,11 @@ public: { return isRuntimeStarted_; } + + void SetSanitizerKindRuntimeVersion(SanitizerKind kind) + { + sanitizerKind_ = kind; + } void InitCJAppNS(const std::string& path); void InitCJSDKNS(const std::string& path); void InitCJSysNS(const std::string& path); @@ -91,9 +88,9 @@ private: bool isRuntimeStarted_{false}; bool isUISchedulerStarted_{false}; void* uiScheduler_ {nullptr}; + SanitizerKind sanitizerKind_ {SanitizerKind::NONE}; }; -CJ_EXPORT bool IsCJAbility(const std::string& info); } #endif //OHOS_ABILITY_RUNTIME_CJ_ENVIRONMENT_H diff --git a/cj_environment/interfaces/inner_api/cj_envsetup.h b/cj_environment/interfaces/inner_api/cj_envsetup.h new file mode 100644 index 0000000000..ae425359c7 --- /dev/null +++ b/cj_environment/interfaces/inner_api/cj_envsetup.h @@ -0,0 +1,63 @@ +/* +* 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_ENVSETUP_H +#define OHOS_ABILITY_RUNTIME_CJ_ENVSETUP_H + +#include + +namespace OHOS { +struct CJErrorObject { + const char* name; + const char* message; + const char* stack; +}; + +struct CJUncaughtExceptionInfo { + const char* hapPath; + std::function uncaughtTask; +}; + +enum SanitizerKind { + NONE, + ASAN, + TSAN, + HWASAN, +}; + +struct CJEnvMethods { + void (*initCJAppNS)(const std::string& path) = nullptr; + void (*initCJSDKNS)(const std::string& path) = nullptr; + void (*initCJSysNS)(const std::string& path) = nullptr; + void (*initCJChipSDKNS)(const std::string& path) = nullptr; + bool (*startRuntime)() = nullptr; + bool (*startUIScheduler)() = nullptr; + void* (*loadCJModule)(const char* dllName) = nullptr; + void* (*loadLibrary)(uint32_t kind, const char* dllName) = nullptr; + void* (*getSymbol)(void* handle, const char* symbol) = nullptr; + void* (*loadCJLibrary)(const char* dllName) = nullptr; + bool (*startDebugger)() = nullptr; + void (*registerCJUncaughtExceptionHandler)(const CJUncaughtExceptionInfo& uncaughtExceptionInfo) = nullptr; + void (*setSanitizerKindRuntimeVersion)(SanitizerKind kind) = nullptr; +}; + +class CJEnv { +public: + static CJEnvMethods* LoadInstance(); +}; + +} + +#endif // OHOS_ABILITY_RUNTIME_CJ_ENVSETUP_H diff --git a/cj_environment/test/unittest/BUILD.gn b/cj_environment/test/unittest/BUILD.gn new file mode 100644 index 0000000000..0cd400b514 --- /dev/null +++ b/cj_environment/test/unittest/BUILD.gn @@ -0,0 +1,21 @@ +# 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("../../cj_environment.gni") + +group("unittest") { + testonly = true + + deps = [ "cj_environment_test:unittest" ] +} diff --git a/cj_environment/test/unittest/cj_environment_test/BUILD.gn b/cj_environment/test/unittest/cj_environment_test/BUILD.gn new file mode 100644 index 0000000000..f4b4aac4a7 --- /dev/null +++ b/cj_environment/test/unittest/cj_environment_test/BUILD.gn @@ -0,0 +1,39 @@ +# 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") + +module_output_path = "ability_runtime/cj_environment" + +ohos_unittest("cj_environment_test") { + module_out_path = module_output_path + sources = [ "cj_environment_test.cpp" ] + sources += [ "cj_invoker.h" ] + + deps = [ + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_runtime:cj_environment", + "hilog:libhilog", + ] +} + +group("unittest") { + testonly = true + deps = [] + + deps += [ ":cj_environment_test" ] +} diff --git a/cj_environment/test/unittest/cj_environment_test/cj_environment_test.cpp b/cj_environment/test/unittest/cj_environment_test/cj_environment_test.cpp new file mode 100644 index 0000000000..3256a2e5c7 --- /dev/null +++ b/cj_environment/test/unittest/cj_environment_test/cj_environment_test.cpp @@ -0,0 +1,349 @@ +/* + * 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 +#define private public +#define protected public +#include "cj_environment.h" +#include "cj_invoker.h" +#undef private +#undef protected + +using namespace testing; +using namespace testing::ext; +using namespace testing::mt; + +namespace OHOS { + +class CjEnvironmentTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; + +void CjEnvironmentTest::SetUpTestCase() {} + +void CjEnvironmentTest::TearDownTestCase() {} + +void CjEnvironmentTest::SetUp() {} + +void CjEnvironmentTest::TearDown() {} + +void RegisterCJUncaughtExceptionHandlerTest(const CJUncaughtExceptionInfo &handle) {} + +/** + * @tc.name: CJEnvironment_GetInstance_0001 + * @tc.desc: JsRuntime test for UpdatePkgContextInfoJson. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CJEnvironment_GetInstance_0100, TestSize.Level1) +{ + auto cJEnvironment = std::make_shared(); + CJEnvironment *ret = nullptr; + ret = cJEnvironment->GetInstance(); + EXPECT_NE(ret, nullptr); +} + +/** + * @tc.name: CJEnvironment_IsRuntimeStarted_0001 + * @tc.desc: JsRuntime test for IsRuntimeStarted. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CJEnvironment_IsRuntimeStarted_0100, TestSize.Level1) +{ + auto cJEnvironment = std::make_shared(); + bool ret = cJEnvironment->IsRuntimeStarted(); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: CJEnvironment_SetSanitizerKindRuntimeVersion_0001 + * @tc.desc: JsRuntime test for SetSanitizerKindRuntimeVersion. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CJEnvironment_SetSanitizerKindRuntimeVersion_0100, TestSize.Level1) +{ + auto cJEnvironment = std::make_shared(); + SanitizerKind kind = SanitizerKind::ASAN; + + cJEnvironment->SetSanitizerKindRuntimeVersion(kind); + EXPECT_NE(cJEnvironment->sanitizerKind_, SanitizerKind::NONE); +} + +/** + * @tc.name: CJEnvironment_InitCJAppNS_0001 + * @tc.desc: JsRuntime test for InitCJAppNS. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CJEnvironment_InitCJAppNS_0100, TestSize.Level1) +{ + auto cJEnvironment = std::make_shared(); + std::string path = "ability_runtime/CjEnvironmentTest"; + + cJEnvironment->InitCJAppNS(path); + EXPECT_NE(cJEnvironment->cjAppNSName, nullptr); +} + +/** + * @tc.name: CJEnvironment_InitCJSDKNS_0001 + * @tc.desc: JsRuntime test for InitCJSDKNS. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CJEnvironment_InitCJSDKNS_0100, TestSize.Level1) +{ + auto cJEnvironment = std::make_shared(); + std::string path = "ability_runtime/CjEnvironmentTest"; + cJEnvironment->InitCJSDKNS(path); + EXPECT_NE(cJEnvironment->cjAppNSName, nullptr); +} + +/** + * @tc.name: CJEnvironment_InitCJSysNS_0001 + * @tc.desc: JsRuntime test for InitCJSysNS. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CJEnvironment_InitCJSysNS_0100, TestSize.Level1) +{ + auto cJEnvironment = std::make_shared(); + std::string path = "ability_runtime/CjEnvironmentTest"; + cJEnvironment->InitCJSysNS(path); + std::string getTempCjAppNSName = cJEnvironment->cjAppNSName; + EXPECT_NE(cJEnvironment->cjAppNSName, nullptr); +} + +/** + * @tc.name: CJEnvironment_InitCJChipSDKNS_0001 + * @tc.desc: JsRuntime test for InitCJChipSDKNS. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CJEnvironment_InitCJChipSDKNS_0100, TestSize.Level1) +{ + auto cJEnvironment = std::make_shared(); + std::string path = "ability_runtime/CjEnvironmentTest"; + cJEnvironment->InitCJChipSDKNS(path); + EXPECT_NE(cJEnvironment->cjAppNSName, nullptr); +} + +/** + * @tc.name: CJEnvironment_StartRuntime_0001 + * @tc.desc: JsRuntime test for StartRuntime. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CJEnvironment_StartRuntime_0100, TestSize.Level1) +{ + auto cJEnvironment = std::make_shared(); + + bool ret = cJEnvironment->StartRuntime(); + EXPECT_EQ(ret, false); + + cJEnvironment->isRuntimeStarted_ = true; + ret = cJEnvironment->StartRuntime(); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: CJEnvironment_StopRuntime_0001 + * @tc.desc: JsRuntime test for StopRuntime. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CJEnvironment_StopRuntime_0100, TestSize.Level1) +{ + auto cJEnvironment = std::make_shared(); + cJEnvironment->StopRuntime(); + EXPECT_EQ(cJEnvironment->isRuntimeStarted_, false); + + cJEnvironment->isUISchedulerStarted_ = true; + EXPECT_EQ(cJEnvironment->isRuntimeStarted_, false); +} + +/** + * @tc.name: CJEnvironment_RegisterCJUncaughtExceptionHandler_0001 + * @tc.desc: JsRuntime test for RegisterCJUncaughtExceptionHandler. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CJEnvironment_RegisterCJUncaughtExceptionHandler_0100, TestSize.Level1) +{ + // using RegisterUncaughtExceptionType = void (*)(const CJUncaughtExceptionInfo& handle); + CJEnvironment cJEnvironment; + CJUncaughtExceptionInfo handle; + handle.hapPath = "/test1/"; + handle.uncaughtTask = [](const char* summary, const CJErrorObject errorObj) {}; + + CJRuntimeAPI api { + .InitCJRuntime = nullptr, + .InitUIScheduler = nullptr, + .RunUIScheduler = nullptr, + .FiniCJRuntime = nullptr, + .InitCJLibrary = nullptr, + .RegisterEventHandlerCallbacks = nullptr, + .RegisterCJUncaughtExceptionHandler = RegisterCJUncaughtExceptionHandlerTest, + }; + + CJEnvironment::lazyApis_ = api; + + cJEnvironment.RegisterCJUncaughtExceptionHandler(handle); + + EXPECT_NE(cJEnvironment.lazyApis_.RegisterCJUncaughtExceptionHandler, nullptr); +} + +/** + * @tc.name: CJEnvironment_IsUISchedulerStarted_0001 + * @tc.desc: JsRuntime test for IsUISchedulerStarted. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CJEnvironment_IsUISchedulerStarted_0100, TestSize.Level1) +{ + auto cJEnvironment = std::make_shared(); + bool ret = cJEnvironment->IsUISchedulerStarted(); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: StartUIScheduler_0100 + * @tc.desc: Test when isUISchedulerStarted_ is true. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, StartUIScheduler_0100, TestSize.Level1) +{ + auto cjEnv = std::make_shared(); + cjEnv->isUISchedulerStarted_ = true; + auto res = cjEnv->StartUIScheduler(); + EXPECT_EQ(res, true); +} + +/** + * @tc.name: StopUIScheduler_0100 + * @tc.desc: Test StopUIScheduler. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, StopUIScheduler_0100, TestSize.Level1) +{ + auto cjEnv = std::make_shared(); + EXPECT_NE(cjEnv, nullptr); + cjEnv->StopUIScheduler(); +} + +/** + * @tc.name: LoadCJLibrary_0100 + * @tc.desc: Test LoadCJLibrary. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, LoadCJLibrary_0100, TestSize.Level1) +{ + auto cjEnv = std::make_shared(); + char dlNames[5] = "Name"; + char* dlName = dlNames; + auto res = cjEnv->LoadCJLibrary(dlName); + EXPECT_EQ(res, nullptr); +} + +/** + * @tc.name: LoadCJLibrary_0200 + * @tc.desc: Test LoadCJLibrary. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, LoadCJLibrary_0200, TestSize.Level1) +{ + auto cjEnv = std::make_shared(); + CJEnvironment::LibraryKind kind = CJEnvironment::SYSTEM; + char dlNames[] = "Name"; + char* dlName = dlNames; + auto res = cjEnv->LoadCJLibrary(kind, dlName); + EXPECT_EQ(res, nullptr); +} + +/** + * @tc.name: UnLoadCJLibrary_0100 + * @tc.desc: Test LoadCJLibrary. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, UnLoadCJLibrary_0100, TestSize.Level1) +{ + auto cjEnv = std::make_shared(); + EXPECT_NE(cjEnv, nullptr); + cjEnv->UnLoadCJLibrary(nullptr); +} + +/** + * @tc.name: GetUIScheduler_0100 + * @tc.desc: Test GetUIScheduler. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, GetUIScheduler_0100, TestSize.Level1) +{ + auto cjEnv = std::make_shared(); + cjEnv->isUISchedulerStarted_ = true; + auto res = cjEnv->GetUIScheduler(); + EXPECT_EQ(res, nullptr); +} + +/** + * @tc.name: GetSymbol_0100 + * @tc.desc: Test GetSymbol. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, GetSymbol_0100, TestSize.Level1) +{ + auto cjEnv = std::make_shared(); + EXPECT_NE(cjEnv, nullptr); + void* dso = nullptr; + char symbols[] = "symbol"; + char* symbol = symbols; + auto res = cjEnv->GetSymbol(dso, symbol); + EXPECT_EQ(res, nullptr); +} + +/** + * @tc.name: StartDebugger_0100 + * @tc.desc: Test StartDebugger. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, StartDebugger_0100, TestSize.Level1) +{ + auto cjEnv = std::make_shared(); + EXPECT_NE(cjEnv, nullptr); + auto res = cjEnv->StartDebugger(); + EXPECT_EQ(res, false); +} + +/** + * @tc.name: PostTask_0100 + * @tc.desc: Test PostTask. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, PostTask_0100, TestSize.Level1) +{ + auto cjEnv = std::make_shared(); + TaskFuncType task = nullptr; + auto res = cjEnv->PostTask(task); + EXPECT_EQ(res, false); +} + +/** + * @tc.name: HasHigherPriorityTask_0100 + * @tc.desc: Test HasHigherPriorityTask. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, HasHigherPriorityTask_0100, TestSize.Level1) +{ + auto cjEnv = std::make_shared(); + EXPECT_NE(cjEnv, nullptr); + auto res = cjEnv->HasHigherPriorityTask(); + EXPECT_EQ(res, false); +} +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/cj/BUILD.gn b/frameworks/cj/BUILD.gn index b4830fb179..e406ddb028 100755 --- a/frameworks/cj/BUILD.gn +++ b/frameworks/cj/BUILD.gn @@ -18,5 +18,6 @@ group("cj_ability_packages") { deps = [ "${ability_runtime_path}/frameworks/cj/ffi:cj_ability_ffi", "${ability_runtime_path}/frameworks/cj/ffi/app/errormanager:cj_errormanager_ffi", + "${ability_runtime_path}/frameworks/cj/ffi/ark_interop_helper:ark_interop_helper_ffi", ] } diff --git a/frameworks/cj/ffi/ark_interop_helper/BUILD.gn b/frameworks/cj/ffi/ark_interop_helper/BUILD.gn new file mode 100644 index 0000000000..bf0cc02472 --- /dev/null +++ b/frameworks/cj/ffi/ark_interop_helper/BUILD.gn @@ -0,0 +1,54 @@ +# 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") + +ohos_shared_library("ark_interop_helper_ffi") { + defines = [] + + sources = [ "ark_interop_helper.cpp" ] + + external_deps = [ + "ets_runtime:libark_jsruntime", + "hilog:libhilog", + "napi:ace_napi", + "napi:ark_interop", + ] + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + + deps = [] + + if (build_ohos_sdk) { + defines += [ "PREVIEW" ] + } else { + deps += [ + "${ability_runtime_innerkits_path}/napi_base_context:napi_base_context", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/appkit:appkit_native", + ] + external_deps += [ "ace_engine:ace_container_scope" ] + } + + if (current_os == "mingw") { + defines += [ "__WINDOWS__" ] + } + + innerapi_tags = [ "platformsdk" ] + part_name = "ability_runtime" + subsystem_name = "ability" +} diff --git a/frameworks/cj/ffi/ark_interop_helper/ark_interop_helper.cpp b/frameworks/cj/ffi/ark_interop_helper/ark_interop_helper.cpp new file mode 100644 index 0000000000..74fa04bb91 --- /dev/null +++ b/frameworks/cj/ffi/ark_interop_helper/ark_interop_helper.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 "ark_interop_helper.h" +#include "ark_native_engine.h" +#include "inner_api/cjffi/ark_interop/ark_interop_internal.h" +#include "inner_api/cjffi/ark_interop/ark_interop_log.h" +#ifndef PREVIEW +#include "core/common/container_scope.h" +#include "custom_scope.h" +#include "napi_base_context.h" +#include "ability.h" +#endif + +using namespace panda::ecmascript; + +extern "C" { +napi_value ArkTsValuetoNapiValue(napi_env env, ARKTS_Value arkValue) +{ + LOGI("ArkTsValuetoNapiValue start"); + if (env == nullptr) { + LOGE("FfiOHOSArkTsValuetoNapiValue Error: env is null!"); + return nullptr; + } + Local js_value_ref = ARKTS_ToHandle(arkValue); + auto ark_native_obj = ArkNativeEngine::ArkValueToNapiValue(env, js_value_ref); + return ark_native_obj; +}; + +ARKTS_Value NapiValueToArkTsValue(napi_value value) +{ + auto ref = BIT_CAST(value, Local); + return ARKTS_FromHandle(ref); +} + +bool IsStageMode(napi_env env, napi_value context) +{ +#ifndef PREVIEW + LOGI("IsStageMode start"); + bool isStageMode = false; + napi_status status = OHOS::AbilityRuntime::IsStageContext(env, context, isStageMode); + if (status != napi_ok || !isStageMode) { + LOGI("IsStageMode false"); + return false; + } else { + LOGI("IsStageMode true"); + return true; + } +#else + return false; +#endif +} + +void* GetContextStageMode(napi_env env, napi_value context) +{ +#ifndef PREVIEW + LOGI("GetContextStageMode start"); + if (!env || !context) { + LOGE("argument invalid"); + return nullptr; + } + napi_valuetype type; + if (napi_typeof(env, context, &type) != napi_ok) { + LOGE("invalid napi value"); + return nullptr; + } + if (type != napi_object) { + LOGE("not a object"); + return nullptr; + } + void* data; + if (napi_unwrap(env, context, &data) != napi_ok) { + LOGE("no bind native object"); + return nullptr; + } + if (!data) { + LOGE("native object is null"); + return nullptr; + } + auto ability = OHOS::AbilityRuntime::GetStageModeContext(env, context); + if (ability == nullptr) { + LOGE("Failed to get native ability instance"); + return nullptr; + } + LOGI("GetContextStageMode success"); + return ability.get(); +#else + return nullptr; +#endif +} +#ifndef PREVIEW +void CustomScope::Enter() +{ + last_ = OHOS::Ace::ContainerScope::CurrentId(); + OHOS::Ace::ContainerScope::UpdateCurrent(id_); +} + +void CustomScope::Exit() const +{ + OHOS::Ace::ContainerScope::UpdateCurrent(last_); +} + +int32_t ARKTS_GetCurrentContainerId() +{ + return OHOS::Ace::ContainerScope::CurrentId(); +} + +ContainerScope ARKTS_CreateContainerScope(int32_t id) +{ + return new CustomScope(id); +} + +void ARKTS_DestroyContainerScope(ContainerScope scope) +{ + delete scope; +} + +void ARKTS_EnterContainerScope(ContainerScope scope) +{ + scope->Enter(); +} + +void ARKTS_ExitContainerScope(ContainerScope scope) +{ + scope->Exit(); +} +#else +int32_t ARKTS_GetCurrentContainerId() { return 0; } +ContainerScope ARKTS_CreateContainerScope(int32_t id) { return nullptr; } +void ARKTS_DestroyContainerScope(ContainerScope scope) {} +void ARKTS_EnterContainerScope(ContainerScope scope) {} +void ARKTS_ExitContainerScope(ContainerScope scope) {} +#endif +} \ No newline at end of file diff --git a/frameworks/cj/ffi/ark_interop_helper/ark_interop_helper.h b/frameworks/cj/ffi/ark_interop_helper/ark_interop_helper.h new file mode 100644 index 0000000000..fec91a5b1c --- /dev/null +++ b/frameworks/cj/ffi/ark_interop_helper/ark_interop_helper.h @@ -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. + */ + +#ifndef NAPI_ARK_INTEROP_HELPER_H +#define NAPI_ARK_INTEROP_HELPER_H + +#include "inner_api/cjffi/ark_interop/ark_interop_napi.h" +#include "napi/native_api.h" + +#include + +using ContainerScope = class CustomScope*; + +extern "C" { +EXPORT napi_value ArkTsValuetoNapiValue(napi_env env, ARKTS_Value arkValue); +EXPORT ARKTS_Value NapiValueToArkTsValue(napi_value value); +EXPORT bool IsStageMode(napi_env env, napi_value context); +EXPORT void* GetContextStageMode(napi_env env, napi_value context); +EXPORT int32_t ARKTS_GetCurrentContainerId(); +EXPORT ContainerScope ARKTS_CreateContainerScope(int32_t); +EXPORT void ARKTS_DestroyContainerScope(ContainerScope scope); +EXPORT void ARKTS_EnterContainerScope(ContainerScope scope); +EXPORT void ARKTS_ExitContainerScope(ContainerScope scope); +} + +#endif // NAPI_ARK_INTEROP_HELPER_H \ No newline at end of file diff --git a/frameworks/cj/ffi/ark_interop_helper/custom_scope.h b/frameworks/cj/ffi/ark_interop_helper/custom_scope.h new file mode 100644 index 0000000000..2a17b6e775 --- /dev/null +++ b/frameworks/cj/ffi/ark_interop_helper/custom_scope.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 NAPI_CUSTOM_SCOPE_H +#define NAPI_CUSTOM_SCOPE_H + +#include + +class CustomScope { +public: + explicit CustomScope(int32_t id): id_(id), last_(0) {} + + void Enter(); + void Exit() const; + +private: + int32_t id_ = 0; + int32_t last_ = 0; +}; + +#endif // NAPI_CUSTOM_SCOPE_H diff --git a/frameworks/cj/ffi/ark_interop_helper/utils.h b/frameworks/cj/ffi/ark_interop_helper/utils.h new file mode 100644 index 0000000000..587d7c9999 --- /dev/null +++ b/frameworks/cj/ffi/ark_interop_helper/utils.h @@ -0,0 +1,31 @@ +/* + * 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 ARK_INTEROP_HELPER_UTILS_H +#define ARK_INTEROP_HELPER_UTILS_H + +#include +#include +#include + +#ifndef EXPORT +#ifdef __WINDOWS__ +#define EXPORT __declspec(dllexport) +#else +#define EXPORT __attribute__((visibility("default"))) +#endif +#endif + +#endif // ARK_INTEROP_HELPER_UTILS_H \ No newline at end of file diff --git a/frameworks/cj/ffi/cj_ability_delegator.cpp b/frameworks/cj/ffi/cj_ability_delegator.cpp index 739d5c6e76..c0d58d50b1 100644 --- a/frameworks/cj/ffi/cj_ability_delegator.cpp +++ b/frameworks/cj/ffi/cj_ability_delegator.cpp @@ -21,7 +21,6 @@ #include "cj_utils_ffi.h" #include "application_context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityDelegatorCJ { diff --git a/frameworks/cj/ffi/cj_application_context.cpp b/frameworks/cj/ffi/cj_application_context.cpp index 1861adb834..6dd2ab80e0 100644 --- a/frameworks/cj/ffi/cj_application_context.cpp +++ b/frameworks/cj/ffi/cj_application_context.cpp @@ -19,7 +19,6 @@ #include "application_context.h" #include "cj_utils_ffi.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace ApplicationContextCJ { diff --git a/frameworks/cj/ffi/cj_element_name_ffi.cpp b/frameworks/cj/ffi/cj_element_name_ffi.cpp index fb96009584..e86e8ff522 100644 --- a/frameworks/cj/ffi/cj_element_name_ffi.cpp +++ b/frameworks/cj/ffi/cj_element_name_ffi.cpp @@ -18,7 +18,6 @@ #include "cj_utils_ffi.h" #include "element_name.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using OHOS::AppExecFwk::ElementName; diff --git a/frameworks/cj/ffi/cj_utils_ffi.cpp b/frameworks/cj/ffi/cj_utils_ffi.cpp index 7fcc5cf0b9..4506e5a5ac 100644 --- a/frameworks/cj/ffi/cj_utils_ffi.cpp +++ b/frameworks/cj/ffi/cj_utils_ffi.cpp @@ -18,7 +18,6 @@ #include "securec.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" char* CreateCStringFromString(const std::string& source) { diff --git a/frameworks/cj/ffi/cj_want_ffi.cpp b/frameworks/cj/ffi/cj_want_ffi.cpp index c63a032140..d45858bb7d 100644 --- a/frameworks/cj/ffi/cj_want_ffi.cpp +++ b/frameworks/cj/ffi/cj_want_ffi.cpp @@ -23,7 +23,6 @@ #include "want.h" #include "want_params_wrapper.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using OHOS::AAFwk::Want; using OHOS::AppExecFwk::ElementName; diff --git a/frameworks/js/napi/BUILD.gn b/frameworks/js/napi/BUILD.gn index fee3fa07d2..e424a4642f 100644 --- a/frameworks/js/napi/BUILD.gn +++ b/frameworks/js/napi/BUILD.gn @@ -42,6 +42,7 @@ group("napi_packages") { "${ability_runtime_napi_path}/app/error_manager:errormanager_napi", "${ability_runtime_napi_path}/app/js_app_manager:appmanager", "${ability_runtime_napi_path}/app/recovery:apprecovery_napi", + "${ability_runtime_napi_path}/app/sendable_context_manager:sendablecontextmanager_napi", "${ability_runtime_napi_path}/app/test_runner:testrunner_napi", "${ability_runtime_napi_path}/app_startup/async_task_callback:asynctaskcallback_napi", "${ability_runtime_napi_path}/app_startup/async_task_excutor:asynctaskexcutor_napi", @@ -88,6 +89,9 @@ group("napi_packages") { "${ability_runtime_napi_path}/share_extension_ability:shareextensionability_napi", "${ability_runtime_napi_path}/ui_extension_ability:uiextensionability_napi", "${ability_runtime_napi_path}/ui_extension_context:uiextensioncontext_napi", + "${ability_runtime_napi_path}/ui_service_extension_ability:uiserviceextensionability", + "${ability_runtime_napi_path}/ui_service_extension_ability:uiserviceextensionability_napi", + "${ability_runtime_napi_path}/ui_service_extension_context:uiserviceextensioncontext_napi", "${ability_runtime_napi_path}/uri_permission:uripermissionmanager_napi", "${ability_runtime_napi_path}/wantConstant:wantconstant", "${ability_runtime_napi_path}/wantConstant:wantconstant_napi", diff --git a/frameworks/js/napi/ability/BUILD.gn b/frameworks/js/napi/ability/BUILD.gn index bcd3f151e9..f0d62f746f 100644 --- a/frameworks/js/napi/ability/BUILD.gn +++ b/frameworks/js/napi/ability/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_ability_abc") { diff --git a/frameworks/js/napi/abilityDataUriUtils/BUILD.gn b/frameworks/js/napi/abilityDataUriUtils/BUILD.gn index 4da19db54e..b0a1bd7857 100644 --- a/frameworks/js/napi/abilityDataUriUtils/BUILD.gn +++ b/frameworks/js/napi/abilityDataUriUtils/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_ability_data_uri_utils_abc") { diff --git a/frameworks/js/napi/ability_auto_startup_callback/BUILD.gn b/frameworks/js/napi/ability_auto_startup_callback/BUILD.gn index eed5ae7066..477aeb266d 100644 --- a/frameworks/js/napi/ability_auto_startup_callback/BUILD.gn +++ b/frameworks/js/napi/ability_auto_startup_callback/BUILD.gn @@ -18,6 +18,7 @@ ohos_shared_library("autostartupcallback") { include_dirs = [ "./", "${ability_runtime_napi_path}/inner/napi_common/", + "${ability_runtime_utils_path}/global/constant", ] sources = [ 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 1ac5ccf4ce..6bef7d671a 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 @@ -16,7 +16,6 @@ #include "js_ability_auto_startup_callback.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_ability_auto_startup_manager_utils.h" #include "js_runtime.h" #include "js_runtime_utils.h" 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 5c12513a76..523c73494d 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 @@ -14,6 +14,8 @@ */ #include "js_ability_auto_startup_manager_utils.h" + +#include "global_constant.h" #include "hilog_tag_wrapper.h" #include "napi_common_util.h" @@ -68,7 +70,7 @@ bool IsNormalObject(napi_env env, napi_value value) napi_value CreateJsAutoStartupInfoArray(napi_env env, const std::vector &infoList) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); napi_value arrayObj = nullptr; napi_create_array(env, &arrayObj); for (size_t i = 0; i < infoList.size(); ++i) { @@ -89,7 +91,7 @@ napi_value CreateJsAutoStartupInfoArray(napi_env env, const std::vector= 0 && info.appCloneIndex < GlobalConstant::MAX_APP_CLONE_INDEX) { napi_value appCloneIndex = AppExecFwk::WrapInt32ToJS(env, info.appCloneIndex); if (appCloneIndex == nullptr) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "Convert ability type name failed."); diff --git a/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_manager_utils.h b/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_manager_utils.h index db35f4e804..a5c8048f96 100644 --- a/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_manager_utils.h +++ b/frameworks/js/napi/ability_auto_startup_callback/js_ability_auto_startup_manager_utils.h @@ -17,7 +17,6 @@ #define OHOS_ABILITY_RUNTIME_JS_ABILITY_AUTO_STARTUP_MANAGER_UTILS_H #include "auto_startup_info.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "js_runtime_utils.h" #include "native_engine/native_engine.h" diff --git a/frameworks/js/napi/ability_auto_startup_manager/js_ability_auto_startup_manager.cpp b/frameworks/js/napi/ability_auto_startup_manager/js_ability_auto_startup_manager.cpp index b66e1a8512..1ee8f3b4c7 100644 --- a/frameworks/js/napi/ability_auto_startup_manager/js_ability_auto_startup_manager.cpp +++ b/frameworks/js/napi/ability_auto_startup_manager/js_ability_auto_startup_manager.cpp @@ -19,7 +19,6 @@ #include "ability_manager_interface.h" #include "auto_startup_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "js_ability_auto_startup_manager_utils.h" #include "js_error_utils.h" @@ -41,7 +40,7 @@ constexpr const char *ON_OFF_TYPE_SYSTEM = "systemAutoStartup"; void JsAbilityAutoStartupManager::Finalizer(napi_env env, void *data, void *hint) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); std::unique_ptr(static_cast(data)); } @@ -82,7 +81,7 @@ bool JsAbilityAutoStartupManager::CheckCallerIsSystemApp() napi_value JsAbilityAutoStartupManager::OnRegisterAutoStartupCallback(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); if (info.argc < ARGC_TWO) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "The param is invalid."); ThrowTooFewParametersError(env); @@ -130,7 +129,7 @@ napi_value JsAbilityAutoStartupManager::OnRegisterAutoStartupCallback(napi_env e napi_value JsAbilityAutoStartupManager::OnUnregisterAutoStartupCallback(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "OnUnregisterAutoStartupCallback Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); if (info.argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "The argument is invalid."); ThrowTooFewParametersError(env); @@ -175,7 +174,7 @@ napi_value JsAbilityAutoStartupManager::OnUnregisterAutoStartupCallback(napi_env napi_value JsAbilityAutoStartupManager::OnSetApplicationAutoStartup(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "OnSetApplicationAutoStartup Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); if (info.argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "The argument is invalid."); ThrowTooFewParametersError(env); @@ -225,7 +224,7 @@ napi_value JsAbilityAutoStartupManager::OnSetApplicationAutoStartup(napi_env env napi_value JsAbilityAutoStartupManager::OnCancelApplicationAutoStartup(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "OnCancelApplicationAutoStartup Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); if (info.argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "The param is invalid."); ThrowTooFewParametersError(env); @@ -276,7 +275,7 @@ napi_value JsAbilityAutoStartupManager::OnCancelApplicationAutoStartup(napi_env napi_value JsAbilityAutoStartupManager::OnQueryAllAutoStartupApplications(napi_env env, const NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); if (!CheckCallerIsSystemApp()) { ThrowError(env, AbilityErrorCode::ERROR_CODE_NOT_SYSTEM_APP); return CreateJsUndefined(env); @@ -316,7 +315,7 @@ napi_value JsAbilityAutoStartupManager::OnQueryAllAutoStartupApplications(napi_e napi_value JsAbilityAutoStartupManagerInit(napi_env env, napi_value exportObj) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); if (env == nullptr || exportObj == nullptr) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "Env or exportObj nullptr."); return nullptr; diff --git a/frameworks/js/napi/ability_constant/ability_constant_module.cpp b/frameworks/js/napi/ability_constant/ability_constant_module.cpp index 1a6e05c3ec..3888afac8d 100644 --- a/frameworks/js/napi/ability_constant/ability_constant_module.cpp +++ b/frameworks/js/napi/ability_constant/ability_constant_module.cpp @@ -15,7 +15,6 @@ #include "ability_window_configuration.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "launch_param.h" #include "mission_info.h" #include "napi/native_api.h" diff --git a/frameworks/js/napi/ability_context/BUILD.gn b/frameworks/js/napi/ability_context/BUILD.gn index a57af7d015..e3bf547c57 100644 --- a/frameworks/js/napi/ability_context/BUILD.gn +++ b/frameworks/js/napi/ability_context/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_ability_context_abc") { diff --git a/frameworks/js/napi/ability_context/ability_context.js b/frameworks/js/napi/ability_context/ability_context.js index 520a219823..7a83688596 100644 --- a/frameworks/js/napi/ability_context/ability_context.js +++ b/frameworks/js/napi/ability_context/ability_context.js @@ -112,6 +112,18 @@ class AbilityContext extends Context { startAbilityForResultWithAccount(want, accountId, options, callback) { return this.__context_impl__.startAbilityForResultWithAccount(want, accountId, options, callback); } + + startUIServiceExtensionAbility(want, callback) { + return this.__context_impl__.startUIServiceExtensionAbility(want, callback); + } + + connectUIServiceExtensionAbility(want, callback) { + return this.__context_impl__.connectUIServiceExtensionAbility(want, callback); + } + + disconnectUIServiceExtensionAbility(proxy) { + return this.__context_impl__.disconnectUIServiceExtensionAbility(proxy); + } startServiceExtensionAbility(want, callback) { return this.__context_impl__.startServiceExtensionAbility(want, callback); 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 19eb11eb4e..b24fd1d068 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 @@ -16,7 +16,6 @@ #include "js_ability_foreground_state_observer.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" namespace OHOS { @@ -28,7 +27,7 @@ JSAbilityForegroundStateObserver::JSAbilityForegroundStateObserver(napi_env env) void JSAbilityForegroundStateObserver::OnAbilityStateChanged(const AbilityStateData &abilityStateData) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (!valid_) { TAG_LOGE(AAFwkTag::ABILITYMGR, "The app manager may has destroyed."); return; @@ -50,7 +49,7 @@ void JSAbilityForegroundStateObserver::OnAbilityStateChanged(const AbilityStateD void JSAbilityForegroundStateObserver::HandleOnAbilityStateChanged(const AbilityStateData &abilityStateData) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); for (auto &item : jsObserverObjectSet_) { if (item == nullptr) { continue; diff --git a/frameworks/js/napi/ability_manager/js_ability_manager.cpp b/frameworks/js/napi/ability_manager/js_ability_manager.cpp index 18a3ba11f8..4d33a17df9 100644 --- a/frameworks/js/napi/ability_manager/js_ability_manager.cpp +++ b/frameworks/js/napi/ability_manager/js_ability_manager.cpp @@ -26,7 +26,6 @@ #include "errors.h" #include "event_runner.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" @@ -149,7 +148,7 @@ private: napi_value OnOn(napi_env env, size_t argc, napi_value *argv) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (argc < ARGC_TWO) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Not enough params."); ThrowTooFewParametersError(env); @@ -195,7 +194,7 @@ private: napi_value OnOff(napi_env env, size_t argc, napi_value *argv) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Not enough params when off."); ThrowTooFewParametersError(env); @@ -233,7 +232,7 @@ private: napi_value OnNotifyDebugAssertResult(napi_env env, size_t argc, napi_value *argv) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (argc < ARGC_TWO) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Not enough params when off."); ThrowTooFewParametersError(env); @@ -550,7 +549,7 @@ private: napi_value OnGetForegroundUIAbilities(napi_env env, size_t argc, napi_value *argv) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); NapiAsyncTask::CompleteCallback complete = [](napi_env env, NapiAsyncTask &task, int32_t status) { std::vector list; int32_t ret = AbilityManagerClient::GetInstance()->GetForegroundUIAbilities(list); @@ -571,7 +570,7 @@ private: napi_value OnSetResidentProcessEnabled(napi_env env, size_t argc, napi_value *argv) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (argc < ARGC_TWO) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Not enough params when off."); ThrowTooFewParametersError(env); @@ -621,7 +620,7 @@ private: napi_value OnIsEmbeddedOpenAllowed(napi_env env, NapiCallbackInfo& info) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (info.argc < ARGC_TWO) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Not enough params"); ThrowTooFewParametersError(env); 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 cc47a5ace1..447666481a 100644 --- a/frameworks/js/napi/ability_manager/js_ability_manager_utils.cpp +++ b/frameworks/js/napi/ability_manager/js_ability_manager_utils.cpp @@ -19,7 +19,6 @@ #include "ability_state.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "js_runtime_utils.h" #include "napi_common_want.h" @@ -119,7 +118,7 @@ napi_value AbilityStateInit(napi_env env) napi_value UserStatusInit(napi_env env) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); napi_value objValue = nullptr; napi_create_object(env, &objValue); @@ -132,7 +131,7 @@ napi_value UserStatusInit(napi_env env) napi_value CreateJsAbilityStateData(napi_env env, const AbilityStateData &abilityStateData) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); napi_value object = nullptr; napi_create_object(env, &object); if (object == nullptr) { diff --git a/frameworks/js/napi/action_extension_ability/BUILD.gn b/frameworks/js/napi/action_extension_ability/BUILD.gn index ed8b9e0fea..0553ca9e05 100755 --- a/frameworks/js/napi/action_extension_ability/BUILD.gn +++ b/frameworks/js/napi/action_extension_ability/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_action_extension_ability_abc") { diff --git a/frameworks/js/napi/app/ability_delegator/ability_monitor.cpp b/frameworks/js/napi/app/ability_delegator/ability_monitor.cpp index 6b267ed5ff..1a830f3dc0 100644 --- a/frameworks/js/napi/app/ability_delegator/ability_monitor.cpp +++ b/frameworks/js/napi/app/ability_delegator/ability_monitor.cpp @@ -16,7 +16,6 @@ #include "ability_monitor.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "js_ability_delegator_utils.h" #include "napi/native_common.h" diff --git a/frameworks/js/napi/app/ability_delegator/js_ability_delegator.cpp b/frameworks/js/napi/app/ability_delegator/js_ability_delegator.cpp index 0f172b8f39..fa63bf5033 100644 --- a/frameworks/js/napi/app/ability_delegator/js_ability_delegator.cpp +++ b/frameworks/js/napi/app/ability_delegator/js_ability_delegator.cpp @@ -18,7 +18,6 @@ #include #include "ability_delegator_registry.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_ability_delegator_utils.h" #include "js_context_utils.h" #include "js_error_utils.h" diff --git a/frameworks/js/napi/app/ability_delegator/js_ability_delegator_registry.cpp b/frameworks/js/napi/app/ability_delegator/js_ability_delegator_registry.cpp index 870e422c8f..8bd4856748 100644 --- a/frameworks/js/napi/app/ability_delegator/js_ability_delegator_registry.cpp +++ b/frameworks/js/napi/app/ability_delegator/js_ability_delegator_registry.cpp @@ -19,7 +19,6 @@ #include "ability_delegator.h" #include "ability_delegator_registry.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_ability_delegator.h" #include "js_ability_delegator_utils.h" #include "js_runtime_utils.h" diff --git a/frameworks/js/napi/app/ability_delegator/js_ability_delegator_utils.cpp b/frameworks/js/napi/app/ability_delegator/js_ability_delegator_utils.cpp index 753a3fbd2e..b3c21d4214 100644 --- a/frameworks/js/napi/app/ability_delegator/js_ability_delegator_utils.cpp +++ b/frameworks/js/napi/app/ability_delegator/js_ability_delegator_utils.cpp @@ -17,7 +17,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_ability_monitor.h" #include "napi/native_common.h" diff --git a/frameworks/js/napi/app/ability_delegator/js_ability_monitor.h b/frameworks/js/napi/app/ability_delegator/js_ability_monitor.h index 2ce1007e6f..7b3f52adb1 100644 --- a/frameworks/js/napi/app/ability_delegator/js_ability_monitor.h +++ b/frameworks/js/napi/app/ability_delegator/js_ability_monitor.h @@ -18,7 +18,6 @@ #include #include -#include "hilog_wrapper.h" #include "native_engine/native_reference.h" namespace OHOS { diff --git a/frameworks/js/napi/app/ability_lifecycle_callback/BUILD.gn b/frameworks/js/napi/app/ability_lifecycle_callback/BUILD.gn index b5dd3a8f6c..b06d092825 100644 --- a/frameworks/js/napi/app/ability_lifecycle_callback/BUILD.gn +++ b/frameworks/js/napi/app/ability_lifecycle_callback/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_ability_lifecycle_callback_abc") { diff --git a/frameworks/js/napi/app/ability_lifecycle_callback/ability_lifecycle_callback.js b/frameworks/js/napi/app/ability_lifecycle_callback/ability_lifecycle_callback.js index 8f67916249..36f032f2ab 100644 --- a/frameworks/js/napi/app/ability_lifecycle_callback/ability_lifecycle_callback.js +++ b/frameworks/js/napi/app/ability_lifecycle_callback/ability_lifecycle_callback.js @@ -83,6 +83,26 @@ class AbilityLifecycleCallback { onAbilityWillBackground(ability) { console.log('onAbilityWillBackground'); } + + onAbilityWillContinue(ability) { + console.log('onAbilityWillContinue'); + } + + onWindowStageWillRestore(ability, windowStage) { + console.log('onWindowStageWillRestore'); + } + + onWindowStageRestore(ability, windowStage) { + console.log('onWindowStageRestore'); + } + + onAbilityWillSaveState(ability) { + console.log('onAbilityWillSaveState'); + } + + onAbilitySaveState(ability) { + console.log('onAbilitySaveState'); + } } export default AbilityLifecycleCallback; \ No newline at end of file diff --git a/frameworks/js/napi/app/ability_stage/BUILD.gn b/frameworks/js/napi/app/ability_stage/BUILD.gn index 0ef1ebbc7c..22f5fff80f 100644 --- a/frameworks/js/napi/app/ability_stage/BUILD.gn +++ b/frameworks/js/napi/app/ability_stage/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_ability_stage_abc") { diff --git a/frameworks/js/napi/app/ability_stage_context/BUILD.gn b/frameworks/js/napi/app/ability_stage_context/BUILD.gn index 588f624cd8..c0508957bb 100644 --- a/frameworks/js/napi/app/ability_stage_context/BUILD.gn +++ b/frameworks/js/napi/app/ability_stage_context/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_ability_stage_context_abc") { 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 aa8f550645..08a2c91963 100644 --- a/frameworks/js/napi/app/app_manager/js_app_manager.cpp +++ b/frameworks/js/napi/app/app_manager/js_app_manager.cpp @@ -19,9 +19,9 @@ #include #include "ability_manager_interface.h" +#include "ability_manager_errors.h" #include "app_mgr_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "js_runtime_utils.h" #include "napi/native_api.h" @@ -179,32 +179,37 @@ private: } } - NapiAsyncTask::CompleteCallback complete = - [appManager = appManager_, observer = observer_, observerId, errCode]( - napi_env env, NapiAsyncTask& task, int32_t status) { - if (errCode != 0) { - task.Reject(env, CreateJsError(env, errCode, "Invalidate params.")); - return; - } - if (observer == nullptr || appManager == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "observer or appManager nullptr"); - task.Reject(env, CreateJsError(env, ERROR_CODE_ONE, "observer or appManager nullptr")); - return; - } - int32_t ret = appManager->UnregisterApplicationStateObserver(observer); - if (ret == 0 && observer->RemoveJsObserverObject(observerId)) { - task.Resolve(env, CreateJsUndefined(env)); - TAG_LOGD(AAFwkTag::APPMGR, "success size:%{public}zu", observer->GetJsObserverMapSize()); - } else { - TAG_LOGE(AAFwkTag::APPMGR, "failed error:%{public}d", ret); - task.Reject(env, CreateJsError(env, ret, "UnregisterApplicationStateObserver failed")); - } - }; - napi_value lastParam = (argc == ARGC_TWO) ? argv[INDEX_ONE] : nullptr; napi_value result = nullptr; - NapiAsyncTask::Schedule("JSAppManager::OnUnregisterApplicationStateObserver", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [appManager = appManager_, observer = observer_, observerId, errCode, + env, task = napiAsyncTask.get()]() { + if (errCode != 0) { + task->Reject(env, CreateJsError(env, errCode, "Invalidate params.")); + delete task; + return; + } + if (observer == nullptr || appManager == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "observer or appManager nullptr"); + task->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "observer or appManager nullptr")); + delete task; + return; + } + int32_t ret = appManager->UnregisterApplicationStateObserver(observer); + if (ret == 0 && observer->RemoveJsObserverObject(observerId)) { + task->Resolve(env, CreateJsUndefined(env)); + TAG_LOGD(AAFwkTag::APPMGR, "success size:%{public}zu", observer->GetJsObserverMapSize()); + } else { + TAG_LOGE(AAFwkTag::APPMGR, "failed error:%{public}d", ret); + task->Reject(env, CreateJsError(env, ret, "UnregisterApplicationStateObserver failed")); + } + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_high)) { + napiAsyncTask->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "send event failed")); + } else { + napiAsyncTask.release(); + } return result; } @@ -218,32 +223,38 @@ private: TAG_LOGE(AAFwkTag::APPMGR, "Not enough params"); errCode = ERR_NOT_OK; } - NapiAsyncTask::CompleteCallback complete = - [appManager = appManager_, errCode](napi_env env, NapiAsyncTask& task, int32_t status) { - if (errCode != 0) { - task.Reject(env, CreateJsError(env, errCode, "Invalidate params.")); - return; - } - if (appManager == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "appManager nullptr"); - task.Reject(env, CreateJsError(env, ERROR_CODE_ONE, "appManager nullptr")); - return; - } - std::vector list; - int32_t ret = appManager->GetForegroundApplications(list); - if (ret == 0) { - TAG_LOGD(AAFwkTag::APPMGR, "success."); - task.Resolve(env, CreateJsAppStateDataArray(env, list)); - } else { - TAG_LOGE(AAFwkTag::APPMGR, "failed error:%{public}d", ret); - task.Reject(env, CreateJsError(env, ret, "OnGetForegroundApplications failed")); - } - }; napi_value lastParam = (argc == ARGC_ONE) ? argv[INDEX_ZERO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::Schedule("JSAppManager::OnGetForegroundApplications", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [appManager = appManager_, errCode, env, task = napiAsyncTask.get()]() { + if (errCode != 0) { + task->Reject(env, CreateJsError(env, errCode, "Invalidate params.")); + delete task; + return; + } + if (appManager == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "appManager nullptr"); + task->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "appManager nullptr")); + delete task; + return; + } + std::vector list; + int32_t ret = appManager->GetForegroundApplications(list); + if (ret == 0) { + TAG_LOGD(AAFwkTag::APPMGR, "success."); + task->Resolve(env, CreateJsAppStateDataArray(env, list)); + } else { + TAG_LOGE(AAFwkTag::APPMGR, "failed error:%{public}d", ret); + task->Reject(env, CreateJsError(env, ret, "OnGetForegroundApplications failed")); + } + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_high)) { + napiAsyncTask->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "send event failed")); + } else { + napiAsyncTask.release(); + } return result; } @@ -257,25 +268,30 @@ private: TAG_LOGE(AAFwkTag::APPMGR, "Not enough params"); errCode = ERR_NOT_OK; } - NapiAsyncTask::CompleteCallback complete = - [appManager = appManager_, errCode](napi_env env, NapiAsyncTask &task, int32_t status) { - if (errCode != 0) { - task.Reject(env, CreateJsError(env, errCode, "Invalidate params.")); - return; - } - std::vector infos; - auto ret = appManager->GetAllRunningProcesses(infos); - if (ret == 0) { - task.Resolve(env, CreateJsProcessRunningInfoArray(env, infos)); - } else { - task.Reject(env, CreateJsError(env, ret, "Get mission infos failed.")); - } - }; napi_value lastParam = (argc == ARGC_ONE) ? argv[INDEX_ZERO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::Schedule("JSAppManager::OnGetProcessRunningInfos", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [appManager = appManager_, errCode, env, task = napiAsyncTask.get()]() { + if (errCode != 0) { + task->Reject(env, CreateJsError(env, errCode, "Invalidate params.")); + delete task; + return; + } + std::vector infos; + auto ret = appManager->GetAllRunningProcesses(infos); + if (ret == 0) { + task->Resolve(env, CreateJsProcessRunningInfoArray(env, infos)); + } else { + task->Reject(env, CreateJsError(env, ret, "Get mission infos failed.")); + } + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_high)) { + napiAsyncTask->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "send event failed")); + } else { + napiAsyncTask.release(); + } return result; } @@ -289,29 +305,51 @@ private: TAG_LOGE(AAFwkTag::APPMGR, "Not enough arguments"); errCode = ERR_NOT_OK; } - NapiAsyncTask::CompleteCallback complete = - [abilityManager = abilityManager_, errCode](napi_env env, NapiAsyncTask& task, int32_t status) { - if (errCode != 0) { - task.Reject(env, CreateJsError(env, errCode, "Invalidate params.")); - return; - } - if (abilityManager == nullptr) { - TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); - task.Reject(env, CreateJsError(env, ERROR_CODE_ONE, "abilityManager nullptr")); - return; - } - bool ret = abilityManager->IsRunningInStabilityTest(); - TAG_LOGI(AAFwkTag::APPMGR, "result:%{public}d", ret); - task.Resolve(env, CreateJsValue(env, ret)); - }; napi_value lastParam = (argc == ARGC_ONE) ? argv[INDEX_ZERO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::Schedule("JSAppManager::OnIsRunningInStabilityTest", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [abilityManager = abilityManager_, errCode, env, task = napiAsyncTask.get()]() { + if (errCode != 0) { + task->Reject(env, CreateJsError(env, errCode, "Invalidate params.")); + delete task; + return; + } + if (abilityManager == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); + task->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "abilityManager nullptr")); + delete task; + return; + } + bool ret = abilityManager->IsRunningInStabilityTest(); + TAG_LOGI(AAFwkTag::APPMGR, "result:%{public}d", ret); + task->Resolve(env, CreateJsValue(env, ret)); + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_high)) { + napiAsyncTask->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "send event failed")); + } else { + napiAsyncTask.release(); + } return result; } + static void OnKillProcessByBundleNameInner(std::string bundleName, bool clearPageStack, + sptr abilityManager, napi_env env, NapiAsyncTask *task) + { + if (abilityManager == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "abilityManager null"); + task->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "abilityManager nullptr")); + return; + } + auto ret = abilityManager->KillProcess(bundleName, clearPageStack); + if (ret == 0) { + task->Resolve(env, CreateJsValue(env, ret)); + } else { + task->Reject(env, CreateJsError(env, ret, "kill process failed.")); + } + } + napi_value OnKillProcessByBundleName(napi_env env, size_t argc, napi_value* argv) { TAG_LOGD(AAFwkTag::APPMGR, "called"); @@ -340,29 +378,23 @@ private: TAG_LOGI(AAFwkTag::APPMGR, "kill [%{public}s], hasClearPageStack [%{public}d], clearPageStack [%{public}d],appIndex [%{public}d]", bundleName.c_str(), hasClearPageStack, clearPageStack, appIndex); - NapiAsyncTask::CompleteCallback complete = - [bundleName, clearPageStack, abilityManager = abilityManager_, errCode](napi_env env, NapiAsyncTask& task, - int32_t status) { - if (errCode != 0) { - task.Reject(env, CreateJsError(env, errCode, "Invalidate params.")); - return; - } - if (abilityManager == nullptr) { - TAG_LOGW(AAFwkTag::APPMGR, "abilityManager null"); - task.Reject(env, CreateJsError(env, ERROR_CODE_ONE, "abilityManager nullptr")); - return; - } - auto ret = abilityManager->KillProcess(bundleName, clearPageStack); - if (ret == 0) { - task.Resolve(env, CreateJsValue(env, ret)); - } else { - task.Reject(env, CreateJsError(env, ret, "kill process failed.")); - } - }; napi_value lastParam = (argc == ARGC_TWO && !hasClearPageStack) ? argv[INDEX_ONE] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnKillProcessByBundleName", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [bundleName, clearPageStack, abilityManager = abilityManager_, errCode, + env, task = napiAsyncTask.get()]() { + if (errCode != 0) { + task->Reject(env, CreateJsError(env, errCode, "Invalidate params.")); + } else { + OnKillProcessByBundleNameInner(bundleName, clearPageStack, abilityManager, env, task); + } + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) { + napiAsyncTask->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "send event failed")); + } else { + napiAsyncTask.release(); + } return result; } @@ -385,30 +417,35 @@ private: } } - NapiAsyncTask::CompleteCallback complete = - [bundleName, appManager = appManager_, errCode](napi_env env, NapiAsyncTask& task, - int32_t status) { + napi_value lastParam = (argc == ARGC_TWO) ? argv[INDEX_ONE] : nullptr; + napi_value result = nullptr; + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [bundleName, appManager = appManager_, errCode, env, task = napiAsyncTask.get()]() { if (errCode != 0) { - task.Reject(env, CreateJsError(env, errCode, "Invalidate params.")); + task->Reject(env, CreateJsError(env, errCode, "Invalidate params.")); + delete task; return; } if (appManager == nullptr) { TAG_LOGW(AAFwkTag::APPMGR, "appManager nullptr"); - task.Reject(env, CreateJsError(env, ERROR_CODE_ONE, "appManager nullptr")); + task->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "appManager nullptr")); + delete task; return; } auto ret = appManager->ClearUpApplicationData(bundleName, 0); if (ret == 0) { - task.Resolve(env, CreateJsValue(env, ret)); + task->Resolve(env, CreateJsValue(env, ret)); } else { - task.Reject(env, CreateJsError(env, ret, "clear up application failed.")); + task->Reject(env, CreateJsError(env, AAFwk::CLEAR_APPLICATION_DATA_FAIL, + "clear up application failed.")); } + delete task; }; - - napi_value lastParam = (argc == ARGC_TWO) ? argv[INDEX_ONE] : nullptr; - napi_value result = nullptr; - NapiAsyncTask::Schedule("JSAppManager::OnClearUpApplicationData", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_high)) { + napiAsyncTask->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "send event failed")); + } else { + napiAsyncTask.release(); + } return result; } @@ -445,27 +482,32 @@ private: TAG_LOGI(AAFwkTag::APPMGR, "kill [%{public}s], hasClearPageStack [%{public}d], clearPageStack [%{public}d],appIndex [%{public}d]", bundleName.c_str(), hasClearPageStack, clearPageStack, appIndex); - NapiAsyncTask::CompleteCallback complete = - [appManager = appManager_, bundleName, accountId, clearPageStack, errCode]( - napi_env env, NapiAsyncTask &task, int32_t status) { - if (errCode != 0) { - task.Reject(env, CreateJsError(env, errCode, "Invalidate params.")); - return; - } - auto ret = appManager->GetAmsMgr()->KillProcessWithAccount(bundleName, accountId, clearPageStack); - if (ret == 0) { - task.Resolve(env, CreateJsUndefined(env)); - } else { - TAG_LOGD(AAFwkTag::APPMGR, "failed error:%{public}d", ret); - task.Reject(env, CreateJsError(env, ret, "Kill processes failed.")); - } - }; napi_value lastParam = (argc == ARGC_THREE) ? argv[INDEX_TWO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnKillProcessWithAccount", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); - return result; + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [appManager = appManager_, bundleName, accountId, clearPageStack, errCode, + env, task = napiAsyncTask.get()]() { + if (errCode != 0) { + task->Reject(env, CreateJsError(env, errCode, "Invalidate params.")); + delete task; + return; + } + auto ret = appManager->GetAmsMgr()->KillProcessWithAccount(bundleName, accountId, clearPageStack); + if (ret == 0) { + task->Resolve(env, CreateJsUndefined(env)); + } else { + TAG_LOGD(AAFwkTag::APPMGR, "failed error:%{public}d", ret); + task->Reject(env, CreateJsError(env, ret, "Kill processes failed.")); + } + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) { + napiAsyncTask->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "send event failed")); + } else { + napiAsyncTask.release(); + } TAG_LOGD(AAFwkTag::APPMGR, "end"); + return result; } napi_value OnGetAppMemorySize(napi_env env, const size_t argc, napi_value* argv) @@ -477,26 +519,32 @@ private: TAG_LOGE(AAFwkTag::APPMGR, "Insufficient params"); errCode = ERR_NOT_OK; } - NapiAsyncTask::CompleteCallback complete = - [abilityManager = abilityManager_, errCode](napi_env env, NapiAsyncTask& task, int32_t status) { - if (errCode != 0) { - task.Reject(env, CreateJsError(env, errCode, "Invalidate params.")); - return; - } - if (abilityManager == nullptr) { - TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); - task.Reject(env, CreateJsError(env, ERROR_CODE_ONE, "abilityManager nullptr")); - return; - } - int32_t memorySize = abilityManager->GetAppMemorySize(); - TAG_LOGI(AAFwkTag::APPMGR, "memorySize:%{public}d", memorySize); - task.Resolve(env, CreateJsValue(env, memorySize)); - }; napi_value lastParam = (argc == ARGC_ONE) ? argv[INDEX_ZERO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnGetAppMemorySize", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [abilityManager = abilityManager_, errCode, env, task = napiAsyncTask.get()]() { + if (errCode != 0) { + task->Reject(env, CreateJsError(env, errCode, "Invalidate params.")); + delete task; + return; + } + if (abilityManager == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); + task->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "abilityManager nullptr")); + delete task; + return; + } + int32_t memorySize = abilityManager->GetAppMemorySize(); + TAG_LOGI(AAFwkTag::APPMGR, "memorySize:%{public}d", memorySize); + task->Resolve(env, CreateJsValue(env, memorySize)); + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) { + napiAsyncTask->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "send event failed")); + } else { + napiAsyncTask.release(); + } return result; } @@ -509,26 +557,32 @@ private: TAG_LOGE(AAFwkTag::APPMGR, "Not enough parameters"); errCode = ERR_NOT_OK; } - NapiAsyncTask::CompleteCallback complete = - [abilityManager = abilityManager_, errCode](napi_env env, NapiAsyncTask& task, int32_t status) { - if (errCode != 0) { - task.Reject(env, CreateJsError(env, errCode, "Invalidate params.")); - return; - } - if (abilityManager == nullptr) { - TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); - task.Reject(env, CreateJsError(env, ERROR_CODE_ONE, "abilityManager nullptr")); - return; - } - bool ret = abilityManager->IsRamConstrainedDevice(); - TAG_LOGI(AAFwkTag::APPMGR, "result:%{public}d", ret); - task.Resolve(env, CreateJsValue(env, ret)); - }; napi_value lastParam = (argc == ARGC_ONE) ? argv[INDEX_ZERO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnIsRamConstrainedDevice", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [abilityManager = abilityManager_, errCode, env, task = napiAsyncTask.get()]() { + if (errCode != 0) { + task->Reject(env, CreateJsError(env, errCode, "Invalidate params.")); + delete task; + return; + } + if (abilityManager == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); + task->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "abilityManager nullptr")); + delete task; + return; + } + bool ret = abilityManager->IsRamConstrainedDevice(); + TAG_LOGI(AAFwkTag::APPMGR, "result:%{public}d", ret); + task->Resolve(env, CreateJsValue(env, ret)); + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) { + napiAsyncTask->Reject(env, CreateJsError(env, ERROR_CODE_ONE, "send event failed")); + } else { + napiAsyncTask.release(); + } return result; } }; diff --git a/frameworks/js/napi/app/app_manager/js_app_manager_utils.cpp b/frameworks/js/napi/app/app_manager/js_app_manager_utils.cpp index c2cf72b895..bf44c08311 100644 --- a/frameworks/js/napi/app/app_manager/js_app_manager_utils.cpp +++ b/frameworks/js/napi/app/app_manager/js_app_manager_utils.cpp @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iapplication_state_observer.h" #include "js_runtime.h" #include "js_runtime_utils.h" 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 5fe5949d42..158069790f 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 @@ -15,7 +15,6 @@ #include "js_app_state_observer.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" #include "js_app_manager_utils.h" diff --git a/frameworks/js/napi/app/application_context/BUILD.gn b/frameworks/js/napi/app/application_context/BUILD.gn index ba02c84d4b..27c5067d6c 100644 --- a/frameworks/js/napi/app/application_context/BUILD.gn +++ b/frameworks/js/napi/app/application_context/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_application_context_abc") { diff --git a/frameworks/js/napi/app/application_state_change_callback/BUILD.gn b/frameworks/js/napi/app/application_state_change_callback/BUILD.gn index 3e1e18b17b..39fc58e92a 100644 --- a/frameworks/js/napi/app/application_state_change_callback/BUILD.gn +++ b/frameworks/js/napi/app/application_state_change_callback/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_application_state_change_callback_abc") { diff --git a/frameworks/js/napi/app/context/BUILD.gn b/frameworks/js/napi/app/context/BUILD.gn index fd9309805e..46d7a1c625 100644 --- a/frameworks/js/napi/app/context/BUILD.gn +++ b/frameworks/js/napi/app/context/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_context_abc") { diff --git a/frameworks/js/napi/app/environment_callback/BUILD.gn b/frameworks/js/napi/app/environment_callback/BUILD.gn index 5767d7c18a..4aefb70ebe 100644 --- a/frameworks/js/napi/app/environment_callback/BUILD.gn +++ b/frameworks/js/napi/app/environment_callback/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_environment_callback_abc") { 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 792c626ad0..e34dbf8345 100644 --- a/frameworks/js/napi/app/error_manager/js_error_manager.cpp +++ b/frameworks/js/napi/app/error_manager/js_error_manager.cpp @@ -22,7 +22,6 @@ #include "application_data_manager.h" #include "event_runner.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_error_observer.h" #include "js_error_utils.h" #include "js_runtime.h" @@ -541,7 +540,7 @@ private: loopObserver_ = nullptr; TAG_LOGI(AAFwkTag::JSNAPI, "Remove loopObserver success"); } else { - TAG_LOGI(AAFwkTag::JSNAPI, "Unregister loopObserver Called."); + TAG_LOGI(AAFwkTag::JSNAPI, "called"); } return nullptr; } diff --git a/frameworks/js/napi/app/error_manager/js_error_observer.cpp b/frameworks/js/napi/app/error_manager/js_error_observer.cpp index d537b83a52..f91cc62ce6 100644 --- a/frameworks/js/napi/app/error_manager/js_error_observer.cpp +++ b/frameworks/js/napi/app/error_manager/js_error_observer.cpp @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "js_runtime_utils.h" #include "napi/native_api.h" diff --git a/frameworks/js/napi/app/js_app_manager/js_ability_first_frame_state_observer.cpp b/frameworks/js/napi/app/js_app_manager/js_ability_first_frame_state_observer.cpp index 0d1f05b39e..94ffa00e39 100644 --- a/frameworks/js/napi/app/js_app_manager/js_ability_first_frame_state_observer.cpp +++ b/frameworks/js/napi/app/js_app_manager/js_ability_first_frame_state_observer.cpp @@ -48,7 +48,7 @@ void JSAbilityFirstFrameStateObserver::OnAbilityFirstFrameState( void JSAbilityFirstFrameStateObserver::HandleOnAbilityFirstFrameState( const AbilityFirstFrameStateData &AbilityFirstFrameStateData) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); napi_value obj = jsObserverObject_->GetNapiValue(); napi_value argv[] = { CreateJsAbilityFirstFrameStateData(env_, AbilityFirstFrameStateData) }; CallJsFunction(obj, "onAbilityFirstFrameDrawn", argv, ARGC_ONE); @@ -57,7 +57,7 @@ void JSAbilityFirstFrameStateObserver::HandleOnAbilityFirstFrameState( void JSAbilityFirstFrameStateObserver::CallJsFunction( const napi_value value, const char *methodName, const napi_value *argv, const size_t argc) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (value == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "value is nullptr."); return; @@ -128,7 +128,7 @@ bool JSAbilityFirstFrameStateObserverManager::IsObserverObjectExist(const napi_v void JSAbilityFirstFrameStateObserverManager::RemoveAllJsObserverObjects( sptr &abilityManager) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (abilityManager == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityManager is nullptr."); return; @@ -144,7 +144,7 @@ void JSAbilityFirstFrameStateObserverManager::RemoveAllJsObserverObjects( void JSAbilityFirstFrameStateObserverManager::RemoveJsObserverObject( sptr &abilityManager, const napi_value &jsObserverObject) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (abilityManager == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityManager is nullptr."); return; 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 6b33ee615a..9fac524d68 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 @@ -27,7 +27,7 @@ JSAppForegroundStateObserver::JSAppForegroundStateObserver(napi_env env) : env_( void JSAppForegroundStateObserver::OnAppStateChanged(const AppStateData &appStateData) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!valid_) { TAG_LOGE(AAFwkTag::APPMGR, "The app manager may has destroyed."); return; @@ -49,7 +49,7 @@ void JSAppForegroundStateObserver::OnAppStateChanged(const AppStateData &appStat void JSAppForegroundStateObserver::HandleOnAppStateChanged(const AppStateData &appStateData) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::lock_guard lock(jsObserverObjectSetLock_); for (auto &item : jsObserverObjectSet_) { napi_value obj = item->GetNapiValue(); 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 2f19d98cf3..91252800a7 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 @@ -26,7 +26,6 @@ #include "application_info.h" #include "event_runner.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" @@ -343,7 +342,7 @@ private: napi_value OnOnForeground(napi_env env, size_t argc, napi_value *argv) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (argc < ARGC_TWO) { TAG_LOGE(AAFwkTag::APPMGR, "Not enough params."); ThrowTooFewParametersError(env); @@ -482,6 +481,23 @@ private: return CreateJsUndefined(env); } #endif + static void OnOffOldInner(sptr appManager, sptr observer, + int64_t observerId, napi_env env, NapiAsyncTask *task) + { + if (observer == nullptr || appManager == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "observer or appManager nullptr"); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + return; + } + int32_t ret = appManager->UnregisterApplicationStateObserver(observer); + if (ret == 0 && observer->RemoveJsObserverObject(observerId)) { + task->ResolveWithNoError(env, CreateJsUndefined(env)); + TAG_LOGD(AAFwkTag::APPMGR, "success size:%{public}zu", observer->GetJsObserverMapSize()); + } else { + TAG_LOGE(AAFwkTag::APPMGR, "failed error:%{public}d", ret); + task->Reject(env, CreateJsErrorByNativeErr(env, ret)); + } + } napi_value OnOffOld(napi_env env, size_t argc, napi_value* argv) { @@ -511,29 +527,20 @@ private: } TAG_LOGD(AAFwkTag::APPMGR, "find observer exist observer:%{public}d", static_cast(observerId)); - NapiAsyncTask::CompleteCallback complete = - [appManager = appManager_, observer = observer_, observerId]( - napi_env env, NapiAsyncTask& task, int32_t status) { - if (observer == nullptr || appManager == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "observer or appManager nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - int32_t ret = appManager->UnregisterApplicationStateObserver(observer); - if (ret == 0 && observer->RemoveJsObserverObject(observerId)) { - task.ResolveWithNoError(env, CreateJsUndefined(env)); - TAG_LOGD(AAFwkTag::APPMGR, "success size:%{public}zu", - observer->GetJsObserverMapSize()); - } else { - TAG_LOGE(AAFwkTag::APPMGR, "failed error:%{public}d", ret); - task.Reject(env, CreateJsErrorByNativeErr(env, ret)); - } - }; - napi_value lastParam = (argc > ARGC_TWO) ? argv[INDEX_TWO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::Schedule("JSAppManager::OnUnregisterApplicationStateObserver", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [appManager = appManager_, observer = observer_, observerId, + env, task = napiAsyncTask.get()]() { + OnOffOldInner(appManager, observer, observerId, env, task); + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_high)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } @@ -575,7 +582,7 @@ private: napi_value OnOffForeground(napi_env env, size_t argc, napi_value *argv) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::APPMGR, "Not enough params when off."); ThrowTooFewParametersError(env); @@ -611,54 +618,66 @@ private: napi_value OnGetForegroundApplications(napi_env env, size_t argc, napi_value *argv) { TAG_LOGD(AAFwkTag::APPMGR, "called"); - NapiAsyncTask::CompleteCallback complete = - [appManager = appManager_](napi_env env, NapiAsyncTask& task, int32_t status) { - if (appManager == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "appManager nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - std::vector list; - int32_t ret = appManager->GetForegroundApplications(list); - if (ret == 0) { - TAG_LOGD(AAFwkTag::APPMGR, "success."); - task.ResolveWithNoError(env, CreateJsAppStateDataArray(env, list)); - } else { - TAG_LOGE(AAFwkTag::APPMGR, "failed error:%{public}d", ret); - task.Reject(env, CreateJsError(env, GetJsErrorCodeByNativeError(ret))); - } - }; napi_value lastParam = (argc > ARGC_ZERO) ? argv[INDEX_ZERO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::Schedule("JSAppManager::OnGetForegroundApplications", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [appManager = appManager_, env, task = napiAsyncTask.get()]() { + if (appManager == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "appManager nullptr"); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + delete task; + return; + } + std::vector list; + int32_t ret = appManager->GetForegroundApplications(list); + if (ret == 0) { + TAG_LOGD(AAFwkTag::APPMGR, "success."); + task->ResolveWithNoError(env, CreateJsAppStateDataArray(env, list)); + } else { + TAG_LOGE(AAFwkTag::APPMGR, "failed error:%{public}d", ret); + task->Reject(env, CreateJsError(env, GetJsErrorCodeByNativeError(ret))); + } + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_high)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } napi_value OnGetRunningProcessInformation(napi_env env, size_t argc, napi_value* argv) { TAG_LOGD(AAFwkTag::APPMGR, "called"); - NapiAsyncTask::CompleteCallback complete = - [appManager = appManager_](napi_env env, NapiAsyncTask &task, int32_t status) { - if (appManager == nullptr) { - TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - std::vector infos; - auto ret = appManager->GetAllRunningProcesses(infos); - if (ret == 0) { - task.ResolveWithNoError(env, CreateJsRunningProcessInfoArray(env, infos)); - } else { - task.Reject(env, CreateJsError(env, GetJsErrorCodeByNativeError(ret))); - } - }; napi_value lastParam = (argc > ARGC_ZERO) ? argv[INDEX_ZERO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::Schedule("JSAppManager::OnGetRunningProcessInformation", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [appManager = appManager_, env, task = napiAsyncTask.get()]() { + if (appManager == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + delete task; + return; + } + std::vector infos; + auto ret = appManager->GetAllRunningProcesses(infos); + if (ret == 0) { + task->ResolveWithNoError(env, CreateJsRunningProcessInfoArray(env, infos)); + } else { + task->Reject(env, CreateJsError(env, GetJsErrorCodeByNativeError(ret))); + } + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_high)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } @@ -729,52 +748,78 @@ private: ThrowInvalidParamError(env, "Parse param bundleType failed, must not be less then zero."); return CreateJsUndefined(env); } - NapiAsyncTask::CompleteCallback complete = - [appManager = appManager_, bundleType](napi_env env, NapiAsyncTask &task, int32_t status) { - if (appManager == nullptr) { - TAG_LOGW(AAFwkTag::APPMGR, "appManager nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - std::vector infos; - auto ret = appManager->GetRunningProcessesByBundleType( - static_cast(bundleType), infos); - if (ret == 0) { - task.ResolveWithNoError(env, CreateJsRunningProcessInfoArray(env, infos)); - } else { - task.Reject(env, CreateJsError(env, GetJsErrorCodeByNativeError(ret))); - } - }; napi_value lastParam = (argc > ARGC_ONE) ? argv[INDEX_ONE] : nullptr; napi_value result = nullptr; - NapiAsyncTask::Schedule("JSAppManager::OnGetRunningProcessInformationByBundleType", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [appManager = appManager_, bundleType, env, task = napiAsyncTask.get()]() { + if (appManager == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "appManager nullptr"); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + delete task; + return; + } + std::vector infos; + auto ret = appManager->GetRunningProcessesByBundleType( + static_cast(bundleType), infos); + if (ret == 0) { + task->ResolveWithNoError(env, CreateJsRunningProcessInfoArray(env, infos)); + } else { + task->Reject(env, CreateJsError(env, GetJsErrorCodeByNativeError(ret))); + } + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_high)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } napi_value OnIsRunningInStabilityTest(napi_env env, size_t argc, napi_value* argv) { TAG_LOGD(AAFwkTag::APPMGR, "called"); - NapiAsyncTask::CompleteCallback complete = - [abilityManager = abilityManager_](napi_env env, NapiAsyncTask& task, int32_t status) { - if (abilityManager == nullptr) { - TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - bool ret = abilityManager->IsRunningInStabilityTest(); - TAG_LOGD(AAFwkTag::APPMGR, "result:%{public}d", ret); - task.ResolveWithNoError(env, CreateJsValue(env, ret)); - }; - napi_value lastParam = (argc > ARGC_ZERO) ? argv[INDEX_ZERO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::Schedule("JSAppManager::OnIsRunningInStabilityTest", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [abilityManager = abilityManager_, env, task = napiAsyncTask.get()]() { + if (abilityManager == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + delete task; + return; + } + bool ret = abilityManager->IsRunningInStabilityTest(); + TAG_LOGD(AAFwkTag::APPMGR, "result:%{public}d", ret); + task->ResolveWithNoError(env, CreateJsValue(env, ret)); + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_high)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } + static void OnKillProcessesByBundleNameInner(std::string bundleName, bool clearPageStack, + sptr abilityManager, napi_env env, NapiAsyncTask *task) + { + if (abilityManager == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + return; + } + auto ret = abilityManager->KillProcess(bundleName, clearPageStack); + if (ret == 0) { + task->ResolveWithNoError(env, CreateJsUndefined(env)); + } else { + task->Reject(env, CreateJsErrorByNativeErr(env, ret, "kill process failed.")); + } + } napi_value OnKillProcessesByBundleName(napi_env env, size_t argc, napi_value* argv) { TAG_LOGD(AAFwkTag::APPMGR, "OnKillProcessesByBundleName called"); @@ -803,25 +848,20 @@ private: TAG_LOGI(AAFwkTag::APPMGR, "kill [%{public}s], hasClearPageStack [%{public}d], clearPageStack [%{public}d],appIndex [%{public}d]", bundleName.c_str(), hasClearPageStack, clearPageStack, appIndex); - NapiAsyncTask::CompleteCallback complete = - [bundleName, clearPageStack, abilityManager = abilityManager_]( - napi_env env, NapiAsyncTask& task, int32_t status) { - if (abilityManager == nullptr) { - TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - auto ret = abilityManager->KillProcess(bundleName, clearPageStack); - if (ret == 0) { - task.ResolveWithNoError(env, CreateJsUndefined(env)); - } else { - task.Reject(env, CreateJsErrorByNativeErr(env, ret, "kill process failed.")); - } - }; napi_value lastParam = (argc == ARGC_TWO && !hasClearPageStack) ? argv[INDEX_ONE] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnKillProcessesByBundleName", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [bundleName, clearPageStack, abilityManager = abilityManager_, + env, task = napiAsyncTask.get()]() { + OnKillProcessesByBundleNameInner(bundleName, clearPageStack, abilityManager, env, task); + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } @@ -841,25 +881,30 @@ private: return CreateJsUndefined(env); } - NapiAsyncTask::CompleteCallback complete = - [bundleName, appManager = appManager_](napi_env env, NapiAsyncTask& task, int32_t status) { + napi_value lastParam = (argc == ARGC_TWO) ? argv[INDEX_ONE] : nullptr; + napi_value result = nullptr; + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [bundleName, appManager = appManager_, env, task = napiAsyncTask.get()]() { if (appManager == nullptr) { TAG_LOGW(AAFwkTag::APPMGR, "appManager nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + delete task; return; } auto ret = appManager->ClearUpApplicationData(bundleName, 0); if (ret == 0) { - task.ResolveWithNoError(env, CreateJsUndefined(env)); + task->ResolveWithNoError(env, CreateJsUndefined(env)); } else { - task.Reject(env, CreateJsErrorByNativeErr(env, ret, "clear up application failed.")); + task->Reject(env, CreateJsErrorByNativeErr(env, ret, "clear up application failed.")); } + delete task; }; - - napi_value lastParam = (argc == ARGC_TWO) ? argv[INDEX_ONE] : nullptr; - napi_value result = nullptr; - NapiAsyncTask::Schedule("JSAppManager::OnClearUpApplicationData", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_high)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } @@ -885,24 +930,29 @@ private: return CreateJsUndefined(env); } - NapiAsyncTask::CompleteCallback complete = - [bundleName, appCloneIndex, appManager = appManager_](napi_env env, NapiAsyncTask& task, int32_t status) { + napi_value result = nullptr; + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, nullptr, &result); + auto asyncTask = [bundleName, appCloneIndex, appManager = appManager_, env, task = napiAsyncTask.get()]() { if (appManager == nullptr) { TAG_LOGW(AAFwkTag::APPMGR, "appManager nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + delete task; return; } auto ret = appManager->ClearUpApplicationData(bundleName, appCloneIndex); if (ret == 0) { - task.ResolveWithNoError(env, CreateJsUndefined(env)); + task->ResolveWithNoError(env, CreateJsUndefined(env)); } else { - task.Reject(env, CreateJsErrorByNativeErr(env, ret, "clear up application failed.")); + task->Reject(env, CreateJsErrorByNativeErr(env, ret, "clear up application failed.")); } + delete task; }; - - napi_value result = nullptr; - NapiAsyncTask::Schedule("JSAppManager::OnClearUpAppData", - env, CreateAsyncTaskWithLastParam(env, nullptr, nullptr, std::move(complete), &result)); + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_high)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } @@ -929,22 +979,27 @@ private: return CreateJsUndefined(env); } - NapiAsyncTask::CompleteCallback complete = - [bundleName, versionCode, appManager = appManager_](napi_env env, NapiAsyncTask& task, int32_t status) { + napi_value lastParam = (argc == ARGC_THREE) ? argv[INDEX_TWO] : nullptr; + napi_value result = nullptr; + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [bundleName, versionCode, appManager = appManager_, env, task = napiAsyncTask.get()]() { if (appManager == nullptr) { TAG_LOGW(AAFwkTag::APPMGR, "appManager nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + delete task; return; } bool ret = appManager->IsSharedBundleRunning(bundleName, versionCode); TAG_LOGI(AAFwkTag::APPMGR, "result:%{public}d", ret); - task.ResolveWithNoError(env, CreateJsValue(env, ret)); + task->ResolveWithNoError(env, CreateJsValue(env, ret)); + delete task; }; - - napi_value lastParam = (argc == ARGC_THREE) ? argv[INDEX_TWO] : nullptr; - napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnIsSharedBundleRunning", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } @@ -981,67 +1036,83 @@ private: TAG_LOGI(AAFwkTag::APPMGR, "kill [%{public}s], hasClearPageStack [%{public}d], clearPageStack [%{public}d],appIndex [%{public}d]", bundleName.c_str(), hasClearPageStack, clearPageStack, appIndex); - NapiAsyncTask::CompleteCallback complete = - [appManager = appManager_, bundleName, accountId, clearPageStack]( - napi_env env, NapiAsyncTask &task, int32_t status) { - if (appManager == nullptr || appManager->GetAmsMgr() == nullptr) { - TAG_LOGW(AAFwkTag::APPMGR, "appManager is nullptr or amsMgr is nullptr."); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - auto ret = appManager->GetAmsMgr()->KillProcessWithAccount(bundleName, accountId, clearPageStack); - if (ret == 0) { - task.ResolveWithNoError(env, CreateJsUndefined(env)); - } else { - task.Reject(env, CreateJsErrorByNativeErr(env, ret, "Kill processes failed.")); - } - }; napi_value lastParam = (argc == ARGC_THREE && !hasClearPageStack) ? argv[INDEX_TWO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnKillProcessWithAccount", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [appManager = appManager_, bundleName, accountId, clearPageStack, + env, task = napiAsyncTask.get()]() { + if (appManager == nullptr || appManager->GetAmsMgr() == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "appManager is nullptr or amsMgr is nullptr."); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + delete task; + return; + } + auto ret = appManager->GetAmsMgr()->KillProcessWithAccount(bundleName, accountId, clearPageStack); + if (ret == 0) { + task->ResolveWithNoError(env, CreateJsUndefined(env)); + } else { + task->Reject(env, CreateJsErrorByNativeErr(env, ret, "Kill processes failed.")); + } + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } napi_value OnGetAppMemorySize(napi_env env, size_t argc, napi_value* argv) { - NapiAsyncTask::CompleteCallback complete = - [abilityManager = abilityManager_](napi_env env, NapiAsyncTask& task, int32_t status) { - if (abilityManager == nullptr) { - TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - int32_t memorySize = abilityManager->GetAppMemorySize(); - TAG_LOGI(AAFwkTag::APPMGR, "memorySize:%{public}d", memorySize); - task.ResolveWithNoError(env, CreateJsValue(env, memorySize)); - }; - napi_value lastParam = (argc > ARGC_ZERO) ? argv[INDEX_ZERO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnGetAppMemorySize", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [abilityManager = abilityManager_, env, task = napiAsyncTask.get()]() { + if (abilityManager == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + delete task; + return; + } + int32_t memorySize = abilityManager->GetAppMemorySize(); + TAG_LOGI(AAFwkTag::APPMGR, "memorySize:%{public}d", memorySize); + task->ResolveWithNoError(env, CreateJsValue(env, memorySize)); + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } napi_value OnIsRamConstrainedDevice(napi_env env, size_t argc, napi_value* argv) { - NapiAsyncTask::CompleteCallback complete = - [abilityManager = abilityManager_](napi_env env, NapiAsyncTask& task, int32_t status) { - if (abilityManager == nullptr) { - TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - bool ret = abilityManager->IsRamConstrainedDevice(); - TAG_LOGI(AAFwkTag::APPMGR, "result:%{public}d", ret); - task.ResolveWithNoError(env, CreateJsValue(env, ret)); - }; - napi_value lastParam = (argc > ARGC_ZERO) ? argv[INDEX_ZERO] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnIsRamConstrainedDevice", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [abilityManager = abilityManager_, env, task = napiAsyncTask.get()]() { + if (abilityManager == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "abilityManager nullptr"); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + delete task; + return; + } + bool ret = abilityManager->IsRamConstrainedDevice(); + TAG_LOGI(AAFwkTag::APPMGR, "result:%{public}d", ret); + task->ResolveWithNoError(env, CreateJsValue(env, ret)); + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } @@ -1061,29 +1132,50 @@ private: return CreateJsUndefined(env); } - NapiAsyncTask::CompleteCallback complete = - [pid, appManager = appManager_](napi_env env, NapiAsyncTask &task, int32_t status) { - if (appManager == nullptr) { - TAG_LOGW(AAFwkTag::APPMGR, "appManager is nullptr"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - int32_t memSize = 0; - int32_t ret = appManager->GetProcessMemoryByPid(pid, memSize); - if (ret == 0) { - task.ResolveWithNoError(env, CreateJsValue(env, memSize)); - } else { - task.Reject(env, CreateJsErrorByNativeErr(env, ret)); - } - }; - napi_value lastParam = (argc == ARGC_TWO) ? argv[INDEX_ONE] : nullptr; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnGetProcessMemoryByPid", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [pid, appManager = appManager_, env, task = napiAsyncTask.get()]() { + if (appManager == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "appManager is nullptr"); + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + delete task; + return; + } + int32_t memSize = 0; + int32_t ret = appManager->GetProcessMemoryByPid(pid, memSize); + if (ret == 0) { + task->ResolveWithNoError(env, CreateJsValue(env, memSize)); + } else { + task->Reject(env, CreateJsErrorByNativeErr(env, ret)); + } + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } + static void OnGetRunningProcessInfoByBundleNameInner(std::string bundleName, int userId, + sptr appManager, napi_env env, NapiAsyncTask *task) + { + if (appManager == nullptr) { + task->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + return; + } + std::vector infos; + int32_t ret = appManager->GetRunningProcessInformation(bundleName, userId, infos); + if (ret == 0) { + task->ResolveWithNoError(env, CreateJsRunningProcessInfoArray(env, infos)); + } else { + task->Reject(env, CreateJsErrorByNativeErr(env, ret)); + } + } + napi_value OnGetRunningProcessInfoByBundleName(napi_env env, size_t argc, napi_value* argv) { if (argc < ARGC_ONE) { @@ -1116,30 +1208,25 @@ private: return CreateJsUndefined(env); } - NapiAsyncTask::CompleteCallback complete = - [bundleName, userId, appManager = appManager_](napi_env env, NapiAsyncTask &task, int32_t status) { - if (appManager == nullptr) { - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - std::vector infos; - int32_t ret = appManager->GetRunningProcessInformation(bundleName, userId, infos); - if (ret == 0) { - task.ResolveWithNoError(env, CreateJsRunningProcessInfoArray(env, infos)); - } else { - task.Reject(env, CreateJsErrorByNativeErr(env, ret)); - } - }; napi_value lastParam = isPromiseType ? nullptr : argv[argc - 1]; napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JSAppManager::OnGetRunningProcessInfoByBundleName", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + std::unique_ptr napiAsyncTask = CreateEmptyAsyncTask(env, lastParam, &result); + auto asyncTask = [bundleName, userId, appManager = appManager_, env, task = napiAsyncTask.get()]() { + OnGetRunningProcessInfoByBundleNameInner(bundleName, userId, appManager, env, task); + delete task; + }; + if (napi_status::napi_ok != napi_send_event(env, asyncTask, napi_eprio_immediate)) { + napiAsyncTask->Reject(env, CreateJsErrorByNativeErr(env, + static_cast(AbilityErrorCode::ERROR_CODE_INNER), "send event failed!")); + } else { + napiAsyncTask.release(); + } return result; } napi_value OnIsApplicationRunning(napi_env env, size_t argc, napi_value *argv) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::APPMGR, "Params not match."); ThrowTooFewParametersError(env); @@ -1184,7 +1271,7 @@ private: napi_value OnIsAppRunning(napi_env env, size_t argc, napi_value *argv) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::APPMGR, "Params not match."); ThrowTooFewParametersError(env); 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 f2f016bfe7..441b97bcc4 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 @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iapplication_state_observer.h" #include "js_runtime.h" #include "js_runtime_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 de7aa3cc66..1ee9d18357 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 @@ -15,7 +15,6 @@ #include "js_app_state_observer.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" #include "js_app_manager_utils.h" diff --git a/frameworks/js/napi/app/recovery/app_recovery_api.cpp b/frameworks/js/napi/app/recovery/app_recovery_api.cpp index 5c4d5d7fc6..a99b26c018 100644 --- a/frameworks/js/napi/app/recovery/app_recovery_api.cpp +++ b/frameworks/js/napi/app/recovery/app_recovery_api.cpp @@ -17,7 +17,6 @@ #include "app_recovery.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "js_runtime_utils.h" diff --git a/frameworks/js/napi/app/sendable_context_manager/BUILD.gn b/frameworks/js/napi/app/sendable_context_manager/BUILD.gn new file mode 100644 index 0000000000..a71acf76a6 --- /dev/null +++ b/frameworks/js/napi/app/sendable_context_manager/BUILD.gn @@ -0,0 +1,62 @@ +# 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") + +ohos_shared_library("sendablecontextmanager_napi") { + 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_napi_path}/ability_auto_startup_callback", + "${ability_runtime_path}/interfaces/kits/native/ability/native/ability_runtime", + ] + + sources = [ + "js_sendable_context_manager.cpp", + "native_module.cpp", + ] + + configs = [ "${ability_runtime_services_path}/common:common_config" ] + + deps = [ + "${ability_runtime_innerkits_path}/napi_base_context:napi_base_context", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_napi_path}/inner/napi_common:napi_common", + "${ability_runtime_native_path}/ability:ability_context_native", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/appkit:app_context", + "${ability_runtime_native_path}/appkit:app_context_utils", + "${ability_runtime_native_path}/appkit:appkit_native", + ] + + external_deps = [ + "ability_base:want", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "hilog:libhilog", + "napi:ace_napi", + ] + + relative_install_dir = "module/app/ability" + subsystem_name = "ability" + part_name = "ability_runtime" +} diff --git a/frameworks/js/napi/app/sendable_context_manager/js_sendable_context_manager.cpp b/frameworks/js/napi/app/sendable_context_manager/js_sendable_context_manager.cpp new file mode 100644 index 0000000000..6228410bf9 --- /dev/null +++ b/frameworks/js/napi/app/sendable_context_manager/js_sendable_context_manager.cpp @@ -0,0 +1,433 @@ +/* + * 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 "js_sendable_context_manager.h" + +#include "ability_context.h" +#include "ability_stage_context.h" +#include "application_context.h" +#include "context.h" +#include "js_ability_context.h" +#include "js_ability_stage_context.h" +#include "js_application_context_utils.h" +#include "js_context_utils.h" +#include "js_error_utils.h" +#include "js_runtime_utils.h" +#include "hilog_tag_wrapper.h" +#include "napi_base_context.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr size_t ARGC_ONE = 1; +} // namespace + +class JsContext { +public: + explicit JsContext(std::weak_ptr&& context) : context_(std::move(context)) {} + virtual ~JsContext() = default; + + static void Finalizer(napi_env env, void* data, void* hint); + + std::weak_ptr context_; +}; + +void JsContext::Finalizer(napi_env env, void* data, void* hint) +{ + TAG_LOGD(AAFwkTag::CONTEXT, "JsContext finalizer."); + if (data == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Input data invalid."); + return; + } + std::unique_ptr(static_cast(data)); +} + +napi_value CreateSendableContextObject(napi_env env, std::shared_ptr context) +{ + auto jsContext = std::make_unique(context); + napi_value objValue = nullptr; + auto status = napi_ok; + // Sendable context has no property for now. + status = napi_create_sendable_object_with_properties(env, 0, nullptr, &objValue); + if (status != napi_ok) { + TAG_LOGE(AAFwkTag::CONTEXT, "Create sendable context failed with %{public}d.", status); + return nullptr; + } + + status = napi_wrap_sendable(env, objValue, jsContext.release(), JsContext::Finalizer, nullptr); + if (status != napi_ok) { + TAG_LOGE(AAFwkTag::CONTEXT, "Wrap sendable failed with %{public}d.", status); + return nullptr; + } + + return objValue; +} + +napi_value CreateJsBaseContextFromSendable(napi_env env, void* wrapped) +{ + JsContext *sendableContext = static_cast(wrapped); + if (sendableContext == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Get sendable context failed."); + return nullptr; + } + + auto weakContext = sendableContext->context_; + std::shared_ptr context = weakContext.lock(); + if (context == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Context invalid."); + return nullptr; + } + + auto contextPtr = Context::ConvertTo(context); + if (contextPtr == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Convert to context failed."); + return nullptr; + } + + // create normal context + auto value = CreateJsBaseContext(env, contextPtr); + auto systemModule = JsRuntime::LoadSystemModuleByEngine(env, "application.Context", &value, 1); + if (systemModule == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Load context module failed."); + return nullptr; + } + + return systemModule->GetNapiValue(); +} + +napi_value CreateJsApplicationContextFromSendable(napi_env env, void* wrapped) +{ + JsContext *sendableContext = static_cast(wrapped); + if (sendableContext == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Get sendable context failed."); + return nullptr; + } + + auto weakContext = sendableContext->context_; + std::shared_ptr context = weakContext.lock(); + if (context == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Context invalid."); + return nullptr; + } + + auto applicationContext = Context::ConvertTo(context); + if (applicationContext == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Convert to application context failed."); + return nullptr; + } + + // create application context + auto value = JsApplicationContextUtils::CreateJsApplicationContext(env); + auto systemModule = JsRuntime::LoadSystemModuleByEngine(env, "application.ApplicationContext", &value, 1); + if (systemModule == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Load application context module failed."); + return nullptr; + } + + return systemModule->GetNapiValue(); +} + +napi_value CreateJsAbilityStageContextFromSendable(napi_env env, void* wrapped) +{ + JsContext *sendableContext = static_cast(wrapped); + if (sendableContext == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Get sendable context failed."); + return nullptr; + } + + auto weakContext = sendableContext->context_; + std::shared_ptr context = weakContext.lock(); + if (context == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Context invalid."); + return nullptr; + } + + auto abilitystageContext = Context::ConvertTo(context); + if (abilitystageContext == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Convert to ability stage context failed."); + return nullptr; + } + + // create normal abilitystage context + auto value = CreateJsAbilityStageContext(env, abilitystageContext); + auto systemModule = JsRuntime::LoadSystemModuleByEngine(env, "application.AbilityStageContext", &value, 1); + if (systemModule == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Load ability stage context module failed."); + return nullptr; + } + + return systemModule->GetNapiValue(); +} + +napi_value CreateJsUIAbilityContextFromSendable(napi_env env, void* wrapped) +{ + JsContext *sendableContext = static_cast(wrapped); + if (sendableContext == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Get sendable context failed."); + return nullptr; + } + + auto weakContext = sendableContext->context_; + std::shared_ptr context = weakContext.lock(); + if (context == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Context invalid."); + return nullptr; + } + + auto uiAbilityContext = Context::ConvertTo(context); + if (uiAbilityContext == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Convert to UIAbility context failed."); + return nullptr; + } + + // create normal uiability context + auto value = CreateJsAbilityContext(env, uiAbilityContext); + auto systemModule = JsRuntime::LoadSystemModuleByEngine(env, "application.AbilityContext", &value, 1); + if (systemModule == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Load ability context module failed."); + return nullptr; + } + + return systemModule->GetNapiValue(); +} + +class JsSendableContextManager { +public: + JsSendableContextManager() = default; + ~JsSendableContextManager() = default; + + static void Finalizer(napi_env env, void *data, void *hint) + { + TAG_LOGD(AAFwkTag::CONTEXT, "JsSendableContextManager finalizer."); + if (data == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Input data invalid."); + return; + } + std::unique_ptr(static_cast(data)); + } + + static napi_value ConvertFromContext(napi_env env, napi_callback_info info) + { + GET_NAPI_INFO_AND_CALL(env, info, JsSendableContextManager, OnConvertFromContext); + } + + static napi_value ConvertToContext(napi_env env, napi_callback_info info) + { + GET_NAPI_INFO_AND_CALL(env, info, JsSendableContextManager, OnConvertToContext); + } + + static napi_value ConvertToApplicationContext(napi_env env, napi_callback_info info) + { + GET_NAPI_INFO_AND_CALL(env, info, JsSendableContextManager, OnConvertToApplicationContext); + } + + static napi_value ConvertToAbilityStageContext(napi_env env, napi_callback_info info) + { + GET_NAPI_INFO_AND_CALL(env, info, JsSendableContextManager, OnConvertToAbilityStageContext); + } + + static napi_value ConvertToUIAbilityContext(napi_env env, napi_callback_info info) + { + GET_NAPI_INFO_AND_CALL(env, info, JsSendableContextManager, OnConvertToUIAbilityContext); + } + +private: + napi_value OnConvertFromContext(napi_env env, NapiCallbackInfo &info) + { + TAG_LOGD(AAFwkTag::CONTEXT, "Convert from context."); + if (info.argc != ARGC_ONE) { + TAG_LOGE(AAFwkTag::CONTEXT, "The number of parameter is invalid."); + ThrowInvalidParamError(env, "Parameter error: The number of parameter is invalid."); + return CreateJsUndefined(env); + } + + // Get native context + bool stageMode = false; + napi_status status = IsStageContext(env, info.argv[0], stageMode); + if (status != napi_ok || !stageMode) { + TAG_LOGE(AAFwkTag::CONTEXT, "Context isn't stageMode, status is %{public}d.", status); + ThrowInvalidParamError(env, "Parse param context failed, must be a context of stageMode."); + return CreateJsUndefined(env); + } + + auto context = GetStageModeContext(env, info.argv[0]); + if (context == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Get context failed"); + ThrowInvalidParamError(env, "Parse param context failed, must not be nullptr."); + return CreateJsUndefined(env); + } + + auto contextPtr = Context::ConvertTo(context); + if (contextPtr == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Convert to context failed."); + ThrowInvalidParamError(env, "Parse param context failed, must be a context."); + return CreateJsUndefined(env); + } + + // create sendable context + return CreateSendableContextObject(env, contextPtr); + } + + napi_value OnConvertToContext(napi_env env, NapiCallbackInfo &info) + { + TAG_LOGD(AAFwkTag::CONTEXT, "Convert to context."); + if (info.argc != ARGC_ONE) { + TAG_LOGE(AAFwkTag::CONTEXT, "The number of parameter is invalid."); + ThrowInvalidParamError(env, "Parameter error: The number of parameter is invalid."); + return CreateJsUndefined(env); + } + + // Get context + void *wrapped = nullptr; + auto status = napi_unwrap_sendable(env, info.argv[0], &wrapped); + if (status != napi_ok) { + TAG_LOGE(AAFwkTag::CONTEXT, "Unwrap sendable object failed with %{public}d.", status); + ThrowInvalidParamError(env, "Parameter error: Input parameter is invalid."); + return CreateJsUndefined(env); + } + + // Create normal context + auto object = CreateJsBaseContextFromSendable(env, wrapped); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Create base context failed."); + ThrowInvalidParamError(env, "Parameter error: Create context failed."); + return CreateJsUndefined(env); + } + + return object; + } + + napi_value OnConvertToApplicationContext(napi_env env, NapiCallbackInfo &info) + { + TAG_LOGD(AAFwkTag::CONTEXT, "Convert to application context."); + if (info.argc != ARGC_ONE) { + TAG_LOGE(AAFwkTag::CONTEXT, "The number of parameter is invalid."); + ThrowInvalidParamError(env, "Parameter error: The number of parameter is invalid."); + return CreateJsUndefined(env); + } + + // Get context + void *wrapped = nullptr; + auto status = napi_unwrap_sendable(env, info.argv[0], &wrapped); + if (status != napi_ok) { + TAG_LOGE(AAFwkTag::CONTEXT, "Unwrap sendable object failed with %{public}d.", status); + ThrowInvalidParamError(env, "Parameter error: Input parameter is invalid."); + return CreateJsUndefined(env); + } + + // Create normal context + auto object = CreateJsApplicationContextFromSendable(env, wrapped); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Create base context failed."); + ThrowInvalidParamError(env, "Parameter error: Create application context failed."); + return CreateJsUndefined(env); + } + + return object; + } + + napi_value OnConvertToAbilityStageContext(napi_env env, NapiCallbackInfo &info) + { + TAG_LOGD(AAFwkTag::CONTEXT, "Convert to ability stage context."); + if (info.argc != ARGC_ONE) { + TAG_LOGE(AAFwkTag::CONTEXT, "The number of parameter is invalid."); + ThrowInvalidParamError(env, "Parameter error: The number of parameter is invalid."); + return CreateJsUndefined(env); + } + + // Get context + void *wrapped = nullptr; + auto status = napi_unwrap_sendable(env, info.argv[0], &wrapped); + if (status != napi_ok) { + TAG_LOGE(AAFwkTag::CONTEXT, "Unwrap sendable object failed with %{public}d.", status); + ThrowInvalidParamError(env, "Parameter error: Input parameter is invalid."); + return CreateJsUndefined(env); + } + + // Create normal context + auto object = CreateJsAbilityStageContextFromSendable(env, wrapped); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Create base context failed."); + ThrowInvalidParamError(env, "Parameter error: Create ability stage context failed."); + return CreateJsUndefined(env); + } + + return object; + } + + napi_value OnConvertToUIAbilityContext(napi_env env, NapiCallbackInfo &info) + { + TAG_LOGD(AAFwkTag::CONTEXT, "Convert to uiability context."); + if (info.argc != ARGC_ONE) { + TAG_LOGE(AAFwkTag::CONTEXT, "The number of parameter is invalid."); + ThrowInvalidParamError(env, "Parameter error: The number of parameter is invalid."); + return CreateJsUndefined(env); + } + + // Get context + void *wrapped = nullptr; + auto status = napi_unwrap_sendable(env, info.argv[0], &wrapped); + if (status != napi_ok) { + TAG_LOGE(AAFwkTag::CONTEXT, "Unwrap sendable object failed with %{public}d.", status); + ThrowInvalidParamError(env, "Parameter error: Input parameter is invalid."); + return CreateJsUndefined(env); + } + + // Create uiability context + auto object = CreateJsUIAbilityContextFromSendable(env, wrapped); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Create uiability context failed."); + ThrowInvalidParamError(env, "Parameter error: Create uiability context failed."); + return CreateJsUndefined(env); + } + + return object; + } +}; + +napi_value CreateJsSendableContextManager(napi_env env, napi_value exportObj) +{ + TAG_LOGD(AAFwkTag::CONTEXT, "Create sendable context manager."); + if (env == nullptr || exportObj == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "Invalid parameter."); + return nullptr; + } + + napi_status status = napi_ok; + std::unique_ptr sendableMgr = std::make_unique(); + status = napi_wrap(env, exportObj, sendableMgr.release(), JsSendableContextManager::Finalizer, nullptr, nullptr); + if (status != napi_ok) { + TAG_LOGE(AAFwkTag::CONTEXT, "napi wrap failed with %{public}d.", status); + return nullptr; + } + + napi_property_descriptor properties[] = { + DECLARE_NAPI_FUNCTION("convertFromContext", JsSendableContextManager::ConvertFromContext), + DECLARE_NAPI_FUNCTION("convertToContext", JsSendableContextManager::ConvertToContext), + DECLARE_NAPI_FUNCTION("convertToApplicationContext", JsSendableContextManager::ConvertToApplicationContext), + DECLARE_NAPI_FUNCTION("convertToAbilityStageContext", JsSendableContextManager::ConvertToAbilityStageContext), + DECLARE_NAPI_FUNCTION("convertToUIAbilityContext", JsSendableContextManager::ConvertToUIAbilityContext), + }; + + status = napi_define_properties(env, exportObj, sizeof(properties) / sizeof(properties[0]), properties); + if (status != napi_ok) { + TAG_LOGE(AAFwkTag::CONTEXT, "napi define property failed with %{public}d.", status); + return nullptr; + } + + return exportObj; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/frameworks/js/napi/app/sendable_context_manager/js_sendable_context_manager.h b/frameworks/js/napi/app/sendable_context_manager/js_sendable_context_manager.h new file mode 100644 index 0000000000..e5a3a2dbde --- /dev/null +++ b/frameworks/js/napi/app/sendable_context_manager/js_sendable_context_manager.h @@ -0,0 +1,32 @@ +/* + * 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_JS_SENDABLE_CONTEXT_MANAGER_H +#define OHOS_ABILITY_RUNTIME_JS_SENDABLE_CONTEXT_MANAGER_H + +#include "native_engine/native_engine.h" + +namespace OHOS { +namespace AbilityRuntime { +class Context; +napi_value CreateJsSendableContextManager(napi_env env, napi_value exportObj); +napi_value CreateSendableContextObject(napi_env env, std::shared_ptr context); +napi_value CreateJsBaseContextFromSendable(napi_env env, void* wrapped); +napi_value CreateJsApplicationContextFromSendable(napi_env env, void* wrapped); +napi_value CreateJsAbilityStageContextFromSendable(napi_env env, void* wrapped); +napi_value CreateJsUIAbilityContextFromSendable(napi_env env, void* wrapped); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_JS_SENDABLE_CONTEXT_MANAGER_H diff --git a/frameworks/js/napi/app/sendable_context_manager/native_module.cpp b/frameworks/js/napi/app/sendable_context_manager/native_module.cpp new file mode 100644 index 0000000000..c967bbeb8c --- /dev/null +++ b/frameworks/js/napi/app/sendable_context_manager/native_module.cpp @@ -0,0 +1,30 @@ +/* + * 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 "js_sendable_context_manager.h" +#include "native_engine/native_engine.h" + +static napi_module _module = { + .nm_version = 0, + .nm_filename = "app/ability/libsendablecontextmanager_napi.so", + .nm_register_func = OHOS::AbilityRuntime::CreateJsSendableContextManager, + .nm_modname = "app.ability.sendableContextManager", +}; + +extern "C" __attribute__((constructor)) +void NapiAppAbilitySendableContextManagerAutoRegister() +{ + napi_module_register(&_module); +} diff --git a/frameworks/js/napi/app/test_runner/BUILD.gn b/frameworks/js/napi/app/test_runner/BUILD.gn index 945e8b494c..4d9da6349c 100644 --- a/frameworks/js/napi/app/test_runner/BUILD.gn +++ b/frameworks/js/napi/app/test_runner/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_test_runner_abc") { diff --git a/frameworks/js/napi/app_startup/async_task_callback/BUILD.gn b/frameworks/js/napi/app_startup/async_task_callback/BUILD.gn index 9d39201ce6..e1fd83af61 100644 --- a/frameworks/js/napi/app_startup/async_task_callback/BUILD.gn +++ b/frameworks/js/napi/app_startup/async_task_callback/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_async_task_callback_abc") { diff --git a/frameworks/js/napi/app_startup/async_task_excutor/BUILD.gn b/frameworks/js/napi/app_startup/async_task_excutor/BUILD.gn index d83dae5e86..e9d42eb088 100644 --- a/frameworks/js/napi/app_startup/async_task_excutor/BUILD.gn +++ b/frameworks/js/napi/app_startup/async_task_excutor/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_async_task_excutor_abc") { diff --git a/frameworks/js/napi/app_startup/startup_config_entry/BUILD.gn b/frameworks/js/napi/app_startup/startup_config_entry/BUILD.gn index 6f1476a305..61c9b11786 100644 --- a/frameworks/js/napi/app_startup/startup_config_entry/BUILD.gn +++ b/frameworks/js/napi/app_startup/startup_config_entry/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_startup_config_entry_abc") { diff --git a/frameworks/js/napi/app_startup/startup_listener/BUILD.gn b/frameworks/js/napi/app_startup/startup_listener/BUILD.gn index 591c4f2709..b846d2f744 100644 --- a/frameworks/js/napi/app_startup/startup_listener/BUILD.gn +++ b/frameworks/js/napi/app_startup/startup_listener/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_startup_listener_abc") { diff --git a/frameworks/js/napi/app_startup/startup_manager/js_startup_manager.cpp b/frameworks/js/napi/app_startup/startup_manager/js_startup_manager.cpp index 500409ce04..9c910722d1 100644 --- a/frameworks/js/napi/app_startup/startup_manager/js_startup_manager.cpp +++ b/frameworks/js/napi/app_startup/startup_manager/js_startup_manager.cpp @@ -17,7 +17,6 @@ #include "ability_runtime_error_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_startup_config.h" #include "js_startup_task_result.h" #include "napi/native_api.h" @@ -34,7 +33,7 @@ constexpr size_t ARGC_TWO = 2; } // namespace void JsStartupManager::Finalizer(napi_env env, void *data, void *hint) { - TAG_LOGD(AAFwkTag::STARTUP, "Called."); + TAG_LOGD(AAFwkTag::STARTUP, "called"); std::unique_ptr(static_cast(data)); } @@ -204,7 +203,7 @@ napi_value JsStartupManager::OnRemoveResult(napi_env env, NapiCallbackInfo &info napi_value JsStartupManagerInit(napi_env env, napi_value exportObj) { - TAG_LOGD(AAFwkTag::STARTUP, "Called."); + TAG_LOGD(AAFwkTag::STARTUP, "called"); if (env == nullptr || exportObj == nullptr) { TAG_LOGE(AAFwkTag::STARTUP, "Env or exportObj nullptr."); return nullptr; diff --git a/frameworks/js/napi/app_startup/startup_task/BUILD.gn b/frameworks/js/napi/app_startup/startup_task/BUILD.gn index 8b732f6131..6bcfee46f2 100644 --- a/frameworks/js/napi/app_startup/startup_task/BUILD.gn +++ b/frameworks/js/napi/app_startup/startup_task/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_startup_task_abc") { diff --git a/frameworks/js/napi/auto_fill_extension_ability/BUILD.gn b/frameworks/js/napi/auto_fill_extension_ability/BUILD.gn index 1131a4ccb7..f1757b2157 100644 --- a/frameworks/js/napi/auto_fill_extension_ability/BUILD.gn +++ b/frameworks/js/napi/auto_fill_extension_ability/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_auto_fill_extension_ability_abc") { diff --git a/frameworks/js/napi/auto_fill_extension_context/BUILD.gn b/frameworks/js/napi/auto_fill_extension_context/BUILD.gn index b08d67b18d..cdb3cee610 100755 --- a/frameworks/js/napi/auto_fill_extension_context/BUILD.gn +++ b/frameworks/js/napi/auto_fill_extension_context/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_auto_fill_extension_context_abc") { 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 8e3e109202..229820d1fa 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 @@ -18,7 +18,6 @@ #include "ability_business_error.h" #include "auto_fill_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "js_error_utils.h" @@ -32,7 +31,7 @@ constexpr size_t ARGC_ONE = 1; void JsAutoFillManager::Finalizer(napi_env env, void *data, void *hint) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); std::unique_ptr(static_cast(data)); } @@ -43,7 +42,7 @@ napi_value JsAutoFillManager::RequestAutoSave(napi_env env, napi_callback_info i napi_value JsAutoFillManager::OnRequestAutoSave(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); if (info.argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "The param is invalid."); ThrowTooFewParametersError(env); @@ -72,7 +71,7 @@ napi_value JsAutoFillManager::OnRequestAutoSave(napi_env env, NapiCallbackInfo & return CreateJsUndefined(env); } - auto autoSaveMangerFunc = std::bind(&JsAutoFillManager::OnRequestAutoSaveDone, this, std::placeholders::_1); + auto autoSaveMangerFunc = [this](const int32_t arg) { this->OnRequestAutoSaveDone(arg); }; saveCallback = std::make_shared(env, instanceId, autoSaveMangerFunc); if (saveCallback == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "saveCallback is nullptr."); @@ -107,7 +106,8 @@ void JsAutoFillManager::OnRequestAutoSaveInner(napi_env env, int32_t instanceId, AutoFill::AutoFillRequest request; uiContent->DumpViewData(request.viewData, request.autoFillType); request.autoFillCommand = AutoFill::AutoFillCommand::SAVE; - auto ret = AutoFillManager::GetInstance().RequestAutoSave(uiContent, request, saveRequestCallback); + AbilityRuntime::AutoFill::AutoFillResult result; + auto ret = AutoFillManager::GetInstance().RequestAutoSave(uiContent, request, saveRequestCallback, result); if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Request auto save error[%{public}d].", ret); ThrowError(env, GetJsErrorCodeByNativeError(ret)); @@ -140,7 +140,7 @@ void JsAutoFillManager::OnRequestAutoSaveDone(int32_t instanceId) napi_value CreateJsAutoFillType(napi_env env) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); napi_value objValue = nullptr; napi_create_object(env, &objValue); @@ -191,7 +191,7 @@ napi_value CreateJsAutoFillType(napi_env env) napi_value CreateJsPopupPlacement(napi_env env) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); napi_value objValue = nullptr; napi_create_object(env, &objValue); @@ -215,7 +215,7 @@ napi_value CreateJsPopupPlacement(napi_env env) napi_value JsAutoFillManagerInit(napi_env env, napi_value exportObj) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); if (env == nullptr || exportObj == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Env or exportObj nullptr."); return nullptr; diff --git a/frameworks/js/napi/auto_fill_manager/js_auto_save_request_callback.cpp b/frameworks/js/napi/auto_fill_manager/js_auto_save_request_callback.cpp index 07269bbe88..222937e62d 100644 --- a/frameworks/js/napi/auto_fill_manager/js_auto_save_request_callback.cpp +++ b/frameworks/js/napi/auto_fill_manager/js_auto_save_request_callback.cpp @@ -16,7 +16,6 @@ #include "js_auto_save_request_callback.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_auto_fill_manager.h" #include "js_runtime.h" #include "js_runtime_utils.h" @@ -35,7 +34,7 @@ JsAutoSaveRequestCallback::~JsAutoSaveRequestCallback() {} void JsAutoSaveRequestCallback::OnSaveRequestSuccess() { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); JSCallFunction(METHOD_ON_SAVE_REQUEST_SUCCESS); if (autoFillManagerFunc_ != nullptr) { autoFillManagerFunc_(instanceId_); @@ -44,7 +43,7 @@ void JsAutoSaveRequestCallback::OnSaveRequestSuccess() void JsAutoSaveRequestCallback::OnSaveRequestFailed() { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); JSCallFunction(METHOD_ON_SAVE_REQUEST_FAILED); if (autoFillManagerFunc_ != nullptr) { autoFillManagerFunc_(instanceId_); @@ -53,7 +52,7 @@ void JsAutoSaveRequestCallback::OnSaveRequestFailed() void JsAutoSaveRequestCallback::Register(napi_value value) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); if (IsJsCallbackEquals(callback_, value)) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "The current callback already exists."); return; diff --git a/frameworks/js/napi/callee/BUILD.gn b/frameworks/js/napi/callee/BUILD.gn index f302ecddb5..802a96d09b 100644 --- a/frameworks/js/napi/callee/BUILD.gn +++ b/frameworks/js/napi/callee/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_callee_abc") { diff --git a/frameworks/js/napi/caller/BUILD.gn b/frameworks/js/napi/caller/BUILD.gn index 0326089f0b..6b07666ece 100644 --- a/frameworks/js/napi/caller/BUILD.gn +++ b/frameworks/js/napi/caller/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_caller_abc") { diff --git a/frameworks/js/napi/dataUriUtils/BUILD.gn b/frameworks/js/napi/dataUriUtils/BUILD.gn index 6c37ca4c88..995b8aea9d 100644 --- a/frameworks/js/napi/dataUriUtils/BUILD.gn +++ b/frameworks/js/napi/dataUriUtils/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") import("//build/templates/abc/ohos_abc.gni") diff --git a/frameworks/js/napi/dialog_request_info/request_info.cpp b/frameworks/js/napi/dialog_request_info/request_info.cpp index 5beacc175e..396ab63aed 100755 --- a/frameworks/js/napi/dialog_request_info/request_info.cpp +++ b/frameworks/js/napi/dialog_request_info/request_info.cpp @@ -16,7 +16,6 @@ #include "request_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" namespace OHOS { diff --git a/frameworks/js/napi/embeddable_ui_ability/BUILD.gn b/frameworks/js/napi/embeddable_ui_ability/BUILD.gn index badb91ce3d..a0ba11cdd6 100644 --- a/frameworks/js/napi/embeddable_ui_ability/BUILD.gn +++ b/frameworks/js/napi/embeddable_ui_ability/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_embeddable_ui_ability_abc") { diff --git a/frameworks/js/napi/embeddable_ui_ability_context/BUILD.gn b/frameworks/js/napi/embeddable_ui_ability_context/BUILD.gn index 51fb6b3e4a..025fab8fd7 100644 --- a/frameworks/js/napi/embeddable_ui_ability_context/BUILD.gn +++ b/frameworks/js/napi/embeddable_ui_ability_context/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_embeddable_ui_ability_context_abc") { diff --git a/frameworks/js/napi/embedded_ui_extension_ability/BUILD.gn b/frameworks/js/napi/embedded_ui_extension_ability/BUILD.gn index 5ab30d0cd8..65b1758bde 100755 --- a/frameworks/js/napi/embedded_ui_extension_ability/BUILD.gn +++ b/frameworks/js/napi/embedded_ui_extension_ability/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_embedded_ui_extension_ability_abc") { diff --git a/frameworks/js/napi/extension_ability/BUILD.gn b/frameworks/js/napi/extension_ability/BUILD.gn index d8b10337f5..f5e6b15ae9 100644 --- a/frameworks/js/napi/extension_ability/BUILD.gn +++ b/frameworks/js/napi/extension_ability/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_extension_ability_abc") { diff --git a/frameworks/js/napi/extensioncontext/BUILD.gn b/frameworks/js/napi/extensioncontext/BUILD.gn index 6f8f7e3a30..512f486185 100644 --- a/frameworks/js/napi/extensioncontext/BUILD.gn +++ b/frameworks/js/napi/extensioncontext/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_extension_context_abc") { diff --git a/frameworks/js/napi/featureAbility/feature_ability.cpp b/frameworks/js/napi/featureAbility/feature_ability.cpp index 4e7696678b..2d98456143 100644 --- a/frameworks/js/napi/featureAbility/feature_ability.cpp +++ b/frameworks/js/napi/featureAbility/feature_ability.cpp @@ -23,7 +23,6 @@ #include "ability_process.h" #include "element_name.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "js_runtime_utils.h" #ifdef SUPPORT_SCREEN diff --git a/frameworks/js/napi/featureAbility/feature_ability_constant.cpp b/frameworks/js/napi/featureAbility/feature_ability_constant.cpp index 9d2c0ac352..3844412b99 100644 --- a/frameworks/js/napi/featureAbility/feature_ability_constant.cpp +++ b/frameworks/js/napi/featureAbility/feature_ability_constant.cpp @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "securec.h" namespace OHOS { diff --git a/frameworks/js/napi/featureAbility/napi_data_ability_operation.cpp b/frameworks/js/napi/featureAbility/napi_data_ability_operation.cpp index 6923011a26..e0eae3ae1d 100644 --- a/frameworks/js/napi/featureAbility/napi_data_ability_operation.cpp +++ b/frameworks/js/napi/featureAbility/napi_data_ability_operation.cpp @@ -19,7 +19,6 @@ #include "data_ability_predicates.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi_common_want.h" #include "napi_data_ability_helper.h" #include "values_bucket.h" @@ -62,28 +61,37 @@ napi_value UnwrapDataAbilityOperation( return result; } -napi_value BuildDataAbilityOperation( - std::shared_ptr &dataAbilityOperation, napi_env env, napi_value param) +bool ParseUriAndType(napi_env env, napi_value ¶m, std::shared_ptr &uri, int &type) { - TAG_LOGI(AAFwkTag::FA, "start"); - // get uri property std::string uriStr(""); if (!UnwrapStringByPropertyName(env, param, "uri", uriStr)) { - TAG_LOGE(AAFwkTag::FA, "uri is not exist"); - return nullptr; + TAG_LOGE(AAFwkTag::FA, "%{public}s, uri is not exist.", __func__); + return false; } - TAG_LOGI(AAFwkTag::FA, "uri:%{public}s", uriStr.c_str()); - std::shared_ptr uri = std::make_shared(uriStr); + TAG_LOGI(AAFwkTag::FA, "%{public}s, uri:%{public}s", __func__, uriStr.c_str()); + uri = std::make_shared(uriStr); // get type property - int type = 0; if (!UnwrapInt32ByPropertyName(env, param, "type", type)) { - TAG_LOGE(AAFwkTag::FA, "type:%{public}d is not exist", type); - return nullptr; + TAG_LOGE(AAFwkTag::FA, "%{public}s, type:%{public}d is not exist.", __func__, type); + return false; } TAG_LOGI(AAFwkTag::FA, "type:%{public}d", type); + return true; +} + +napi_value BuildDataAbilityOperation( + std::shared_ptr &dataAbilityOperation, napi_env env, napi_value param) +{ + TAG_LOGI(AAFwkTag::FA, "%{public}s start.", __func__); + std::shared_ptr uri = nullptr; + int type = 0; + if (!ParseUriAndType(env, param, uri, type)) { + return nullptr; + } + std::shared_ptr builder = nullptr; if (!GetDataAbilityOperationBuilder(builder, type, uri)) { TAG_LOGE(AAFwkTag::FA, "GetDataAbilityOperationBuilder failed"); diff --git a/frameworks/js/napi/feature_ability/js_feature_ability.cpp b/frameworks/js/napi/feature_ability/js_feature_ability.cpp index fd35b098b8..50f0fd891c 100644 --- a/frameworks/js/napi/feature_ability/js_feature_ability.cpp +++ b/frameworks/js/napi/feature_ability/js_feature_ability.cpp @@ -18,7 +18,6 @@ #include "distribute_constants.h" #include "distribute_req_param.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi_common_util.h" #include "js_error_utils.h" diff --git a/frameworks/js/napi/inner/napi_ability_common/BUILD.gn b/frameworks/js/napi/inner/napi_ability_common/BUILD.gn index be85ea95e4..b66be43a6f 100644 --- a/frameworks/js/napi/inner/napi_ability_common/BUILD.gn +++ b/frameworks/js/napi/inner/napi_ability_common/BUILD.gn @@ -47,7 +47,6 @@ ohos_shared_library("napi_ability_common") { external_deps = [ "ability_base:base", - "ability_base:configuration", "ability_base:want", "access_token:libtokenid_sdk", "bundle_framework:appexecfwk_base", @@ -62,7 +61,6 @@ ohos_shared_library("napi_ability_common") { public_external_deps = [ "ability_base:configuration", "bundle_framework:appexecfwk_core", - "window_manager:libwm_lite", ] if (ability_runtime_graphics) { @@ -70,6 +68,11 @@ ohos_shared_library("napi_ability_common") { "SUPPORT_GRAPHICS", "SUPPORT_SCREEN", ] + public_external_deps += [ + "form_fwk:fmskit_provider_client", + "form_fwk:form_manager", + "window_manager:libdm", + ] } innerapi_tags = [ "platformsdk" ] diff --git a/frameworks/js/napi/inner/napi_ability_common/js_napi_common.cpp b/frameworks/js/napi/inner/napi_ability_common/js_napi_common.cpp index d0317b2f1e..aa88123527 100644 --- a/frameworks/js/napi/inner/napi_ability_common/js_napi_common.cpp +++ b/frameworks/js/napi/inner/napi_ability_common/js_napi_common.cpp @@ -24,11 +24,16 @@ #include "napi_common_ability_wrap_utils.h" #include "napi_common_util.h" #include "napi_context.h" +#include "napi_remote_object.h" using namespace OHOS::AbilityRuntime; namespace OHOS { namespace AppExecFwk { +static std::map, key_compare> connects_; +static std::mutex g_connectionsLock_; +static int64_t serialNumber_ = 0; + JsNapiCommon::JsNapiCommon() : ability_(nullptr) {} @@ -1413,10 +1418,14 @@ void JsNapiCommon::AddFreeInstallObserver(napi_env env, const AAFwk::Want &want, { // adapter free install async return install and start result TAG_LOGD(AAFwkTag::JSNAPI, "AddFreeInstallObserver start."); + if (ability_ == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "the ability is nullptr"); + return; + } int ret = 0; if (freeInstallObserver_ == nullptr) { freeInstallObserver_ = new JsFreeInstallObserver(env); - ret = AAFwk::AbilityManagerClient::GetInstance()->AddFreeInstallObserver(freeInstallObserver_); + ret = ability_->AddFreeInstallObserver(freeInstallObserver_); } if (ret != ERR_OK) { @@ -1430,5 +1439,348 @@ void JsNapiCommon::AddFreeInstallObserver(napi_env env, const AAFwk::Want &want, freeInstallObserver_->AddJsObserverObject(bundleName, abilityName, startTime, callback, result); } } + +void ClearCallbackWork(uv_work_t* req, int) +{ + std::unique_ptr work(req); + if (!req) { + TAG_LOGE(AAFwkTag::JSNAPI, "work null"); + return; + } + std::unique_ptr callback(reinterpret_cast(req->data)); + if (!callback) { + TAG_LOGE(AAFwkTag::JSNAPI, "data null"); + return; + } + callback->Reset(); +} + +void ConnectionCallback::Reset() +{ + auto engine = reinterpret_cast(env); + if (engine == nullptr) { + removeKey = nullptr; + return; + } + if (pthread_self() == engine->GetTid()) { + TAG_LOGD(AAFwkTag::JSNAPI, "in-js-thread"); + if (connectCallbackRef) { + napi_delete_reference(env, connectCallbackRef); + connectCallbackRef = nullptr; + } + if (disconnectCallbackRef) { + napi_delete_reference(env, disconnectCallbackRef); + disconnectCallbackRef = nullptr; + } + if (failedCallbackRef) { + napi_delete_reference(env, failedCallbackRef); + failedCallbackRef = nullptr; + } + env = nullptr; + removeKey = nullptr; + return; + } + TAG_LOGI(AAFwkTag::JSNAPI, "not in-js-thread"); + auto loop = engine->GetUVLoop(); + if (loop == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, loop == nullptr.", __func__); + env = nullptr; + removeKey = nullptr; + return; + } + uv_work_t *work = new(std::nothrow) uv_work_t; + if (work == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "work == nullptr."); + return; + } + ConnectionCallback *data = new(std::nothrow) ConnectionCallback(std::move(*this)); + work->data = data; + auto ret = uv_queue_work(loop, work, [](uv_work_t*) {}, ClearCallbackWork); + if (ret != 0) { + TAG_LOGE(AAFwkTag::JSNAPI, "uv_queue_work failed: %{public}d", ret); + data->env = nullptr; + data->removeKey = nullptr; + delete data; + delete work; + } +} + +void NAPIAbilityConnection::AddConnectionCallback(std::shared_ptr callback) +{ + std::lock_guard guard(lock_); + callbacks_.emplace_back(callback); +} + +int NAPIAbilityConnection::GetConnectionState() const +{ + std::lock_guard guard(lock_); + return connectionState_; +} + +void NAPIAbilityConnection::SetConnectionState(int connectionState) +{ + std::lock_guard guard(lock_); + connectionState_ = connectionState; +} + +size_t NAPIAbilityConnection::GetCallbackSize() +{ + std::lock_guard guard(lock_); + return callbacks_.size(); +} + +size_t NAPIAbilityConnection::RemoveAllCallbacks(ConnectRemoveKeyType key) +{ + size_t result = 0; + std::lock_guard guard(lock_); + for (auto it = callbacks_.begin(); it != callbacks_.end();) { + auto callback = *it; + if (callback && callback->removeKey == key) { + it = callbacks_.erase(it); + result++; + } else { + ++it; + } + } + TAG_LOGI(AAFwkTag::JSNAPI, "RemoveAllCallbacks removed size:%{public}zu, left size:%{public}zu", result, + callbacks_.size()); + return result; +} + +void UvWorkOnAbilityConnectDone(uv_work_t *work, int status) +{ + TAG_LOGI(AAFwkTag::JSNAPI, "UvWorkOnAbilityConnectDone, uv_queue_work"); + std::unique_ptr managedWork(work); + if (work == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "UvWorkOnAbilityConnectDone, work is null"); + return; + } + // JS Thread + std::unique_ptr connectAbilityCB(static_cast(work->data)); + if (connectAbilityCB == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "UvWorkOnAbilityConnectDone, connectAbilityCB is null"); + return; + } + CallbackInfo &cbInfo = connectAbilityCB->cbBase.cbInfo; + napi_handle_scope scope = nullptr; + napi_open_handle_scope(cbInfo.env, &scope); + if (scope == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "napi_open_handle_scope failed"); + return; + } + + napi_value globalValue; + napi_get_global(cbInfo.env, &globalValue); + napi_value func; + napi_get_named_property(cbInfo.env, globalValue, "requireNapi", &func); + + napi_value rpcInfo; + napi_create_string_utf8(cbInfo.env, "rpc", NAPI_AUTO_LENGTH, &rpcInfo); + napi_value funcArgv[1] = { rpcInfo }; + napi_value returnValue; + napi_call_function(cbInfo.env, globalValue, func, 1, funcArgv, &returnValue); + + napi_value result[ARGS_TWO] = {nullptr}; + result[PARAM0] = + WrapElementName(cbInfo.env, connectAbilityCB->abilityConnectionCB.elementName); + napi_value jsRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject( + cbInfo.env, connectAbilityCB->abilityConnectionCB.connection); + result[PARAM1] = jsRemoteObject; + + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_get_undefined(cbInfo.env, &undefined); + napi_value callResult = nullptr; + napi_get_reference_value(cbInfo.env, cbInfo.callback, &callback); + + napi_call_function( + cbInfo.env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); + if (cbInfo.callback != nullptr) { + napi_delete_reference(cbInfo.env, cbInfo.callback); + } + napi_close_handle_scope(cbInfo.env, scope); + TAG_LOGI(AAFwkTag::JSNAPI, "UvWorkOnAbilityConnectDone, uv_queue_work end"); +} + +void NAPIAbilityConnection::HandleOnAbilityConnectDone(ConnectionCallback &callback, int resultCode) +{ + TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s called.", __func__); + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(callback.env, &loop); + if (loop == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, loop == null.", __func__); + return; + } + + uv_work_t *work = new(std::nothrow) uv_work_t; + if (work == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, work == null.", __func__); + return; + } + + ConnectAbilityCB *connectAbilityCB = new (std::nothrow) ConnectAbilityCB; + if (connectAbilityCB == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, connectAbilityCB == null.", __func__); + if (work != nullptr) { + delete work; + work = nullptr; + } + return; + } + connectAbilityCB->cbBase.cbInfo.env = callback.env; + connectAbilityCB->cbBase.cbInfo.callback = callback.connectCallbackRef; + callback.connectCallbackRef = nullptr; + connectAbilityCB->abilityConnectionCB.elementName = element_; + connectAbilityCB->abilityConnectionCB.resultCode = resultCode; + connectAbilityCB->abilityConnectionCB.connection = serviceRemoteObject_; + work->data = static_cast(connectAbilityCB); + + int rev = uv_queue_work_with_qos( + loop, work, [](uv_work_t *work) {}, UvWorkOnAbilityConnectDone, uv_qos_user_initiated); + if (rev != 0) { + if (connectAbilityCB != nullptr) { + delete connectAbilityCB; + connectAbilityCB = nullptr; + } + if (work != nullptr) { + delete work; + work = nullptr; + } + } +} + +void NAPIAbilityConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s bundleName:%{public}s abilityName:%{public}s, resultCode:%{public}d", + __func__, element.GetBundleName().c_str(), element.GetAbilityName().c_str(), resultCode); + if (remoteObject == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, remoteObject == nullptr.", __func__); + return; + } + std::lock_guard guard(lock_); + element_ = element; + serviceRemoteObject_ = remoteObject; + for (const auto &callback : callbacks_) { + HandleOnAbilityConnectDone(*callback, resultCode); + } + connectionState_ = CONNECTION_STATE_CONNECTED; + TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s, end.", __func__); +} + +void UvWorkOnAbilityDisconnectDone(uv_work_t *work, int status) +{ + TAG_LOGI(AAFwkTag::JSNAPI, "UvWorkOnAbilityDisconnectDone, uv_queue_work"); + std::unique_ptr managedWork(work); + if (work == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "UvWorkOnAbilityDisconnectDone, work is null"); + return; + } + // JS Thread + std::unique_ptr connectAbilityCB(static_cast(work->data)); + if (connectAbilityCB == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "UvWorkOnAbilityDisconnectDone, connectAbilityCB is null"); + return; + } + CallbackInfo &cbInfo = connectAbilityCB->cbBase.cbInfo; + napi_handle_scope scope = nullptr; + napi_open_handle_scope(cbInfo.env, &scope); + if (scope == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "napi_open_handle_scope failed"); + return; + } + napi_value result = WrapElementName(cbInfo.env, connectAbilityCB->abilityConnectionCB.elementName); + if (cbInfo.callback != nullptr) { + napi_value callback = nullptr; + napi_value callResult = nullptr; + napi_value undefined = nullptr; + napi_get_undefined(cbInfo.env, &undefined); + napi_get_reference_value(cbInfo.env, cbInfo.callback, &callback); + napi_call_function(cbInfo.env, undefined, callback, ARGS_ONE, &result, &callResult); + napi_delete_reference(cbInfo.env, cbInfo.callback); + cbInfo.callback = nullptr; + } + napi_close_handle_scope(cbInfo.env, scope); + + // release connect + std::lock_guard lock(g_connectionsLock_); + TAG_LOGI(AAFwkTag::JSNAPI, "UvWorkOnAbilityDisconnectDone connects_.size:%{public}zu", connects_.size()); + std::string deviceId = connectAbilityCB->abilityConnectionCB.elementName.GetDeviceID(); + std::string bundleName = connectAbilityCB->abilityConnectionCB.elementName.GetBundleName(); + std::string abilityName = connectAbilityCB->abilityConnectionCB.elementName.GetAbilityName(); + auto item = std::find_if(connects_.begin(), connects_.end(), + [deviceId, bundleName, abilityName](const std::map>::value_type &obj) { + return (deviceId == obj.first.want.GetDeviceId()) && + (bundleName == obj.first.want.GetBundle()) && + (abilityName == obj.first.want.GetElement().GetAbilityName()); + }); + if (item != connects_.end()) { + // match deviceid & bundlename && abilityname + connects_.erase(item); + TAG_LOGI(AAFwkTag::JSNAPI, "UvWorkOnAbilityDisconnectDone erase connects_.size:%{public}zu", connects_.size()); + } + TAG_LOGI(AAFwkTag::JSNAPI, "UvWorkOnAbilityDisconnectDone, uv_queue_work end"); +} + +void NAPIAbilityConnection::HandleOnAbilityDisconnectDone(ConnectionCallback &callback, int resultCode) +{ + TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s called.", __func__); + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(callback.env, &loop); + if (loop == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, loop == nullptr.", __func__); + return; + } + + uv_work_t *work = new(std::nothrow) uv_work_t; + if (work == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "work == nullptr."); + return; + } + + ConnectAbilityCB *connectAbilityCB = new (std::nothrow) ConnectAbilityCB; + if (connectAbilityCB == nullptr) { + TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, connectAbilityCB == nullptr.", __func__); + if (work != nullptr) { + delete work; + work = nullptr; + } + return; + } + + connectAbilityCB->cbBase.cbInfo.env = callback.env; + connectAbilityCB->cbBase.cbInfo.callback = callback.disconnectCallbackRef; + callback.disconnectCallbackRef = nullptr; + connectAbilityCB->abilityConnectionCB.elementName = element_; + connectAbilityCB->abilityConnectionCB.resultCode = resultCode; + work->data = static_cast(connectAbilityCB); + + int rev = uv_queue_work( + loop, work, [](uv_work_t *work) {}, UvWorkOnAbilityDisconnectDone); + if (rev != 0) { + if (connectAbilityCB != nullptr) { + delete connectAbilityCB; + connectAbilityCB = nullptr; + } + if (work != nullptr) { + delete work; + work = nullptr; + } + } +} + +void NAPIAbilityConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) +{ + TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s bundleName:%{public}s abilityName:%{public}s, resultCode:%{public}d", + __func__, element.GetBundleName().c_str(), element.GetAbilityName().c_str(), resultCode); + std::lock_guard guard(lock_); + element_ = element; + for (const auto &callback : callbacks_) { + HandleOnAbilityDisconnectDone(*callback, resultCode); + } + connectionState_ = CONNECTION_STATE_DISCONNECTED; + TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s, end.", __func__); +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file 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 3d9b5dd890..016b7f06e7 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 @@ -15,6 +15,8 @@ #ifndef OHOS_ABILITY_RUNTIME_JS_NAPI_COMMON_ABILITY_H #define OHOS_ABILITY_RUNTIME_JS_NAPI_COMMON_ABILITY_H + +#include "ability_connect_callback_stub.h" #include "ability_info.h" #include "ability_manager_errors.h" #include "application_info.h" @@ -143,6 +145,104 @@ public: Ability *ability_; sptr freeInstallObserver_ = nullptr; }; + +enum { + CONNECTION_STATE_DISCONNECTED = -1, + + CONNECTION_STATE_CONNECTED = 0, + + CONNECTION_STATE_CONNECTING = 1 +}; + +using ConnectRemoveKeyType = JsNapiCommon*; +struct ConnectionCallback { + ConnectionCallback(napi_env env, napi_value cbInfo, ConnectRemoveKeyType key) + { + this->env = env; + napi_value jsMethod = nullptr; + napi_get_named_property(env, cbInfo, "onConnect", &jsMethod); + napi_create_reference(env, jsMethod, 1, &connectCallbackRef); + napi_get_named_property(env, cbInfo, "onDisconnect", &jsMethod); + napi_create_reference(env, jsMethod, 1, &disconnectCallbackRef); + napi_get_named_property(env, cbInfo, "onFailed", &jsMethod); + napi_create_reference(env, jsMethod, 1, &failedCallbackRef); + removeKey = key; + } + ConnectionCallback(ConnectionCallback &) = delete; + ConnectionCallback(ConnectionCallback &&other) + : env(other.env), connectCallbackRef(other.connectCallbackRef), + disconnectCallbackRef(other.disconnectCallbackRef), failedCallbackRef(other.failedCallbackRef), + removeKey(other.removeKey) + { + other.env = nullptr; + other.connectCallbackRef = nullptr; + other.disconnectCallbackRef = nullptr; + other.failedCallbackRef = nullptr; + other.removeKey = nullptr; + } + const ConnectionCallback &operator=(ConnectionCallback &) = delete; + const ConnectionCallback &operator=(ConnectionCallback &&other) + { + Reset(); + env = other.env; + connectCallbackRef = other.connectCallbackRef; + disconnectCallbackRef = other.disconnectCallbackRef; + failedCallbackRef = other.failedCallbackRef; + other.env = nullptr; + other.connectCallbackRef = nullptr; + other.disconnectCallbackRef = nullptr; + other.failedCallbackRef = nullptr; + other.removeKey = nullptr; + return *this; + } + ~ConnectionCallback() + { + Reset(); + } + void Reset(); + + napi_env env = nullptr; + napi_ref connectCallbackRef = nullptr; + napi_ref disconnectCallbackRef = nullptr; + napi_ref failedCallbackRef = nullptr; + ConnectRemoveKeyType removeKey = nullptr; +}; + +class NAPIAbilityConnection : public AAFwk::AbilityConnectionStub { +public: + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + void AddConnectionCallback(std::shared_ptr callback); + void HandleOnAbilityConnectDone(ConnectionCallback &callback, int resultCode); + void HandleOnAbilityDisconnectDone(ConnectionCallback &callback, int resultCode); + int GetConnectionState() const; + void SetConnectionState(int connectionState); + size_t GetCallbackSize(); + size_t RemoveAllCallbacks(ConnectRemoveKeyType key); + +private: + std::list> callbacks_; + AppExecFwk::ElementName element_; + sptr serviceRemoteObject_ = nullptr; + int connectionState_ = CONNECTION_STATE_DISCONNECTED; + mutable std::mutex lock_; +}; + +struct ConnectionKey { + Want want; + int64_t id; +}; + +struct key_compare { + bool operator()(const ConnectionKey &key1, const ConnectionKey &key2) const + { + if (key1.id < key2.id) { + return true; + } + return false; + } +}; } // namespace AppExecFwk } // namespace OHOS #endif // OHOS_ABILITY_RUNTIME_JS_NAPI_COMMON_ABILITY_H 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 59eddfe129..a438e73072 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 @@ -21,7 +21,6 @@ #include #include "ability_util.h" -#include "ability_manager_client.h" #include "hilog_tag_wrapper.h" #include "js_napi_common_ability.h" #include "js_runtime_utils.h" @@ -1016,349 +1015,6 @@ napi_value NAPI_StopAbilityCommon(napi_env env, napi_callback_info info, Ability return ret; } -void ClearCallbackWork(uv_work_t* req, int) -{ - std::unique_ptr work(req); - if (!req) { - TAG_LOGE(AAFwkTag::JSNAPI, "work null"); - return; - } - std::unique_ptr callback(reinterpret_cast(req->data)); - if (!callback) { - TAG_LOGE(AAFwkTag::JSNAPI, "data null"); - return; - } - callback->Reset(); -} - -void ConnectionCallback::Reset() -{ - auto engine = reinterpret_cast(env); - if (engine == nullptr) { - removeKey = nullptr; - return; - } - if (pthread_self() == engine->GetTid()) { - TAG_LOGD(AAFwkTag::JSNAPI, "in-js-thread"); - if (connectCallbackRef) { - napi_delete_reference(env, connectCallbackRef); - connectCallbackRef = nullptr; - } - if (disconnectCallbackRef) { - napi_delete_reference(env, disconnectCallbackRef); - disconnectCallbackRef = nullptr; - } - if (failedCallbackRef) { - napi_delete_reference(env, failedCallbackRef); - failedCallbackRef = nullptr; - } - env = nullptr; - removeKey = nullptr; - return; - } - TAG_LOGI(AAFwkTag::JSNAPI, "not in-js-thread"); - auto loop = engine->GetUVLoop(); - if (loop == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, loop == nullptr.", __func__); - env = nullptr; - removeKey = nullptr; - return; - } - uv_work_t *work = new(std::nothrow) uv_work_t; - if (work == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "work == nullptr."); - return; - } - ConnectionCallback *data = new(std::nothrow) ConnectionCallback(std::move(*this)); - work->data = data; - auto ret = uv_queue_work(loop, work, [](uv_work_t*) {}, ClearCallbackWork); - if (ret != 0) { - TAG_LOGE(AAFwkTag::JSNAPI, "uv_queue_work failed: %{public}d", ret); - data->env = nullptr; - data->removeKey = nullptr; - delete data; - delete work; - } -} - -void NAPIAbilityConnection::AddConnectionCallback(std::shared_ptr callback) -{ - std::lock_guard guard(lock_); - callbacks_.emplace_back(callback); -} - -int NAPIAbilityConnection::GetConnectionState() const -{ - std::lock_guard guard(lock_); - return connectionState_; -} - -void NAPIAbilityConnection::SetConnectionState(int connectionState) -{ - std::lock_guard guard(lock_); - connectionState_ = connectionState; -} - -size_t NAPIAbilityConnection::GetCallbackSize() -{ - std::lock_guard guard(lock_); - return callbacks_.size(); -} - -size_t NAPIAbilityConnection::RemoveAllCallbacks(ConnectRemoveKeyType key) -{ - size_t result = 0; - std::lock_guard guard(lock_); - for (auto it = callbacks_.begin(); it != callbacks_.end();) { - auto callback = *it; - if (callback && callback->removeKey == key) { - it = callbacks_.erase(it); - result++; - } else { - ++it; - } - } - TAG_LOGI(AAFwkTag::JSNAPI, "RemoveAllCallbacks removed size:%{public}zu, left size:%{public}zu", result, - callbacks_.size()); - return result; -} - -void UvWorkOnAbilityConnectDone(uv_work_t *work, int status) -{ - TAG_LOGI(AAFwkTag::JSNAPI, "UvWorkOnAbilityConnectDone, uv_queue_work"); - std::unique_ptr managedWork(work); - if (work == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "UvWorkOnAbilityConnectDone, work is null"); - return; - } - // JS Thread - std::unique_ptr connectAbilityCB(static_cast(work->data)); - if (connectAbilityCB == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "UvWorkOnAbilityConnectDone, connectAbilityCB is null"); - return; - } - CallbackInfo &cbInfo = connectAbilityCB->cbBase.cbInfo; - napi_handle_scope scope = nullptr; - napi_open_handle_scope(cbInfo.env, &scope); - if (scope == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "napi_open_handle_scope failed"); - return; - } - - napi_value globalValue; - napi_get_global(cbInfo.env, &globalValue); - napi_value func; - napi_get_named_property(cbInfo.env, globalValue, "requireNapi", &func); - - napi_value rpcInfo; - napi_create_string_utf8(cbInfo.env, "rpc", NAPI_AUTO_LENGTH, &rpcInfo); - napi_value funcArgv[1] = { rpcInfo }; - napi_value returnValue; - napi_call_function(cbInfo.env, globalValue, func, 1, funcArgv, &returnValue); - - napi_value result[ARGS_TWO] = {nullptr}; - result[PARAM0] = - WrapElementName(cbInfo.env, connectAbilityCB->abilityConnectionCB.elementName); - napi_value jsRemoteObject = NAPI_ohos_rpc_CreateJsRemoteObject( - cbInfo.env, connectAbilityCB->abilityConnectionCB.connection); - result[PARAM1] = jsRemoteObject; - - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_get_undefined(cbInfo.env, &undefined); - napi_value callResult = nullptr; - napi_get_reference_value(cbInfo.env, cbInfo.callback, &callback); - - napi_call_function( - cbInfo.env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); - if (cbInfo.callback != nullptr) { - napi_delete_reference(cbInfo.env, cbInfo.callback); - } - napi_close_handle_scope(cbInfo.env, scope); - TAG_LOGI(AAFwkTag::JSNAPI, "UvWorkOnAbilityConnectDone, uv_queue_work end"); -} - -void NAPIAbilityConnection::HandleOnAbilityConnectDone(ConnectionCallback &callback, int resultCode) -{ - TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s called.", __func__); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(callback.env, &loop); - if (loop == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, loop == null.", __func__); - return; - } - - uv_work_t *work = new(std::nothrow) uv_work_t; - if (work == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, work == null.", __func__); - return; - } - - ConnectAbilityCB *connectAbilityCB = new (std::nothrow) ConnectAbilityCB; - if (connectAbilityCB == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, connectAbilityCB == null.", __func__); - if (work != nullptr) { - delete work; - work = nullptr; - } - return; - } - connectAbilityCB->cbBase.cbInfo.env = callback.env; - connectAbilityCB->cbBase.cbInfo.callback = callback.connectCallbackRef; - callback.connectCallbackRef = nullptr; - connectAbilityCB->abilityConnectionCB.elementName = element_; - connectAbilityCB->abilityConnectionCB.resultCode = resultCode; - connectAbilityCB->abilityConnectionCB.connection = serviceRemoteObject_; - work->data = static_cast(connectAbilityCB); - - int rev = uv_queue_work_with_qos( - loop, work, [](uv_work_t *work) {}, UvWorkOnAbilityConnectDone, uv_qos_user_initiated); - if (rev != 0) { - if (connectAbilityCB != nullptr) { - delete connectAbilityCB; - connectAbilityCB = nullptr; - } - if (work != nullptr) { - delete work; - work = nullptr; - } - } -} - -void NAPIAbilityConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s bundleName:%{public}s abilityName:%{public}s, resultCode:%{public}d", - __func__, element.GetBundleName().c_str(), element.GetAbilityName().c_str(), resultCode); - if (remoteObject == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, remoteObject == nullptr.", __func__); - return; - } - std::lock_guard guard(lock_); - element_ = element; - serviceRemoteObject_ = remoteObject; - for (const auto &callback : callbacks_) { - HandleOnAbilityConnectDone(*callback, resultCode); - } - connectionState_ = CONNECTION_STATE_CONNECTED; - TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s, end.", __func__); -} - -void UvWorkOnAbilityDisconnectDone(uv_work_t *work, int status) -{ - TAG_LOGI(AAFwkTag::JSNAPI, "UvWorkOnAbilityDisconnectDone, uv_queue_work"); - std::unique_ptr managedWork(work); - if (work == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "UvWorkOnAbilityDisconnectDone, work is null"); - return; - } - // JS Thread - std::unique_ptr connectAbilityCB(static_cast(work->data)); - if (connectAbilityCB == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "UvWorkOnAbilityDisconnectDone, connectAbilityCB is null"); - return; - } - CallbackInfo &cbInfo = connectAbilityCB->cbBase.cbInfo; - napi_handle_scope scope = nullptr; - napi_open_handle_scope(cbInfo.env, &scope); - if (scope == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "napi_open_handle_scope failed"); - return; - } - napi_value result = WrapElementName(cbInfo.env, connectAbilityCB->abilityConnectionCB.elementName); - if (cbInfo.callback != nullptr) { - napi_value callback = nullptr; - napi_value callResult = nullptr; - napi_value undefined = nullptr; - napi_get_undefined(cbInfo.env, &undefined); - napi_get_reference_value(cbInfo.env, cbInfo.callback, &callback); - napi_call_function(cbInfo.env, undefined, callback, ARGS_ONE, &result, &callResult); - napi_delete_reference(cbInfo.env, cbInfo.callback); - cbInfo.callback = nullptr; - } - napi_close_handle_scope(cbInfo.env, scope); - - // release connect - std::lock_guard lock(g_connectionsLock_); - TAG_LOGI(AAFwkTag::JSNAPI, "UvWorkOnAbilityDisconnectDone connects_.size:%{public}zu", connects_.size()); - std::string deviceId = connectAbilityCB->abilityConnectionCB.elementName.GetDeviceID(); - std::string bundleName = connectAbilityCB->abilityConnectionCB.elementName.GetBundleName(); - std::string abilityName = connectAbilityCB->abilityConnectionCB.elementName.GetAbilityName(); - auto item = std::find_if(connects_.begin(), connects_.end(), - [deviceId, bundleName, abilityName](const std::map>::value_type &obj) { - return (deviceId == obj.first.want.GetDeviceId()) && - (bundleName == obj.first.want.GetBundle()) && - (abilityName == obj.first.want.GetElement().GetAbilityName()); - }); - if (item != connects_.end()) { - // match deviceid & bundlename && abilityname - connects_.erase(item); - TAG_LOGI(AAFwkTag::JSNAPI, "UvWorkOnAbilityDisconnectDone erase connects_.size:%{public}zu", connects_.size()); - } - TAG_LOGI(AAFwkTag::JSNAPI, "UvWorkOnAbilityDisconnectDone, uv_queue_work end"); -} - -void NAPIAbilityConnection::HandleOnAbilityDisconnectDone(ConnectionCallback &callback, int resultCode) -{ - TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s called.", __func__); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(callback.env, &loop); - if (loop == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, loop == nullptr.", __func__); - return; - } - - uv_work_t *work = new(std::nothrow) uv_work_t; - if (work == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "work == nullptr."); - return; - } - - ConnectAbilityCB *connectAbilityCB = new (std::nothrow) ConnectAbilityCB; - if (connectAbilityCB == nullptr) { - TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, connectAbilityCB == nullptr.", __func__); - if (work != nullptr) { - delete work; - work = nullptr; - } - return; - } - - connectAbilityCB->cbBase.cbInfo.env = callback.env; - connectAbilityCB->cbBase.cbInfo.callback = callback.disconnectCallbackRef; - callback.disconnectCallbackRef = nullptr; - connectAbilityCB->abilityConnectionCB.elementName = element_; - connectAbilityCB->abilityConnectionCB.resultCode = resultCode; - work->data = static_cast(connectAbilityCB); - - int rev = uv_queue_work( - loop, work, [](uv_work_t *work) {}, UvWorkOnAbilityDisconnectDone); - if (rev != 0) { - if (connectAbilityCB != nullptr) { - delete connectAbilityCB; - connectAbilityCB = nullptr; - } - if (work != nullptr) { - delete work; - work = nullptr; - } - } -} - -void NAPIAbilityConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) -{ - TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s bundleName:%{public}s abilityName:%{public}s, resultCode:%{public}d", - __func__, element.GetBundleName().c_str(), element.GetAbilityName().c_str(), resultCode); - std::lock_guard guard(lock_); - element_ = element; - for (const auto &callback : callbacks_) { - HandleOnAbilityDisconnectDone(*callback, resultCode); - } - connectionState_ = CONNECTION_STATE_DISCONNECTED; - TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s, end.", __func__); -} - /** * @brief AcquireDataAbilityHelper. * diff --git a/frameworks/js/napi/inner/napi_ability_common/napi_common_ability.h b/frameworks/js/napi/inner/napi_ability_common/napi_common_ability.h index 575aa293d3..3414e119c4 100644 --- a/frameworks/js/napi/inner/napi_ability_common/napi_common_ability.h +++ b/frameworks/js/napi/inner/napi_ability_common/napi_common_ability.h @@ -20,7 +20,6 @@ #include #include -#include "ability_connect_callback_stub.h" #include "ability_info.h" #include "ability_manager_errors.h" #include "application_info.h" @@ -167,90 +166,6 @@ napi_value NAPI_GetAbilityNameCommon(napi_env env, napi_callback_info info, Abil */ napi_value NAPI_StopAbilityCommon(napi_env env, napi_callback_info info, AbilityType abilityType); -enum { - CONNECTION_STATE_DISCONNECTED = -1, - - CONNECTION_STATE_CONNECTED = 0, - - CONNECTION_STATE_CONNECTING = 1 -}; - -class JsNapiCommon; -using ConnectRemoveKeyType = JsNapiCommon*; -struct ConnectionCallback { - ConnectionCallback(napi_env env, napi_value cbInfo, ConnectRemoveKeyType key) - { - this->env = env; - napi_value jsMethod = nullptr; - napi_get_named_property(env, cbInfo, "onConnect", &jsMethod); - napi_create_reference(env, jsMethod, 1, &connectCallbackRef); - napi_get_named_property(env, cbInfo, "onDisconnect", &jsMethod); - napi_create_reference(env, jsMethod, 1, &disconnectCallbackRef); - napi_get_named_property(env, cbInfo, "onFailed", &jsMethod); - napi_create_reference(env, jsMethod, 1, &failedCallbackRef); - removeKey = key; - } - ConnectionCallback(ConnectionCallback &) = delete; - ConnectionCallback(ConnectionCallback &&other) - : env(other.env), connectCallbackRef(other.connectCallbackRef), - disconnectCallbackRef(other.disconnectCallbackRef), failedCallbackRef(other.failedCallbackRef), - removeKey(other.removeKey) - { - other.env = nullptr; - other.connectCallbackRef = nullptr; - other.disconnectCallbackRef = nullptr; - other.failedCallbackRef = nullptr; - other.removeKey = nullptr; - } - const ConnectionCallback &operator=(ConnectionCallback &) = delete; - const ConnectionCallback &operator=(ConnectionCallback &&other) - { - Reset(); - env = other.env; - connectCallbackRef = other.connectCallbackRef; - disconnectCallbackRef = other.disconnectCallbackRef; - failedCallbackRef = other.failedCallbackRef; - other.env = nullptr; - other.connectCallbackRef = nullptr; - other.disconnectCallbackRef = nullptr; - other.failedCallbackRef = nullptr; - other.removeKey = nullptr; - return *this; - } - ~ConnectionCallback() - { - Reset(); - } - void Reset(); - - napi_env env = nullptr; - napi_ref connectCallbackRef = nullptr; - napi_ref disconnectCallbackRef = nullptr; - napi_ref failedCallbackRef = nullptr; - ConnectRemoveKeyType removeKey = nullptr; -}; - -class NAPIAbilityConnection : public AAFwk::AbilityConnectionStub { -public: - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; - void AddConnectionCallback(std::shared_ptr callback); - void HandleOnAbilityConnectDone(ConnectionCallback &callback, int resultCode); - void HandleOnAbilityDisconnectDone(ConnectionCallback &callback, int resultCode); - int GetConnectionState() const; - void SetConnectionState(int connectionState); - size_t GetCallbackSize(); - size_t RemoveAllCallbacks(ConnectRemoveKeyType key); - -private: - std::list> callbacks_; - AppExecFwk::ElementName element_; - sptr serviceRemoteObject_ = nullptr; - int connectionState_ = CONNECTION_STATE_DISCONNECTED; - mutable std::mutex lock_; -}; - /** * @brief acquireDataAbilityHelper processing function. * @@ -294,23 +209,6 @@ napi_value NAPI_StartBackgroundRunningCommon(napi_env env, napi_callback_info in */ napi_value NAPI_CancelBackgroundRunningCommon(napi_env env, napi_callback_info info); -struct ConnectionKey { - Want want; - int64_t id; -}; - -struct key_compare { - bool operator()(const ConnectionKey &key1, const ConnectionKey &key2) const - { - if (key1.id < key2.id) { - return true; - } - return false; - } -}; -static std::map, key_compare> connects_; -static std::mutex g_connectionsLock_; -static int64_t serialNumber_ = 0; enum ErrorCode { NO_ERROR = 0, INVALID_PARAMETER = -1, 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 0b4ad48489..cae1f3f88f 100644 --- a/frameworks/js/napi/inner/napi_ability_common/napi_context.cpp +++ b/frameworks/js/napi/inner/napi_ability_common/napi_context.cpp @@ -25,7 +25,6 @@ #include "feature_ability_common.h" #include "file_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_napi_common_ability.h" #include "permission_list_state.h" #include "securec.h" diff --git a/frameworks/js/napi/inner/napi_common/BUILD.gn b/frameworks/js/napi/inner/napi_common/BUILD.gn index e02e55fb26..98c0e60231 100644 --- a/frameworks/js/napi/inner/napi_common/BUILD.gn +++ b/frameworks/js/napi/inner/napi_common/BUILD.gn @@ -28,6 +28,7 @@ ohos_shared_library("napi_common") { ] sources = [ + "napi_common_child_process_param.cpp", "napi_common_configuration.cpp", "napi_common_execute_param.cpp", "napi_common_execute_result.cpp", @@ -41,12 +42,12 @@ ohos_shared_library("napi_common") { "${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}/app_manager:app_manager", "${ability_runtime_innerkits_path}/runtime:runtime", ] external_deps = [ "ability_base:base", - "ability_base:configuration", "ability_base:session_info", "ability_base:want", "access_token:libtokenid_sdk", @@ -63,7 +64,7 @@ ohos_shared_library("napi_common") { public_external_deps = [ "ability_base:configuration", "bundle_framework:appexecfwk_core", - "window_manager:libwm_lite", + "input:libmmi-client", ] if (ability_runtime_graphics) { @@ -71,6 +72,10 @@ ohos_shared_library("napi_common") { "SUPPORT_GRAPHICS", "SUPPORT_SCREEN", ] + public_external_deps += [ + "form_fwk:form_manager", + "window_manager:libdm", + ] } innerapi_tags = [ "platformsdk" ] diff --git a/frameworks/js/napi/inner/napi_common/napi_common_child_process_param.cpp b/frameworks/js/napi/inner/napi_common/napi_common_child_process_param.cpp new file mode 100644 index 0000000000..e95191ebbe --- /dev/null +++ b/frameworks/js/napi/inner/napi_common/napi_common_child_process_param.cpp @@ -0,0 +1,133 @@ +/* + * 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 "napi_common_child_process_param.h" + +#include "hilog_tag_wrapper.h" +#include "napi_common_util.h" + +namespace OHOS { +namespace AppExecFwk { +bool UnwrapChildProcessArgs(napi_env env, napi_value jsValue, AppExecFwk::ChildProcessArgs &args, + std::string &errorMsg) +{ + if (!IsTypeForNapiValue(env, jsValue, napi_object)) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Parameter error. The type of args must be ProcessArgs."); + errorMsg = "Parameter error. The type of args must be ProcessArgs."; + return false; + } + + if (IsExistsByPropertyName(env, jsValue, "entryParams") && + !UnwrapStringByPropertyName(env, jsValue, "entryParams", args.entryParams)) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Parameter error. The type of args.entryParams must be string."); + errorMsg = "Parameter error. The type of args.entryParams must be string."; + return false; + } + + if (IsExistsByPropertyName(env, jsValue, "fds")) { + napi_value jsFds = GetPropertyValueByPropertyName(env, jsValue, "fds", napi_object); + if (jsFds == nullptr) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "The type of args.fds must be Record."); + errorMsg = "The type of args.fds must be Record."; + return false; + } + if (!UnwrapChildProcessFds(env, jsFds, args.fds, errorMsg)) { + return false; + } + } + + return true; +} + +bool UnwrapChildProcessFds(napi_env env, napi_value param, std::map &map, std::string &errorMsg) +{ + napi_value jsKeyList = nullptr; + uint32_t keyCount = 0; + NAPI_CALL_BASE(env, napi_get_property_names(env, param, &jsKeyList), false); + NAPI_CALL_BASE(env, napi_get_array_length(env, jsKeyList, &keyCount), false); + if (keyCount > CHILD_PROCESS_ARGS_FDS_MAX_COUNT) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "fds count must <= %{public}d.", CHILD_PROCESS_ARGS_FDS_MAX_COUNT); + errorMsg = "fds count must <= " + std::to_string(CHILD_PROCESS_ARGS_FDS_MAX_COUNT); + return false; + } + + napi_value jsKey = nullptr; + for (uint32_t index = 0; index < keyCount; index++) { + NAPI_CALL_BASE(env, napi_get_element(env, jsKeyList, index, &jsKey), false); + std::string key; + if (!UnwrapStringFromJS2(env, jsKey, key)) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "The type of args.fds must be Record."); + errorMsg = "The type of args.fds must be Record."; + return false; + } + if (!ChildProcessArgs::CheckFdKeyLength(key)) { + errorMsg = "fd key length must <= " + std::to_string(CHILD_PROCESS_ARGS_FD_KEY_MAX_LENGTH); + return false; + } + + int32_t value; + if (!UnwrapInt32ByPropertyName(env, param, key.c_str(), value)) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "The type of args.fds must be Record."); + errorMsg = "The type of args.fds must be Record."; + return false; + } + map.emplace(key, value); + } + return true; +} + +bool UnwrapChildProcessOptions(napi_env env, napi_value jsValue, AppExecFwk::ChildProcessOptions &options, + std::string &errorMsg) +{ + if (!IsTypeForNapiValue(env, jsValue, napi_object)) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Parameter error. The type of options must be ProcessOptions."); + errorMsg = "Parameter error. The type of options must be ProcessOptions."; + return false; + } + + if (IsExistsByPropertyName(env, jsValue, "isolationMode") && + !UnwrapBooleanByPropertyName(env, jsValue, "isolationMode", options.isolationMode)) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Parameter error. The type of options.isolationMode must be boolean."); + errorMsg = "Parameter error. The type of options.isolationMode must be boolean."; + return false; + } + return true; +} + +napi_value WrapChildProcessArgs(napi_env env, AppExecFwk::ChildProcessArgs &args) +{ + napi_value jsArgs = nullptr; + NAPI_CALL(env, napi_create_object(env, &jsArgs)); + + napi_value jsEntryParams = WrapStringToJS(env, args.entryParams); + SetPropertyValueByPropertyName(env, jsArgs, "entryParams", jsEntryParams); + + napi_value jsFds = nullptr; + NAPI_CALL(env, napi_create_object(env, &jsFds)); + if (!args.CheckFdsSize()) { + return jsArgs; + } + auto &fds = args.fds; + for (auto iter = fds.begin(); iter != fds.end(); iter++) { + std::string key = iter->first; + napi_value jsValue = WrapInt32ToJS(env, iter->second); + SetPropertyValueByPropertyName(env, jsFds, key.c_str(), jsValue); + } + + SetPropertyValueByPropertyName(env, jsArgs, "fds", jsFds); + return jsArgs; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/js/napi/inner/napi_common/napi_common_child_process_param.h b/frameworks/js/napi/inner/napi_common/napi_common_child_process_param.h new file mode 100644 index 0000000000..f2e3927759 --- /dev/null +++ b/frameworks/js/napi/inner/napi_common/napi_common_child_process_param.h @@ -0,0 +1,36 @@ +/* + * 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 perns and + * limitations under the License. + */ + +#ifndef OHOS_ABILITY_RUNTIME_NAPI_COMMON_CHILD_PROCESS_PARAM +#define OHOS_ABILITY_RUNTIME_NAPI_COMMON_CHILD_PROCESS_PARAM + +#include "child_process_args.h" +#include "child_process_options.h" +#include "napi/native_api.h" + +namespace OHOS { +namespace AppExecFwk { +bool UnwrapChildProcessArgs(napi_env env, napi_value jsValue, AppExecFwk::ChildProcessArgs &args, + std::string &errorMsg); + +bool UnwrapChildProcessFds(napi_env env, napi_value param, std::map &map, std::string &errorMsg); + +bool UnwrapChildProcessOptions(napi_env env, napi_value jsValue, AppExecFwk::ChildProcessOptions &options, + std::string &errorMsg); + +napi_value WrapChildProcessArgs(napi_env env, AppExecFwk::ChildProcessArgs &args); +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_NAPI_COMMON_CHILD_PROCESS_PARAM diff --git a/frameworks/js/napi/inner/napi_common/napi_common_configuration.cpp b/frameworks/js/napi/inner/napi_common/napi_common_configuration.cpp index 6883f4750d..cd3df90966 100644 --- a/frameworks/js/napi/inner/napi_common/napi_common_configuration.cpp +++ b/frameworks/js/napi/inner/napi_common/napi_common_configuration.cpp @@ -17,7 +17,6 @@ #include "configuration_convertor.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi_common_util.h" namespace OHOS { diff --git a/frameworks/js/napi/inner/napi_common/napi_common_execute_param.cpp b/frameworks/js/napi/inner/napi_common/napi_common_execute_param.cpp index 0a41e2c286..44f2ce694b 100644 --- a/frameworks/js/napi/inner/napi_common/napi_common_execute_param.cpp +++ b/frameworks/js/napi/inner/napi_common/napi_common_execute_param.cpp @@ -16,7 +16,6 @@ #include "napi_common_execute_param.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi_common_util.h" #include "napi_common_want.h" 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 1d4c34668b..37cc6108d8 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 @@ -16,7 +16,6 @@ #include "napi_common_execute_result.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "insight_intent_execute_result.h" #include "napi_common_util.h" #include "napi_common_want.h" diff --git a/frameworks/js/napi/inner/napi_common/napi_common_start_options.cpp b/frameworks/js/napi/inner/napi_common/napi_common_start_options.cpp index c1342aa00f..a306b1bb82 100644 --- a/frameworks/js/napi/inner/napi_common/napi_common_start_options.cpp +++ b/frameworks/js/napi/inner/napi_common/napi_common_start_options.cpp @@ -16,7 +16,6 @@ #include "napi_common_start_options.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi_common_util.h" #include "napi_common_want.h" #include "int_wrapper.h" diff --git a/frameworks/js/napi/inner/napi_common/napi_common_util.cpp b/frameworks/js/napi/inner/napi_common/napi_common_util.cpp index 369f2c2ebb..59c753b0bf 100644 --- a/frameworks/js/napi/inner/napi_common/napi_common_util.cpp +++ b/frameworks/js/napi/inner/napi_common/napi_common_util.cpp @@ -17,7 +17,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi_common_data.h" #include "napi_common_error.h" #include "securec.h" diff --git a/frameworks/js/napi/inner/napi_common/napi_common_want.cpp b/frameworks/js/napi/inner/napi_common/napi_common_want.cpp index c4739dcfbc..a5e48ce4ae 100644 --- a/frameworks/js/napi/inner/napi_common/napi_common_want.cpp +++ b/frameworks/js/napi/inner/napi_common/napi_common_want.cpp @@ -22,7 +22,6 @@ #include "double_wrapper.h" #include "float_wrapper.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "int_wrapper.h" #include "ipc_skeleton.h" #include "js_runtime_utils.h" @@ -1319,7 +1318,11 @@ bool WrapJsWantParamsArray(napi_env env, napi_value object, const std::string &k } else if (AAFwk::Array::IsDoubleArray(ao)) { return InnerWrapWantParamsArray( env, object, key, ao); + } else if (AAFwk::Array::IsWantParamsArray(ao)) { + TAG_LOGD(AAFwkTag::JSNAPI, "Array type is WantParams"); + return InnerWrapWantParamsArrayWantParams(env, object, key, ao); } else { + TAG_LOGE(AAFwkTag::JSNAPI, "Array type unknown"); return false; } } 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 0f6c415565..a4db405e50 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 @@ -16,7 +16,6 @@ #include "napi_common_open_link_options.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "int_wrapper.h" #include "napi_common_util.h" #include "napi_common_want.h" diff --git a/frameworks/js/napi/insight_intent/insight_intent/js_insight_intent.cpp b/frameworks/js/napi/insight_intent/insight_intent/js_insight_intent.cpp index 7818bb932f..4562819f7d 100644 --- a/frameworks/js/napi/insight_intent/insight_intent/js_insight_intent.cpp +++ b/frameworks/js/napi/insight_intent/insight_intent/js_insight_intent.cpp @@ -16,7 +16,6 @@ #include "js_insight_intent.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_error_utils.h" #include "js_runtime_utils.h" #include "native_engine/native_value.h" diff --git a/frameworks/js/napi/insight_intent/insight_intent_driver/js_insight_intent_driver.cpp b/frameworks/js/napi/insight_intent/insight_intent_driver/js_insight_intent_driver.cpp index 6487a5028f..d36932ef32 100644 --- a/frameworks/js/napi/insight_intent/insight_intent_driver/js_insight_intent_driver.cpp +++ b/frameworks/js/napi/insight_intent/insight_intent_driver/js_insight_intent_driver.cpp @@ -20,7 +20,6 @@ #include "event_handler.h" #include "event_runner.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "insight_intent_callback_interface.h" #include "insight_intent_host_client.h" #include "insight_intent_execute_result.h" diff --git a/frameworks/js/napi/insight_intent/insight_intent_driver/js_insight_intent_driver_utils.cpp b/frameworks/js/napi/insight_intent/insight_intent_driver/js_insight_intent_driver_utils.cpp index 4d4e29a9c6..a1cc25c99a 100644 --- a/frameworks/js/napi/insight_intent/insight_intent_driver/js_insight_intent_driver_utils.cpp +++ b/frameworks/js/napi/insight_intent/insight_intent_driver/js_insight_intent_driver_utils.cpp @@ -18,7 +18,6 @@ #include #include "ability_state.h" -#include "hilog_wrapper.h" #include "napi_common_want.h" #include "napi_remote_object.h" #include "js_runtime.h" diff --git a/frameworks/js/napi/insight_intent/insight_intent_executor/BUILD.gn b/frameworks/js/napi/insight_intent/insight_intent_executor/BUILD.gn index 81a7c37eda..add8c609eb 100644 --- a/frameworks/js/napi/insight_intent/insight_intent_executor/BUILD.gn +++ b/frameworks/js/napi/insight_intent/insight_intent_executor/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_insight_intent_executor_abc") { diff --git a/frameworks/js/napi/insight_intent_context/BUILD.gn b/frameworks/js/napi/insight_intent_context/BUILD.gn index 19113b5742..bba90dcaf9 100644 --- a/frameworks/js/napi/insight_intent_context/BUILD.gn +++ b/frameworks/js/napi/insight_intent_context/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_insight_intent_context_abc") { diff --git a/frameworks/js/napi/js_child_process/BUILD.gn b/frameworks/js/napi/js_child_process/BUILD.gn index 03b0c06fd0..f3402e8fdc 100644 --- a/frameworks/js/napi/js_child_process/BUILD.gn +++ b/frameworks/js/napi/js_child_process/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_child_process_abc") { diff --git a/frameworks/js/napi/js_child_process_manager/BUILD.gn b/frameworks/js/napi/js_child_process_manager/BUILD.gn index 4f1765f11d..3398d75150 100644 --- a/frameworks/js/napi/js_child_process_manager/BUILD.gn +++ b/frameworks/js/napi/js_child_process_manager/BUILD.gn @@ -25,14 +25,17 @@ ohos_shared_library("childprocessmanager_napi") { include_dirs = [] deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/child_process_manager:child_process_manager", "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/ability/native:ability_business_error", + "${ability_runtime_native_path}/ability/native:abilitykit_native", ] external_deps = [ "ability_base:session_info", + "c_utils:utils", "hilog:libhilog", "napi:ace_napi", ] diff --git a/frameworks/js/napi/js_child_process_manager/js_child_process_manager.cpp b/frameworks/js/napi/js_child_process_manager/js_child_process_manager.cpp index d6f6a55562..784303014f 100644 --- a/frameworks/js/napi/js_child_process_manager/js_child_process_manager.cpp +++ b/frameworks/js/napi/js_child_process_manager/js_child_process_manager.cpp @@ -20,9 +20,9 @@ #include "child_process_manager.h" #include "child_process_manager_error_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_error_utils.h" #include "js_runtime_utils.h" +#include "napi_common_child_process_param.h" #include "napi_common_util.h" #include "napi/native_api.h" @@ -31,7 +31,6 @@ namespace AbilityRuntime { namespace { constexpr const char *PROCESS_MANAGER_NAME = "JsChildProcessManager"; constexpr size_t ARGC_TWO = 2; - enum { MODE_SELF_FORK = 0, MODE_APP_SPAWN_FORK = 1, @@ -54,10 +53,15 @@ public: GET_CB_INFO_AND_CALL(env, info, JsChildProcessManager, OnStartChildProcess); } + static napi_value StartArkChildProcess(napi_env env, napi_callback_info info) + { + GET_CB_INFO_AND_CALL(env, info, JsChildProcessManager, OnStartArkChildProcess); + } + private: napi_value OnStartChildProcess(napi_env env, size_t argc, napi_value* argv) { - TAG_LOGI(AAFwkTag::PROCESSMGR, "called."); + TAG_LOGI(AAFwkTag::PROCESSMGR, "OnStartChildProcess called."); if (ChildProcessManager::GetInstance().IsChildProcess()) { TAG_LOGE(AAFwkTag::PROCESSMGR, "Already in child process"); ThrowError(env, AbilityErrorCode::ERROR_CODE_OPERATION_NOT_SUPPORTED); @@ -70,12 +74,12 @@ private: } std::string srcEntry; int32_t startMode; - if (!ConvertFromJsValue(env, argv[0], srcEntry)) { + if (!ConvertFromJsValue(env, argv[PARAM0], srcEntry)) { TAG_LOGE(AAFwkTag::PROCESSMGR, "Parse param srcEntry failed"); ThrowInvalidParamError(env, "Parse param srcEntry failed, must be a valid string."); return CreateJsUndefined(env); } - if (!ConvertFromJsValue(env, argv[1], startMode)) { + if (!ConvertFromJsValue(env, argv[PARAM1], startMode)) { TAG_LOGE(AAFwkTag::PROCESSMGR, "Parse param startMode failed"); ThrowInvalidParamError(env, "Unsupported startMode, must be StartMode.SELF_FORK or StartMode.APP_SPAWN_FORK."); @@ -88,45 +92,138 @@ private: "Unsupported startMode, must be StartMode.SELF_FORK or StartMode.APP_SPAWN_FORK."); return CreateJsUndefined(env); } - NapiAsyncTask::CompleteCallback complete = [srcEntry, startMode](napi_env env, NapiAsyncTask &task, - int32_t status) { - ForkProcess(env, task, srcEntry, startMode); - }; - napi_value lastParam = (argc <= ARGC_TWO) ? nullptr : argv[ARGC_TWO]; napi_value result = nullptr; - NapiAsyncTask::Schedule("JsChildProcessManager::OnStartChildProcess", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + napi_value lastParam = (argc <= ARGC_TWO) ? nullptr : argv[ARGC_TWO]; + if (startMode == MODE_SELF_FORK) { + StartChildProcessSelfForkTask(env, lastParam, result, srcEntry); + } else { + StartChildProcessAppSpawnForkTask(env, lastParam, result, srcEntry); + } return result; } - static void ForkProcess(napi_env env, NapiAsyncTask &task, const std::string &srcEntry, const int32_t startMode) + void StartChildProcessSelfForkTask(const napi_env &env, const napi_value &lastParam, napi_value &result, + const std::string &srcEntry) { - TAG_LOGD(AAFwkTag::PROCESSMGR, "called."); - pid_t pid = 0; - ChildProcessManagerErrorCode errorCode; - switch (startMode) { - case MODE_SELF_FORK: { - errorCode = ChildProcessManager::GetInstance().StartChildProcessBySelfFork(srcEntry, pid); - break; + NapiAsyncTask::CompleteCallback complete = [srcEntry](napi_env env, NapiAsyncTask &task, int32_t status) { + pid_t pid = 0; + ChildProcessManagerErrorCode errorCode = + ChildProcessManager::GetInstance().StartChildProcessByAppSpawnFork(srcEntry, pid); + if (errorCode == ChildProcessManagerErrorCode::ERR_OK) { + task.ResolveWithNoError(env, CreateJsValue(env, pid)); + } else { + task.Reject(env, CreateJsError(env, + ChildProcessManagerErrorUtil::GetAbilityErrorCode(errorCode))); } - case MODE_APP_SPAWN_FORK: { - errorCode = ChildProcessManager::GetInstance().StartChildProcessByAppSpawnFork(srcEntry, pid); - break; - } - default: { - TAG_LOGE(AAFwkTag::PROCESSMGR, "Not supported StartMode"); - task.Reject(env, CreateInvalidParamJsError(env, - "Unsupported startMode,must be StartMode.SELF_FORK or StartMode.APP_SPAWN_FORK.")); + }; + NapiAsyncTask::Schedule("JsChildProcessManager::OnStartChildProcess", + env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + } + + void StartChildProcessAppSpawnForkTask(const napi_env &env, const napi_value &lastParam, napi_value &result, + const std::string &srcEntry) + { + auto innerErrorCode = std::make_shared(ChildProcessManagerErrorCode::ERR_OK); + auto pid = std::make_shared(ERR_INVALID_VALUE); + NapiAsyncTask::ExecuteCallback execute = [srcEntry, pid, innerErrorCode]() { + if (!pid || !innerErrorCode) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "innerErrorCode or pid is nullptr"); return; } + *innerErrorCode = ChildProcessManager::GetInstance().StartChildProcessByAppSpawnFork(srcEntry, *pid); + }; + NapiAsyncTask::CompleteCallback complete = + [pid, innerErrorCode](napi_env env, NapiAsyncTask &task, int32_t status) { + if (!pid || !innerErrorCode) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "innerErrorCode or pid is nullptr"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + return; + } + if (*innerErrorCode == ChildProcessManagerErrorCode::ERR_OK) { + task.ResolveWithNoError(env, CreateJsValue(env, *pid)); + } else { + task.Reject(env, CreateJsError(env, + ChildProcessManagerErrorUtil::GetAbilityErrorCode(*innerErrorCode))); + } + }; + NapiAsyncTask::Schedule("JsChildProcessManager::OnStartChildProcess", + env, CreateAsyncTaskWithLastParam(env, lastParam, std::move(execute), std::move(complete), &result)); + } + + napi_value OnStartArkChildProcess(napi_env env, size_t argc, napi_value* argv) + { + TAG_LOGI(AAFwkTag::PROCESSMGR, "OnStartArkChildProcess called."); + if (ChildProcessManager::GetInstance().IsChildProcess()) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Already in child process"); + ThrowError(env, AbilityErrorCode::ERROR_CODE_OPERATION_NOT_SUPPORTED); + return CreateJsUndefined(env); } - TAG_LOGD( - AAFwkTag::PROCESSMGR, "ChildProcessManager start resultCode: %{public}d, pid:%{public}d", errorCode, pid); - if (errorCode == ChildProcessManagerErrorCode::ERR_OK) { - task.ResolveWithNoError(env, CreateJsValue(env, pid)); - } else { - task.Reject(env, CreateJsError(env, ChildProcessManagerErrorUtil::GetAbilityErrorCode(errorCode))); + if (argc < ARGC_TWO) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); } + std::string srcEntry; + AppExecFwk::ChildProcessArgs args; + AppExecFwk::ChildProcessOptions options; + if (!ConvertFromJsValue(env, argv[PARAM0], srcEntry)) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Parse param srcEntry failed, must be a valid string."); + ThrowInvalidParamError(env, "Parse param srcEntry failed, must be a valid string."); + return CreateJsUndefined(env); + } + if (srcEntry.empty()) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Param srcEntry cannot be empty."); + ThrowInvalidParamError(env, "Param srcEntry cannot be empty."); + return CreateJsUndefined(env); + } + std::string errorMsg; + if (!UnwrapChildProcessArgs(env, argv[PARAM1], args, errorMsg)) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Parse param args failed."); + ThrowInvalidParamError(env, errorMsg); + return CreateJsUndefined(env); + } + if (argc > ARGS_TWO && !UnwrapChildProcessOptions(env, argv[PARAM2], options, errorMsg)) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "Parse param options failed."); + ThrowInvalidParamError(env, errorMsg); + return CreateJsUndefined(env); + } + napi_value result = nullptr; + StartArkChildProcessTask(env, result, srcEntry, args, options); + return result; + } + + void StartArkChildProcessTask(const napi_env &env, napi_value &result, const std::string &srcEntry, + const AppExecFwk::ChildProcessArgs &args, const AppExecFwk::ChildProcessOptions &options) + { + TAG_LOGD(AAFwkTag::PROCESSMGR, "OnStartArkChildProcess, srcEntry:%{private}s, args.entryParams:%{private}s," + " args.fds size:%{public}zu, options.isolationMode:%{public}d", srcEntry.c_str(), + args.entryParams.c_str(), args.fds.size(), options.isolationMode); + auto innerErrorCode = std::make_shared(ChildProcessManagerErrorCode::ERR_OK); + auto pid = std::make_shared(0); + NapiAsyncTask::ExecuteCallback execute = [srcEntry, args, options, pid, innerErrorCode]() { + if (!pid || !innerErrorCode) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "innerErrorCode or pid is nullptr"); + return; + } + *innerErrorCode = ChildProcessManager::GetInstance().StartArkChildProcess(srcEntry, *pid, + AppExecFwk::CHILD_PROCESS_TYPE_ARK, args, options); + }; + NapiAsyncTask::CompleteCallback complete = + [pid, innerErrorCode](napi_env env, NapiAsyncTask &task, int32_t status) { + if (!pid || !innerErrorCode) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "innerErrorCode or pid is nullptr"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + return; + } + if (*innerErrorCode == ChildProcessManagerErrorCode::ERR_OK) { + task.ResolveWithNoError(env, CreateJsValue(env, *pid)); + } else { + task.Reject(env, CreateJsError(env, + ChildProcessManagerErrorUtil::GetAbilityErrorCode(*innerErrorCode))); + } + }; + NapiAsyncTask::ScheduleHighQos("JsChildProcessManager::OnStartArkChildProcess", + env, CreateAsyncTaskWithLastParam(env, nullptr, std::move(execute), std::move(complete), &result)); } }; @@ -143,6 +240,7 @@ napi_value JsChildProcessManagerInit(napi_env env, napi_value exportObj) const char *moduleName = PROCESS_MANAGER_NAME; BindNativeFunction(env, exportObj, "startChildProcess", moduleName, JsChildProcessManager::StartChildProcess); + BindNativeFunction(env, exportObj, "startArkChildProcess", moduleName, JsChildProcessManager::StartArkChildProcess); return CreateJsUndefined(env); } } // namespace AbilityRuntime 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 717af3c4dc..2eb955d9bc 100755 --- a/frameworks/js/napi/js_dialog_request/js_dialog_request.cpp +++ b/frameworks/js/napi/js_dialog_request/js_dialog_request.cpp @@ -16,7 +16,6 @@ #include "js_dialog_request.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_error_utils.h" #include "js_dialog_request_callback.h" #include "js_runtime_utils.h" diff --git a/frameworks/js/napi/js_dialog_request/js_dialog_request_callback.cpp b/frameworks/js/napi/js_dialog_request/js_dialog_request_callback.cpp index 37993c7da9..1d43a28e1a 100755 --- a/frameworks/js/napi/js_dialog_request/js_dialog_request_callback.cpp +++ b/frameworks/js/napi/js_dialog_request/js_dialog_request_callback.cpp @@ -16,7 +16,6 @@ #include "js_dialog_request_callback.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_context_utils.h" #include "js_error_utils.h" #include "js_runtime.h" diff --git a/frameworks/js/napi/js_dialog_session/js_dialog_session.cpp b/frameworks/js/napi/js_dialog_session/js_dialog_session.cpp index 9dc185c553..3639e9055c 100644 --- a/frameworks/js/napi/js_dialog_session/js_dialog_session.cpp +++ b/frameworks/js/napi/js_dialog_session/js_dialog_session.cpp @@ -17,7 +17,6 @@ #include "ability_manager_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_error_utils.h" #include "napi/native_api.h" #include "napi_common_ability.h" 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 a67fcee65f..9b1d01a567 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 @@ -15,7 +15,6 @@ #include "js_dialog_session_utils.h" -#include "hilog_wrapper.h" #include "json/json.h" #include "napi_common_ability.h" #include "napi_common_want.h" @@ -68,6 +67,10 @@ napi_value WrapDialogAbilityInfo(napi_env env, const AAFwk::DialogAbilityInfo &d SetPropertyValueByPropertyName(env, jsObject, "abilityLabelId", jsValue); jsValue = WrapBoolToJS(env, dialogAbilityInfo.visible); SetPropertyValueByPropertyName(env, jsObject, "visible", jsValue); + jsValue = WrapInt32ToJS(env, dialogAbilityInfo.appIndex); + SetPropertyValueByPropertyName(env, jsObject, "appIndex", jsValue); + jsValue = WrapMultiAppModeData(env, dialogAbilityInfo.multiAppMode); + SetPropertyValueByPropertyName(env, jsObject, "multiAppMode", jsValue); return jsObject; } @@ -90,5 +93,20 @@ napi_value WrapDialogSessionInfo(napi_env env, const AAFwk::DialogSessionInfo &d return jsObject; } + +napi_value WrapMultiAppModeData(napi_env env, const AppExecFwk::MultiAppModeData &multiAppMode) +{ + napi_value jsObject = nullptr; + napi_value jsValue = nullptr; + NAPI_CALL(env, napi_create_object(env, &jsObject)); + + jsValue = WrapInt32ToJS(env, static_cast(multiAppMode.multiAppModeType)); + SetPropertyValueByPropertyName(env, jsObject, "multiAppModeType", jsValue); + + jsValue = WrapInt32ToJS(env, static_cast(multiAppMode.maxCount)); + SetPropertyValueByPropertyName(env, jsObject, "maxCount", jsValue); + + return jsObject; +} } // namespace AbilityRuntime } // nampspace OHOS diff --git a/frameworks/js/napi/js_dialog_session/js_dialog_session_utils.h b/frameworks/js/napi/js_dialog_session/js_dialog_session_utils.h index 1f9d4864c0..a7932e032b 100644 --- a/frameworks/js/napi/js_dialog_session/js_dialog_session_utils.h +++ b/frameworks/js/napi/js_dialog_session/js_dialog_session_utils.h @@ -23,13 +23,14 @@ #include "js_dialog_session.h" #include "js_runtime_utils.h" #include "native_engine/native_engine.h" -#include "dialog_session_record.h" +#include "dialog_session_manager.h" namespace OHOS { namespace AppExecFwk { napi_value WrapArrayDialogAbilityInfoToJS(napi_env env, const std::vector &value); napi_value WrapDialogSessionInfo(napi_env env, const AAFwk::DialogSessionInfo &dialogSessionInfo); napi_value WrapDialogAbilityInfo(napi_env env, const AAFwk::DialogAbilityInfo &dialogAbilityInfo); +napi_value WrapMultiAppModeData(napi_env env, const AppExecFwk::MultiAppModeData &multiAppMode); } // namespace AppExecFwk } // namespace OHOS #endif // OHOS_ABILITY_RUNTIME_JS_DIALOG_SESSION_UTILS_H diff --git a/frameworks/js/napi/js_mission_manager/js_mission_info_utils.cpp b/frameworks/js/napi/js_mission_manager/js_mission_info_utils.cpp index 3410785705..4c93628e4b 100755 --- a/frameworks/js/napi/js_mission_manager/js_mission_info_utils.cpp +++ b/frameworks/js/napi/js_mission_manager/js_mission_info_utils.cpp @@ -16,7 +16,6 @@ #include "js_mission_info_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi_common_want.h" #include "napi_remote_object.h" #include "bool_wrapper.h" diff --git a/frameworks/js/napi/js_mission_manager/js_mission_listener.cpp b/frameworks/js/napi/js_mission_manager/js_mission_listener.cpp index 7390aa91ae..3684b131af 100755 --- a/frameworks/js/napi/js_mission_manager/js_mission_listener.cpp +++ b/frameworks/js/napi/js_mission_manager/js_mission_listener.cpp @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" #ifdef SUPPORT_SCREEN diff --git a/frameworks/js/napi/js_mission_manager/mission_manager.cpp b/frameworks/js/napi/js_mission_manager/mission_manager.cpp index 4bf647d335..bda250387f 100755 --- a/frameworks/js/napi/js_mission_manager/mission_manager.cpp +++ b/frameworks/js/napi/js_mission_manager/mission_manager.cpp @@ -19,7 +19,6 @@ #include "event_handler.h" #include "event_runner.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_error_utils.h" #include "js_mission_info_utils.h" #include "js_mission_listener.h" diff --git a/frameworks/js/napi/mission_manager/distributed_mission_manager.cpp b/frameworks/js/napi/mission_manager/distributed_mission_manager.cpp index 9906b0b7fa..3b90f9e49e 100644 --- a/frameworks/js/napi/mission_manager/distributed_mission_manager.cpp +++ b/frameworks/js/napi/mission_manager/distributed_mission_manager.cpp @@ -20,7 +20,6 @@ #include "ability_manager_client.h" #include "dms_sa_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "napi_common_data.h" #include "napi_common_util.h" @@ -840,7 +839,6 @@ void OffExecuteCB(napi_env env, OnCB *onCB) onCB->onRegistration->DelOnCallbackCBRef(env, onCB->onCallbackCB.napiCallback); if (!onCB->onRegistration->GetOnCallbackCBRef().empty()) { TAG_LOGI(AAFwkTag::MISSION, "There are still other remaining callback"); - return; } DmsSaClient::GetInstance().DelListener(onCB->type, onCB->onRegistration); if (onCB->result == NO_ERROR) { diff --git a/frameworks/js/napi/mission_manager/distributed_mission_manager_helper.cpp b/frameworks/js/napi/mission_manager/distributed_mission_manager_helper.cpp index e6a3687780..2d94a00398 100644 --- a/frameworks/js/napi/mission_manager/distributed_mission_manager_helper.cpp +++ b/frameworks/js/napi/mission_manager/distributed_mission_manager_helper.cpp @@ -20,7 +20,6 @@ #include "ability_manager_client.h" #include "dms_sa_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "napi_common_data.h" #include "napi_common_util.h" diff --git a/frameworks/js/napi/mission_manager/js_mission_info_utils.cpp b/frameworks/js/napi/mission_manager/js_mission_info_utils.cpp index 560536b083..c832893cf9 100644 --- a/frameworks/js/napi/mission_manager/js_mission_info_utils.cpp +++ b/frameworks/js/napi/mission_manager/js_mission_info_utils.cpp @@ -16,7 +16,6 @@ #include "js_mission_info_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi_common_want.h" #include "napi_remote_object.h" #include "bool_wrapper.h" diff --git a/frameworks/js/napi/mission_manager/js_mission_listener.cpp b/frameworks/js/napi/mission_manager/js_mission_listener.cpp index 42d67ffc05..df65269700 100644 --- a/frameworks/js/napi/mission_manager/js_mission_listener.cpp +++ b/frameworks/js/napi/mission_manager/js_mission_listener.cpp @@ -17,7 +17,6 @@ #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" #ifdef SUPPORT_SCREEN diff --git a/frameworks/js/napi/mission_manager/mission_continue_stub.cpp b/frameworks/js/napi/mission_manager/mission_continue_stub.cpp index a0be6383e5..35e1cbe16d 100644 --- a/frameworks/js/napi/mission_manager/mission_continue_stub.cpp +++ b/frameworks/js/napi/mission_manager/mission_continue_stub.cpp @@ -16,7 +16,6 @@ #include "mission_continue_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" #include "want.h" diff --git a/frameworks/js/napi/mission_manager/mission_manager.cpp b/frameworks/js/napi/mission_manager/mission_manager.cpp index df2ffe01bf..fac1adeba1 100644 --- a/frameworks/js/napi/mission_manager/mission_manager.cpp +++ b/frameworks/js/napi/mission_manager/mission_manager.cpp @@ -19,7 +19,6 @@ #include "event_handler.h" #include "event_runner.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_error_utils.h" #include "js_mission_info_utils.h" #include "js_mission_listener.h" diff --git a/frameworks/js/napi/particleAbility/particle_ability.cpp b/frameworks/js/napi/particleAbility/particle_ability.cpp index 6c7d44d2c2..8321001f27 100644 --- a/frameworks/js/napi/particleAbility/particle_ability.cpp +++ b/frameworks/js/napi/particleAbility/particle_ability.cpp @@ -19,7 +19,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" #include "napi_common_ability.h" #include "napi/native_api.h" diff --git a/frameworks/js/napi/photo_editor_extension_ability/BUILD.gn b/frameworks/js/napi/photo_editor_extension_ability/BUILD.gn index 28f96ada2f..ae87a44f9f 100755 --- a/frameworks/js/napi/photo_editor_extension_ability/BUILD.gn +++ b/frameworks/js/napi/photo_editor_extension_ability/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_photo_editor_extension_ability_abc") { diff --git a/frameworks/js/napi/photo_editor_extension_ability/photo_editor_extension_ability.js b/frameworks/js/napi/photo_editor_extension_ability/photo_editor_extension_ability.js index ed321878ec..fa526e5088 100644 --- a/frameworks/js/napi/photo_editor_extension_ability/photo_editor_extension_ability.js +++ b/frameworks/js/napi/photo_editor_extension_ability/photo_editor_extension_ability.js @@ -18,6 +18,6 @@ let UIExtensionAbility = requireNapi('app.ability.UIExtensionAbility'); export default class PhotoEditorExtensionAbility extends UIExtensionAbility { onStartContentEditing(uri, want, session) { - console.log("onStartContentEditing: " + uri); + console.log('onStartContentEditing: ' + uri); } } \ No newline at end of file diff --git a/frameworks/js/napi/photo_editor_extension_context/BUILD.gn b/frameworks/js/napi/photo_editor_extension_context/BUILD.gn index 0083cb3d58..de262e2a03 100755 --- a/frameworks/js/napi/photo_editor_extension_context/BUILD.gn +++ b/frameworks/js/napi/photo_editor_extension_context/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_photo_editor_extension_context_abc") { diff --git a/frameworks/js/napi/photo_editor_extension_context/photo_editor_extension_context.js b/frameworks/js/napi/photo_editor_extension_context/photo_editor_extension_context.js index 081a1bb4a4..b2e7e12e0a 100755 --- a/frameworks/js/napi/photo_editor_extension_context/photo_editor_extension_context.js +++ b/frameworks/js/napi/photo_editor_extension_context/photo_editor_extension_context.js @@ -21,12 +21,12 @@ export class PhotoEditorExtensionContext extends UIExtensionContext { } saveEditedContentWithUri(uri, asyncCallback) { - console.log("saveEditedContent with uri: " + uri); + console.log('saveEditedContent with uri: ' + uri); return this.__context_impl__.saveEditedContentWithUri(uri, asyncCallback); } saveEditedContentWithImage(image, option, asyncCallback) { - console.log("saveEditedContent with image pixmap."); + console.log('saveEditedContent with image pixmap.'); return this.__context_impl__.saveEditedContentWithImage(image, option, asyncCallback); } } \ No newline at end of file diff --git a/frameworks/js/napi/quick_fix/js_quick_fix_manager.cpp b/frameworks/js/napi/quick_fix/js_quick_fix_manager.cpp index 062496f908..03d123c1c5 100644 --- a/frameworks/js/napi/quick_fix/js_quick_fix_manager.cpp +++ b/frameworks/js/napi/quick_fix/js_quick_fix_manager.cpp @@ -16,7 +16,6 @@ #include "js_quick_fix_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_application_quick_fix_info.h" #include "js_runtime_utils.h" #include "napi_common_util.h" diff --git a/frameworks/js/napi/service_extension_ability/BUILD.gn b/frameworks/js/napi/service_extension_ability/BUILD.gn index e3c2840621..fcb1d34720 100644 --- a/frameworks/js/napi/service_extension_ability/BUILD.gn +++ b/frameworks/js/napi/service_extension_ability/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_service_extension_ability_abc") { diff --git a/frameworks/js/napi/service_extension_context/BUILD.gn b/frameworks/js/napi/service_extension_context/BUILD.gn index 87a16c15dd..84cd644117 100644 --- a/frameworks/js/napi/service_extension_context/BUILD.gn +++ b/frameworks/js/napi/service_extension_context/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_service_extension_context_abc") { diff --git a/frameworks/js/napi/service_extension_context/service_extension_context.js b/frameworks/js/napi/service_extension_context/service_extension_context.js index 548bdfb6a1..2adf22cffc 100644 --- a/frameworks/js/napi/service_extension_context/service_extension_context.js +++ b/frameworks/js/napi/service_extension_context/service_extension_context.js @@ -65,6 +65,11 @@ class ServiceExtensionContext extends ExtensionContext { return this.__context_impl__.startServiceExtensionAbility(want, callback); } + startUIServiceExtensionAbility(want, callback) { + console.log('startUIServiceExtensionAbility'); + return this.__context_impl__.startUIServiceExtensionAbility(want, callback); + } + startServiceExtensionAbilityWithAccount(want, accountId, callback) { console.log('startServiceExtensionAbilityWithAccount'); return this.__context_impl__.startServiceExtensionAbilityWithAccount(want, accountId, callback); @@ -154,6 +159,11 @@ class ServiceExtensionContext extends ExtensionContext { return; }); } + + preStartMission(bundleName, moduleName, abilityName, startTime) { + console.log('preStartMission'); + return this.__context_impl__.preStartMission(bundleName, moduleName, abilityName, startTime); + } } export default ServiceExtensionContext; diff --git a/frameworks/js/napi/share_extension_ability/BUILD.gn b/frameworks/js/napi/share_extension_ability/BUILD.gn index 37e620a030..9388f58551 100755 --- a/frameworks/js/napi/share_extension_ability/BUILD.gn +++ b/frameworks/js/napi/share_extension_ability/BUILD.gn @@ -9,9 +9,9 @@ # 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("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_share_extension_ability_abc") { diff --git a/frameworks/js/napi/ui_extension_ability/BUILD.gn b/frameworks/js/napi/ui_extension_ability/BUILD.gn index 60aeaf00d1..af23dfd573 100755 --- a/frameworks/js/napi/ui_extension_ability/BUILD.gn +++ b/frameworks/js/napi/ui_extension_ability/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_ui_extension_ability_abc") { diff --git a/frameworks/js/napi/ui_extension_context/BUILD.gn b/frameworks/js/napi/ui_extension_context/BUILD.gn index c96af30065..e49ad18138 100755 --- a/frameworks/js/napi/ui_extension_context/BUILD.gn +++ b/frameworks/js/napi/ui_extension_context/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_ui_extension_context_abc") { diff --git a/frameworks/js/napi/ui_extension_context/ui_extension_context.js b/frameworks/js/napi/ui_extension_context/ui_extension_context.js index 1459ef67cd..6bf5395574 100755 --- a/frameworks/js/napi/ui_extension_context/ui_extension_context.js +++ b/frameworks/js/napi/ui_extension_context/ui_extension_context.js @@ -34,6 +34,19 @@ class UIExtensionContext extends ExtensionContext { return this.__context_impl__.startAbility(want, options, callback); } + startUIServiceExtensionAbility(want, callback) { + console.log('startUIServiceExtensionAbility'); + return this.__context_impl__.startUIServiceExtensionAbility(want, callback); + } + + connectUIServiceExtensionAbility(want, callback) { + return this.__context_impl__.connectUIServiceExtensionAbility(want, callback); + } + + disconnectUIServiceExtensionAbility(proxy) { + return this.__context_impl__.disconnectUIServiceExtensionAbility(proxy); + } + openLink(link, options, callback) { console.log('openLink'); return this.__context_impl__.openLink(link, options, callback); diff --git a/frameworks/js/napi/ui_service_extension_ability/BUILD.gn b/frameworks/js/napi/ui_service_extension_ability/BUILD.gn new file mode 100644 index 0000000000..35981050ec --- /dev/null +++ b/frameworks/js/napi/ui_service_extension_ability/BUILD.gn @@ -0,0 +1,89 @@ +# 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/config/components/ets_frontend/es2abc_config.gni") +import("//build/ohos.gni") + +es2abc_gen_abc("gen_ui_service_extension_ability_abc") { + src_js = rebase_path("ui_service_extension_ability.js") + dst_file = rebase_path(target_out_dir + "/ui_service_extension_ability.abc") + in_puts = [ "ui_service_extension_ability.js" ] + out_puts = [ target_out_dir + "/ui_service_extension_ability.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("ui_service_extension_ability_js") { + input = "ui_service_extension_ability.js" + output = target_out_dir + "/ui_service_extension_ability.o" +} + +gen_js_obj("ui_service_extension_ability_abc") { + input = get_label_info(":gen_ui_service_extension_ability_abc", + "target_out_dir") + "/ui_service_extension_ability.abc" + output = target_out_dir + "/ui_service_extension_ability_abc.o" + dep = ":gen_ui_service_extension_ability_abc" +} + +ohos_shared_library("uiserviceextensionability_napi") { + 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" + + sources = [ "ui_service_extension_ability_module.cpp" ] + + deps = [ + ":ui_service_extension_ability_abc", + ":ui_service_extension_ability_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "ability" + part_name = "ability_runtime" +} + +ohos_shared_library("uiserviceextensionability") { + 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" + + sources = [ "ui_service_extension_ability_module.cpp" ] + + deps = [ + ":ui_service_extension_ability_abc", + ":ui_service_extension_ability_js", + ] + + external_deps = [ "napi:ace_napi" ] + + defines = [ "ENABLE_ERRCODE" ] + + relative_install_dir = "module/app/ability" + subsystem_name = "ability" + part_name = "ability_runtime" +} diff --git a/frameworks/js/napi/ui_service_extension_ability/ui_service_extension_ability.js b/frameworks/js/napi/ui_service_extension_ability/ui_service_extension_ability.js new file mode 100644 index 0000000000..1063924513 --- /dev/null +++ b/frameworks/js/napi/ui_service_extension_ability/ui_service_extension_ability.js @@ -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. + */ + +let ExtensionAbility = requireNapi('app.ability.ExtensionAbility'); + +class UIServiceExtensionAbility extends ExtensionAbility { + onCreate(want) { + console.log('onCreate, want:' + want.abilityName); + } + + onRequest(want, startId) { + console.log('onRequest, want:' + want.abilityName + ', startId:' + startId); + } + + onConnect(want, proxy) { + console.log('onConnect, want:' + want.abilityName + ''); + } + + onDisconnect(want, proxy) { + console.log('onDisconnect'); + } + + onWindowWillCreate(config) { + console.log('onWindowStageWillCreate'); + } + + onWindowDidCreate(window) { + console.log('onWindowStageDidCreate'); + } + + onData(data) { + console.log('onData'); + } + + onDestroy() { + console.log('onDestroy'); + } +} + +export default UIServiceExtensionAbility; diff --git a/frameworks/js/napi/ui_service_extension_ability/ui_service_extension_ability_module.cpp b/frameworks/js/napi/ui_service_extension_ability/ui_service_extension_ability_module.cpp new file mode 100644 index 0000000000..0cb01a1a6e --- /dev/null +++ b/frameworks/js/napi/ui_service_extension_ability/ui_service_extension_ability_module.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 "native_engine/native_engine.h" + +extern const char _binary_ui_service_extension_ability_js_start[]; +extern const char _binary_ui_service_extension_ability_js_end[]; +extern const char _binary_ui_service_extension_ability_abc_start[]; +extern const char _binary_ui_service_extension_ability_abc_end[]; + +static napi_module _module = { + .nm_version = 0, + .nm_filename = "app/ability/libuiserviceextensionability_napi.so/ui_service_extension_ability.js", + .nm_modname = "app.ability.UIServiceExtensionAbility", +}; +extern "C" __attribute__((constructor)) +void NAPI_app_ability_UIServiceExtensionAbility_AutoRegister() +{ + napi_module_register(&_module); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_app_ability_UIServiceExtensionAbility_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_ui_service_extension_ability_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_ui_service_extension_ability_js_end - _binary_ui_service_extension_ability_js_start; + } +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_app_ability_UIServiceExtensionAbility_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_ui_service_extension_ability_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_ui_service_extension_ability_abc_end - _binary_ui_service_extension_ability_abc_start; + } +} diff --git a/frameworks/js/napi/ui_service_extension_context/BUILD.gn b/frameworks/js/napi/ui_service_extension_context/BUILD.gn new file mode 100644 index 0000000000..7428637b69 --- /dev/null +++ b/frameworks/js/napi/ui_service_extension_context/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/config/components/ets_frontend/es2abc_config.gni") +import("//build/ohos.gni") + +es2abc_gen_abc("gen_ui_service_extension_context_abc") { + src_js = rebase_path("ui_service_extension_context.js") + dst_file = rebase_path(target_out_dir + "/ui_service_extension_context.abc") + in_puts = [ "ui_service_extension_context.js" ] + out_puts = [ target_out_dir + "/ui_service_extension_context.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("ui_service_extension_context_js") { + input = "ui_service_extension_context.js" + output = target_out_dir + "/ui_service_extension_context.o" +} + +gen_js_obj("ui_service_extension_context_abc") { + input = get_label_info(":gen_ui_service_extension_context_abc", + "target_out_dir") + "/ui_service_extension_context.abc" + output = target_out_dir + "/ui_service_extension_context_abc.o" + dep = ":gen_ui_service_extension_context_abc" +} + +ohos_shared_library("uiserviceextensioncontext_napi") { + 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" + + sources = [ "ui_service_extension_context_module.cpp" ] + + deps = [ + ":ui_service_extension_context_abc", + ":ui_service_extension_context_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/application" + subsystem_name = "ability" + part_name = "ability_runtime" +} diff --git a/frameworks/js/napi/ui_service_extension_context/ui_service_extension_context.js b/frameworks/js/napi/ui_service_extension_context/ui_service_extension_context.js new file mode 100644 index 0000000000..af7d30ea91 --- /dev/null +++ b/frameworks/js/napi/ui_service_extension_context/ui_service_extension_context.js @@ -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. + */ + +let ExtensionContext = requireNapi('application.ExtensionContext'); + +class UIServiceExtensionContext extends ExtensionContext { + constructor(obj) { + super(obj); + } + + startAbility(want, options) { + console.log('startAbility'); + return this.__context_impl__.startAbility(want, options); + } + + terminateSelf() { + console.log('terminateSelf'); + return this.__context_impl__.terminateSelf(); + } + + startAbilityByType(type, wantParam, abilityStartCallback) { + console.log('startAbilityByType'); + return this.__context_impl__.startAbilityByType(type, wantParam, abilityStartCallback); + } + +} + +export default UIServiceExtensionContext; diff --git a/frameworks/js/napi/ui_service_extension_context/ui_service_extension_context_module.cpp b/frameworks/js/napi/ui_service_extension_context/ui_service_extension_context_module.cpp new file mode 100644 index 0000000000..4a43af2222 --- /dev/null +++ b/frameworks/js/napi/ui_service_extension_context/ui_service_extension_context_module.cpp @@ -0,0 +1,56 @@ +/* + * 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_engine/native_engine.h" + +extern const char _binary_ui_service_extension_context_js_start[]; +extern const char _binary_ui_service_extension_context_js_end[]; +extern const char _binary_ui_service_extension_context_abc_start[]; +extern const char _binary_ui_service_extension_context_abc_end[]; + +static napi_module _module = { + .nm_version = 0, + .nm_filename = "application/libuiserviceextensioncontext_napi.so/UIServiceExtensionContext.js", + .nm_modname = "application.UIServiceExtensionContext", +}; +extern "C" __attribute__((constructor)) +void NAPI_application_UIServiceExtensionContext_AutoRegister() +{ + napi_module_register(&_module); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_application_UIServiceExtensionContext_GetJSCode(const char **buf, int *bufLen) +{ + if (buf != nullptr) { + *buf = _binary_ui_service_extension_context_js_start; + } + + if (bufLen != nullptr) { + *bufLen = _binary_ui_service_extension_context_js_end - _binary_ui_service_extension_context_js_start; + } +} + +// ability_context JS register +extern "C" __attribute__((visibility("default"))) +void NAPI_application_UIServiceExtensionContext_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_ui_service_extension_context_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_ui_service_extension_context_abc_end - _binary_ui_service_extension_context_abc_start; + } +} 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 ab3aa50245..b8f1646976 100644 --- a/frameworks/js/napi/uri_permission/js_uri_perm_mgr.cpp +++ b/frameworks/js/napi/uri_permission/js_uri_perm_mgr.cpp @@ -19,7 +19,6 @@ #include "ability_manager_errors.h" #include "ability_runtime_error_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "js_error_utils.h" #include "js_runtime_utils.h" diff --git a/frameworks/js/napi/wantConstant/want_constant.cpp b/frameworks/js/napi/wantConstant/want_constant.cpp index 406a449b7b..15953d7a36 100644 --- a/frameworks/js/napi/wantConstant/want_constant.cpp +++ b/frameworks/js/napi/wantConstant/want_constant.cpp @@ -15,7 +15,6 @@ #include "want_constant.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { @@ -114,6 +113,11 @@ napi_value WantConstantInit(napi_env env, napi_value exports) SetNamedProperty(env, params, "ohos.extra.param.key.supportContinueSourceExit", "SUPPORT_CONTINUE_SOURCE_EXIT_KEY"); SetNamedProperty(env, params, "ohos.extra.param.key.showMode", "SHOW_MODE_KEY"); SetNamedProperty(env, params, "ohos.extra.param.key.appCloneIndex", "APP_CLONE_INDEX_KEY"); + SetNamedProperty(env, params, "ohos.param.atomicservice.pagePath", "PAGE_PATH"); + SetNamedProperty(env, params, "ohos.param.atomicservice.routerName", "ROUTER_NAME"); + SetNamedProperty(env, params, "ohos.param.atomicservice.pageSourceFile", "PAGE_SOURCE_FILE"); + SetNamedProperty(env, params, "ohos.param.atomicservice.buildFunction", "BUILD_FUNCTION"); + SetNamedProperty(env, params, "ohos.param.atomicservice.subpackageName", "SUB_PACKAGE_NAME"); napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("Action", action), DECLARE_NAPI_PROPERTY("Entity", entity), diff --git a/frameworks/js/napi/wantagent/ability_want_agent/want_agent_module.cpp b/frameworks/js/napi/wantagent/ability_want_agent/want_agent_module.cpp index c9a5757bec..c938944218 100644 --- a/frameworks/js/napi/wantagent/ability_want_agent/want_agent_module.cpp +++ b/frameworks/js/napi/wantagent/ability_want_agent/want_agent_module.cpp @@ -23,7 +23,6 @@ #include "napi/native_node_api.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" using namespace OHOS::AbilityRuntime; diff --git a/frameworks/js/napi/wantagent/napi_want_agent.cpp b/frameworks/js/napi/wantagent/napi_want_agent.cpp index 243b73d9f8..f889830acc 100644 --- a/frameworks/js/napi/wantagent/napi_want_agent.cpp +++ b/frameworks/js/napi/wantagent/napi_want_agent.cpp @@ -22,9 +22,7 @@ #include "ability_runtime_error_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" -#include "js_runtime_utils.h" #include "napi_common.h" #include "start_options.h" #include "want_agent_helper.h" @@ -75,7 +73,7 @@ void TriggerCompleteCallBack::SetCallbackInfo(napi_env env, NativeReference* ref triggerCompleteInfo_.nativeRef.reset(ref); } -void TriggerCompleteCallBack::SetWantAgentInstance(WantAgent* wantAgent) +void TriggerCompleteCallBack::SetWantAgentInstance(std::shared_ptr wantAgent) { triggerCompleteInfo_.wantAgent = wantAgent; } @@ -222,7 +220,9 @@ void TriggerCompleteCallBack::OnSendFinished( dataWorker->resultExtras = resultExtras; dataWorker->env = triggerCompleteInfo_.env; dataWorker->nativeRef = std::move(triggerCompleteInfo_.nativeRef); - dataWorker->wantAgent = triggerCompleteInfo_.wantAgent; + if (triggerCompleteInfo_.wantAgent != nullptr) { + dataWorker->wantAgent = new WantAgent(triggerCompleteInfo_.wantAgent->GetPendingWant()); + } work->data = static_cast(dataWorker); int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, OnSendFinishedUvAfterWorkCallback); if (ret != 0) { @@ -313,6 +313,40 @@ napi_value JsWantAgent::NapiGetOperationType(napi_env env, napi_callback_info in return (me != nullptr) ? me->OnNapiGetOperationType(env, info) : nullptr; }; +napi_value JsWantAgent::HandleInvalidParam(napi_env env, napi_value lastParam, const std::string &errorMessage) +{ + #ifdef ENABLE_ERRCODE + ThrowInvalidParamError(env, errorMessage); + return CreateJsUndefined(env); + #else + return RetErrMsg(env, lastParam, ERR_NOT_OK); + #endif +} + +void HandleAsyncTaskResult(napi_env env, NapiAsyncTask &task, ErrCode retCode) +{ + bool ret = false; + #ifdef ENABLE_ERRCODE + if (retCode == ERR_NOT_OK) { + ret = false; + task.ResolveWithNoError(env, CreateJsValue(env, ret)); + } else if (retCode == ERR_OK) { + ret = true; + task.ResolveWithNoError(env, CreateJsValue(env, ret)); + } else { + task.Reject(env, CreateJsError(env, retCode, AbilityRuntimeErrorUtil::GetErrMessage(retCode))); + } + #else + if (retCode != ERR_OK) { + ret = false; + task.Resolve(env, CreateJsValue(env, ret)); + } else { + ret = true; + task.Resolve(env, CreateJsValue(env, ret)); + } + #endif +} + napi_value JsWantAgent::OnEqual(napi_env env, napi_callback_info info) { size_t argc = ARGS_MAX_COUNT; @@ -332,44 +366,25 @@ napi_value JsWantAgent::OnEqual(napi_env env, napi_callback_info info) napi_value lastParam = (argc >= ARGC_THREE) ? argv[INDEX_TWO] : nullptr; if (!CheckTypeForNapiValue(env, argv[0], napi_object)) { TAG_LOGE(AAFwkTag::WANTAGENT, "Wrong argument type. Object expected."); -#ifdef ENABLE_ERRCODE - ThrowInvalidParamError(env, "Wrong argument type. Agent must be a WantAgent."); - return CreateJsUndefined(env); -#else - return RetErrMsg(env, lastParam, ERR_NOT_OK); -#endif + return HandleInvalidParam(env, lastParam, "Wrong argument type. Agent must be a WantAgent."); } UnwrapWantAgent(env, argv[0], reinterpret_cast(&pWantAgentFirst)); if (pWantAgentFirst == nullptr) { TAG_LOGE(AAFwkTag::WANTAGENT, "Parse pWantAgentFirst failed"); -#ifdef ENABLE_ERRCODE - ThrowInvalidParamError(env, "Parse pWantAgentFirst failed. Agent must be a WantAgent."); - return CreateJsUndefined(env); -#else - return RetErrMsg(env, lastParam, ERR_NOT_OK); -#endif + return HandleInvalidParam(env, lastParam, "Parse pWantAgentFirst failed. Agent must be a WantAgent."); } if (!CheckTypeForNapiValue(env, argv[1], napi_object)) { TAG_LOGE(AAFwkTag::WANTAGENT, "Wrong argument type. Object expected."); -#ifdef ENABLE_ERRCODE - ThrowInvalidParamError(env, "Wrong argument type. OtherAgent must be a WantAgent."); - return CreateJsUndefined(env); -#else - return RetErrMsg(env, lastParam, ERR_NOT_OK); -#endif + return HandleInvalidParam(env, lastParam, "Wrong argument type. OtherAgent must be a WantAgent."); } UnwrapWantAgent(env, argv[1], reinterpret_cast(&pWantAgentSecond)); if (pWantAgentSecond == nullptr) { TAG_LOGE(AAFwkTag::WANTAGENT, "Parse pWantAgentSceond failed"); -#ifdef ENABLE_ERRCODE - ThrowInvalidParamError(env, "Parse pWantAgentSceond failed. OtherAgent must be a WantAgent."); - return CreateJsUndefined(env); -#else - return RetErrMsg(env, lastParam, ERR_NOT_OK); -#endif + return HandleInvalidParam(env, lastParam, + "Parse pWantAgentSceond failed. OtherAgent must be a WantAgent."); } std::shared_ptr wantAgentFirst = std::make_shared(*pWantAgentFirst); @@ -377,27 +392,8 @@ napi_value JsWantAgent::OnEqual(napi_env env, napi_callback_info info) NapiAsyncTask::CompleteCallback complete = [wantAgentFirst, wantAgentSecond](napi_env env, NapiAsyncTask &task, int32_t status) { TAG_LOGD(AAFwkTag::WANTAGENT, "OnEqual NapiAsyncTask is called"); - bool ret = false; ErrCode retCode = WantAgentHelper::IsEquals(wantAgentFirst, wantAgentSecond); -#ifdef ENABLE_ERRCODE - if (retCode == ERR_NOT_OK) { - ret = false; - task.ResolveWithNoError(env, CreateJsValue(env, ret)); - } else if (retCode == ERR_OK) { - ret = true; - task.ResolveWithNoError(env, CreateJsValue(env, ret)); - } else { - task.Reject(env, CreateJsError(env, retCode, AbilityRuntimeErrorUtil::GetErrMessage(retCode))); - } -#else - if (retCode != ERR_OK) { - ret = false; - task.Resolve(env, CreateJsValue(env, ret)); - } else { - ret = true; - task.Resolve(env, CreateJsValue(env, ret)); - } -#endif + HandleAsyncTaskResult(env, task, retCode); }; napi_value result = nullptr; @@ -535,7 +531,19 @@ napi_value JsWantAgent::OnGetBundleName(napi_env env, napi_callback_info info) } std::shared_ptr wantAgent = std::make_shared(*pWantAgent); - NapiAsyncTask::CompleteCallback complete = [wantAgent](napi_env env, NapiAsyncTask &task, int32_t status) { + NapiAsyncTask::CompleteCallback complete; + SetOnGetBundleNameCallback(wantAgent, complete); + + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("JsWantAgent::OnGetBundleName", + env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +void JsWantAgent::SetOnGetBundleNameCallback(std::shared_ptr wantAgent, + NapiAsyncTask::CompleteCallback &complete) +{ + complete = [wantAgent](napi_env env, NapiAsyncTask &task, int32_t status) { TAG_LOGD(AAFwkTag::WANTAGENT, "OnGetBundleName NapiAsyncTask is called"); std::string bundleName = ""; #ifdef ENABLE_ERRCODE @@ -550,11 +558,6 @@ napi_value JsWantAgent::OnGetBundleName(napi_env env, napi_callback_info info) task.Resolve(env, CreateJsValue(env, bundleName)); #endif }; - - napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JsWantAgent::OnGetBundleName", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); - return result; } napi_value JsWantAgent::OnGetUid(napi_env env, napi_callback_info info) @@ -595,7 +598,19 @@ napi_value JsWantAgent::OnGetUid(napi_env env, napi_callback_info info) } std::shared_ptr wantAgent = std::make_shared(*pWantAgent); - NapiAsyncTask::CompleteCallback complete = [wantAgent](napi_env env, NapiAsyncTask &task, int32_t status) { + NapiAsyncTask::CompleteCallback complete; + SetOnGetUidCallback(wantAgent, complete); + + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("JsWantAgent::OnGetUid", + env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +void JsWantAgent::SetOnGetUidCallback(std::shared_ptr wantAgent, + NapiAsyncTask::CompleteCallback &complete) +{ + complete = [wantAgent](napi_env env, NapiAsyncTask &task, int32_t status) { TAG_LOGD(AAFwkTag::WANTAGENT, "OnGetUid NapiAsyncTask is called"); int uid = -1; #ifdef ENABLE_ERRCODE @@ -610,10 +625,6 @@ napi_value JsWantAgent::OnGetUid(napi_env env, napi_callback_info info) task.Resolve(env, CreateJsValue(env, uid)); #endif }; - napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JsWantAgent::OnGetUid", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); - return result; } napi_value JsWantAgent::OnCancel(napi_env env, napi_callback_info info) @@ -654,8 +665,19 @@ napi_value JsWantAgent::OnCancel(napi_env env, napi_callback_info info) } std::shared_ptr wantAgent = std::make_shared(*pWantAgent); - NapiAsyncTask::CompleteCallback complete = - [wantAgent](napi_env env, NapiAsyncTask &task, int32_t status) { + NapiAsyncTask::CompleteCallback complete; + SetOnCancelCallback(wantAgent, complete); + + napi_value result = nullptr; + NapiAsyncTask::Schedule("JsWantAgent::OnCancel", + env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +void JsWantAgent::SetOnCancelCallback(std::shared_ptr wantAgent, + NapiAsyncTask::CompleteCallback &complete) +{ + complete = [wantAgent](napi_env env, NapiAsyncTask &task, int32_t status) { TAG_LOGD(AAFwkTag::WANTAGENT, "OnCancel NapiAsyncTask is called"); #ifdef ENABLE_ERRCODE ErrCode result = WantAgentHelper::Cancel(wantAgent); @@ -669,11 +691,6 @@ napi_value JsWantAgent::OnCancel(napi_env env, napi_callback_info info) task.Resolve(env, CreateJsUndefined(env)); #endif }; - - napi_value result = nullptr; - NapiAsyncTask::Schedule("JsWantAgent::OnCancel", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); - return result; } napi_value JsWantAgent::OnTrigger(napi_env env, napi_callback_info info) @@ -745,7 +762,65 @@ int32_t JsWantAgent::UnWrapTriggerInfoParam(napi_env env, napi_callback_info inf napi_ref ref = nullptr; napi_create_reference(env, argv[ARGC_TWO], 1, &ref); triggerObj->SetCallbackInfo(env, reinterpret_cast(ref)); - triggerObj->SetWantAgentInstance(pWantAgent); + triggerObj->SetWantAgentInstance(std::make_shared(pWantAgent->GetPendingWant())); + + return BUSINESS_ERROR_CODE_OK; +} + +int32_t JsWantAgent::GetTriggerWant(napi_env env, napi_value param, std::shared_ptr &want) +{ + bool hasWant = false; + napi_has_named_property(env, param, "want", &hasWant); + if (hasWant) { + napi_value jsWant = nullptr; + napi_get_named_property(env, param, "want", &jsWant); + want = std::make_shared(); + if (!UnwrapWant(env, jsWant, *want)) { + TAG_LOGE(AAFwkTag::WANTAGENT, "GetTriggerInfo convert want error!"); + return ERR_NOT_OK; + } + } + + return BUSINESS_ERROR_CODE_OK; +} + +int32_t JsWantAgent::GetTriggerPermission(napi_env env, napi_value param, std::string &permission) +{ + bool hasPermission = false; + napi_has_named_property(env, param, "permission", &hasPermission); + if (hasPermission) { + napi_value jsPermission = nullptr; + napi_get_named_property(env, param, "permission", &jsPermission); + if (!ConvertFromJsValue(env, jsPermission, permission)) { + TAG_LOGE(AAFwkTag::WANTAGENT, "GetTriggerInfo convert permission error!"); + return ERR_NOT_OK; + } + } + + return BUSINESS_ERROR_CODE_OK; +} + +int32_t JsWantAgent::GetTriggerExtraInfo(napi_env env, napi_value param, std::shared_ptr &extraInfo) +{ + bool hasExtraInfo = false; + napi_value jsExtraInfo = nullptr; + napi_has_named_property(env, param, "extraInfos", &hasExtraInfo); + if (hasExtraInfo) { + napi_get_named_property(env, param, "extraInfos", &jsExtraInfo); + } else { + napi_has_named_property(env, param, "extraInfo", &hasExtraInfo); + if (hasExtraInfo) { + napi_get_named_property(env, param, "extraInfo", &jsExtraInfo); + } + } + if (hasExtraInfo) { + extraInfo = std::make_shared(); + if (!UnwrapWantParams(env, (jsExtraInfo), + *extraInfo)) { + TAG_LOGE(AAFwkTag::WANTAGENT, "GetTriggerInfo convert extraInfo error!"); + return ERR_NOT_OK; + } + } return BUSINESS_ERROR_CODE_OK; } @@ -767,49 +842,21 @@ int32_t JsWantAgent::GetTriggerInfo(napi_env env, napi_value param, TriggerInfo } std::shared_ptr want = nullptr; - bool hasWant = false; - napi_has_named_property(env, param, "want", &hasWant); - if (hasWant) { - napi_value jsWant = nullptr; - napi_get_named_property(env, param, "want", &jsWant); - want = std::make_shared(); - if (!UnwrapWant(env, jsWant, *want)) { - TAG_LOGE(AAFwkTag::WANTAGENT, "GetTriggerInfo convert want error!"); - return ERR_NOT_OK; - } + if (GetTriggerWant(env, param, want) == ERR_NOT_OK) { + TAG_LOGE(AAFwkTag::WANTAGENT, "Call GetTriggerWant GetTriggerInfo convert code error!"); + return ERR_NOT_OK; } std::string permission = ""; - bool hasPermission = false; - napi_has_named_property(env, param, "permission", &hasPermission); - if (hasPermission) { - napi_value jsPermission = nullptr; - napi_get_named_property(env, param, "permission", &jsPermission); - if (!ConvertFromJsValue(env, jsPermission, permission)) { - TAG_LOGE(AAFwkTag::WANTAGENT, "GetTriggerInfo convert permission error!"); - return ERR_NOT_OK; - } + if (GetTriggerPermission(env, param, permission) == ERR_NOT_OK) { + TAG_LOGE(AAFwkTag::WANTAGENT, "Call GetTriggerPermission GetTriggerInfo convert code error!"); + return ERR_NOT_OK; } std::shared_ptr extraInfo = nullptr; - bool hasExtraInfo = false; - napi_value jsExtraInfo = nullptr; - napi_has_named_property(env, param, "extraInfos", &hasExtraInfo); - if (hasExtraInfo) { - napi_get_named_property(env, param, "extraInfos", &jsExtraInfo); - } else { - napi_has_named_property(env, param, "extraInfo", &hasExtraInfo); - if (hasExtraInfo) { - napi_get_named_property(env, param, "extraInfo", &jsExtraInfo); - } - } - if (hasExtraInfo) { - extraInfo = std::make_shared(); - if (!UnwrapWantParams(env, (jsExtraInfo), - *extraInfo)) { - TAG_LOGE(AAFwkTag::WANTAGENT, "GetTriggerInfo convert extraInfo error!"); - return ERR_NOT_OK; - } + if (GetTriggerExtraInfo(env, param, extraInfo) == ERR_NOT_OK) { + TAG_LOGE(AAFwkTag::WANTAGENT, "Call GetTriggerExtraInfo GetTriggerInfo convert code error!"); + return ERR_NOT_OK; } std::shared_ptr startOptions = nullptr; @@ -1193,7 +1240,20 @@ napi_value JsWantAgent::OnNapiGetWantAgent(napi_env env, napi_callback_info info return CreateJsUndefined(env); } - NapiAsyncTask::CompleteCallback complete = [weak = weak_from_this(), parasobj = spParas](napi_env env, + NapiAsyncTask::CompleteCallback complete; + SetOnNapiGetWantAgentCallback(spParas, complete); + + napi_value lastParam = (argc >= ARGC_TWO) ? argv[INDEX_ONE] : nullptr; + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("JsWantAgent::OnNapiGetWantAgent", + env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +void JsWantAgent::SetOnNapiGetWantAgentCallback(std::shared_ptr spParas, + AbilityRuntime::NapiAsyncTask::CompleteCallback &complete) +{ + complete = [weak = weak_from_this(), parasobj = spParas](napi_env env, NapiAsyncTask &task, int32_t status) { TAG_LOGD(AAFwkTag::WANTAGENT, "OnNapiGetWantAgent NapiAsyncTask is called"); auto self = weak.lock(); @@ -1228,12 +1288,6 @@ napi_value JsWantAgent::OnNapiGetWantAgent(napi_env env, napi_callback_info info } } }; - - napi_value lastParam = (argc >= ARGC_TWO) ? argv[INDEX_ONE] : nullptr; - napi_value result = nullptr; - NapiAsyncTask::ScheduleHighQos("JsWantAgent::OnNapiGetWantAgent", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); - return result; } napi_value JsWantAgent::OnNapiGetOperationType(napi_env env, napi_callback_info info) diff --git a/frameworks/js/napi/wantagent/napi_want_agent.h b/frameworks/js/napi/wantagent/napi_want_agent.h index 763266ce3a..dd00fec42e 100644 --- a/frameworks/js/napi/wantagent/napi_want_agent.h +++ b/frameworks/js/napi/wantagent/napi_want_agent.h @@ -24,6 +24,7 @@ #include "ability.h" #include "completed_callback.h" #include "context/application_context.h" +#include "js_runtime_utils.h" #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" @@ -51,7 +52,7 @@ const uint8_t NUMBER_OF_PARAMETERS_NINE = 9; class TriggerCompleteCallBack; struct CallbackInfo { - WantAgent* wantAgent = nullptr; + std::shared_ptr wantAgent; napi_env env = nullptr; std::unique_ptr nativeRef = nullptr; }; @@ -112,6 +113,18 @@ private: std::shared_ptr &triggerObj); int32_t GetTriggerInfo(napi_env env, napi_value param, TriggerInfo &triggerInfo); int32_t GetWantAgentParam(napi_env env, napi_callback_info info, WantAgentWantsParas ¶s); + void SetOnGetBundleNameCallback(std::shared_ptr wantAgent, + AbilityRuntime::NapiAsyncTask::CompleteCallback &complete); + void SetOnGetUidCallback(std::shared_ptr wantAgent, + AbilityRuntime::NapiAsyncTask::CompleteCallback &complete); + void SetOnCancelCallback(std::shared_ptr wantAgent, + AbilityRuntime::NapiAsyncTask::CompleteCallback &complete); + void SetOnNapiGetWantAgentCallback(std::shared_ptr spParas, + AbilityRuntime::NapiAsyncTask::CompleteCallback &complete); + int32_t GetTriggerWant(napi_env env, napi_value param, std::shared_ptr &want); + int32_t GetTriggerPermission(napi_env env, napi_value param, std::string &permission); + int32_t GetTriggerExtraInfo(napi_env env, napi_value param, std::shared_ptr &extraInfo); + napi_value HandleInvalidParam(napi_env env, napi_value lastParam, const std::string &errorMessage); }; class TriggerCompleteCallBack : public CompletedCallback { @@ -123,7 +136,7 @@ public: void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, const AAFwk::WantParams &resultExtras) override; void SetCallbackInfo(napi_env env, NativeReference* ref); - void SetWantAgentInstance(WantAgent* wantAgent); + void SetWantAgentInstance(std::shared_ptr wantAgent); private: CallbackInfo triggerCompleteInfo_; diff --git a/frameworks/native/ability/BUILD.gn b/frameworks/native/ability/BUILD.gn index 1993d8ed19..b36077bc02 100644 --- a/frameworks/native/ability/BUILD.gn +++ b/frameworks/native/ability/BUILD.gn @@ -48,6 +48,7 @@ config("ability_context_public_config") { ohos_shared_library("ability_context_native") { public_configs = [ ":ability_context_public_config" ] + include_dirs = [ "${ability_runtime_path}/interfaces/kits/native/ability/native/ui_service_extension_ability/connection" ] sources = [ "ability_runtime/ability_connection.cpp", diff --git a/frameworks/native/ability/ability_runtime/ability_connection.cpp b/frameworks/native/ability/ability_runtime/ability_connection.cpp index d6789aa2cf..1c43bfe263 100644 --- a/frameworks/native/ability/ability_runtime/ability_connection.cpp +++ b/frameworks/native/ability/ability_runtime/ability_connection.cpp @@ -19,7 +19,6 @@ #include "connection_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/ability/ability_runtime/ability_context_impl.cpp b/frameworks/native/ability/ability_runtime/ability_context_impl.cpp index 14cfad71c2..e1dd5e01af 100644 --- a/frameworks/native/ability/ability_runtime/ability_context_impl.cpp +++ b/frameworks/native/ability/ability_runtime/ability_context_impl.cpp @@ -23,7 +23,6 @@ #include "dialog_request_callback_impl.h" #include "dialog_ui_extension_callback.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "remote_object_wrapper.h" #include "request_constants.h" #include "session_info.h" @@ -274,6 +273,18 @@ ErrCode AbilityContextImpl::StartAbilityForResultWithAccount( return err; } +ErrCode AbilityContextImpl::StartUIServiceExtensionAbility(const AAFwk::Want& want, int32_t accountId) +{ + TAG_LOGI(AAFwkTag::CONTEXT, "name:%{public}s %{public}s, accountId=%{public}d", + want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), accountId); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility( + want, token_, accountId, AppExecFwk::ExtensionAbilityType::UI_SERVICE); + if (err != ERR_OK) { + TAG_LOGE(AAFwkTag::CONTEXT, "StartUIServiceExtension is failed %{public}d", err); + } + return err; +} + ErrCode AbilityContextImpl::StartServiceExtensionAbility(const AAFwk::Want& want, int32_t accountId) { TAG_LOGI(AAFwkTag::CONTEXT, "name:%{public}s %{public}s, accountId=%{public}d", @@ -301,7 +312,7 @@ ErrCode AbilityContextImpl::StopServiceExtensionAbility(const AAFwk::Want& want, ErrCode AbilityContextImpl::TerminateAbilityWithResult(const AAFwk::Want& want, int resultCode) { TAG_LOGI(AAFwkTag::CONTEXT, "TerminateAbilityWithResult"); - isTerminating_ = true; + isTerminating_.store(true); #ifdef SUPPORT_SCREEN if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { auto sessionToken = GetSessionToken(); @@ -539,7 +550,7 @@ ErrCode AbilityContextImpl::MoveUIAbilityToBackground() ErrCode AbilityContextImpl::TerminateSelf() { TAG_LOGI(AAFwkTag::CONTEXT, "TerminateSelf"); - isTerminating_ = true; + isTerminating_.store(true); auto sessionToken = GetSessionToken(); if (sessionToken == nullptr) { TAG_LOGW(AAFwkTag::CONTEXT, "sessionToken is null"); @@ -576,7 +587,7 @@ ErrCode AbilityContextImpl::CloseAbility() { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::CONTEXT, "CloseAbility"); - isTerminating_ = true; + isTerminating_.store(true); AAFwk::Want resultWant; ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->CloseAbility(token_, -1, &resultWant); if (err != ERR_OK) { @@ -766,8 +777,12 @@ ErrCode AbilityContextImpl::GetMissionId(int32_t &missionId) ErrCode AbilityContextImpl::SetMissionContinueState(const AAFwk::ContinueState &state) { TAG_LOGD(AAFwkTag::CONTEXT, "SetMissionContinueState: %{public}d", state); - ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->SetMissionContinueState(token_, state, - sessionToken_.promote()); + auto sessionToken = GetSessionToken(); + if (sessionToken == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "sessionToken is null"); + return ERR_INVALID_VALUE; + } + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->SetMissionContinueState(token_, state, sessionToken); if (err != ERR_OK) { TAG_LOGE(AAFwkTag::CONTEXT, "SetMissionContinueState failed: %{public}d", err); } @@ -779,6 +794,13 @@ void AbilityContextImpl::InsertResultCallbackTask(int requestCode, RuntimeTask & TAG_LOGD(AAFwkTag::CONTEXT, "InsertResultCallbackTask"); resultCallbacks_.insert(make_pair(requestCode, std::move(task))); } + +void AbilityContextImpl::RemoveResultCallbackTask(int requestCode) +{ + TAG_LOGD(AAFwkTag::CONTEXT, "called"); + resultCallbacks_.erase(requestCode); +} + #ifdef SUPPORT_SCREEN void AbilityContextImpl::GetWindowRect(int32_t &left, int32_t &top, int32_t &width, int32_t &height) { @@ -882,10 +904,16 @@ ErrCode AbilityContextImpl::StartAbilityByType(const std::string &type, wantParams.Remove(FLAG_AUTH_READ_URI_PERMISSION); } Ace::ModalUIExtensionCallbacks callback; - callback.onError = std::bind(&JsUIExtensionCallback::OnError, uiExtensionCallbacks, std::placeholders::_1); - callback.onRelease = std::bind(&JsUIExtensionCallback::OnRelease, uiExtensionCallbacks, std::placeholders::_1); - callback.onResult = std::bind( - &JsUIExtensionCallback::OnResult, uiExtensionCallbacks, std::placeholders::_1, std::placeholders::_2); + callback.onError = [uiExtensionCallbacks](int32_t arg, const std::string &str1, const std::string &str2) { + uiExtensionCallbacks->OnError(arg); + }; + callback.onRelease = [uiExtensionCallbacks](int32_t arg) { + uiExtensionCallbacks->OnRelease(arg); + }; + callback.onResult = [uiExtensionCallbacks](int32_t arg1, const OHOS::AAFwk::Want arg2) { + uiExtensionCallbacks->OnResult(arg1, arg2); + }; + Ace::ModalUIExtensionConfig config; int32_t sessionId = uiContent->CreateModalUIExtension(want, callback, config); if (sessionId == 0) { @@ -940,9 +968,15 @@ ErrCode AbilityContextImpl::CreateModalUIExtensionWithApp(const AAFwk::Want &wan } auto disposedCallback = std::make_shared(abilityCallback); Ace::ModalUIExtensionCallbacks callback; - callback.onError = std::bind(&DialogUIExtensionCallback::OnError, disposedCallback); - callback.onRelease = std::bind(&DialogUIExtensionCallback::OnRelease, disposedCallback); - callback.onDestroy = std::bind(&DialogUIExtensionCallback::OnDestroy, disposedCallback); + callback.onError = [disposedCallback](int32_t arg1, const std::string &str1, const std::string &str2) { + disposedCallback->OnError(); + }; + callback.onRelease = [disposedCallback](int32_t arg1) { + disposedCallback->OnRelease(); + }; + callback.onDestroy = [disposedCallback]() { + disposedCallback->OnDestroy(); + }; Ace::ModalUIExtensionConfig config; int32_t sessionId = uiContent->CreateModalUIExtension(want, callback, config); if (sessionId == 0) { @@ -977,6 +1011,15 @@ ErrCode AbilityContextImpl::ChangeAbilityVisibility(bool isShow) return err; } +ErrCode AbilityContextImpl::AddFreeInstallObserver(const sptr &observer) +{ + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->AddFreeInstallObserver(token_, observer); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::CONTEXT, "AddFreeInstallObserver error, ret: %{public}d", ret); + } + return ret; +} + ErrCode AbilityContextImpl::OpenAtomicService(AAFwk::Want& want, const AAFwk::StartOptions &options, int requestCode, RuntimeTask &&task) { @@ -999,5 +1042,11 @@ bool AbilityContextImpl::GetRestoreEnabled() { return restoreEnabled_.load(); } + +ErrCode AbilityContextImpl::OpenLink(const AAFwk::Want& want, int requestCode) +{ + TAG_LOGD(AAFwkTag::CONTEXT, "called"); + return AAFwk::AbilityManagerClient::GetInstance()->OpenLink(want, token_, -1, requestCode); +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/ability/ability_runtime/authorization_result.cpp b/frameworks/native/ability/ability_runtime/authorization_result.cpp index 7bb24124ad..39f7f3e48b 100755 --- a/frameworks/native/ability/ability_runtime/authorization_result.cpp +++ b/frameworks/native/ability/ability_runtime/authorization_result.cpp @@ -15,7 +15,6 @@ #include "authorization_result.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/ability/ability_runtime/connection_manager.cpp b/frameworks/native/ability/ability_runtime/connection_manager.cpp index 1f41e4da44..e62b6bb1f7 100644 --- a/frameworks/native/ability/ability_runtime/connection_manager.cpp +++ b/frameworks/native/ability/ability_runtime/connection_manager.cpp @@ -22,7 +22,7 @@ #include "hichecker.h" #endif #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" +#include "ui_service_extension_connection_constants.h" namespace OHOS { namespace AbilityRuntime { @@ -88,10 +88,25 @@ ErrCode ConnectionManager::ConnectAbilityInner(const sptr& connec } } +void* ConnectionManager::GetUIServiceExtProxyPtr(const AAFwk::Want& want) +{ + sptr uiServiceExtProxySptr = want.GetRemoteObject(UISERVICEHOSTPROXY_KEY); + void* uiServiceExtProxy = nullptr; + if (uiServiceExtProxySptr != nullptr) { + uiServiceExtProxy = uiServiceExtProxySptr.GetRefPtr(); + } + return uiServiceExtProxy; +} + bool ConnectionManager::MatchConnection( const sptr& connectCaller, const AAFwk::Want& connectReceiver, int32_t accountId, const std::map>>::value_type& connection) { + void* uiServiceExtProxy = GetUIServiceExtProxyPtr(connectReceiver); + if (uiServiceExtProxy != connection.first.uiServiceExtProxy) { + return false; + } + if (accountId != connection.first.userid) { return false; } @@ -124,6 +139,8 @@ ErrCode ConnectionManager::CreateConnection(const sptr& connectCa std::lock_guard lock(connectionsLock_); if (ret == ERR_OK) { ConnectionInfo connectionInfo(connectCaller, want.GetOperation(), abilityConnection, accountId); + void* uiServiceExtProxy = GetUIServiceExtProxyPtr(want); + connectionInfo.SetUIServiceExtProxyPtr(uiServiceExtProxy); std::vector> callbacks; callbacks.push_back(connectCallback); abilityConnections_[connectionInfo] = callbacks; @@ -250,19 +267,19 @@ bool ConnectionManager::DisconnectNonexistentService( std::lock_guard lock(connectionsLock_); abilityConnections = abilityConnections_; } - HILOG_DEBUG("abilityConnectionsSize: %{public}zu", abilityConnections.size()); + TAG_LOGD(AAFwkTag::CONNECTION, "abilityConnectionsSize: %{public}zu", abilityConnections.size()); for (auto &&abilityConnection : abilityConnections) { ConnectionInfo connectionInfo = abilityConnection.first; if (connectionInfo.abilityConnection == connection && connectionInfo.connectReceiver.GetBundleName() == element.GetBundleName()) { - HILOG_DEBUG("find connection."); + TAG_LOGD(AAFwkTag::CONNECTION, "find connection."); exit = true; break; } } if (!exit) { - HILOG_ERROR("this service need disconnect"); + TAG_LOGE(AAFwkTag::CONNECTION, "this service need disconnect"); AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(connection); return true; } diff --git a/frameworks/native/ability/ability_runtime/dialog_request_callback_impl.cpp b/frameworks/native/ability/ability_runtime/dialog_request_callback_impl.cpp index 3ee96d16bc..2a53d60483 100755 --- a/frameworks/native/ability/ability_runtime/dialog_request_callback_impl.cpp +++ b/frameworks/native/ability/ability_runtime/dialog_request_callback_impl.cpp @@ -16,7 +16,6 @@ #include "dialog_request_callback_impl.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/ability/ability_runtime/dialog_ui_extension_callback.cpp b/frameworks/native/ability/ability_runtime/dialog_ui_extension_callback.cpp index b707ef8984..461372fa53 100644 --- a/frameworks/native/ability/ability_runtime/dialog_ui_extension_callback.cpp +++ b/frameworks/native/ability/ability_runtime/dialog_ui_extension_callback.cpp @@ -14,7 +14,6 @@ */ #include "dialog_ui_extension_callback.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { @@ -23,10 +22,10 @@ DialogUIExtensionCallback::DialogUIExtensionCallback(const std::weak_ptr(AppExecFwk::LaunchMode::SINGLETON)); localCallRecord_->SetIsSingleton(isSingleton); - auto callRecipient = new (std::nothrow) CallRecipient( - std::bind(&LocalCallContainer::OnCallStubDied, container, std::placeholders::_1)); + auto callRecipient = new (std::nothrow) CallRecipient([container](const wptr &arg) { + container->OnCallStubDied(arg); + }); localCallRecord_->SetRemoteObject(remoteObject, callRecipient); if (isSingleton) { diff --git a/frameworks/native/ability/ability_runtime/local_call_record.cpp b/frameworks/native/ability/ability_runtime/local_call_record.cpp index 1e50a9b2a1..de878c4ba4 100644 --- a/frameworks/native/ability/ability_runtime/local_call_record.cpp +++ b/frameworks/native/ability/ability_runtime/local_call_record.cpp @@ -15,7 +15,6 @@ #include "local_call_record.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/ability/native/BUILD.gn b/frameworks/native/ability/native/BUILD.gn index a07657ec94..6ee5f85a9c 100644 --- a/frameworks/native/ability/native/BUILD.gn +++ b/frameworks/native/ability/native/BUILD.gn @@ -36,8 +36,6 @@ config("ability_config") { "${ability_runtime_innerkits_path}/uri/include", "${ability_runtime_services_path}/abilitymgr/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/app", - "${ability_runtime_path}/interfaces/kits/native/appkit/app", - "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_innerkits_path}/ability_manager/include/continuation", "${ability_runtime_path}/interfaces/kits/native/appkit/app/task", "${ability_runtime_napi_path}/inner/napi_common", @@ -63,7 +61,6 @@ config("ability_config") { } if (ability_runtime_graphics) { - include_dirs += [ "${form_fwk_path}/interfaces/inner_api/include" ] defines += [ "SUPPORT_GRAPHICS", "SUPPORT_SCREEN", @@ -80,6 +77,7 @@ config("ability_public_config") { include_dirs = [ "${ability_runtime_napi_path}/inner/napi_ability_common", "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/interfaces/kits/native/ability/ability_runtime", "${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/distributed", "${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/kits", "${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/remote_register_service", @@ -96,11 +94,9 @@ config("ability_public_config") { if (ability_runtime_graphics) { include_dirs += [ - "${form_fwk_path}/interfaces/kits/native/include", - "${form_fwk_path}/interfaces/inner_api/include", - "${windowmanager_path}/interfaces/innerkits/dm", "${windowmanager_path}/interfaces/kits/napi/window_runtime/window_stage_napi", - "${windowmanager_path}/utils/include", + "${windowmanager_path}/interfaces/innerkits/wm", + "${windowmanager_path}/interfaces/innerkits/dm", ] defines = [ "SUPPORT_GRAPHICS" ] } @@ -192,7 +188,10 @@ ohos_shared_library("abilitykit_utils") { } ohos_shared_library("abilitykit_native") { - include_dirs = [ "${ability_runtime_path}/utils/global/time/include" ] + include_dirs = [ + "${ability_runtime_path}/utils/global/time/include", + "${ability_runtime_path}/interfaces/kits/native/ability/native/ui_service_extension_ability/connection", + ] sources = [ "${ability_runtime_innerkits_path}/app_manager/src/appmgr/process_info.cpp", @@ -208,12 +207,15 @@ ohos_shared_library("abilitykit_native") { "${ability_runtime_native_path}/ability/native/ability_runtime/js_ability.cpp", "${ability_runtime_native_path}/ability/native/ability_runtime/js_ability_context.cpp", "${ability_runtime_native_path}/ability/native/ability_runtime/js_caller_complex.cpp", + "${ability_runtime_native_path}/ability/native/ability_runtime/js_uiservice_ability_connection.cpp", + "${ability_runtime_native_path}/ability/native/ability_runtime/ui_ability_servicehost_stub_impl.cpp", "${ability_runtime_native_path}/ability/native/continuation/distributed/continuation_handler.cpp", "${ability_runtime_native_path}/ability/native/continuation/distributed/continuation_manager.cpp", "${ability_runtime_native_path}/ability/native/continuation/distributed/reverse_continuation_scheduler_primary.cpp", "${ability_runtime_native_path}/ability/native/data_ability_helper_impl.cpp", "${ability_runtime_native_path}/ability/native/data_ability_impl.cpp", "${ability_runtime_native_path}/ability/native/data_uri_utils.cpp", + "${ability_runtime_native_path}/ability/native/distributed_ability_runtime/distributed_client.cpp", "${ability_runtime_native_path}/ability/native/free_install_observer_proxy.cpp", "${ability_runtime_native_path}/ability/native/free_install_observer_stub.cpp", "${ability_runtime_native_path}/ability/native/insight_intent_host_client.cpp", @@ -236,6 +238,7 @@ ohos_shared_library("abilitykit_native") { deps = [ ":continuation_ipc", ":extension_blocklist_config", + ":ui_service_extension_connection", "${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", @@ -279,16 +282,19 @@ ohos_shared_library("abilitykit_native") { "json:nlohmann_json_static", "napi:ace_napi", "node:node_header_notice", - "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", ] + if (!(host_os == "linux" && host_cpu == "arm64")) { + external_deps += [ "relational_store:native_rdb" ] + } public_external_deps = [ "accessibility:accessibility_common", "bundle_framework:appexecfwk_core", "jsoncpp:jsoncpp", "libuv:uv", + "napi:ace_napi", ] defines = [] @@ -330,17 +336,19 @@ ohos_shared_library("abilitykit_native") { external_deps += [ "ability_base:session_info", - "form_fwk:form_manager", "icu:shared_icuuc", "image_framework:image", - "image_framework:image", "image_framework:image_native", "input:libmmi-client", - "window_manager:libdm", "window_manager:libwm", "window_manager:libwsutils", "window_manager:windowstage_kit", ] + + public_external_deps += [ + "form_fwk:form_manager", + "window_manager:libdm", + ] } innerapi_tags = [ "platformsdk" ] @@ -355,6 +363,7 @@ config("extensionkit_public_config") { "${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/distributed", "${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/kits", "${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/appkit/ability_runtime", "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_innerkits_path}/app_manager/include/appmgr", @@ -406,6 +415,7 @@ ohos_shared_library("extensionkit_native") { "eventhandler:libeventhandler", "hilog:libhilog", "hitrace:hitrace_meter", + "ipc:ipc_core", "json:nlohmann_json_static", "napi:ace_napi", ] @@ -568,7 +578,10 @@ ohos_shared_library("uiabilitykit_native") { "${ability_runtime_native_path}/ability/native/ability_runtime/cj_ui_ability.cpp", ] - include_dirs += [ "${ability_runtime_path}/frameworks/cj/ffi" ] + include_dirs += [ + "${ability_runtime_path}/frameworks/cj/ffi", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] defines = [ "CJ_FRONTEND" ] external_deps += [ "napi:cj_bind_ffi", @@ -680,6 +693,7 @@ ohos_shared_library("form_extension") { external_deps = [ "ability_base:want", + "access_token:libtokenid_sdk", "c_utils:utils", "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", @@ -728,6 +742,14 @@ ohos_shared_library("form_extension_module") { "window_manager:libwm", ] + if (ability_runtime_graphics) { + public_external_deps = [ + "form_fwk:fmskit_provider_client", + "form_fwk:form_manager", + "window_manager:libdm", + ] + } + relative_install_dir = "extensionability" subsystem_name = "ability" part_name = "ability_runtime" @@ -790,6 +812,224 @@ ohos_shared_library("service_extension") { part_name = "ability_runtime" } +ohos_shared_library("ui_service_extension_connection") { + 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" + + defines = [ "AMS_LOG_TAG = \"Ability\"" ] + defines += [ "AMS_LOG_DOMAIN = 0xD001300" ] + include_dirs = [ "${ability_runtime_path}/interfaces/kits/native/ability/native/ui_service_extension_ability/connection" ] + + sources = [ + "${ability_runtime_native_path}/ability/native/ui_service_extension_ability/connection/js_ui_service_host_proxy.cpp", + "${ability_runtime_native_path}/ability/native/ui_service_extension_ability/connection/js_ui_service_proxy.cpp", + "${ability_runtime_native_path}/ability/native/ui_service_extension_ability/connection/ui_service_host_proxy.cpp", + "${ability_runtime_native_path}/ability/native/ui_service_extension_ability/connection/ui_service_host_stub.cpp", + "${ability_runtime_native_path}/ability/native/ui_service_extension_ability/connection/ui_service_proxy.cpp", + "${ability_runtime_native_path}/ability/native/ui_service_extension_ability/connection/ui_service_stub.cpp", + ] + + deps = [ + "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_napi_path}/inner/napi_common:napi_common", + "${ability_runtime_native_path}/ability/native:ability_business_error", + ] + + external_deps = [ + "ability_base:want", + "access_token:libtokenid_sdk", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + "ipc:ipc_napi", + "napi:ace_napi", + ] + + subsystem_name = "ability" + part_name = "ability_runtime" +} + +ohos_shared_library("ui_service_extension") { + 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" + + defines = [ "AMS_LOG_TAG = \"Ability\"" ] + defines += [ "AMS_LOG_DOMAIN = 0xD001300" ] + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/ability/native/ui_service_extension_ability", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/services/common/include", + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_path}/utils/global/freeze/include", + "${ability_runtime_path}/utils/global/time/include", + "${ability_runtime_path}/interfaces/kits/native/ability/native/ui_service_extension_ability/connection", + ] + + sources = [ + "${ability_runtime_native_path}/ability/native/ui_service_extension_ability/js_ui_service_extension.cpp", + "${ability_runtime_native_path}/ability/native/ui_service_extension_ability/js_ui_service_extension_context.cpp", + "${ability_runtime_native_path}/ability/native/ui_service_extension_ability/ui_service_extension.cpp", + "${ability_runtime_path}/frameworks/native/appkit/ability_runtime/ui_service_extension_context.cpp", + ] + + deps = [ + ":abilitykit_native", + ":ui_service_extension_connection", + "${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}/app_manager:app_manager", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_napi_path}/inner/napi_common:napi_common", + "${ability_runtime_native_path}/ability:ability_context_native", + "${ability_runtime_native_path}/ability/native:ability_business_error", + "${ability_runtime_native_path}/ability/native:insight_intent_executor", + "${ability_runtime_native_path}/appkit:app_context", + "${ability_runtime_native_path}/appkit:app_context_utils", + "${ability_runtime_native_path}/appkit:appkit_delegator", + "${ability_runtime_native_path}/insight_intent/insight_intent_context:insightintentcontext", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:want", + "ability_base:zuri", + "ace_engine:ace_uicontent", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "ipc:ipc_napi", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + public_external_deps = [] + if (ability_runtime_graphics) { + external_deps += [ + "ace_engine:ace_uicontent", + "window_manager:libdm", + "window_manager:libwm", + "window_manager:libwsutils", + "window_manager:scene_session", + "window_manager:session_manager_lite", + "window_manager:window_native_kit", + "window_manager:windowstage_kit", + ] + + public_external_deps += [ "window_manager:window_native_kit" ] + } + + subsystem_name = "ability" + part_name = "ability_runtime" +} + +ohos_shared_library("ui_service_extension_module") { + 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 = [ + "${ability_runtime_path}/interfaces/kits/native/ability/native/ui_service_extension_ability", + "${ability_runtime_napi_path}/inner/napi_ability_common", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/distributed", + "${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/kits", + "${ability_runtime_path}/interfaces/kits/native/ability/native/continuation/remote_register_service", + "${ability_runtime_path}/interfaces/kits/native/ability/native/distributed_ability_runtime", + "${ability_runtime_path}/interfaces/kits/native/appkit", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/app", + "${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/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_innerkits_path}/uri/include", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_innerkits_path}/ability_manager/include/continuation", + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/app/task", + "${ability_runtime_napi_path}/inner/napi_common", + "${ability_runtime_napi_path}/featureAbility", + ] + + sources = [ "${ability_runtime_native_path}/ability/native/ui_service_extension_ability/ui_service_extension_module_loader.cpp" ] + + configs = [ ":ability_config" ] + deps = [ ":ui_service_extension" ] + + external_deps = [ + "ability_base:configuration", + "ability_base:session_info", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "form_fwk:fmskit_native", + "hilog:libhilog", + "ipc:ipc_core", + "ipc:ipc_napi", + "napi:ace_napi", + ] + + if (ability_runtime_graphics) { + external_deps += [ + "ace_engine:ace_uicontent", + "form_fwk:form_manager", + "image_framework:image", + "window_manager:libdm", + "window_manager:libwm", + "window_manager:libwsutils", + "window_manager:scene_session", + "window_manager:session_manager_lite", + "window_manager:window_native_kit", + "window_manager:windowstage_kit", + ] + + public_external_deps = [ + "form_fwk:fmskit_native", + "form_fwk:fmskit_provider_client", + "form_fwk:form_manager", + "window_manager:libdm", + "window_manager:libwmutil", + "window_manager:window_native_kit", + "window_manager:windowstage_kit", + ] + } + + relative_install_dir = "extensionability/" + subsystem_name = "ability" + part_name = "ability_runtime" +} + ohos_shared_library("continuation_ipc") { include_dirs = [] @@ -837,6 +1077,13 @@ ohos_shared_library("continuation_ipc") { "libuv:uv", ] + if (ability_runtime_graphics) { + public_external_deps += [ + "form_fwk:form_manager", + "window_manager:libdm", + ] + } + defines = [] if (background_task_mgr_continuous_task_enable) { @@ -874,10 +1121,20 @@ ohos_shared_library("data_ability_helper") { "hitrace:hitrace_meter", "json:nlohmann_json_static", "relational_store:native_dataability", - "relational_store:native_rdb", "relational_store:rdb_data_ability_adapter", "window_manager:libwm", ] + if (!(host_os == "linux" && host_cpu == "arm64")) { + external_deps += [ "relational_store:native_rdb" ] + } + + if (ability_runtime_graphics) { + public_external_deps = [ + "form_fwk:fmskit_provider_client", + "form_fwk:form_manager", + "window_manager:libdm", + ] + } innerapi_tags = [ "platformsdk" ] subsystem_name = "ability" @@ -911,6 +1168,11 @@ ohos_shared_library("service_extension_module") { if (ability_runtime_graphics) { external_deps += [ "image_framework:image", + "window_manager:libwm", + ] + public_external_deps = [ + "form_fwk:fmskit_provider_client", + "form_fwk:form_manager", "window_manager:libdm", ] } @@ -1006,6 +1268,7 @@ group("extension_module") { ":service_extension_module", ":share_extension_module", ":ui_extension_module", + ":ui_service_extension_module", ] if (ability_runtime_graphics) { @@ -1022,25 +1285,28 @@ config("ui_extension_public_config") { "${ability_runtime_path}/interfaces/kits/native/ability/native/ui_extension_ability", "${windowmanager_path}/interfaces/kits/napi/embeddable_window_stage", "${windowmanager_path}/interfaces/kits/napi/extension_window", - "${windowmanager_path}/wm/include", ] } ohos_shared_library("ui_extension") { + include_dirs = [ "${ability_runtime_path}/interfaces/kits/native/ability/native/ui_service_extension_ability/connection" ] sources = [ "${ability_runtime_native_path}/ability/native/ui_extension_ability/js_embeddable_ui_ability_context.cpp", "${ability_runtime_native_path}/ability/native/ui_extension_ability/js_ui_extension.cpp", "${ability_runtime_native_path}/ability/native/ui_extension_ability/js_ui_extension_base.cpp", "${ability_runtime_native_path}/ability/native/ui_extension_ability/js_ui_extension_content_session.cpp", "${ability_runtime_native_path}/ability/native/ui_extension_ability/js_ui_extension_context.cpp", + "${ability_runtime_native_path}/ability/native/ui_extension_ability/js_uiservice_uiext_connection.cpp", "${ability_runtime_native_path}/ability/native/ui_extension_ability/ui_extension.cpp", "${ability_runtime_native_path}/ability/native/ui_extension_ability/ui_extension_context.cpp", + "${ability_runtime_native_path}/ability/native/ui_extension_ability/ui_extension_servicehost_stub_impl.cpp", ] public_configs = [ ":ui_extension_public_config" ] deps = [ ":abilitykit_native", + ":ui_service_extension_connection", "${ability_runtime_innerkits_path}/ability_manager:ability_manager", "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/runtime:runtime", @@ -1076,6 +1342,8 @@ ohos_shared_library("ui_extension") { "window_manager:libdm", "window_manager:libwm", ] + + public_external_deps = [ "window_manager:scene_session_manager" ] } subsystem_name = "ability" @@ -1092,6 +1360,7 @@ ohos_shared_library("ui_extension_module") { deps = [ ":ui_extension", "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_native_path}/appkit:appkit_native", ] external_deps = [ @@ -1103,6 +1372,9 @@ ohos_shared_library("ui_extension_module") { "napi:ace_napi", "window_manager:libwm", ] + if (ability_runtime_graphics) { + external_deps += [ "form_fwk:form_manager" ] + } relative_install_dir = "extensionability/" subsystem_name = "ability" @@ -1234,7 +1506,10 @@ ohos_shared_library("share_extension_module") { ] if (ability_runtime_graphics) { - external_deps += [ "window_manager:libwm" ] + external_deps += [ + "form_fwk:form_manager", + "window_manager:libwm", + ] } relative_install_dir = "extensionability/" @@ -1290,7 +1565,10 @@ ohos_shared_library("action_extension_module") { ] if (ability_runtime_graphics) { - external_deps += [ "window_manager:libwm" ] + external_deps += [ + "form_fwk:form_manager", + "window_manager:libwm", + ] } relative_install_dir = "extensionability/" @@ -1524,6 +1802,7 @@ ohos_shared_library("auto_fill_extension_module") { deps = [ ":auto_fill_extension", "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_native_path}/appkit:appkit_native", ] external_deps = [ @@ -1535,6 +1814,9 @@ ohos_shared_library("auto_fill_extension_module") { "napi:ace_napi", "window_manager:libwm", ] + if (ability_runtime_graphics) { + external_deps += [ "form_fwk:form_manager" ] + } relative_install_dir = "extensionability/" subsystem_name = "ability" diff --git a/frameworks/native/ability/native/ability.cpp b/frameworks/native/ability/native/ability.cpp index 1c23b73fb5..ce200a4b05 100644 --- a/frameworks/native/ability/native/ability.cpp +++ b/frameworks/native/ability/native/ability.cpp @@ -33,7 +33,6 @@ #include "data_uri_utils.h" #include "event_report.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" @@ -448,6 +447,11 @@ ErrCode Ability::StartAbility(const Want &want, AbilityStartSetting abilityStart return err; } +ErrCode Ability::AddFreeInstallObserver(const sptr observer) +{ + return AbilityContext::AddFreeInstallObserver(observer); +} + std::string Ability::GetType(const Uri &uri) { return ""; 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 c067148df6..18129bc45f 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 @@ -75,7 +75,6 @@ constexpr const char* ERROR_MSG_NOT_SUPPORT_CROSS_APP_START = "The application is not allow jumping to other applications when api version is above 11."; constexpr const char* ERROR_MSG_CANNOT_MATCH_ANY_COMPONENT = "Can not match any component."; constexpr const char* ERROR_MSG_TARGET_BUNDLE_NOT_EXIST = "The target bundle does not exist."; -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."; @@ -85,6 +84,7 @@ constexpr const char* ERROR_MSG_NOT_APP_CLONE = "The target app is not Clone."; constexpr const char* ERROR_MSG_EXTENSION_START_THIRD_PARTY_APP_CONTROLLED = "The extension can not start the specified third party application."; constexpr const char* ERROR_MSG_EXTENSION_START_SERVICE_CONTROLLED = "The extension can not start the service."; +constexpr const char* ERROR_MSG_FREE_INSTALL_TASK_NOT_EXIST = "The target free install task does not exist."; // follow ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST of appexecfwk_errors.h in bundle_framework constexpr int32_t ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST = 8521220; @@ -136,7 +136,6 @@ static std::unordered_map ERR_CODE_MAP = { { AbilityErrorCode::ERROR_CODE_NOT_SUPPORT_CROSS_APP_START, ERROR_MSG_NOT_SUPPORT_CROSS_APP_START }, { AbilityErrorCode::ERROR_CODE_CANNOT_MATCH_ANY_COMPONENT, ERROR_MSG_CANNOT_MATCH_ANY_COMPONENT }, { 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 }, @@ -144,7 +143,8 @@ static std::unordered_map ERR_CODE_MAP = { { AbilityErrorCode::ERROR_CODE_EXTENSION_START_THIRD_PARTY_APP_CONTROLLED, ERROR_MSG_EXTENSION_START_THIRD_PARTY_APP_CONTROLLED }, { AbilityErrorCode::ERROR_CODE_EXTENSION_START_SERVICE_CONTROLLED, ERROR_MSG_EXTENSION_START_SERVICE_CONTROLLED}, - { AbilityErrorCode::ERROR_CODE_BUNDLE_NAME_INVALID, ERROR_MSG_TARGET_BUNDLE_NOT_EXIST} + { AbilityErrorCode::ERROR_CODE_BUNDLE_NAME_INVALID, ERROR_MSG_TARGET_BUNDLE_NOT_EXIST}, + { AbilityErrorCode::ERROR_CODE_FREE_INSTALL_TASK_NOT_EXIST, ERROR_MSG_FREE_INSTALL_TASK_NOT_EXIST } }; static std::unordered_map INNER_TO_JS_ERROR_CODE_MAP { @@ -199,7 +199,6 @@ static std::unordered_map INNER_TO_JS_ERROR_CODE_MAP {ERR_IMPLICIT_START_ABILITY_FAIL, AbilityErrorCode::ERROR_CODE_CANNOT_MATCH_ANY_COMPONENT}, {ERR_START_OTHER_APP_FAILED, AbilityErrorCode::ERROR_CODE_NOT_SUPPORT_CROSS_APP_START}, {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}, @@ -207,6 +206,7 @@ static std::unordered_map INNER_TO_JS_ERROR_CODE_MAP AbilityErrorCode::ERROR_CODE_EXTENSION_START_THIRD_PARTY_APP_CONTROLLED}, {EXTENSION_BLOCKED_BY_SERVICE_LIST, AbilityErrorCode::ERROR_CODE_EXTENSION_START_SERVICE_CONTROLLED}, {ERR_BUNDLE_NOT_EXIST, AbilityErrorCode::ERROR_CODE_BUNDLE_NAME_INVALID}, + {ERR_FREE_INSTALL_TASK_NOT_EXIST, AbilityErrorCode::ERROR_CODE_FREE_INSTALL_TASK_NOT_EXIST}, }; } diff --git a/frameworks/native/ability/native/ability_context.cpp b/frameworks/native/ability/native/ability_context.cpp index 2fcf7c35af..1cc4ec1e68 100644 --- a/frameworks/native/ability/native/ability_context.cpp +++ b/frameworks/native/ability/native/ability_context.cpp @@ -13,28 +13,28 @@ * limitations under the License. */ -#include "ability_context.h" +#include "fa_ability_context.h" #include "ability_manager_client.h" #include "accesstoken_kit.h" #include "authorization_result.h" #include "bundle_constants.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" +#include "hitrace_meter.h" #include "iservice_registry.h" #include "os_account_manager_wrapper.h" +#include "remote_object_wrapper.h" #include "resource_manager.h" +#include "session_info.h" +#include "session/host/include/zidl/session_interface.h" +#include "string_wrapper.h" #include "sys_mgr_client.h" #include "system_ability_definition.h" -#include "hitrace_meter.h" -#include "remote_object_wrapper.h" +#include "want_params_wrapper.h" + #ifdef SUPPORT_SCREEN #include "scene_board_judgement.h" #endif // SUPPORT_SCREEN -#include "session/host/include/zidl/session_interface.h" -#include "session_info.h" -#include "string_wrapper.h" -#include "want_params_wrapper.h" namespace OHOS { namespace AppExecFwk { @@ -328,5 +328,14 @@ sptr AbilityContext::GetSessionToken() std::lock_guard lock(sessionTokenMutex_); return sessionToken_; } + +int32_t AbilityContext::AddFreeInstallObserver(const sptr &observer) +{ + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->AddFreeInstallObserver(token_, observer); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::CONTEXT, "AddFreeInstallObserver error, ret: %{public}d", ret); + } + return ret; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/native/ability/native/ability_impl.cpp b/frameworks/native/ability/native/ability_impl.cpp index 5d4c30f7ad..f69db148f7 100644 --- a/frameworks/native/ability/native/ability_impl.cpp +++ b/frameworks/native/ability/native/ability_impl.cpp @@ -20,7 +20,6 @@ #include "data_ability_predicates.h" #include "freeze_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "ohos_application.h" #ifdef SUPPORT_SCREEN diff --git a/frameworks/native/ability/native/ability_impl_factory.cpp b/frameworks/native/ability/native/ability_impl_factory.cpp index 98e017b871..3ab7f9af7f 100644 --- a/frameworks/native/ability/native/ability_impl_factory.cpp +++ b/frameworks/native/ability/native/ability_impl_factory.cpp @@ -16,7 +16,6 @@ #include "ability_impl_factory.h" #include "data_ability_impl.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "new_ability_impl.h" #ifdef SUPPORT_GRAPHICS #include "page_ability_impl.h" diff --git a/frameworks/native/ability/native/ability_lifecycle.cpp b/frameworks/native/ability/native/ability_lifecycle.cpp index 23586430cf..5651a9b1d1 100644 --- a/frameworks/native/ability/native/ability_lifecycle.cpp +++ b/frameworks/native/ability/native/ability_lifecycle.cpp @@ -15,7 +15,6 @@ #include "ability_lifecycle_observer_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/ability/native/ability_loader.cpp b/frameworks/native/ability/native/ability_loader.cpp index 34c0b0577e..4524a5ffa8 100644 --- a/frameworks/native/ability/native/ability_loader.cpp +++ b/frameworks/native/ability/native/ability_loader.cpp @@ -15,7 +15,6 @@ #include "ability_loader.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/ability/native/ability_post_event_timeout.cpp b/frameworks/native/ability/native/ability_post_event_timeout.cpp index 8f16ce4edc..dea3c370d8 100644 --- a/frameworks/native/ability/native/ability_post_event_timeout.cpp +++ b/frameworks/native/ability/native/ability_post_event_timeout.cpp @@ -17,7 +17,6 @@ #include "ability_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/ability/native/ability_process.cpp b/frameworks/native/ability/native/ability_process.cpp index dab6796de2..1d4028ef0e 100644 --- a/frameworks/native/ability/native/ability_process.cpp +++ b/frameworks/native/ability/native/ability_process.cpp @@ -19,7 +19,6 @@ #include "accesstoken_kit.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "permission_list_state.h" using OHOS::Security::AccessToken::AccessTokenKit; diff --git a/frameworks/native/ability/native/ability_runtime/cj_ability_connect_callback_object.cpp b/frameworks/native/ability/native/ability_runtime/cj_ability_connect_callback_object.cpp index 6ac6ae3df9..ae655b18a2 100644 --- a/frameworks/native/ability/native/ability_runtime/cj_ability_connect_callback_object.cpp +++ b/frameworks/native/ability/native/ability_runtime/cj_ability_connect_callback_object.cpp @@ -17,7 +17,6 @@ #include "cj_remote_object_ffi.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace OHOS::AbilityRuntime; diff --git a/frameworks/native/ability/native/ability_runtime/cj_ability_context.cpp b/frameworks/native/ability/native/ability_runtime/cj_ability_context.cpp index bf05e9ad3f..6c942a089e 100644 --- a/frameworks/native/ability/native/ability_runtime/cj_ability_context.cpp +++ b/frameworks/native/ability/native/ability_runtime/cj_ability_context.cpp @@ -17,7 +17,6 @@ #include "cj_common_ffi.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "cj_ability_connect_callback_object.h" namespace OHOS { diff --git a/frameworks/native/ability/native/ability_runtime/cj_ability_context_object.cpp b/frameworks/native/ability/native/ability_runtime/cj_ability_context_object.cpp index 7f9b70ce3e..2fbe608d40 100644 --- a/frameworks/native/ability/native/ability_runtime/cj_ability_context_object.cpp +++ b/frameworks/native/ability/native/ability_runtime/cj_ability_context_object.cpp @@ -21,7 +21,6 @@ #include "cj_common_ffi.h" #include "ffi_remote_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi_common_start_options.h" #include "napi_common_util.h" #include "pixel_map.h" diff --git a/frameworks/native/ability/native/ability_runtime/cj_ability_ffi.cpp b/frameworks/native/ability/native/ability_runtime/cj_ability_ffi.cpp index 178fbe2642..5f7d2ecfe5 100644 --- a/frameworks/native/ability/native/ability_runtime/cj_ability_ffi.cpp +++ b/frameworks/native/ability/native/ability_runtime/cj_ability_ffi.cpp @@ -19,7 +19,6 @@ #include "ability_runtime/cj_ability_context.h" #include "cj_common_ffi.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/ability/native/ability_runtime/cj_ability_object.cpp b/frameworks/native/ability/native/ability_runtime/cj_ability_object.cpp index 293bf653ec..c159c74a24 100644 --- a/frameworks/native/ability/native/ability_runtime/cj_ability_object.cpp +++ b/frameworks/native/ability/native/ability_runtime/cj_ability_object.cpp @@ -16,7 +16,6 @@ #include "ability_runtime/cj_ability_object.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace OHOS; using namespace OHOS::AppExecFwk; diff --git a/frameworks/native/ability/native/ability_runtime/cj_ui_ability.cpp b/frameworks/native/ability/native/ability_runtime/cj_ui_ability.cpp index 1165af6667..901fa6a19d 100644 --- a/frameworks/native/ability/native/ability_runtime/cj_ui_ability.cpp +++ b/frameworks/native/ability/native/ability_runtime/cj_ui_ability.cpp @@ -15,6 +15,7 @@ #include "cj_ui_ability.h" +#include #include #include @@ -27,7 +28,6 @@ #include "connection_manager.h" #include "context/context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "if_system_ability_manager.h" #include "insight_intent_executor_info.h" @@ -55,6 +55,31 @@ const std::string SUPPORT_CONTINUE_PAGE_STACK_PROPERTY_NAME = "ohos.extra.param. // Numerical base (radix) that determines the valid characters and their interpretation. const int32_t BASE_DISPLAY_ID_NUM (10); #endif +const char* CJWINDOW_FFI_LIBNAME = "libcj_window_ffi.z.so"; +const char* FUNC_CREATE_CJWINDOWSTAGE = "OHOS_CreateCJWindowStage"; +using CFFICreateCJWindowStage = int64_t (*)(std::shared_ptr&); + +sptr CreateCJWindowStage(std::shared_ptr windowScene) +{ + static void* handle = nullptr; + if (handle == nullptr) { + handle = dlopen(CJWINDOW_FFI_LIBNAME, RTLD_LAZY); + if (handle == nullptr) { + TAG_LOGE(AAFwkTag::UIABILITY, "dlopen failed %{public}s, %{public}s", CJWINDOW_FFI_LIBNAME, dlerror()); + return nullptr; + } + } + // get function + auto func = reinterpret_cast(dlsym(handle, FUNC_CREATE_CJWINDOWSTAGE)); + if (func == nullptr) { + TAG_LOGE(AAFwkTag::UIABILITY, "dlsym failed %{public}s, %{public}s", FUNC_CREATE_CJWINDOWSTAGE, dlerror()); + dlclose(handle); + handle = nullptr; + return nullptr; + } + auto id = func(windowScene); + return OHOS::FFI::FFIData::GetData(id); +} } UIAbility *CJUIAbility::Create(const std::unique_ptr &runtime) @@ -64,12 +89,12 @@ UIAbility *CJUIAbility::Create(const std::unique_ptr &runtime) CJUIAbility::CJUIAbility(CJRuntime &cjRuntime) : cjRuntime_(cjRuntime) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } CJUIAbility::~CJUIAbility() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (abilityContext_ != nullptr) { abilityContext_->Unbind(); } @@ -227,7 +252,7 @@ void CJUIAbility::OnSceneCreated() TAG_LOGE(AAFwkTag::UIABILITY, "CJAbility is not loaded."); return; } - cjWindowStage_ = OHOS::Rosen::CJWindowStageImpl::CreateCJWindowStage(GetScene()); + cjWindowStage_ = CreateCJWindowStage(GetScene()); if (!cjWindowStage_) { TAG_LOGE(AAFwkTag::UIABILITY, "Failed to create CJWindowStage object."); return; @@ -237,7 +262,7 @@ void CJUIAbility::OnSceneCreated() HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "onWindowStageCreate"); std::string methodName = "OnSceneCreated"; AddLifecycleEventBeforeCall(FreezeUtil::TimeoutState::FOREGROUND, methodName); - cjAbilityObj_->OnSceneCreated(cjWindowStage_.get()); + cjAbilityObj_->OnSceneCreated(cjWindowStage_.GetRefPtr()); AddLifecycleEventAfterCall(FreezeUtil::TimeoutState::FOREGROUND, methodName); } @@ -261,13 +286,13 @@ void CJUIAbility::OnSceneRestored() } if (!cjWindowStage_) { - cjWindowStage_ = OHOS::Rosen::CJWindowStageImpl::CreateCJWindowStage(scene_); + cjWindowStage_ = CreateCJWindowStage(scene_); if (!cjWindowStage_) { TAG_LOGE(AAFwkTag::UIABILITY, "Failed to create CJWindowStage object."); return; } } - cjAbilityObj_->OnSceneRestored(cjWindowStage_.get()); + cjAbilityObj_->OnSceneRestored(cjWindowStage_.GetRefPtr()); auto delegator = AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator(); if (delegator) { @@ -527,15 +552,6 @@ void CJUIAbility::ContinuationRestore(const Want &want) NotifyContinuationResult(want, true); } -std::shared_ptr CJUIAbility::GetCJWindowStage() -{ - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); - if (cjWindowStage_ == nullptr) { - TAG_LOGE(AAFwkTag::UIABILITY, "CJWindowSatge is nullptr ."); - } - return cjWindowStage_; -} - const CJRuntime &CJUIAbility::GetCJRuntime() { return cjRuntime_; @@ -547,7 +563,7 @@ void CJUIAbility::ExecuteInsightIntentRepeateForeground(const Want &want, { TAG_LOGD(AAFwkTag::UIABILITY, "called ."); if (executeParam == nullptr) { - HILOG_WARN("Intention execute param invalid."); + TAG_LOGW(AAFwkTag::UIABILITY, "Intention execute param invalid."); RequestFocus(want); InsightIntentExecutorMgr::TriggerCallbackInner(std::move(callback), ERR_OK); return; @@ -580,7 +596,7 @@ void CJUIAbility::ExecuteInsightIntentMoveToForeground(const Want &want, { TAG_LOGD(AAFwkTag::UIABILITY, "called."); if (executeParam == nullptr) { - HILOG_WARN("Intention execute param invalid."); + TAG_LOGW(AAFwkTag::UIABILITY, "Intention execute param invalid."); OnForeground(want); InsightIntentExecutorMgr::TriggerCallbackInner(std::move(callback), ERR_OK); return; @@ -651,7 +667,7 @@ int32_t CJUIAbility::OnSaveState(int32_t reason, WantParams &wantParams) void CJUIAbility::OnConfigurationUpdated(const Configuration &configuration) { UIAbility::OnConfigurationUpdated(configuration); - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); auto fullConfig = GetAbilityContext()->GetConfiguration(); if (!fullConfig) { TAG_LOGE(AAFwkTag::UIABILITY, "configuration is nullptr."); @@ -670,12 +686,12 @@ void CJUIAbility::OnConfigurationUpdated(const Configuration &configuration) void CJUIAbility::OnMemoryLevel(int level) { UIAbility::OnMemoryLevel(level); - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void CJUIAbility::UpdateContextConfiguration() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void CJUIAbility::OnNewWant(const Want &want) @@ -746,7 +762,7 @@ std::shared_ptr CJUIAbility::CreateADeleg void CJUIAbility::Dump(const std::vector ¶ms, std::vector &info) { UIAbility::Dump(params, info); - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (!cjAbilityObj_) { TAG_LOGE(AAFwkTag::UIABILITY, "CJAbility is not loaded."); return; @@ -757,7 +773,7 @@ void CJUIAbility::Dump(const std::vector ¶ms, std::vector CJUIAbility::GetCJAbility() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (cjAbilityObj_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "cjAbility object is nullptr."); } diff --git a/frameworks/native/ability/native/ability_runtime/js_ability.cpp b/frameworks/native/ability/native/ability_runtime/js_ability.cpp index e44042b437..d320cf439c 100644 --- a/frameworks/native/ability/native/ability_runtime/js_ability.cpp +++ b/frameworks/native/ability/native/ability_runtime/js_ability.cpp @@ -25,7 +25,6 @@ #include "ability_start_setting.h" #include "connection_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_data_struct_converter.h" #include "js_runtime.h" #include "js_runtime_utils.h" 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 645ca75aec..d4a4f6d3c0 100644 --- a/frameworks/native/ability/native/ability_runtime/js_ability_context.cpp +++ b/frameworks/native/ability/native/ability_runtime/js_ability_context.cpp @@ -19,10 +19,10 @@ #include #include "ability_manager_client.h" +#include "ability_manager_errors.h" #include "app_utils.h" #include "event_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "ipc_skeleton.h" #include "ability_runtime/js_caller_complex.h" @@ -30,6 +30,8 @@ #include "js_data_struct_converter.h" #include "js_error_utils.h" #include "js_runtime_utils.h" +#include "js_uiservice_ability_connection.h" +#include "js_ui_service_proxy.h" #include "mission_info.h" #include "napi_common_ability.h" #include "napi_common_start_options.h" @@ -40,6 +42,8 @@ #include "open_link/napi_common_open_link_options.h" #include "start_options.h" #include "tokenid_kit.h" +#include "ui_ability_servicehost_stub_impl.h" +#include "ui_service_extension_connection_constants.h" #include "uri.h" #include "want.h" @@ -355,6 +359,21 @@ napi_value JsAbilityContext::SetRestoreEnabled(napi_env env, napi_callback_info GET_NAPI_INFO_AND_CALL(env, info, JsAbilityContext, OnSetRestoreEnabled); } +napi_value JsAbilityContext::StartUIServiceExtension(napi_env env, napi_callback_info info) +{ + GET_NAPI_INFO_AND_CALL(env, info, JsAbilityContext, OnStartUIServiceExtension); +} + +napi_value JsAbilityContext::ConnectUIServiceExtension(napi_env env, napi_callback_info info) +{ + GET_NAPI_INFO_AND_CALL(env, info, JsAbilityContext, OnConnectUIServiceExtension); +} + +napi_value JsAbilityContext::DisconnectUIServiceExtension(napi_env env, napi_callback_info info) +{ + GET_NAPI_INFO_AND_CALL(env, info, JsAbilityContext, OnDisconnectUIServiceExtension); +} + void JsAbilityContext::ClearFailedCallConnection( const std::weak_ptr& abilityContext, const std::shared_ptr &callback) { @@ -452,6 +471,206 @@ napi_value JsAbilityContext::OnStartAbility(napi_env env, NapiCallbackInfo& info return result; } +napi_value JsAbilityContext::OnStartUIServiceExtension(napi_env env, NapiCallbackInfo& info) +{ + TAG_LOGI(AAFwkTag::CONTEXT, "StartUIServiceExtension"); + if (info.argc < ARGC_ONE) { + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + + AAFwk::Want want; + if (!AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want)) { + TAG_LOGE(AAFwkTag::CONTEXT, "Failed to parse want!"); + ThrowInvalidParamError(env, "Parse param want failed, want must be Want."); + return CreateJsUndefined(env); + } + + NapiAsyncTask::CompleteCallback complete = + [weak = context_, want](napi_env env, NapiAsyncTask& task, int32_t status) { + auto context = weak.lock(); + if (!context) { + TAG_LOGW(AAFwkTag::CONTEXT, "context is released"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT)); + return; + } + auto errcode = context->StartUIServiceExtensionAbility(want); + if (errcode == 0) { + task.ResolveWithNoError(env, CreateJsUndefined(env)); + } else { + task.Reject(env, CreateJsErrorByNativeErr(env, errcode)); + } + }; + + napi_value lastParam = (info.argc > ARGC_ONE) ? info.argv[INDEX_ONE] : nullptr; + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("JsAbilityContext::OnStartUIServiceExtension", + env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +bool JsAbilityContext::UnwrapConnectUIServiceExtensionParam(napi_env env, NapiCallbackInfo& info, AAFwk::Want& want) +{ + if (info.argc < ARGC_TWO) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "failed, not enough params."); + ThrowTooFewParametersError(env); + return false; + } + bool unwrapResult = OHOS::AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want); + if (!unwrapResult) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "failed, UnwrapWant failed"); + ThrowInvalidParamError(env, "parse want error"); + return false; + } + TAG_LOGI(AAFwkTag::UISERVC_EXT, "callee:%{public}s.%{public}s", want.GetBundle().c_str(), + want.GetElement().GetAbilityName().c_str()); + if (!CheckTypeForNapiValue(env, info.argv[INDEX_ONE], napi_object)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "failed, callback type incorrect"); + ThrowInvalidParamError(env, "Incorrect parameter types"); + return false; + } + return true; +} + +bool JsAbilityContext::CheckConnectAlreadyExist(napi_env env, + AAFwk::Want& want, napi_value callback, napi_value& result) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + sptr connection = nullptr; + UIServiceConnection::FindUIServiceAbilityConnection(env, want, callback, connection); + if (connection == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "connection == nullptr"); + return false; + } + + std::unique_ptr uasyncTask = CreateAsyncTaskWithLastParam(env, nullptr, nullptr, nullptr, &result); + napi_value proxy = connection->GetProxyObject(); + if (proxy == nullptr) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "can't got proxy object, wait for duplicated connect finish"); + connection->AddDuplicatedPendingTask(uasyncTask); + } else { + TAG_LOGI(AAFwkTag::UISERVC_EXT, "Resolve, got proxy object"); + uasyncTask->ResolveWithNoError(env, proxy); + } + return true; +} + +napi_value JsAbilityContext::OnConnectUIServiceExtension(napi_env env, NapiCallbackInfo& info) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + AAFwk::Want want; + bool unwrapResult = UnwrapConnectUIServiceExtensionParam(env, info, want); + if (!unwrapResult) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "UnwrapConnectUIServiceExtensionParam failed"); + return CreateJsUndefined(env); + } + napi_value callbackObject = nullptr; + if (info.argc > ARGC_ONE) { + callbackObject = info.argv[INDEX_ONE]; + } + napi_value result = nullptr; + bool duplicated = CheckConnectAlreadyExist(env, want, callbackObject, result); + if (duplicated) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "duplicated"); + return result; + } + + sptr connection = sptr::MakeSptr(env); + sptr stub = connection->GetServiceHostStub(); + want.SetParam(UISERVICEHOSTPROXY_KEY, stub->AsObject()); + + result = nullptr; + std::unique_ptr uasyncTask = CreateAsyncTaskWithLastParam(env, nullptr, nullptr, nullptr, &result); + std::shared_ptr uasyncTaskShared = std::move(uasyncTask); + if (info.argc > ARGC_ONE) { + connection->SetJsConnectionObject(callbackObject); + } + connection->SetNapiAsyncTask(uasyncTaskShared); + UIServiceConnection::InsertUIServiceAbilityConnection(connection, want); + std::unique_ptr complete = std::make_unique( + [weak = context_, want, uasyncTaskShared, connection]( + napi_env env, NapiAsyncTask& taskUseless, int32_t status) { + DoConnectUIServiceExtension(env, weak, connection, uasyncTaskShared, want); + }); + napi_ref callback = nullptr; + std::unique_ptr execute = nullptr; + NapiAsyncTask::ScheduleHighQos("JsAbilityContext::OnConnectUIServiceExtension", + env, std::make_unique(callback, std::move(execute), std::move(complete))); + return result; +} + +void JsAbilityContext::DoConnectUIServiceExtension(napi_env env, + std::weak_ptr weakContext, sptr connection, + std::shared_ptr uasyncTaskShared, const AAFwk::Want& want) +{ + if (uasyncTaskShared == nullptr) { + return; + } + + uint64_t connectId = connection->GetConnectionId(); + auto context = weakContext.lock(); + if (!context) { + TAG_LOGE(AAFwkTag::CONTEXT, "Connect ability failed, context is released."); + uasyncTaskShared->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT)); + UIServiceConnection::RemoveUIServiceAbilityConnection(connectId); + return; + } + + auto innerErrorCode = context->ConnectAbility(want, connection); + AbilityErrorCode errcode = AbilityRuntime::GetJsErrorCodeByNativeError(innerErrorCode); + if (errcode != AbilityErrorCode::ERROR_OK) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "ConnectAbility failed, errcode is %{public}d.", errcode); + uasyncTaskShared->Reject(env, CreateJsError(env, errcode)); + UIServiceConnection::RemoveUIServiceAbilityConnection(connectId); + } +} + +napi_value JsAbilityContext::OnDisconnectUIServiceExtension(napi_env env, NapiCallbackInfo& info) +{ + if (info.argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "failed, not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + AAFwk::JsUIServiceProxy* proxy = nullptr; + napi_status status = napi_unwrap(env, info.argv[INDEX_ZERO], reinterpret_cast(&proxy)); + if (status != napi_ok || proxy == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "napi_unwrap err or proxy == nullptr"); + ThrowInvalidParamError(env, "Parameter verification failed"); + return CreateJsUndefined(env); + } + + AAFwk::Want want; + int64_t connectId = proxy->GetConnectionId(); + sptr connection = nullptr; + TAG_LOGI(AAFwkTag::UISERVC_EXT, "connectionId: %{public}d.", static_cast(connectId)); + UIServiceConnection::FindUIServiceAbilityConnection(connectId, want, connection); + + NapiAsyncTask::CompleteCallback complete = + [weak = context_, want, connectId, connection]( + napi_env env, NapiAsyncTask& task, int32_t status) { + auto context = weak.lock(); + if (!context) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "OnDisconnectUIServiceExtension context is released"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT)); + UIServiceConnection::RemoveUIServiceAbilityConnection(connectId); + } else if (!connection) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "OnDisconnectUIServiceExtension connection nullptr"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + UIServiceConnection::RemoveUIServiceAbilityConnection(connectId); + } else { + TAG_LOGI(AAFwkTag::UISERVC_EXT, "context->DisconnectAbility"); + context->DisconnectAbility(want, connection); + task.ResolveWithNoError(env, CreateJsUndefined(env)); + } + }; + + napi_value result = nullptr; + NapiAsyncTask::Schedule("JsAbilityContext::OnDisconnectUIServiceExtension", + env, CreateAsyncTaskWithLastParam(env, nullptr, nullptr, std::move(complete), &result)); + return result; +} + static bool CheckUrl(std::string &urlValue) { if (urlValue.empty()) { @@ -480,26 +699,32 @@ bool JsAbilityContext::CreateOpenLinkTask(const napi_env &env, const napi_value if (abilityResult == nullptr) { TAG_LOGW(AAFwkTag::CONTEXT, "wrap abilityResult error"); asyncTask->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - } else { - if (isInner) { - asyncTask->Reject(env, CreateJsErrorByNativeErr(env, resultCode)); - } else { - asyncTask->ResolveWithNoError(env, abilityResult); - } + return; } + isInner ? asyncTask->Reject(env, CreateJsErrorByNativeErr(env, resultCode)) : + asyncTask->ResolveWithNoError(env, abilityResult); }; curRequestCode_ = (curRequestCode_ == INT_MAX) ? 0 : (curRequestCode_ + 1); requestCode = curRequestCode_; auto context = context_.lock(); - if (context == nullptr) { + if (!context) { TAG_LOGW(AAFwkTag::CONTEXT, "context is released"); return false; - } else { - context->InsertResultCallbackTask(requestCode, std::move(task)); } + context->InsertResultCallbackTask(requestCode, std::move(task)); return true; } +void JsAbilityContext::RemoveOpenLinkTask(int requestCode) +{ + auto context = context_.lock(); + if (!context) { + TAG_LOGW(AAFwkTag::CONTEXT, "context is released"); + return; + } + context->RemoveResultCallbackTask(requestCode); +} + static bool ParseOpenLinkParams(const napi_env &env, const NapiCallbackInfo &info, std::string &linkValue, AAFwk::OpenLinkOptions &openLinkOptions, AAFwk::Want &want) { @@ -532,11 +757,10 @@ napi_value JsAbilityContext::OnOpenLink(napi_env env, NapiCallbackInfo& info) { StartAsyncTrace(HITRACE_TAG_ABILITY_MANAGER, TRACE_ATOMIC_SERVICE, TRACE_ATOMIC_SERVICE_ID); HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGI(AAFwkTag::CONTEXT, "OnOpenLink"); + TAG_LOGD(AAFwkTag::CONTEXT, "OnOpenLink"); std::string linkValue(""); AAFwk::OpenLinkOptions openLinkOptions; - napi_value lastParam = nullptr; AAFwk::Want want; want.SetParam(AppExecFwk::APP_LINKING_ONLY, false); @@ -547,15 +771,22 @@ napi_value JsAbilityContext::OnOpenLink(napi_env env, NapiCallbackInfo& info) return CreateJsUndefined(env); } - TAG_LOGI(AAFwkTag::CONTEXT, "open link:%{public}s.", linkValue.c_str()); want.SetUri(linkValue); + std::string startTime = std::to_string(std::chrono::duration_cast(std::chrono:: + system_clock::now().time_since_epoch()).count()); + want.SetParam(Want::PARAM_RESV_START_TIME, startTime); + int requestCode = -1; if (CheckTypeForNapiValue(env, info.argv[INDEX_TWO], napi_function)) { TAG_LOGD(AAFwkTag::CONTEXT, "completionHandler is used."); - lastParam = info.argv[INDEX_TWO]; - CreateOpenLinkTask(env, lastParam, want, requestCode); + CreateOpenLinkTask(env, info.argv[INDEX_TWO], want, requestCode); } + return OnOpenLinkInner(env, want, requestCode, startTime, linkValue); +} +napi_value JsAbilityContext::OnOpenLinkInner(napi_env env, const AAFwk::Want& want, + int requestCode, const std::string& startTime, const std::string& url) +{ auto innerErrorCode = std::make_shared(ERR_OK); NapiAsyncTask::ExecuteCallback execute = [weak = context_, want, innerErrorCode, requestCode]() { auto context = weak.lock(); @@ -564,22 +795,34 @@ napi_value JsAbilityContext::OnOpenLink(napi_env env, NapiCallbackInfo& info) *innerErrorCode = static_cast(AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT); return; } - *innerErrorCode = context->StartAbility(want, requestCode); + *innerErrorCode = context->OpenLink(want, requestCode); }; - NapiAsyncTask::CompleteCallback complete = [innerErrorCode](napi_env env, NapiAsyncTask& task, int32_t status) { + NapiAsyncTask::CompleteCallback complete = [innerErrorCode, requestCode, startTime, url, this]( + napi_env env, NapiAsyncTask& task, int32_t status) { if (*innerErrorCode == 0) { - TAG_LOGI(AAFwkTag::CONTEXT, "OpenLink success."); - task.ResolveWithNoError(env, CreateJsUndefined(env)); - } else { - TAG_LOGI(AAFwkTag::CONTEXT, "OpenLink failed."); - task.Reject(env, CreateJsErrorByNativeErr(env, *innerErrorCode)); + TAG_LOGI(AAFwkTag::CONTEXT, "OpenLink succeeded."); + return; } + if (freeInstallObserver_ == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "freeInstallObserver_ is nullptr."); + RemoveOpenLinkTask(requestCode); + return; + } + if (*innerErrorCode == AAFwk::ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK) { + TAG_LOGI(AAFwkTag::CONTEXT, "start ability by default succeeded."); + freeInstallObserver_->OnInstallFinishedByUrl(startTime, url, ERR_OK); + return; + } + TAG_LOGI(AAFwkTag::CONTEXT, "OpenLink failed."); + freeInstallObserver_->OnInstallFinishedByUrl(startTime, url, *innerErrorCode); + RemoveOpenLinkTask(requestCode); }; napi_value result = nullptr; + AddFreeInstallObserver(env, want, nullptr, &result, false, true); NapiAsyncTask::ScheduleHighQos("JsAbilityContext::OnOpenLink", env, - CreateAsyncTaskWithLastParam(env, nullptr, std::move(execute), std::move(complete), &result)); + CreateAsyncTaskWithLastParam(env, nullptr, std::move(execute), std::move(complete), nullptr)); return result; } @@ -1352,11 +1595,8 @@ napi_value JsAbilityContext::OnTerminateSelf(napi_env env, NapiCallbackInfo& inf } auto errcode = context->TerminateSelf(); - if (errcode == 0) { - task.Resolve(env, CreateJsUndefined(env)); - } else { + (errcode == 0) ? task.Resolve(env, CreateJsUndefined(env)) : task.Reject(env, CreateJsErrorByNativeErr(env, errcode)); - } }; napi_value lastParam = (info.argc > ARGC_ZERO) ? info.argv[INDEX_ZERO] : nullptr; @@ -1459,11 +1699,8 @@ napi_value JsAbilityContext::OnReportDrawnCompleted(napi_env env, NapiCallbackIn }; NapiAsyncTask::CompleteCallback complete = [innerErrorCode](napi_env env, NapiAsyncTask& task, int32_t status) { - if (*innerErrorCode == ERR_OK) { - task.Resolve(env, CreateJsUndefined(env)); - } else { + (*innerErrorCode == ERR_OK) ? task.Resolve(env, CreateJsUndefined(env)) : task.Reject(env, CreateJsErrorByNativeErr(env, *innerErrorCode)); - } }; napi_value lastParam = info.argv[INDEX_ZERO]; @@ -1535,26 +1772,35 @@ void JsAbilityContext::ConfigurationUpdated(napi_env env, std::shared_ptrAddFreeInstallObserver(freeInstallObserver_); + auto context = context_.lock(); + if (!context) { + TAG_LOGE(AAFwkTag::CONTEXT, "context is nullptr."); + return; + } + ret = context->AddFreeInstallObserver(freeInstallObserver_); } if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::CONTEXT, "AddFreeInstallObserver error."); - } else { + } + std::string startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME); + if (!isOpenLink) { TAG_LOGI(AAFwkTag::CONTEXT, "AddJsObserverObject"); std::string bundleName = want.GetElement().GetBundleName(); std::string abilityName = want.GetElement().GetAbilityName(); - std::string startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME); freeInstallObserver_->AddJsObserverObject( bundleName, abilityName, startTime, callback, result, isAbilityResult); + return; } + std::string url = want.GetUriString(); + freeInstallObserver_->AddJsObserverObject(startTime, url, callback, result, isAbilityResult); } napi_value CreateJsAbilityContext(napi_env env, std::shared_ptr context) @@ -1625,7 +1871,12 @@ napi_value CreateJsAbilityContext(napi_env env, std::shared_ptr JsAbilityContext::OpenAtomicService); BindNativeFunction(env, object, "moveAbilityToBackground", moduleName, JsAbilityContext::MoveAbilityToBackground); BindNativeFunction(env, object, "setRestoreEnabled", moduleName, JsAbilityContext::SetRestoreEnabled); - + BindNativeFunction(env, object, "startUIServiceExtensionAbility", moduleName, + JsAbilityContext::StartUIServiceExtension); + BindNativeFunction(env, object, "connectUIServiceExtensionAbility", moduleName, + JsAbilityContext::ConnectUIServiceExtension); + BindNativeFunction(env, object, "disconnectUIServiceExtensionAbility", moduleName, + JsAbilityContext::DisconnectUIServiceExtension); #ifdef SUPPORT_GRAPHICS BindNativeFunction(env, object, "setMissionLabel", moduleName, JsAbilityContext::SetMissionLabel); BindNativeFunction(env, object, "setMissionIcon", moduleName, JsAbilityContext::SetMissionIcon); @@ -1637,51 +1888,49 @@ JSAbilityConnection::JSAbilityConnection(napi_env env) : env_(env) {} JSAbilityConnection::~JSAbilityConnection() { + ReleaseNativeReference(jsConnectionObject_.release()); +} + +void JSAbilityConnection::ReleaseNativeReference(NativeReference* ref) +{ + if (ref == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "ReleaseNativeReference: ref == nullptr"); + return; + } uv_loop_t *loop = nullptr; napi_get_uv_event_loop(env_, &loop); if (loop == nullptr) { - TAG_LOGE(AAFwkTag::CONTEXT, "~JSAbilityConnection: failed to get uv loop."); + TAG_LOGE(AAFwkTag::CONTEXT, "ReleaseNativeReference: failed to get uv loop."); + delete ref; return; } - - ConnectCallback *cb = new (std::nothrow) ConnectCallback(); - if (cb == nullptr) { - TAG_LOGE(AAFwkTag::CONTEXT, "~JSAbilityConnection: failed to create cb."); - return; - } - cb->jsConnectionObject_ = std::move(jsConnectionObject_); - uv_work_t *work = new (std::nothrow) uv_work_t; if (work == nullptr) { - TAG_LOGE(AAFwkTag::CONTEXT, "~JSAbilityConnection: failed to create work."); - delete cb; - cb = nullptr; + TAG_LOGE(AAFwkTag::CONTEXT, "ReleaseNativeReference: failed to create work."); + delete ref; return; } - work->data = reinterpret_cast(cb); + work->data = reinterpret_cast(ref); int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { + [](uv_work_t *work, int status) { if (work == nullptr) { - TAG_LOGE(AAFwkTag::CONTEXT, "~JSAbilityConnection: work is nullptr."); + TAG_LOGE(AAFwkTag::CONTEXT, "ReleaseNativeReference: work is nullptr."); return; } if (work->data == nullptr) { - TAG_LOGE(AAFwkTag::CONTEXT, "~JSAbilityConnection: data is nullptr."); + TAG_LOGE(AAFwkTag::CONTEXT, "ReleaseNativeReference: data is nullptr."); delete work; work = nullptr; return; } - ConnectCallback *cb = reinterpret_cast(work->data); - delete cb; - cb = nullptr; + NativeReference *refPtr = reinterpret_cast(work->data); + delete refPtr; + refPtr = nullptr; delete work; work = nullptr; }); if (ret != 0) { - if (cb != nullptr) { - delete cb; - cb = nullptr; - } + delete ref; if (work != nullptr) { delete work; work = nullptr; @@ -1831,6 +2080,33 @@ void JSAbilityConnection::CallJsFailed(int32_t errorCode) TAG_LOGD(AAFwkTag::CONTEXT, "CallJsFailed end"); } +napi_value JSAbilityConnection::CallObjectMethod(const char* name, napi_value const *argv, size_t argc) +{ + TAG_LOGD(AAFwkTag::CONTEXT, "name:%{public}s", name); + if (!jsConnectionObject_) { + TAG_LOGW(AAFwkTag::CONTEXT, "Not found jsConnectionObject_"); + return nullptr; + } + + HandleScope handleScope(env_); + napi_value obj = jsConnectionObject_->GetNapiValue(); + if (!CheckTypeForNapiValue(env_, obj, napi_object)) { + TAG_LOGE(AAFwkTag::CONTEXT, "Failed to get jsConnectionObject_ object"); + return nullptr; + } + + napi_value method = nullptr; + napi_get_named_property(env_, obj, name, &method); + if (!CheckTypeForNapiValue(env_, method, napi_function)) { + TAG_LOGE(AAFwkTag::CONTEXT, "Failed to get '%{public}s' from jsConnectionObject_ object", name); + return nullptr; + } + napi_value result = nullptr; + napi_call_function(env_, obj, method, argc, argv, &result); + TAG_LOGD(AAFwkTag::CONTEXT, "CallFunction(%{public}s) ok", name); + return result; +} + napi_value JSAbilityConnection::ConvertElement(const AppExecFwk::ElementName &element) { return AppExecFwk::WrapElementName(env_, element); @@ -2029,11 +2305,8 @@ napi_value JsAbilityContext::OnStartAbilityByType(napi_env env, NapiCallbackInfo } #ifdef SUPPORT_SCREEN auto errcode = context->StartAbilityByType(type, wantParam, callback); - if (errcode != 0) { - task.Reject(env, CreateJsErrorByNativeErr(env, errcode)); - } else { + (errcode != 0) ? task.Reject(env, CreateJsErrorByNativeErr(env, errcode)) : task.ResolveWithNoError(env, CreateJsUndefined(env)); - } #endif }; @@ -2047,39 +2320,38 @@ napi_value JsAbilityContext::OnStartAbilityByType(napi_env env, NapiCallbackInfo napi_value JsAbilityContext::OnRequestModalUIExtension(napi_env env, NapiCallbackInfo& info) { TAG_LOGD(AAFwkTag::CONTEXT, "called"); - if (info.argc < ARGC_ONE) { ThrowTooFewParametersError(env); return CreateJsUndefined(env); } - AAFwk::Want want; if (!AppExecFwk::UnwrapWant(env, info.argv[0], want)) { TAG_LOGE(AAFwkTag::CONTEXT, "Failed to parse want!"); ThrowInvalidParamError(env, "Parse param want failed, want must be Want."); return CreateJsUndefined(env); } - - NapiAsyncTask::CompleteCallback complete = - [weak = context_, want](napi_env env, NapiAsyncTask& task, int32_t status) { - auto context = weak.lock(); - if (!context) { - TAG_LOGW(AAFwkTag::CONTEXT, "context is released"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - return; - } - auto errcode = context->RequestModalUIExtension(want); - if (errcode == 0) { - task.Resolve(env, CreateJsUndefined(env)); - } else { - task.Reject(env, CreateJsErrorByNativeErr(env, errcode)); - } - }; - + auto innerErrCode = std::make_shared(ERR_OK); + NapiAsyncTask::ExecuteCallback execute = [abilityContext = context_, want, innerErrCode]() { + auto context = abilityContext.lock(); + if (!context) { + TAG_LOGE(AAFwkTag::APPKIT, "context is released"); + *innerErrCode = static_cast(AbilityErrorCode::ERROR_CODE_INNER); + return; + } + *innerErrCode = AAFwk::AbilityManagerClient::GetInstance()->RequestModalUIExtension(want); + }; + NapiAsyncTask::CompleteCallback complete = [innerErrCode](napi_env env, NapiAsyncTask& task, int32_t status) { + if (*innerErrCode == ERR_OK) { + task.Resolve(env, CreateJsUndefined(env)); + } else { + TAG_LOGE(AAFwkTag::APPKIT, "OnRequestModalUIExtension is failed %{public}d", *innerErrCode); + task.Reject(env, CreateJsErrorByNativeErr(env, *innerErrCode)); + } + }; napi_value lastParam = (info.argc > ARGC_ONE) ? info.argv[ARGC_ONE] : nullptr; napi_value result = nullptr; NapiAsyncTask::ScheduleHighQos("JsAbilityContext::OnRequestModalUIExtension", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + env, CreateAsyncTaskWithLastParam(env, lastParam, std::move(execute), std::move(complete), &result)); return result; } @@ -2105,11 +2377,8 @@ napi_value JsAbilityContext::ChangeAbilityVisibility(napi_env env, NapiCallbackI return; } auto errCode = context->ChangeAbilityVisibility(isShow); - if (errCode == 0) { - task.ResolveWithNoError(env, CreateJsUndefined(env)); - } else { + (errCode == 0) ? task.ResolveWithNoError(env, CreateJsUndefined(env)) : task.Reject(env, CreateJsErrorByNativeErr(env, errCode)); - } }; napi_value result = nullptr; @@ -2175,11 +2444,8 @@ napi_value JsAbilityContext::OpenAtomicServiceInner(napi_env env, NapiCallbackIn isInner = true; resultCode = ERR_INVALID_VALUE; } - if (isInner) { - observer->OnInstallFinished(bundleName, abilityName, startTime, resultCode); - } else { + isInner ? observer->OnInstallFinished(bundleName, abilityName, startTime, resultCode) : observer->OnInstallFinished(bundleName, abilityName, startTime, abilityResult); - } }; auto context = context_.lock(); if (context == nullptr) { diff --git a/frameworks/native/ability/native/ability_runtime/js_caller_complex.cpp b/frameworks/native/ability/native/ability_runtime/js_caller_complex.cpp index d09f5a0b49..14108fdcc0 100644 --- a/frameworks/native/ability/native/ability_runtime/js_caller_complex.cpp +++ b/frameworks/native/ability/native/ability_runtime/js_caller_complex.cpp @@ -17,7 +17,6 @@ #include "event_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_context_utils.h" #include "js_data_struct_converter.h" #include "js_error_utils.h" 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 5f55701f4f..34a1ae6419 100644 --- a/frameworks/native/ability/native/ability_runtime/js_ui_ability.cpp +++ b/frameworks/native/ability/native/ability_runtime/js_ui_ability.cpp @@ -27,7 +27,6 @@ #include "context/application_context.h" #include "context/context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "if_system_ability_manager.h" #include "insight_intent_executor_info.h" @@ -147,13 +146,13 @@ UIAbility *JsUIAbility::Create(const std::unique_ptr &runtime) JsUIAbility::JsUIAbility(JsRuntime &jsRuntime) : jsRuntime_(jsRuntime) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } JsUIAbility::~JsUIAbility() { //"maintenance log - TAG_LOGI(AAFwkTag::UIABILITY, "Called."); + TAG_LOGI(AAFwkTag::UIABILITY, "called"); if (abilityContext_ != nullptr) { abilityContext_->Unbind(); } @@ -520,15 +519,21 @@ void JsUIAbility::OnSceneRestored() } UpdateJsWindowStage(jsAppWindowStage->GetNapiValue()); napi_value argv[] = {jsAppWindowStage->GetNapiValue()}; + jsWindowStageObj_ = std::shared_ptr(jsAppWindowStage.release()); + auto applicationContext = AbilityRuntime::Context::GetApplicationContext(); + if (applicationContext != nullptr) { + applicationContext->DispatchOnWindowStageWillRestore(jsAbilityObj_, jsWindowStageObj_); + } CallObjectMethod("onWindowStageRestore", argv, ArraySize(argv)); + if (applicationContext != nullptr) { + applicationContext->DispatchOnWindowStageRestore(jsAbilityObj_, jsWindowStageObj_); + } auto delegator = AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator(); if (delegator) { TAG_LOGD(AAFwkTag::UIABILITY, "Call PostPerformScenceRestored."); delegator->PostPerformScenceRestored(CreateADelegatorAbilityProperty()); } - - jsWindowStageObj_ = std::shared_ptr(jsAppWindowStage.release()); } void JsUIAbility::OnSceneWillDestroy() @@ -887,7 +892,7 @@ void JsUIAbility::RequestFocus(const Want &want) void JsUIAbility::ContinuationRestore(const Want &want) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (!IsRestoredInContinuation() || scene_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "Is not in continuation or scene_ is nullptr."); return; @@ -899,7 +904,7 @@ void JsUIAbility::ContinuationRestore(const Want &want) std::shared_ptr JsUIAbility::GetJsWindowStage() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (jsWindowStageObj_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "JsWindowSatge is nullptr."); } @@ -1074,6 +1079,12 @@ int32_t JsUIAbility::OnContinue(WantParams &wantParams) TAG_LOGE(AAFwkTag::UIABILITY, "Failed to get Ability object."); return AppExecFwk::ContinuationManagerStage::OnContinueResult::REJECT; } + + auto applicationContext = AbilityRuntime::Context::GetApplicationContext(); + if (applicationContext != nullptr) { + applicationContext->DispatchOnAbilityWillContinue(jsAbilityObj_); + } + napi_value jsWantParams = OHOS::AppExecFwk::WrapWantParams(env, wantParams); napi_value result = CallObjectMethod("onContinue", &jsWantParams, 1, true); int32_t onContinueRes = 0; @@ -1089,7 +1100,6 @@ int32_t JsUIAbility::OnContinue(WantParams &wantParams) } } OHOS::AppExecFwk::UnwrapWantParams(env, jsWantParams, wantParams); - auto applicationContext = AbilityRuntime::Context::GetApplicationContext(); if (applicationContext != nullptr) { applicationContext->DispatchOnAbilityContinue(jsAbilityObj_); } @@ -1111,6 +1121,11 @@ int32_t JsUIAbility::OnSaveState(int32_t reason, WantParams &wantParams) return -1; } + auto applicationContext = AbilityRuntime::Context::GetApplicationContext(); + if (applicationContext != nullptr) { + applicationContext->DispatchOnAbilityWillSaveState(jsAbilityObj_); + } + napi_value methodOnSaveState = nullptr; napi_get_named_property(env, obj, "onSaveState", &methodOnSaveState); if (methodOnSaveState == nullptr) { @@ -1130,6 +1145,11 @@ int32_t JsUIAbility::OnSaveState(int32_t reason, WantParams &wantParams) TAG_LOGE(AAFwkTag::UIABILITY, "AppRecovery no result return from onSaveState."); return -1; } + + if (applicationContext != nullptr) { + applicationContext->DispatchOnAbilitySaveState(jsAbilityObj_); + } + return numberResult; } @@ -1137,7 +1157,7 @@ void JsUIAbility::OnConfigurationUpdated(const Configuration &configuration) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); UIAbility::OnConfigurationUpdated(configuration); - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (abilityContext_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "abilityContext_ is nullptr."); return; @@ -1161,7 +1181,7 @@ void JsUIAbility::OnConfigurationUpdated(const Configuration &configuration) void JsUIAbility::OnMemoryLevel(int level) { UIAbility::OnMemoryLevel(level); - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); HandleScope handleScope(jsRuntime_); auto env = jsRuntime_.GetNapiEnv(); @@ -1182,7 +1202,7 @@ void JsUIAbility::OnMemoryLevel(int level) void JsUIAbility::UpdateContextConfiguration() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (abilityContext_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "abilityContext_ is nullptr."); return; @@ -1466,7 +1486,7 @@ std::shared_ptr JsUIAbility::CreateADeleg void JsUIAbility::Dump(const std::vector ¶ms, std::vector &info) { UIAbility::Dump(params, info); - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); HandleScope handleScope(jsRuntime_); auto env = jsRuntime_.GetNapiEnv(); // create js array object of params @@ -1514,7 +1534,7 @@ void JsUIAbility::GetDumpInfo( std::shared_ptr JsUIAbility::GetJsAbility() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (jsAbilityObj_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "JsAbility object is nullptr."); } @@ -1549,7 +1569,7 @@ sptr JsUIAbility::SetNewRuleFlagToCallee(napi_env env, napi_value #ifdef SUPPORT_SCREEN void JsUIAbility::UpdateJsWindowStage(napi_value windowStage) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (shellContextRef_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "shellContextRef_ is nullptr."); return; diff --git a/frameworks/native/ability/native/ability_runtime/js_uiservice_ability_connection.cpp b/frameworks/native/ability/native/ability_runtime/js_uiservice_ability_connection.cpp new file mode 100644 index 0000000000..b7631dd531 --- /dev/null +++ b/frameworks/native/ability/native/ability_runtime/js_uiservice_ability_connection.cpp @@ -0,0 +1,268 @@ +/* + * 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 "js_uiservice_ability_connection.h" + +#include "ability_business_error.h" +#include "hilog_tag_wrapper.h" +#include "js_error_utils.h" +#include "js_ui_service_proxy.h" +#include "napi_common_want.h" +#include "ui_ability_servicehost_stub_impl.h" + +namespace OHOS { +namespace AbilityRuntime { +constexpr size_t ARGC_ONE = 1; + +namespace UIServiceConnection { +static std::map, KeyCompare> g_uiServiceExtensionConnects; +static std::recursive_mutex g_uiServiceExtensionConnectsLock_; +static int64_t g_uiServiceExtensionSerialNumber = 0; + +// This function has to be called from engine thread +void RemoveUIServiceAbilityConnection(int64_t connectId) +{ + std::lock_guard lock(g_uiServiceExtensionConnectsLock_); + auto item = std::find_if(g_uiServiceExtensionConnects.begin(), g_uiServiceExtensionConnects.end(), + [&connectId](const auto &obj) { + return connectId == obj.first.id; + }); + if (item != g_uiServiceExtensionConnects.end()) { + TAG_LOGD(AAFwkTag::CONTEXT, "exist, remove"); + if (item->second) { + item->second->RemoveConnectionObject(); + item->second->SetProxyObject(nullptr); + } + g_uiServiceExtensionConnects.erase(item); + } else { + TAG_LOGD(AAFwkTag::CONTEXT, "not exist"); + } + TAG_LOGI(AAFwkTag::CONTEXT, "Connects new size:%{public}zu", g_uiServiceExtensionConnects.size()); +} + +int64_t InsertUIServiceAbilityConnection(sptr connection, const AAFwk::Want &want) +{ + std::lock_guard lock(g_uiServiceExtensionConnectsLock_); + if (connection == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "connection null"); + return -1; + } + int64_t connectId = g_uiServiceExtensionSerialNumber; + ConnectionKey key; + key.id = g_uiServiceExtensionSerialNumber; + key.want = want; + key.accountId = 0; + connection->SetConnectionId(key.id); + g_uiServiceExtensionConnects.emplace(key, connection); + if (g_uiServiceExtensionSerialNumber < INT32_MAX) { + g_uiServiceExtensionSerialNumber++; + } else { + g_uiServiceExtensionSerialNumber = 0; + } + return connectId; +} + +void FindUIServiceAbilityConnection(const int64_t& connectId, AAFwk::Want& want, + sptr& connection) +{ + std::lock_guard lock(g_uiServiceExtensionConnectsLock_); + TAG_LOGI(AAFwkTag::UI_EXT, "connection:%{public}d", static_cast(connectId)); + auto item = std::find_if(g_uiServiceExtensionConnects.begin(), g_uiServiceExtensionConnects.end(), + [&connectId](const auto &obj) { + return connectId == obj.first.id; + }); + if (item != g_uiServiceExtensionConnects.end()) { + want = item->first.want; + connection = item->second; + TAG_LOGI(AAFwkTag::UI_EXT, "found"); + } else { + TAG_LOGI(AAFwkTag::UI_EXT, "not found"); + } +} + +void FindUIServiceAbilityConnection(napi_env env, AAFwk::Want& want, napi_value callback, + sptr& connection) +{ + std::lock_guard lock(g_uiServiceExtensionConnectsLock_); + auto item = std::find_if(g_uiServiceExtensionConnects.begin(), g_uiServiceExtensionConnects.end(), + [&want, env, callback](const auto &obj) { + bool wantEquals = (obj.first.want.GetElement() == want.GetElement()); + std::unique_ptr& tempCallbackPtr = obj.second->GetJsConnectionObject(); + bool callbackObjectEquals = + JSUIServiceExtAbilityConnection::IsJsCallbackObjectEquals(env, tempCallbackPtr, callback); + return wantEquals && callbackObjectEquals; + }); + if (item == g_uiServiceExtensionConnects.end()) { + return; + } + connection = item->second; +} +} + +JSUIServiceExtAbilityConnection::JSUIServiceExtAbilityConnection(napi_env env) : JSAbilityConnection(env) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "JSUIServiceExtAbilityConnection"); + wptr weakthis = this; + serviceHostStub_ = sptr::MakeSptr(weakthis); +} + +JSUIServiceExtAbilityConnection::~JSUIServiceExtAbilityConnection() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "~JSUIServiceExtAbilityConnection"); + serviceHostStub_ = nullptr; + napiAsyncTask_ = nullptr; + ReleaseNativeReference(serviceProxyObject_.release()); +} + +void JSUIServiceExtAbilityConnection::HandleOnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + if (napiAsyncTask_ != nullptr) { + TAG_LOGI(AAFwkTag::UISERVC_EXT, "HandleOnAbilityConnectDone, CreateJsUIServiceProxy"); + sptr hostStub = GetServiceHostStub(); + sptr hostProxy = nullptr; + if (hostStub != nullptr) { + hostProxy = hostStub->AsObject(); + } + napi_value proxy = AAFwk::JsUIServiceProxy::CreateJsUIServiceProxy(env_, remoteObject, + connectionId_, hostProxy); + SetProxyObject(proxy); + napiAsyncTask_->ResolveWithNoError(env_, proxy); + + ResolveDuplicatedPendingTask(env_, proxy); + } else { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "HandleOnAbilityConnectDone, napiAsyncTask_ null"); + } + napiAsyncTask_ = nullptr; +} + +void JSUIServiceExtAbilityConnection::HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element, + int resultCode) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "HandleOnAbilityDisconnectDone"); + if (napiAsyncTask_ != nullptr) { + napi_value innerError = CreateJsError(env_, AbilityErrorCode::ERROR_CODE_INNER); + napiAsyncTask_->Reject(env_, innerError); + RejectDuplicatedPendingTask(env_, innerError); + napiAsyncTask_ = nullptr; + } + + CallJsOnDisconnect(); + UIServiceConnection::RemoveUIServiceAbilityConnection(connectionId_); +} + +void JSUIServiceExtAbilityConnection::SetNapiAsyncTask(std::shared_ptr& task) +{ + napiAsyncTask_ = task; +} + +void JSUIServiceExtAbilityConnection::AddDuplicatedPendingTask(std::unique_ptr& task) +{ + duplicatedPendingTaskList_.push_back(std::move(task)); +} + +void JSUIServiceExtAbilityConnection::ResolveDuplicatedPendingTask(napi_env env, napi_value proxy) +{ + for (auto &task : duplicatedPendingTaskList_) { + if (task != nullptr) { + task->ResolveWithNoError(env, proxy); + } + } + duplicatedPendingTaskList_.clear(); +} + +void JSUIServiceExtAbilityConnection::RejectDuplicatedPendingTask(napi_env env, napi_value error) +{ + for (auto &task : duplicatedPendingTaskList_) { + if (task != nullptr) { + task->Reject(env, error); + } + } + duplicatedPendingTaskList_.clear(); +} + +void JSUIServiceExtAbilityConnection::SetProxyObject(napi_value proxy) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "SetProxyObject"); + serviceProxyObject_.reset(); + if (proxy != nullptr) { + napi_ref ref = nullptr; + napi_create_reference(env_, proxy, 1, &ref); + serviceProxyObject_ = std::unique_ptr(reinterpret_cast(ref)); + } +} + +napi_value JSUIServiceExtAbilityConnection::GetProxyObject() +{ + if (serviceProxyObject_ == nullptr) { + return nullptr; + } + return serviceProxyObject_->GetNapiValue(); +} + +int32_t JSUIServiceExtAbilityConnection::OnSendData(OHOS::AAFwk::WantParams &data) +{ + wptr connection = this; + std::unique_ptr complete = std::make_unique + ([connection, wantParams = data](napi_env env, NapiAsyncTask &task, int32_t status) { + sptr connectionSptr = connection.promote(); + if (!connectionSptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "connectionSptr nullptr"); + return; + } + connectionSptr->HandleOnSendData(wantParams); + }); + + napi_ref callback = nullptr; + std::unique_ptr execute = nullptr; + NapiAsyncTask::Schedule("JSUIServiceExtAbilityConnection::SendData", + env_, std::make_unique(callback, std::move(execute), std::move(complete))); + + return static_cast(AbilityErrorCode::ERROR_OK); +} + +void JSUIServiceExtAbilityConnection::HandleOnSendData(const OHOS::AAFwk::WantParams &data) +{ + napi_value argv[] = { AppExecFwk::CreateJsWantParams(env_, data) }; + CallObjectMethod("onData", argv, ARGC_ONE); +} + +void JSUIServiceExtAbilityConnection::CallJsOnDisconnect() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + CallObjectMethod("onDisconnect", nullptr, 0); +} + +bool JSUIServiceExtAbilityConnection::IsJsCallbackObjectEquals(napi_env env, + std::unique_ptr &callback, napi_value value) +{ + if (value == nullptr || callback == nullptr) { + return callback.get() == reinterpret_cast(value); + } + auto object = callback->GetNapiValue(); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to get object."); + return false; + } + bool result = false; + if (napi_strict_equals(env, object, value, &result) != napi_ok) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Object does not match value."); + return false; + } + return result; +} + +} +} diff --git a/frameworks/native/ability/native/ability_runtime/ui_ability_servicehost_stub_impl.cpp b/frameworks/native/ability/native/ability_runtime/ui_ability_servicehost_stub_impl.cpp new file mode 100644 index 0000000000..97284731da --- /dev/null +++ b/frameworks/native/ability/native/ability_runtime/ui_ability_servicehost_stub_impl.cpp @@ -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. + */ + +#include "ui_ability_servicehost_stub_impl.h" + +#include "ability_business_error.h" +#include "js_uiservice_ability_connection.h" + +namespace OHOS { +namespace AbilityRuntime { + +UIAbilityServiceHostStubImpl::UIAbilityServiceHostStubImpl(wptr conn) + :conn_(conn) +{ +} + +int32_t UIAbilityServiceHostStubImpl::SendData(OHOS::AAFwk::WantParams &data) +{ + sptr conn = conn_.promote(); + if (conn != nullptr) { + return conn->OnSendData(data); + } + + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); +} + +} +} diff --git a/frameworks/native/ability/native/ability_thread.cpp b/frameworks/native/ability/native/ability_thread.cpp index fc7d93400a..6abba9f632 100644 --- a/frameworks/native/ability/native/ability_thread.cpp +++ b/frameworks/native/ability/native/ability_thread.cpp @@ -19,7 +19,6 @@ #include "fa_ability_thread.h" #include "ui_ability_thread.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" namespace OHOS { diff --git a/frameworks/native/ability/native/ability_window.cpp b/frameworks/native/ability/native/ability_window.cpp index 9ad37effcf..d6c98af9dd 100644 --- a/frameworks/native/ability/native/ability_window.cpp +++ b/frameworks/native/ability/native/ability_window.cpp @@ -17,7 +17,6 @@ #include "ability.h" #include "ability_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "scene_board_judgement.h" namespace OHOS { diff --git a/frameworks/native/ability/native/action_extension_ability/action_extension.cpp b/frameworks/native/ability/native/action_extension_ability/action_extension.cpp index d105b87a61..c4e6938eb8 100644 --- a/frameworks/native/ability/native/action_extension_ability/action_extension.cpp +++ b/frameworks/native/ability/native/action_extension_ability/action_extension.cpp @@ -16,7 +16,6 @@ #include "action_extension.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_action_extension.h" #include "runtime.h" #include "ui_extension_context.h" @@ -25,7 +24,7 @@ namespace OHOS { namespace AbilityRuntime { ActionExtension *ActionExtension::Create(const std::unique_ptr &runtime) { - TAG_LOGD(AAFwkTag::ACTION_EXT, "called."); + TAG_LOGD(AAFwkTag::ACTION_EXT, "called"); if (!runtime) { return new ActionExtension(); } diff --git a/frameworks/native/ability/native/action_extension_ability/action_extension_module_loader.cpp b/frameworks/native/ability/native/action_extension_ability/action_extension_module_loader.cpp index 601479fe7d..7d56618dde 100644 --- a/frameworks/native/ability/native/action_extension_ability/action_extension_module_loader.cpp +++ b/frameworks/native/ability/native/action_extension_ability/action_extension_module_loader.cpp @@ -17,7 +17,6 @@ #include "action_extension.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/ability/native/action_extension_ability/js_action_extension.cpp b/frameworks/native/ability/native/action_extension_ability/js_action_extension.cpp index c8b7efcb52..55f88bc52f 100644 --- a/frameworks/native/ability/native/action_extension_ability/js_action_extension.cpp +++ b/frameworks/native/ability/native/action_extension_ability/js_action_extension.cpp @@ -16,7 +16,6 @@ #include "js_action_extension.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "js_ui_extension_base.h" @@ -35,7 +34,7 @@ JsActionExtension::JsActionExtension(const std::unique_ptr &runtime) JsActionExtension::~JsActionExtension() { - TAG_LOGD(AAFwkTag::ACTION_EXT, "destructor."); + TAG_LOGD(AAFwkTag::ACTION_EXT, "destructor"); } } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/ability/native/auto_fill_extension_ability/auto_fill_extension.cpp b/frameworks/native/ability/native/auto_fill_extension_ability/auto_fill_extension.cpp index fdb3644e39..0051c18941 100644 --- a/frameworks/native/ability/native/auto_fill_extension_ability/auto_fill_extension.cpp +++ b/frameworks/native/ability/native/auto_fill_extension_ability/auto_fill_extension.cpp @@ -17,7 +17,6 @@ #include "auto_fill_extension_context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_auto_fill_extension.h" #include "runtime.h" @@ -25,7 +24,7 @@ namespace OHOS { namespace AbilityRuntime { AutoFillExtension *AutoFillExtension::Create(const std::unique_ptr &runtime) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (runtime == nullptr) { return new AutoFillExtension(); } @@ -41,7 +40,7 @@ void AutoFillExtension::Init(const std::shared_ptr &record, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); ExtensionBase::Init(record, application, handler, token); } diff --git a/frameworks/native/ability/native/auto_fill_extension_ability/auto_fill_extension_context.cpp b/frameworks/native/ability/native/auto_fill_extension_ability/auto_fill_extension_context.cpp index 972cf138a2..63c866f427 100644 --- a/frameworks/native/ability/native/auto_fill_extension_ability/auto_fill_extension_context.cpp +++ b/frameworks/native/ability/native/auto_fill_extension_ability/auto_fill_extension_context.cpp @@ -16,7 +16,6 @@ #include "auto_fill_extension_context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { @@ -33,7 +32,7 @@ void AutoFillExtensionContext::SetSessionInfo(const wptr &se int32_t AutoFillExtensionContext::ReloadInModal(const CustomData &customData) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); auto sessionInfo = sessionInfo_.promote(); if (sessionInfo == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Session info is nullptr."); diff --git a/frameworks/native/ability/native/auto_fill_extension_ability/auto_fill_extension_module_loader.cpp b/frameworks/native/ability/native/auto_fill_extension_ability/auto_fill_extension_module_loader.cpp index 115114b2b6..812155a1d1 100644 --- a/frameworks/native/ability/native/auto_fill_extension_ability/auto_fill_extension_module_loader.cpp +++ b/frameworks/native/ability/native/auto_fill_extension_ability/auto_fill_extension_module_loader.cpp @@ -17,7 +17,6 @@ #include "auto_fill_extension.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/ability/native/auto_fill_extension_ability/js_auto_fill_extension.cpp b/frameworks/native/ability/native/auto_fill_extension_ability/js_auto_fill_extension.cpp index bbdd7d3a0c..f35f42e673 100644 --- a/frameworks/native/ability/native/auto_fill_extension_ability/js_auto_fill_extension.cpp +++ b/frameworks/native/ability/native/auto_fill_extension_ability/js_auto_fill_extension.cpp @@ -24,7 +24,6 @@ #include "context.h" #include "hitrace_meter.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "int_wrapper.h" #include "js_auto_fill_extension_util.h" #include "js_auto_fill_extension_context.h" @@ -57,7 +56,7 @@ constexpr const char *WANT_PARAMS_AUTO_FILL_POPUP_WINDOW_KEY = "ohos.ability.par } napi_value AttachAutoFillExtensionContext(napi_env env, void *value, void *) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (value == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Invalid parameter."); return nullptr; @@ -125,7 +124,7 @@ void JsAutoFillExtension::Init(const std::shared_ptr &record const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); AutoFillExtension::Init(record, application, handler, token); if (abilityInfo_ == nullptr || abilityInfo_->srcEntrance.empty()) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Init ability info failed."); @@ -164,7 +163,7 @@ void JsAutoFillExtension::Init(const std::shared_ptr &record void JsAutoFillExtension::BindContext(napi_env env, napi_value obj) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); auto context = GetContext(); if (context == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Failed to get context."); @@ -208,7 +207,7 @@ void JsAutoFillExtension::BindContext(napi_env env, napi_value obj) void JsAutoFillExtension::OnStart(const AAFwk::Want &want) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); Extension::OnStart(want); HandleScope handleScope(jsRuntime_); napi_env env = jsRuntime_.GetNapiEnv(); @@ -219,7 +218,7 @@ void JsAutoFillExtension::OnStart(const AAFwk::Want &want) void JsAutoFillExtension::OnStop() { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); AutoFillExtension::OnStop(); HandleScope handleScope(jsRuntime_); CallObjectMethod("onDestroy"); @@ -228,7 +227,7 @@ void JsAutoFillExtension::OnStop() void JsAutoFillExtension::OnStop(AppExecFwk::AbilityTransactionCallbackInfo<> *callbackInfo, bool &isAsyncCallback) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (callbackInfo == nullptr) { isAsyncCallback = false; OnStop(); @@ -263,7 +262,7 @@ void JsAutoFillExtension::OnStop(AppExecFwk::AbilityTransactionCallbackInfo<> *c void JsAutoFillExtension::OnStopCallBack() { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); auto context = GetContext(); if (context == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Failed to get context."); @@ -346,7 +345,7 @@ bool JsAutoFillExtension::CallPromise(napi_value result, AppExecFwk::AbilityTran void JsAutoFillExtension::OnCommandWindow( const AAFwk::Want &want, const sptr &sessionInfo, AAFwk::WindowCommand winCmd) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (sessionInfo == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Session info is nullptr."); return; @@ -373,7 +372,7 @@ void JsAutoFillExtension::OnCommandWindow( void JsAutoFillExtension::OnCommandWindowDone(const sptr &sessionInfo, AAFwk::WindowCommand winCmd) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); auto context = GetContext(); if (context == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Failed to get context."); @@ -412,7 +411,7 @@ void JsAutoFillExtension::OnCommand(const AAFwk::Want &want, bool restart, int s void JsAutoFillExtension::OnForeground(const Want &want, sptr sessionInfo) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); Extension::OnForeground(want, sessionInfo); ForegroundWindow(want, sessionInfo); HandleScope handleScope(jsRuntime_); @@ -421,7 +420,7 @@ void JsAutoFillExtension::OnForeground(const Want &want, sptr &sessionInfo, const CustomData &customData) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (!isPopup_) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "The current window type is not popup."); return ERR_INVALID_OPERATION; @@ -462,7 +461,7 @@ int32_t JsAutoFillExtension::OnReloadInModal(const sptr &ses void JsAutoFillExtension::UpdateRequest(const AAFwk::WantParams &wantParams) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); HandleScope handleScope(jsRuntime_); napi_env env = jsRuntime_.GetNapiEnv(); napi_value request = JsAutoFillExtensionUtil::WrapUpdateRequest(wantParams, env); @@ -476,7 +475,7 @@ void JsAutoFillExtension::UpdateRequest(const AAFwk::WantParams &wantParams) bool JsAutoFillExtension::HandleAutoFillCreate(const AAFwk::Want &want, const sptr &sessionInfo) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Invalid session info."); return false; @@ -493,6 +492,7 @@ bool JsAutoFillExtension::HandleAutoFillCreate(const AAFwk::Want &want, const sp option->SetWindowType(Rosen::WindowType::WINDOW_TYPE_UI_EXTENSION); option->SetWindowSessionType(Rosen::WindowSessionType::EXTENSION_SESSION); option->SetParentId(sessionInfo->hostWindowId); + option->SetUIExtensionUsage(static_cast(sessionInfo->uiExtensionUsage)); auto uiWindow = Rosen::Window::Create(option, GetContext(), sessionInfo->sessionToken); if (uiWindow == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Create ui window error."); @@ -514,7 +514,7 @@ bool JsAutoFillExtension::HandleAutoFillCreate(const AAFwk::Want &want, const sp void JsAutoFillExtension::ForegroundWindow(const AAFwk::Want &want, const sptr &sessionInfo) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (sessionInfo == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "sessionInfo is nullptr."); return; @@ -552,7 +552,7 @@ void JsAutoFillExtension::ForegroundWindow(const AAFwk::Want &want, const sptr &sessionInfo) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Invalid sessionInfo."); return; @@ -571,7 +571,7 @@ void JsAutoFillExtension::BackgroundWindow(const sptr &sessi void JsAutoFillExtension::DestroyWindow(const sptr &sessionInfo) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Invalid sessionInfo."); return; @@ -632,7 +632,7 @@ napi_value JsAutoFillExtension::CallObjectMethod(const char *name, napi_value co void JsAutoFillExtension::CallJsOnRequest( const AAFwk::Want &want, const sptr &sessionInfo, const sptr &uiWindow) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (sessionInfo == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "sessionInfo is nullptr."); return; @@ -683,7 +683,7 @@ void JsAutoFillExtension::CallJsOnRequest( void JsAutoFillExtension::RegisterTransferComponentDataListener(const sptr &uiWindow) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (uiWindow == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Invalid ui window object."); return; diff --git a/frameworks/native/ability/native/auto_fill_extension_ability/js_auto_fill_extension_context.cpp b/frameworks/native/ability/native/auto_fill_extension_ability/js_auto_fill_extension_context.cpp index 8366abf5c3..b69ed11808 100755 --- a/frameworks/native/ability/native/auto_fill_extension_ability/js_auto_fill_extension_context.cpp +++ b/frameworks/native/ability/native/auto_fill_extension_ability/js_auto_fill_extension_context.cpp @@ -16,7 +16,6 @@ #include "js_auto_fill_extension_context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_error_utils.h" #include "js_extension_context.h" #include "napi/native_api.h" @@ -31,7 +30,7 @@ constexpr size_t ARGC_ONE = 1; } void JsAutoFillExtensionContext::Finalizer(napi_env env, void *data, void *hint) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); std::unique_ptr(static_cast(data)); } @@ -42,7 +41,7 @@ napi_value JsAutoFillExtensionContext::ReloadInModal(napi_env env, napi_callback napi_value JsAutoFillExtensionContext::OnReloadInModal(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (info.argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Not enough params"); ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); @@ -94,7 +93,7 @@ napi_value JsAutoFillExtensionContext::OnReloadInModal(napi_env env, NapiCallbac napi_value JsAutoFillExtensionContext::CreateJsAutoFillExtensionContext( napi_env env, const std::shared_ptr &context) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); std::shared_ptr abilityInfo = nullptr; if (context != nullptr) { abilityInfo = context->GetAbilityInfo(); diff --git a/frameworks/native/ability/native/auto_fill_extension_ability/js_auto_fill_extension_util.cpp b/frameworks/native/ability/native/auto_fill_extension_ability/js_auto_fill_extension_util.cpp index 399977be42..9d210f1535 100644 --- a/frameworks/native/ability/native/auto_fill_extension_ability/js_auto_fill_extension_util.cpp +++ b/frameworks/native/ability/native/auto_fill_extension_ability/js_auto_fill_extension_util.cpp @@ -16,7 +16,6 @@ #include "js_auto_fill_extension_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi_common_util.h" #include "napi_common_want.h" @@ -59,7 +58,7 @@ constexpr uint32_t PAGE_NODE_COUNT_MAX = 100; napi_value JsAutoFillExtensionUtil::WrapViewData(const napi_env env, const AbilityBase::ViewData &viewData) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); napi_value jsObject = nullptr; NAPI_CALL(env, napi_create_object(env, &jsObject)); napi_value jsValue = nullptr; @@ -103,7 +102,7 @@ napi_value JsAutoFillExtensionUtil::WrapViewData(const napi_env env, const Abili napi_value JsAutoFillExtensionUtil::WrapCustomData(const napi_env env, const AAFwk::WantParams ¶m) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); napi_value jsObject = nullptr; NAPI_CALL(env, napi_create_object(env, &jsObject)); napi_value jsValue = nullptr; @@ -114,7 +113,7 @@ napi_value JsAutoFillExtensionUtil::WrapCustomData(const napi_env env, const AAF napi_value JsAutoFillExtensionUtil::WrapPageNodeInfo(const napi_env env, const AbilityBase::PageNodeInfo &pageNodeInfo) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); napi_value jsObject = nullptr; NAPI_CALL(env, napi_create_object(env, &jsObject)); napi_value jsValue = nullptr; @@ -153,7 +152,7 @@ napi_value JsAutoFillExtensionUtil::WrapPageNodeInfo(const napi_env env, const A napi_value JsAutoFillExtensionUtil::WrapRectData(const napi_env env, const AbilityBase::Rect &rect) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); napi_value jsObject = nullptr; NAPI_CALL(env, napi_create_object(env, &jsObject)); napi_value jsValue = nullptr; @@ -175,7 +174,7 @@ napi_value JsAutoFillExtensionUtil::WrapRectData(const napi_env env, const Abili void JsAutoFillExtensionUtil::UnwrapViewData( const napi_env env, const napi_value value, AbilityBase::ViewData &viewData) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); napi_value jsViewData = GetPropertyValueByPropertyName(env, value, VIEW_DATA_VIEW_DATA, napi_object); if (jsViewData == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Get ViewData from JS failed"); @@ -216,7 +215,7 @@ void JsAutoFillExtensionUtil::UnwrapViewData( void JsAutoFillExtensionUtil::UnwrapPageNodeInfo( const napi_env env, const napi_value jsNode, AbilityBase::PageNodeInfo &node) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); UnwrapInt32ByPropertyName(env, jsNode, PAGE_INFO_ID, node.id); UnwrapInt32ByPropertyName(env, jsNode, PAGE_INFO_DEPTH, node.depth); int32_t type; @@ -235,7 +234,7 @@ void JsAutoFillExtensionUtil::UnwrapPageNodeInfo( void JsAutoFillExtensionUtil::UnwrapRectData( const napi_env env, const napi_value value, AbilityBase::Rect &rect) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); int32_t position; UnwrapInt32ByPropertyName(env, value, RECT_POSITION_LEFT, position); rect.left = position; @@ -252,7 +251,7 @@ void JsAutoFillExtensionUtil::UnwrapRectData( napi_value JsAutoFillExtensionUtil::WrapFillRequest(const AAFwk::Want &want, const napi_env env) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); napi_value jsObject = nullptr; NAPI_CALL(env, napi_create_object(env, &jsObject)); if (jsObject == nullptr) { @@ -308,7 +307,7 @@ napi_value JsAutoFillExtensionUtil::WrapFillRequest(const AAFwk::Want &want, con napi_value JsAutoFillExtensionUtil::WrapUpdateRequest(const AAFwk::WantParams &wantParams, const napi_env env) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); napi_value jsObject = nullptr; NAPI_CALL(env, napi_create_object(env, &jsObject)); if (jsObject == nullptr) { @@ -331,7 +330,7 @@ napi_value JsAutoFillExtensionUtil::WrapUpdateRequest(const AAFwk::WantParams &w void JsAutoFillExtensionUtil::UnwrapFillResponse(const napi_env env, const napi_value value, FillResponse &response) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); UnwrapViewData(env, value, response.viewData); } diff --git a/frameworks/native/ability/native/auto_fill_extension_ability/js_fill_request_callback.cpp b/frameworks/native/ability/native/auto_fill_extension_ability/js_fill_request_callback.cpp index 0376e7efe0..20504aadf3 100644 --- a/frameworks/native/ability/native/auto_fill_extension_ability/js_fill_request_callback.cpp +++ b/frameworks/native/ability/native/auto_fill_extension_ability/js_fill_request_callback.cpp @@ -18,7 +18,6 @@ #include "ability_manager_client.h" #include "accesstoken_kit.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "int_wrapper.h" #include "ipc_skeleton.h" #include "js_auto_fill_extension_util.h" @@ -88,7 +87,7 @@ napi_value JsFillRequestCallback::FillRequestAutoFillPopupConfig(napi_env env, n napi_value JsFillRequestCallback::OnFillRequestSuccess(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (info.argc < ARGC_ONE || !IsTypeForNapiValue(env, info.argv[INDEX_ZERO], napi_object)) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Failed to parse viewData JsonString!"); ThrowError(env, static_cast(AbilityErrorCode::ERROR_CODE_INVALID_PARAM), ERROR_MSG_VIEWDATA_INVALID); @@ -114,14 +113,14 @@ napi_value JsFillRequestCallback::OnFillRequestSuccess(napi_env env, NapiCallbac napi_value JsFillRequestCallback::OnFillRequestFailed(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); SendResultCodeAndViewData(JsAutoFillExtensionUtil::AutoFillResultCode::CALLBACK_FAILED, ""); return CreateJsUndefined(env); } napi_value JsFillRequestCallback::OnFillRequestCanceled(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (info.argc < ARGC_ONE) { SendResultCodeAndViewData(JsAutoFillExtensionUtil::AutoFillResultCode::CALLBACK_CANCEL, ""); return CreateJsUndefined(env); @@ -147,7 +146,7 @@ napi_value JsFillRequestCallback::OnFillRequestCanceled(napi_env env, NapiCallba napi_value JsFillRequestCallback::OnFillRequestAutoFillPopupConfig(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); auto selfToken = IPCSkeleton::GetSelfTokenID(); if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(selfToken)) { TAG_LOGE(AAFwkTag::CONTEXT, "This application is not system-app, can not use system-api"); @@ -207,7 +206,7 @@ bool JsFillRequestCallback::SetPopupConfigToWantParams( void JsFillRequestCallback::SendResultCodeAndViewData( const JsAutoFillExtensionUtil::AutoFillResultCode &resultCode, const std::string &jsString) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (uiWindow_ == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "UiWindow is nullptr."); return; @@ -238,7 +237,7 @@ void JsFillRequestCallback::SendResultCodeAndViewData( napi_value JsFillRequestCallback::CreateJsFillRequestCallback(napi_env env, const sptr &sessionInfo, const sptr &uiWindow) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); napi_value object = nullptr; napi_create_object(env, &object); if (object == nullptr) { diff --git a/frameworks/native/ability/native/auto_fill_extension_ability/js_save_request_callback.cpp b/frameworks/native/ability/native/auto_fill_extension_ability/js_save_request_callback.cpp index ad7c74252e..59a29b8bd0 100644 --- a/frameworks/native/ability/native/auto_fill_extension_ability/js_save_request_callback.cpp +++ b/frameworks/native/ability/native/auto_fill_extension_ability/js_save_request_callback.cpp @@ -18,7 +18,6 @@ #include "ability_manager_client.h" #include "accesstoken_kit.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_auto_fill_extension_util.h" #include "js_error_utils.h" #include "js_runtime_utils.h" @@ -55,21 +54,21 @@ napi_value JsSaveRequestCallback::SaveRequestFailed(napi_env env, napi_callback_ napi_value JsSaveRequestCallback::OnSaveRequestSuccess(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); SendResultCodeAndViewData(JsAutoFillExtensionUtil::AutoFillResultCode::CALLBACK_SUCESS); return CreateJsUndefined(env); } napi_value JsSaveRequestCallback::OnSaveRequestFailed(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); SendResultCodeAndViewData(JsAutoFillExtensionUtil::AutoFillResultCode::CALLBACK_FAILED); return CreateJsUndefined(env); } void JsSaveRequestCallback::SendResultCodeAndViewData(const JsAutoFillExtensionUtil::AutoFillResultCode &resultCode) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); if (uiWindow_ == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "UI window is nullptr."); return; @@ -91,7 +90,7 @@ void JsSaveRequestCallback::SendResultCodeAndViewData(const JsAutoFillExtensionU napi_value JsSaveRequestCallback::CreateJsSaveRequestCallback(napi_env env, const sptr &sessionInfo, const sptr &uiWindow) { - TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "called"); napi_value object = nullptr; napi_create_object(env, &object); if (object == nullptr) { diff --git a/frameworks/native/ability/native/auto_startup_callback_proxy.cpp b/frameworks/native/ability/native/auto_startup_callback_proxy.cpp index 8117160aa5..e3aa9cbe36 100644 --- a/frameworks/native/ability/native/auto_startup_callback_proxy.cpp +++ b/frameworks/native/ability/native/auto_startup_callback_proxy.cpp @@ -17,7 +17,6 @@ #include "ability_manager_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" diff --git a/frameworks/native/ability/native/auto_startup_callback_stub.cpp b/frameworks/native/ability/native/auto_startup_callback_stub.cpp index 7104014bc9..fe00f83d99 100644 --- a/frameworks/native/ability/native/auto_startup_callback_stub.cpp +++ b/frameworks/native/ability/native/auto_startup_callback_stub.cpp @@ -19,7 +19,6 @@ #include "auto_startup_info.h" #include "event_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" @@ -31,18 +30,9 @@ AutoStartupCallBackStub::AutoStartupCallBackStub() Init(); } -AutoStartupCallBackStub::~AutoStartupCallBackStub() -{ - requestFuncMap_.clear(); -} +AutoStartupCallBackStub::~AutoStartupCallBackStub() {} -void AutoStartupCallBackStub::Init() -{ - requestFuncMap_[static_cast(AbilityManagerInterfaceCode::ON_AUTO_STARTUP_ON)] = - &AutoStartupCallBackStub::OnAutoStartupOnInner; - requestFuncMap_[static_cast(AbilityManagerInterfaceCode::ON_AUTO_STARTUP_OFF)] = - &AutoStartupCallBackStub::OnAutoStartupOffInner; -} +void AutoStartupCallBackStub::Init() {} int AutoStartupCallBackStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -54,13 +44,15 @@ int AutoStartupCallBackStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = requestFuncMap_.find(code); - if (itFunc != requestFuncMap_.end()) { - auto requestFunc = itFunc->second; - if (requestFunc != nullptr) { - return (this->*requestFunc)(data, reply); - } + switch (code) { + case static_cast(AbilityManagerInterfaceCode::ON_AUTO_STARTUP_ON): + return OnAutoStartupOnInner(data, reply); + break; + case static_cast(AbilityManagerInterfaceCode::ON_AUTO_STARTUP_OFF): + return OnAutoStartupOffInner(data, reply); + break; } + TAG_LOGW(AAFwkTag::AUTO_STARTUP, "Default case, need check."); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/frameworks/native/ability/native/child_process_manager/child_process.cpp b/frameworks/native/ability/native/child_process_manager/child_process.cpp index d133f7ca29..b2c87b8c0b 100644 --- a/frameworks/native/ability/native/child_process_manager/child_process.cpp +++ b/frameworks/native/ability/native/child_process_manager/child_process.cpp @@ -40,5 +40,7 @@ bool ChildProcess::Init(const std::shared_ptr &info) void ChildProcess::OnStart() {} +void ChildProcess::OnStart(std::shared_ptr args) {} + } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file 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 1fa670da17..7fb076d059 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 @@ -31,13 +31,13 @@ #include "child_process.h" #include "native_child_ipc_process.h" #include "child_process_manager_error_utils.h" +#include "child_process_request.h" #include "child_process_start_info.h" #include "constants.h" #include "event_runner.h" #include "errors.h" #include "hap_module_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parameters.h" #include "runtime.h" #include "sys_mgr_client.h" @@ -51,6 +51,12 @@ namespace { } bool ChildProcessManager::signalRegistered_ = false; +ChildProcessManager &ChildProcessManager::GetInstance() +{ + static ChildProcessManager instance; + return instance; +} + ChildProcessManager::ChildProcessManager() { TAG_LOGD(AAFwkTag::PROCESSMGR, "ChildProcessManager constructor called"); @@ -74,7 +80,7 @@ ChildProcessManagerErrorCode ChildProcessManager::StartChildProcessBySelfFork(co TAG_LOGE(AAFwkTag::PROCESSMGR, "GetBundleInfo failed."); return ChildProcessManagerErrorCode::ERR_GET_BUNDLE_INFO_FAILED; } - + RegisterSignal(); pid = fork(); if (pid < 0) { @@ -95,9 +101,20 @@ ChildProcessManagerErrorCode ChildProcessManager::StartChildProcessBySelfFork(co ChildProcessManagerErrorCode ChildProcessManager::StartChildProcessByAppSpawnFork( const std::string &srcEntry, pid_t &pid) { - TAG_LOGI(AAFwkTag::PROCESSMGR, "called, startWitDebug: %{public}d, processName: %{public}s, native: %{public}d", - g_debugOption.isStartWithDebug, g_debugOption.processName.c_str(), g_debugOption.isStartWithNative); - ChildProcessManagerErrorCode errorCode = PreCheck(); + AppExecFwk::ChildProcessArgs args; + AppExecFwk::ChildProcessOptions options; + return StartArkChildProcess(srcEntry, pid, AppExecFwk::CHILD_PROCESS_TYPE_JS, args, options); +} + +ChildProcessManagerErrorCode ChildProcessManager::StartArkChildProcess( + const std::string &srcEntry, pid_t &pid, int32_t childProcessType, const AppExecFwk::ChildProcessArgs &args, + const AppExecFwk::ChildProcessOptions &options) +{ + TAG_LOGI(AAFwkTag::PROCESSMGR, "StartChildProcessByAppSpawnFork, startWitDebug: %{public}d, processName:" + "%{public}s, native:%{public}d, entryParams:%{private}s, fdsSize:%{public}zu, options.isolationMode:%{public}d", + g_debugOption.isStartWithDebug, g_debugOption.processName.c_str(), g_debugOption.isStartWithNative, + args.entryParams.c_str(), args.fds.size(), options.isolationMode); + ChildProcessManagerErrorCode errorCode = PreCheck(childProcessType != AppExecFwk::CHILD_PROCESS_TYPE_JS); if (errorCode != ChildProcessManagerErrorCode::ERR_OK) { return errorCode; } @@ -106,7 +123,14 @@ ChildProcessManagerErrorCode ChildProcessManager::StartChildProcessByAppSpawnFor TAG_LOGE(AAFwkTag::PROCESSMGR, "GetAppMgr failed."); return ChildProcessManagerErrorCode::ERR_GET_APP_MGR_FAILED; } - auto ret = appMgr->StartChildProcess(srcEntry, pid, childProcessCount_, g_debugOption.isStartWithDebug); + AppExecFwk::ChildProcessRequest request; + request.srcEntry = srcEntry; + request.childProcessType = childProcessType; + request.childProcessCount = childProcessCount_; + request.isStartWithDebug = g_debugOption.isStartWithDebug; + request.args = args; + request.options = options; + auto ret = appMgr->StartChildProcess(pid, request); childProcessCount_++; TAG_LOGD(AAFwkTag::PROCESSMGR, "AppMgr StartChildProcess ret:%{public}d", ret); if (ret != ERR_OK) { @@ -163,11 +187,12 @@ void ChildProcessManager::HandleSigChild(int32_t signo) } } -ChildProcessManagerErrorCode ChildProcessManager::PreCheck() +ChildProcessManagerErrorCode ChildProcessManager::PreCheck(bool useNewErrorCode) { if (!AAFwk::AppUtils::GetInstance().IsMultiProcessModel()) { TAG_LOGE(AAFwkTag::PROCESSMGR, "Multi process model is not enabled"); - return ChildProcessManagerErrorCode::ERR_MULTI_PROCESS_MODEL_DISABLED; + return useNewErrorCode ? ChildProcessManagerErrorCode::ERR_MULTI_PROCESS_MODEL_DISABLED_NEW : + ChildProcessManagerErrorCode::ERR_MULTI_PROCESS_MODEL_DISABLED; } if (IsChildProcess()) { TAG_LOGE(AAFwkTag::PROCESSMGR, "Already in child process"); @@ -193,7 +218,7 @@ ChildProcessManagerErrorCode ChildProcessManager::PreCheckNativeProcess() bool ChildProcessManager::IsChildProcess() { - return isChildProcessBySelfFork_ || hasChildProcessRecord(); + return isChildProcessBySelfFork_ || HasChildProcessRecord(); } void ChildProcessManager::HandleChildProcessBySelfFork(const std::string &srcEntry, @@ -209,7 +234,7 @@ void ChildProcessManager::HandleChildProcessBySelfFork(const std::string &srcEnt eventRunner->Stop(); AppExecFwk::HapModuleInfo hapModuleInfo; - if (!GetHapModuleInfo(bundleInfo, hapModuleInfo)) { + if (!GetEntryHapModuleInfo(bundleInfo, hapModuleInfo)) { TAG_LOGE(AAFwkTag::PROCESSMGR, "GetHapModuleInfo failed."); return; } @@ -223,13 +248,15 @@ void ChildProcessManager::HandleChildProcessBySelfFork(const std::string &srcEnt "isDebugApp is %{public}d, isStartWithNative is %{public}d.", g_debugOption.isStartWithDebug, g_debugOption.processName.c_str(), g_debugOption.isDebugApp, g_debugOption.isStartWithNative); runtime->StartDebugMode(g_debugOption); - LoadJsFile(srcEntry, hapModuleInfo, runtime); + std::string srcPath; + srcPath.append(hapModuleInfo.moduleName).append("/").append(srcEntry); + LoadJsFile(srcPath, hapModuleInfo, runtime); TAG_LOGD(AAFwkTag::PROCESSMGR, "HandleChildProcessBySelfFork end."); exit(0); } bool ChildProcessManager::LoadJsFile(const std::string &srcEntry, const AppExecFwk::HapModuleInfo &hapModuleInfo, - std::unique_ptr &runtime) + std::unique_ptr &runtime, std::shared_ptr args) { std::shared_ptr processStartInfo = std::make_shared(); std::string filename = std::filesystem::path(srcEntry).stem(); @@ -249,7 +276,11 @@ bool ChildProcessManager::LoadJsFile(const std::string &srcEntry, const AppExecF TAG_LOGE(AAFwkTag::PROCESSMGR, "JsChildProcess init failed."); return false; } - process->OnStart(); + if (args) { + process->OnStart(args); + } else { + process->OnStart(); + } TAG_LOGD(AAFwkTag::PROCESSMGR, "LoadJsFile end."); return true; } @@ -325,7 +356,7 @@ bool ChildProcessManager::GetBundleInfo(AppExecFwk::BundleInfo &bundleInfo) static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_METADATA)), bundleInfo) == ERR_OK); } -bool ChildProcessManager::GetHapModuleInfo(const AppExecFwk::BundleInfo &bundleInfo, +bool ChildProcessManager::GetEntryHapModuleInfo(const AppExecFwk::BundleInfo &bundleInfo, AppExecFwk::HapModuleInfo &hapModuleInfo) { if (bundleInfo.hapModuleInfos.empty()) { @@ -344,7 +375,26 @@ bool ChildProcessManager::GetHapModuleInfo(const AppExecFwk::BundleInfo &bundleI return result; } -bool ChildProcessManager::hasChildProcessRecord() +bool ChildProcessManager::GetHapModuleInfo(const AppExecFwk::BundleInfo &bundleInfo, const std::string &moduleName, + AppExecFwk::HapModuleInfo &hapModuleInfo) +{ + if (bundleInfo.hapModuleInfos.empty()) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "hapModuleInfos empty!"); + return false; + } + TAG_LOGD(AAFwkTag::PROCESSMGR, "hapModueInfos size: %{public}zu", bundleInfo.hapModuleInfos.size()); + bool result = false; + for (const auto &info : bundleInfo.hapModuleInfos) { + if (info.name == moduleName) { + result = true; + hapModuleInfo = info; + break; + } + } + return result; +} + +bool ChildProcessManager::HasChildProcessRecord() { sptr appMgr = GetAppMgr(); if (appMgr == nullptr) { @@ -384,6 +434,19 @@ void ChildProcessManager::SetForkProcessDebugOption(const std::string bundleName g_debugOption.isStartWithNative = isStartWithNative; } +void ChildProcessManager::SetAppSpawnForkDebugOption(Runtime::DebugOption &debugOption, + std::shared_ptr processInfo) +{ + if (!processInfo) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "SetAppSpawnDebugOption failed, processInfo is nullptr."); + return; + } + debugOption.processName = processInfo->processName; + debugOption.isStartWithDebug = processInfo->isStartWithDebug; + debugOption.isDebugApp = processInfo->isDebugApp; + debugOption.isStartWithNative = processInfo->isStartWithNative; +} + void ChildProcessManager::MakeProcessName(const std::string &srcEntry) { std::string processName = g_debugOption.bundleName; @@ -402,5 +465,18 @@ void ChildProcessManager::MakeProcessName(const std::string &srcEntry) TAG_LOGD(AAFwkTag::PROCESSMGR, "SetForkProcessDebugOption processName is %{public}s", processName.c_str()); g_debugOption.processName = processName; } + +std::string ChildProcessManager::GetModuleNameFromSrcEntry(const std::string &srcEntry) +{ + std::string::size_type pos = srcEntry.find_first_of('/'); + if (pos == std::string::npos) { + return ""; + } + std::string moduleName = srcEntry.substr(0, pos); + if (moduleName == ".") { + return ""; + } + return moduleName; +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/ability/native/child_process_manager/js_child_process.cpp b/frameworks/native/ability/native/child_process_manager/js_child_process.cpp index 71bf64a88e..74a90be3f5 100644 --- a/frameworks/native/ability/native/child_process_manager/js_child_process.cpp +++ b/frameworks/native/ability/native/child_process_manager/js_child_process.cpp @@ -17,9 +17,9 @@ #include "child_process.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "js_runtime_utils.h" +#include "napi_common_child_process_param.h" namespace OHOS { namespace AbilityRuntime { @@ -51,9 +51,7 @@ bool JsChildProcess::Init(const std::shared_ptr &info) TAG_LOGE(AAFwkTag::PROCESSMGR, "ChildProcessStartInfo srcEntry is empty"); return false; } - std::string srcPath; - srcPath.append(info->moduleName).append("/"); - srcPath.append(info->srcEntry); + std::string srcPath = info->srcEntry; if (srcPath.rfind(".") != std::string::npos) { srcPath.erase(srcPath.rfind(".")); } @@ -77,6 +75,23 @@ void JsChildProcess::OnStart() CallObjectMethod("onStart"); } +void JsChildProcess::OnStart(std::shared_ptr args) +{ + TAG_LOGI(AAFwkTag::PROCESSMGR, "JsChildProcess OnStart called"); + if (!args) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "args is nullptr"); + return; + } + ChildProcess::OnStart(args); + + HandleScope handleScope(jsRuntime_); + auto env = jsRuntime_.GetNapiEnv(); + + napi_value jsArgs = WrapChildProcessArgs(env, *args); + napi_value argv[] = { jsArgs }; + CallObjectMethod("onStart", argv, ArraySize(argv)); +} + napi_value JsChildProcess::CallObjectMethod(const char *name, napi_value const *argv, size_t argc) { TAG_LOGD(AAFwkTag::PROCESSMGR, "JsChildProcess::CallObjectMethod(%{public}s)", name); 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 index 0ad1e63ce3..35144b82da 100644 --- 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 @@ -18,7 +18,6 @@ #include #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "child_process_manager_error_utils.h" namespace OHOS { diff --git a/frameworks/native/ability/native/configuration_utils.cpp b/frameworks/native/ability/native/configuration_utils.cpp index 9771a5b0d4..4ba9c954c3 100644 --- a/frameworks/native/ability/native/configuration_utils.cpp +++ b/frameworks/native/ability/native/configuration_utils.cpp @@ -17,7 +17,6 @@ #include "configuration_convertor.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #ifdef SUPPORT_GRAPHICS #include "window.h" diff --git a/frameworks/native/ability/native/continuation/distributed/continuation_handler.cpp b/frameworks/native/ability/native/continuation/distributed/continuation_handler.cpp index 537c46c364..da9c6f777b 100644 --- a/frameworks/native/ability/native/continuation/distributed/continuation_handler.cpp +++ b/frameworks/native/ability/native/continuation/distributed/continuation_handler.cpp @@ -18,7 +18,6 @@ #include "distributed_errors.h" #include "element_name.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using OHOS::AAFwk::WantParams; namespace OHOS { @@ -153,7 +152,7 @@ void ContinuationHandler::HandleReceiveRemoteScheduler(const sptr if (schedulerDeathRecipient_ == nullptr) { schedulerDeathRecipient_ = new (std::nothrow) ReverseContinuationSchedulerRecipient( - std::bind(&ContinuationHandler::OnReplicaDied, this, std::placeholders::_1)); + [this](const wptr &arg) { this->OnReplicaDied(arg); }); } remoteReplicaProxy_ = iface_cast(remoteReplica); diff --git a/frameworks/native/ability/native/continuation/distributed/continuation_handler_stage.cpp b/frameworks/native/ability/native/continuation/distributed/continuation_handler_stage.cpp index c16fddd9b6..2d39d9dc57 100644 --- a/frameworks/native/ability/native/continuation/distributed/continuation_handler_stage.cpp +++ b/frameworks/native/ability/native/continuation/distributed/continuation_handler_stage.cpp @@ -20,7 +20,6 @@ #include "distributed_errors.h" #include "element_name.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using OHOS::AAFwk::WantParams; namespace OHOS { @@ -146,7 +145,9 @@ void ContinuationHandlerStage::HandleReceiveRemoteScheduler(const sptr &arg) { + this->OnReplicaDied(arg); + }); } remoteReplicaProxy_ = iface_cast(remoteReplica); @@ -175,7 +176,7 @@ void ContinuationHandlerStage::HandleCompleteContinuation(int result) void ContinuationHandlerStage::SetReversible(bool reversible) { - TAG_LOGD(AAFwkTag::CONTINUATION, "Called."); + TAG_LOGD(AAFwkTag::CONTINUATION, "called"); reversible_ = reversible; } @@ -189,13 +190,13 @@ void ContinuationHandlerStage::SetAbilityInfo(std::shared_ptr &abil void ContinuationHandlerStage::SetPrimaryStub(const sptr &Primary) { - TAG_LOGD(AAFwkTag::CONTINUATION, "Called."); + TAG_LOGD(AAFwkTag::CONTINUATION, "called"); remotePrimaryStub_ = Primary; } void ContinuationHandlerStage::ClearDeviceInfo(std::shared_ptr &abilityInfo) { - TAG_LOGD(AAFwkTag::CONTINUATION, "Called."); + TAG_LOGD(AAFwkTag::CONTINUATION, "called"); abilityInfo->deviceId = ""; abilityInfo->deviceTypes.clear(); } @@ -268,13 +269,13 @@ Want ContinuationHandlerStage::SetWantParams(const WantParams &wantParams) void ContinuationHandlerStage::CleanUpAfterReverse() { - TAG_LOGD(AAFwkTag::CONTINUATION, "Called."); + TAG_LOGD(AAFwkTag::CONTINUATION, "called"); remoteReplicaProxy_ = nullptr; } void ContinuationHandlerStage::PassPrimary(const sptr &Primary) { - TAG_LOGD(AAFwkTag::CONTINUATION, "Called."); + TAG_LOGD(AAFwkTag::CONTINUATION, "called"); remotePrimaryProxy_ = iface_cast(Primary); } diff --git a/frameworks/native/ability/native/continuation/distributed/continuation_manager.cpp b/frameworks/native/ability/native/continuation/distributed/continuation_manager.cpp index 11ae0c2c0d..668b1af503 100644 --- a/frameworks/native/ability/native/continuation/distributed/continuation_manager.cpp +++ b/frameworks/native/ability/native/continuation/distributed/continuation_manager.cpp @@ -22,7 +22,6 @@ #include "continuation_handler.h" #include "distributed_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "operation_builder.h" #include "string_ex.h" #include "string_wrapper.h" diff --git a/frameworks/native/ability/native/continuation/distributed/continuation_manager_stage.cpp b/frameworks/native/ability/native/continuation/distributed/continuation_manager_stage.cpp index 5bfc66cdc9..8d3663e376 100644 --- a/frameworks/native/ability/native/continuation/distributed/continuation_manager_stage.cpp +++ b/frameworks/native/ability/native/continuation/distributed/continuation_manager_stage.cpp @@ -21,7 +21,6 @@ #include "continuation_handler.h" #include "distributed_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "operation_builder.h" #include "string_ex.h" #include "string_wrapper.h" diff --git a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary.cpp b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary.cpp index 84673e1304..03af8308ff 100644 --- a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary.cpp +++ b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary.cpp @@ -16,7 +16,6 @@ #include "reverse_continuation_scheduler_primary.h" #include "continuation_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_proxy.cpp b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_proxy.cpp index e713cf440e..96c92aecea 100644 --- a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_proxy.cpp +++ b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_proxy.cpp @@ -16,7 +16,6 @@ #include "reverse_continuation_scheduler_primary_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_stage.cpp b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_stage.cpp index 723379184d..0c933ad589 100644 --- a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_stage.cpp +++ b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_stage.cpp @@ -17,7 +17,6 @@ #include "continuation_handler_stage.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_stub.cpp b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_stub.cpp index 3fc0ec3fad..e1b7e521fa 100644 --- a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_stub.cpp +++ b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_stub.cpp @@ -16,7 +16,6 @@ #include "reverse_continuation_scheduler_primary_stub.h" #include "ability_scheduler_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "string_ex.h" namespace OHOS { @@ -24,16 +23,9 @@ namespace AppExecFwk { const std::string ReverseContinuationSchedulerPrimaryStub::DESCRIPTOR( "ohos.abilityshell.ReverseContinuationSchedulerMaster"); -ReverseContinuationSchedulerPrimaryStub::ReverseContinuationSchedulerPrimaryStub() -{ - requestFuncMap_[NOTIFY_REPLICA_TERMINATED] = &ReverseContinuationSchedulerPrimaryStub::NotifyReplicaTerminatedInner; - requestFuncMap_[CONTINUATION_BACK] = &ReverseContinuationSchedulerPrimaryStub::ContinuationBackInner; -} +ReverseContinuationSchedulerPrimaryStub::ReverseContinuationSchedulerPrimaryStub() {} -ReverseContinuationSchedulerPrimaryStub::~ReverseContinuationSchedulerPrimaryStub() -{ - requestFuncMap_.clear(); -} +ReverseContinuationSchedulerPrimaryStub::~ReverseContinuationSchedulerPrimaryStub() {} /** * @brief Sets an entry for receiving requests. @@ -56,19 +48,11 @@ int ReverseContinuationSchedulerPrimaryStub::OnRemoteRequest( "ReverseContinuationSchedulerPrimaryStub::OnRemoteRequest failed, DESCRIPTOR != touken"); return -1; } - - auto iter = requestFuncMap_.find(code); - if (iter != requestFuncMap_.end()) { - auto func = iter->second; - if (func != nullptr) { - return (this->*func)(data, reply); - } else { - TAG_LOGW(AAFwkTag::CONTINUATION, - "ReverseContinuationSchedulerPrimaryStub::OnRemoteRequest failed, func is nullptr"); - } - } else { - TAG_LOGW(AAFwkTag::CONTINUATION, - "ReverseContinuationSchedulerPrimaryStub::OnRemoteRequest failed, iter not find"); + switch (code) { + case NOTIFY_REPLICA_TERMINATED: + return NotifyReplicaTerminatedInner(data, reply); + case CONTINUATION_BACK: + return ContinuationBackInner(data, reply); } TAG_LOGI(AAFwkTag::CONTINUATION, "%{public}s called end", __func__); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); diff --git a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica.cpp b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica.cpp index 1b2d3e6a02..f18dc0bfd1 100644 --- a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica.cpp +++ b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica.cpp @@ -15,7 +15,6 @@ #include "reverse_continuation_scheduler_replica.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica_proxy.cpp b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica_proxy.cpp index e35ecd8330..006ec10c44 100644 --- a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica_proxy.cpp +++ b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica_proxy.cpp @@ -15,7 +15,6 @@ #include "reverse_continuation_scheduler_replica_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica_stub.cpp b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica_stub.cpp index a11f2510e1..c63ef86566 100644 --- a/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica_stub.cpp +++ b/frameworks/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica_stub.cpp @@ -15,23 +15,13 @@ #include "reverse_continuation_scheduler_replica_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { -ReverseContinuationSchedulerReplicaStub::ReverseContinuationSchedulerReplicaStub() -{ - continuationFuncMap_[static_cast(IReverseContinuationSchedulerReplica::Message::PASS_PRIMARY)] = - &ReverseContinuationSchedulerReplicaStub::PassPrimaryInner; - continuationFuncMap_[static_cast(IReverseContinuationSchedulerReplica::Message::REVERSE_CONTINUATION)] = - &ReverseContinuationSchedulerReplicaStub::ReverseContinuationInner; - continuationFuncMap_[static_cast(IReverseContinuationSchedulerReplica::Message::NOTIFY_REVERSE_RESULT)] = - &ReverseContinuationSchedulerReplicaStub::NotifyReverseResultInner; -} -ReverseContinuationSchedulerReplicaStub::~ReverseContinuationSchedulerReplicaStub() -{ - continuationFuncMap_.clear(); -} +ReverseContinuationSchedulerReplicaStub::ReverseContinuationSchedulerReplicaStub() {} + +ReverseContinuationSchedulerReplicaStub::~ReverseContinuationSchedulerReplicaStub() {} + int32_t ReverseContinuationSchedulerReplicaStub::PassPrimaryInner(MessageParcel &data, MessageParcel &reply) { TAG_LOGI(AAFwkTag::CONTINUATION, "%{public}s called begin", __func__); @@ -69,13 +59,13 @@ int ReverseContinuationSchedulerReplicaStub::OnRemoteRequest( TAG_LOGE(AAFwkTag::CONTINUATION, "ReverseContinuationSchedulerReplicaStub::OnRemoteRequest token is invalid"); return ERR_INVALID_STATE; } - - auto itFunc = continuationFuncMap_.find(code); - if (itFunc != continuationFuncMap_.end()) { - auto continuationFunc = itFunc->second; - if (continuationFunc != nullptr) { - return (this->*continuationFunc)(data, reply); - } + switch (code) { + case static_cast(IReverseContinuationSchedulerReplica::Message::PASS_PRIMARY): + return PassPrimaryInner(data, reply); + case static_cast(IReverseContinuationSchedulerReplica::Message::REVERSE_CONTINUATION): + return ReverseContinuationInner(data, reply); + case static_cast(IReverseContinuationSchedulerReplica::Message::NOTIFY_REVERSE_RESULT): + return NotifyReverseResultInner(data, reply); } TAG_LOGI(AAFwkTag::CONTINUATION, "%{public}s called end", __func__); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); diff --git a/frameworks/native/ability/native/continuation/remote_register_service/connect_callback_proxy.cpp b/frameworks/native/ability/native/continuation/remote_register_service/connect_callback_proxy.cpp index 015cdee5fc..ab8527a62d 100644 --- a/frameworks/native/ability/native/continuation/remote_register_service/connect_callback_proxy.cpp +++ b/frameworks/native/ability/native/continuation/remote_register_service/connect_callback_proxy.cpp @@ -16,7 +16,6 @@ #include "extra_params.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "string_ex.h" namespace OHOS { diff --git a/frameworks/native/ability/native/continuation/remote_register_service/connect_callback_stub.cpp b/frameworks/native/ability/native/continuation/remote_register_service/connect_callback_stub.cpp index 59ffaaf5ed..6858241f1a 100644 --- a/frameworks/native/ability/native/continuation/remote_register_service/connect_callback_stub.cpp +++ b/frameworks/native/ability/native/continuation/remote_register_service/connect_callback_stub.cpp @@ -16,16 +16,11 @@ #include "ipc_types.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "string_ex.h" namespace OHOS { namespace AppExecFwk { -ConnectCallbackStub::ConnectCallbackStub() -{ - memberFuncMap_[COMMAND_CONNECT] = &ConnectCallbackStub::ConnectInner; - memberFuncMap_[COMMAND_DISCONNECT] = &ConnectCallbackStub::DisconnectInner; -} +ConnectCallbackStub::ConnectCallbackStub() {} int ConnectCallbackStub::ConnectInner(MessageParcel &data, MessageParcel &reply) { @@ -61,12 +56,11 @@ int ConnectCallbackStub::OnRemoteRequest( TAG_LOGE(AAFwkTag::CONTINUATION, "%{public}s Descriptor is wrong", __func__); return OHOS::ERR_INVALID_REPLY; } - auto localFuncIt = memberFuncMap_.find(code); - if (localFuncIt != memberFuncMap_.end()) { - auto memberFunc = localFuncIt->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + switch (code) { + case COMMAND_CONNECT: + return ConnectInner(data, reply); + case COMMAND_DISCONNECT: + return DisconnectInner(data, reply); } TAG_LOGI(AAFwkTag::CONTINUATION, "ConnectCallbackStub::OnRemoteRequest, default case, need check."); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); diff --git a/frameworks/native/ability/native/continuation/remote_register_service/continuation_connector.cpp b/frameworks/native/ability/native/continuation/remote_register_service/continuation_connector.cpp index b58e55b889..e0b9f7c86f 100644 --- a/frameworks/native/ability/native/continuation/remote_register_service/continuation_connector.cpp +++ b/frameworks/native/ability/native/continuation/remote_register_service/continuation_connector.cpp @@ -17,7 +17,6 @@ #include "continuation_device_callback_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "remote_register_service_proxy.h" namespace OHOS { diff --git a/frameworks/native/ability/native/continuation/remote_register_service/continuation_device_callback_proxy.cpp b/frameworks/native/ability/native/continuation/remote_register_service/continuation_device_callback_proxy.cpp index 2009b4710e..d904538aea 100644 --- a/frameworks/native/ability/native/continuation/remote_register_service/continuation_device_callback_proxy.cpp +++ b/frameworks/native/ability/native/continuation/remote_register_service/continuation_device_callback_proxy.cpp @@ -14,7 +14,6 @@ */ #include "continuation_device_callback_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { /** diff --git a/frameworks/native/ability/native/continuation/remote_register_service/continuation_register_manager.cpp b/frameworks/native/ability/native/continuation/remote_register_service/continuation_register_manager.cpp index 71ebce2f2a..716a8b5c5d 100644 --- a/frameworks/native/ability/native/continuation/remote_register_service/continuation_register_manager.cpp +++ b/frameworks/native/ability/native/continuation/remote_register_service/continuation_register_manager.cpp @@ -18,7 +18,6 @@ #include "continuation_register_manager_proxy.h" #include "extra_params.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "request_callback.h" namespace OHOS { diff --git a/frameworks/native/ability/native/continuation/remote_register_service/continuation_register_manager_proxy.cpp b/frameworks/native/ability/native/continuation/remote_register_service/continuation_register_manager_proxy.cpp index 382c085b7b..91ca5ce1e1 100644 --- a/frameworks/native/ability/native/continuation/remote_register_service/continuation_register_manager_proxy.cpp +++ b/frameworks/native/ability/native/continuation/remote_register_service/continuation_register_manager_proxy.cpp @@ -19,7 +19,6 @@ #include "continuation_device_callback_interface.h" #include "continuation_request.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "request_callback.h" namespace OHOS { diff --git a/frameworks/native/ability/native/continuation/remote_register_service/remote_register_service_proxy.cpp b/frameworks/native/ability/native/continuation/remote_register_service/remote_register_service_proxy.cpp index a6f577b4bb..d53f0f0ae6 100644 --- a/frameworks/native/ability/native/continuation/remote_register_service/remote_register_service_proxy.cpp +++ b/frameworks/native/ability/native/continuation/remote_register_service/remote_register_service_proxy.cpp @@ -14,7 +14,6 @@ */ #include "remote_register_service_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/ability/native/continuation/remote_register_service/remote_register_service_stub.cpp b/frameworks/native/ability/native/continuation/remote_register_service/remote_register_service_stub.cpp index 3727d10e4e..917c8d6e26 100644 --- a/frameworks/native/ability/native/continuation/remote_register_service/remote_register_service_stub.cpp +++ b/frameworks/native/ability/native/continuation/remote_register_service/remote_register_service_stub.cpp @@ -14,22 +14,12 @@ */ #include "remote_register_service_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { -RemoteRegisterServiceStub::RemoteRegisterServiceStub() -{ - requestFuncMap_[COMMAND_REGISTER] = &RemoteRegisterServiceStub::RegisterInner; - requestFuncMap_[COMMAND_UNREGISTER] = &RemoteRegisterServiceStub::UnregisterInner; - requestFuncMap_[COMMAND_UPDATE_CONNECT_STATUS] = &RemoteRegisterServiceStub::UpdateConnectStatusInner; - requestFuncMap_[COMMAND_SHOW_DEVICE_LIST] = &RemoteRegisterServiceStub::ShowDeviceListInner; -} +RemoteRegisterServiceStub::RemoteRegisterServiceStub() {} -RemoteRegisterServiceStub::~RemoteRegisterServiceStub() -{ - requestFuncMap_.clear(); -} +RemoteRegisterServiceStub::~RemoteRegisterServiceStub() {} int RemoteRegisterServiceStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -43,15 +33,16 @@ int RemoteRegisterServiceStub::OnRemoteRequest( TAG_LOGI(AAFwkTag::CONTINUATION, "%{public}s local descriptor is not equal to remote", __func__); return ERR_INVALID_STATE; } - - auto itFunc = requestFuncMap_.find(code); - if (itFunc != requestFuncMap_.end()) { - auto requestFunc = itFunc->second; - if (requestFunc != nullptr) { - return (this->*requestFunc)(data, reply); - } + switch (code) { + case COMMAND_REGISTER: + return RegisterInner(data, reply); + case COMMAND_UNREGISTER: + return UnregisterInner(data, reply); + case COMMAND_UPDATE_CONNECT_STATUS: + return UpdateConnectStatusInner(data, reply); + case COMMAND_SHOW_DEVICE_LIST: + return ShowDeviceListInner(data, reply); } - TAG_LOGI(AAFwkTag::CONTINUATION, "%{public}s Not found cmd, need check.", __func__); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/frameworks/native/ability/native/data_ability_helper.cpp b/frameworks/native/ability/native/data_ability_helper.cpp index 5fa94e5220..28ee265f11 100644 --- a/frameworks/native/ability/native/data_ability_helper.cpp +++ b/frameworks/native/ability/native/data_ability_helper.cpp @@ -17,7 +17,6 @@ #include "abs_shared_result_set.h" #include "datashare_helper.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "rdb_data_ability_utils.h" @@ -291,7 +290,7 @@ std::vector DataAbilityHelper::GetFileTypes(Uri &uri, const std::st */ int DataAbilityHelper::OpenFile(Uri &uri, const std::string &mode) { - TAG_LOGI(AAFwkTag::DATA_ABILITY, "OpenFile Called."); + TAG_LOGI(AAFwkTag::DATA_ABILITY, "called"); int fd = -1; auto dataAbilityHelperImpl = GetDataAbilityHelperImpl(); if (dataAbilityHelperImpl) { diff --git a/frameworks/native/ability/native/data_ability_helper_impl.cpp b/frameworks/native/ability/native/data_ability_helper_impl.cpp index d957a26b2d..00915344cd 100644 --- a/frameworks/native/ability/native/data_ability_helper_impl.cpp +++ b/frameworks/native/ability/native/data_ability_helper_impl.cpp @@ -25,7 +25,6 @@ #include "data_ability_predicates.h" #include "data_ability_result.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "values_bucket.h" namespace OHOS { diff --git a/frameworks/native/ability/native/data_ability_impl.cpp b/frameworks/native/ability/native/data_ability_impl.cpp index b85e3d9150..e0f0c0967f 100644 --- a/frameworks/native/ability/native/data_ability_impl.cpp +++ b/frameworks/native/ability/native/data_ability_impl.cpp @@ -20,7 +20,6 @@ #include "data_ability_operation.h" #include "data_ability_predicates.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "values_bucket.h" diff --git a/frameworks/native/ability/native/data_ability_operation.cpp b/frameworks/native/ability/native/data_ability_operation.cpp index 86c8a156dc..38dd33ad37 100644 --- a/frameworks/native/ability/native/data_ability_operation.cpp +++ b/frameworks/native/ability/native/data_ability_operation.cpp @@ -17,7 +17,6 @@ #include "data_ability_predicates.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "values_bucket.h" namespace OHOS { diff --git a/frameworks/native/ability/native/data_ability_operation_builder.cpp b/frameworks/native/ability/native/data_ability_operation_builder.cpp index cf872e7910..4a9a76e3b9 100644 --- a/frameworks/native/ability/native/data_ability_operation_builder.cpp +++ b/frameworks/native/ability/native/data_ability_operation_builder.cpp @@ -16,7 +16,6 @@ #include "data_ability_operation_builder.h" #include "data_ability_predicates.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "values_bucket.h" namespace OHOS { diff --git a/frameworks/native/ability/native/data_ability_result.cpp b/frameworks/native/ability/native/data_ability_result.cpp index 5f4c2ddcd4..deb8bd95a8 100644 --- a/frameworks/native/ability/native/data_ability_result.cpp +++ b/frameworks/native/ability/native/data_ability_result.cpp @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parcel_macro_base.h" namespace OHOS { diff --git a/frameworks/native/ability/native/dialog_request_callback/dialog_request_callback_proxy.cpp b/frameworks/native/ability/native/dialog_request_callback/dialog_request_callback_proxy.cpp index 7796ff48aa..514e360ad3 100755 --- a/frameworks/native/ability/native/dialog_request_callback/dialog_request_callback_proxy.cpp +++ b/frameworks/native/ability/native/dialog_request_callback/dialog_request_callback_proxy.cpp @@ -16,7 +16,6 @@ #include "dialog_request_callback_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" diff --git a/frameworks/native/ability/native/dialog_request_callback/dialog_request_callback_stub.cpp b/frameworks/native/ability/native/dialog_request_callback/dialog_request_callback_stub.cpp index 519f851adb..68743db463 100755 --- a/frameworks/native/ability/native/dialog_request_callback/dialog_request_callback_stub.cpp +++ b/frameworks/native/ability/native/dialog_request_callback/dialog_request_callback_stub.cpp @@ -16,7 +16,6 @@ #include "dialog_request_callback_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" diff --git a/services/abilitymgr/src/distributed_client.cpp b/frameworks/native/ability/native/distributed_ability_runtime/distributed_client.cpp similarity index 99% rename from services/abilitymgr/src/distributed_client.cpp rename to frameworks/native/ability/native/distributed_ability_runtime/distributed_client.cpp index 3be1e2d402..4e4c11cc5d 100644 --- a/services/abilitymgr/src/distributed_client.cpp +++ b/frameworks/native/ability/native/distributed_ability_runtime/distributed_client.cpp @@ -183,7 +183,7 @@ int32_t DistributedClient::StartContinuation(const OHOS::AAFwk::Want& want, int3 } ErrCode DistributedClient::NotifyCompleteContinuation( - const std::u16string &devId, int32_t sessionId, bool isSuccess) + const std::u16string &devId, int32_t sessionId, bool isSuccess, const std::string &callerBundleName) { TAG_LOGI(AAFwkTag::DISTRIBUTED, "called"); sptr remote = GetDmsProxy(); @@ -208,6 +208,10 @@ ErrCode DistributedClient::NotifyCompleteContinuation( TAG_LOGE(AAFwkTag::DISTRIBUTED, "write result error"); return ERR_FLATTEN_OBJECT; } + if (!data.WriteString(callerBundleName)) { + TAG_LOGE(AAFwkTag::DISTRIBUTED, "write callerBundleName error"); + return ERR_FLATTEN_OBJECT; + } MessageParcel reply; MessageOption option = {MessageOption::TF_ASYNC}; TAG_LOGI(AAFwkTag::DISTRIBUTED, "NotifyCompleteContinuation SendRequest async begin."); diff --git a/frameworks/native/ability/native/dummy_values_bucket.cpp b/frameworks/native/ability/native/dummy_values_bucket.cpp index dfc5a6eb6e..695af33e46 100644 --- a/frameworks/native/ability/native/dummy_values_bucket.cpp +++ b/frameworks/native/ability/native/dummy_values_bucket.cpp @@ -15,7 +15,6 @@ #include "dummy_values_bucket.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "string_ex.h" namespace OHOS { diff --git a/frameworks/native/ability/native/embedded_ui_extension_ability/embedded_ui_extension.cpp b/frameworks/native/ability/native/embedded_ui_extension_ability/embedded_ui_extension.cpp index c6d3beed67..5e0b700cd3 100644 --- a/frameworks/native/ability/native/embedded_ui_extension_ability/embedded_ui_extension.cpp +++ b/frameworks/native/ability/native/embedded_ui_extension_ability/embedded_ui_extension.cpp @@ -16,7 +16,6 @@ #include "embedded_ui_extension.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_embedded_ui_extension.h" #include "runtime.h" #include "ui_extension_context.h" @@ -25,7 +24,7 @@ namespace OHOS { namespace AbilityRuntime { EmbeddedUIExtension *EmbeddedUIExtension::Create(const std::unique_ptr &runtime) { - TAG_LOGD(AAFwkTag::EMBEDDED_EXT, "called."); + TAG_LOGD(AAFwkTag::EMBEDDED_EXT, "called"); if (runtime == nullptr) { return new EmbeddedUIExtension(); } diff --git a/frameworks/native/ability/native/embedded_ui_extension_ability/embedded_ui_extension_module_loader.cpp b/frameworks/native/ability/native/embedded_ui_extension_ability/embedded_ui_extension_module_loader.cpp index af1038b5e4..2737dcee8f 100644 --- a/frameworks/native/ability/native/embedded_ui_extension_ability/embedded_ui_extension_module_loader.cpp +++ b/frameworks/native/ability/native/embedded_ui_extension_ability/embedded_ui_extension_module_loader.cpp @@ -17,7 +17,6 @@ #include "embedded_ui_extension.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/ability/native/embedded_ui_extension_ability/js_embedded_ui_extension.cpp b/frameworks/native/ability/native/embedded_ui_extension_ability/js_embedded_ui_extension.cpp index 623b330ebf..0868bc08d2 100644 --- a/frameworks/native/ability/native/embedded_ui_extension_ability/js_embedded_ui_extension.cpp +++ b/frameworks/native/ability/native/embedded_ui_extension_ability/js_embedded_ui_extension.cpp @@ -16,7 +16,6 @@ #include "js_embedded_ui_extension.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "js_ui_extension_base.h" @@ -35,7 +34,7 @@ JsEmbeddedUIExtension::JsEmbeddedUIExtension(const std::unique_ptr &run JsEmbeddedUIExtension::~JsEmbeddedUIExtension() { - TAG_LOGD(AAFwkTag::EMBEDDED_EXT, "destructor."); + TAG_LOGD(AAFwkTag::EMBEDDED_EXT, "destructor"); } } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/ability/native/extension.cpp b/frameworks/native/ability/native/extension.cpp index 71b070995b..8b62c47f70 100644 --- a/frameworks/native/ability/native/extension.cpp +++ b/frameworks/native/ability/native/extension.cpp @@ -19,7 +19,6 @@ #include "configuration.h" #include "extension_context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" namespace OHOS { diff --git a/frameworks/native/ability/native/extension_ability_thread.cpp b/frameworks/native/ability/native/extension_ability_thread.cpp index dee2d4eff8..fab6cfb75e 100644 --- a/frameworks/native/ability/native/extension_ability_thread.cpp +++ b/frameworks/native/ability/native/extension_ability_thread.cpp @@ -20,7 +20,6 @@ #include "ability_loader.h" #include "ability_manager_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "ui_extension_utils.h" @@ -32,7 +31,6 @@ namespace { constexpr static char FORM_EXTENSION[] = "FormExtension"; constexpr static char UI_EXTENSION[] = "UIExtensionAbility"; constexpr static char CUSTOM_EXTENSION[] = "ExtensionAbility"; -constexpr static char MEDIA_CONTROL_EXTENSION[] = "MediaControlExtensionAbility"; constexpr static char USER_AUTH_EXTENSION[] = "UserAuthExtensionAbility"; constexpr static char ACTION_EXTENSION[] = "ActionExtensionAbility"; constexpr static char SHARE_EXTENSION[] = "ShareExtensionAbility"; @@ -151,11 +149,6 @@ void ExtensionAbilityThread::CreateExtensionAbilityName( if (abilityInfo->extensionAbilityType == AppExecFwk::ExtensionAbilityType::INPUTMETHOD) { abilityName = INPUTMETHOD_EXTENSION; } -#ifdef SUPPORT_GRAPHICS - if (abilityInfo->extensionAbilityType == AppExecFwk::ExtensionAbilityType::SYSPICKER_MEDIACONTROL) { - abilityName = MEDIA_CONTROL_EXTENSION; - } -#endif // SUPPORT_GRAPHICS if (abilityInfo->extensionAbilityType == AppExecFwk::ExtensionAbilityType::APP_ACCOUNT_AUTHORIZATION) { abilityName = APP_ACCOUNT_AUTHORIZATION_EXTENSION; } @@ -410,7 +403,7 @@ void ExtensionAbilityThread::ScheduleAbilityTransaction( void ExtensionAbilityThread::ScheduleConnectAbility(const Want &want) { - TAG_LOGD(AAFwkTag::EXT, "Called."); + TAG_LOGD(AAFwkTag::EXT, "called"); if (abilityHandler_ == nullptr) { TAG_LOGE(AAFwkTag::EXT, "abilityHandler_ is nullptr."); return; @@ -433,7 +426,7 @@ void ExtensionAbilityThread::ScheduleConnectAbility(const Want &want) void ExtensionAbilityThread::ScheduleDisconnectAbility(const Want &want) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::EXT, "Called."); + TAG_LOGD(AAFwkTag::EXT, "called"); if (abilityHandler_ == nullptr) { TAG_LOGE(AAFwkTag::EXT, "abilityHandler_ is nullptr."); return; diff --git a/frameworks/native/ability/native/extension_config_mgr.cpp b/frameworks/native/ability/native/extension_config_mgr.cpp index 791cba3c23..87b7971d2a 100644 --- a/frameworks/native/ability/native/extension_config_mgr.cpp +++ b/frameworks/native/ability/native/extension_config_mgr.cpp @@ -20,7 +20,6 @@ #include "app_module_checker.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS::AbilityRuntime { namespace { diff --git a/frameworks/native/ability/native/extension_impl.cpp b/frameworks/native/ability/native/extension_impl.cpp index 631b48815c..cdb94b03c1 100644 --- a/frameworks/native/ability/native/extension_impl.cpp +++ b/frameworks/native/ability/native/extension_impl.cpp @@ -19,13 +19,19 @@ #include "ability_local_record.h" #include "ability_transaction_callback_info.h" #include "hitrace_meter.h" +#include "ipc_object_proxy.h" #include "extension_context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ui_extension_utils.h" + namespace OHOS { namespace AbilityRuntime { +ExtensionImpl::~ExtensionImpl() +{ + TAG_LOGI(AAFwkTag::EXT, "~ExtensionImpl"); +} + void ExtensionImpl::Init(const std::shared_ptr &application, const std::shared_ptr &record, std::shared_ptr &extension, @@ -48,12 +54,33 @@ void ExtensionImpl::Init(const std::shared_ptr &app extension_->SetExtensionWindowLifeCycleListener( sptr(new ExtensionWindowLifeCycleImpl(token_, shared_from_this()))); } + if (record->GetAbilityInfo()->name == "com.ohos.callui.ServiceAbility") { + PrintTokenInfo(); + } } extension_->Init(record, application, handler, token); lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL; skipCommandExtensionWithIntent_ = false; } +void ExtensionImpl::PrintTokenInfo() const +{ + if (token_ == nullptr) { + TAG_LOGI(AAFwkTag::EXT, "com.ohos.callui.ServiceAbility token is null"); + return; + } + if (!token_->IsProxyObject()) { + TAG_LOGI(AAFwkTag::EXT, "com.ohos.callui.ServiceAbility token is not proxy"); + return; + } + IPCObjectProxy *tokenProxyObject = reinterpret_cast(token_.GetRefPtr()); + if (tokenProxyObject != nullptr) { + std::string remoteDescriptor = Str16ToStr8(tokenProxyObject->GetInterfaceDescriptor()); + TAG_LOGI(AAFwkTag::EXT, "com.ohos.callui.ServiceAbility handle: %{public}d, descriptor: %{public}s", + tokenProxyObject->GetHandle(), remoteDescriptor.c_str()); + } +} + /** * @brief Handling the life cycle switching of Extension. * @@ -66,7 +93,7 @@ void ExtensionImpl::HandleExtensionTransaction(const Want &want, const AAFwk::Li sptr sessionInfo) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::EXT, "sourceState:%{public}d;targetState:%{public}d;isNewWant:%{public}d", + TAG_LOGI(AAFwkTag::EXT, "sourceState:%{public}d;targetState:%{public}d;isNewWant:%{public}d", lifecycleState_, targetState.state, targetState.isNewWant); if (lifecycleState_ == targetState.state) { TAG_LOGE(AAFwkTag::EXT, "Org lifeCycleState equals to Dst lifeCycleState."); @@ -74,7 +101,6 @@ void ExtensionImpl::HandleExtensionTransaction(const Want &want, const AAFwk::Li } SetLaunchParam(targetState.launchParam); bool ret = true; - switch (targetState.state) { case AAFwk::ABILITY_STATE_INITIAL: { bool isAsyncCallback = false; @@ -109,7 +135,6 @@ void ExtensionImpl::HandleExtensionTransaction(const Want &want, const AAFwk::Li break; } } - if (ret && !UIExtensionAbilityExecuteInsightIntent(want)) { TAG_LOGD(AAFwkTag::EXT, "call abilityms"); AAFwk::PacMap restoreData; @@ -164,7 +189,8 @@ void ExtensionImpl::Start(const Want &want, sptr sessionInfo } TAG_LOGD(AAFwkTag::EXT, "ExtensionImpl::Start"); - if (extension_->abilityInfo_->extensionAbilityType == AppExecFwk::ExtensionAbilityType::WINDOW) { + if (extension_->abilityInfo_->extensionAbilityType == AppExecFwk::ExtensionAbilityType::WINDOW || + extension_->abilityInfo_->extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) { extension_->OnStart(want, sessionInfo); } else { extension_->OnStart(want); @@ -442,9 +468,9 @@ void ExtensionImpl::SendResult(int requestCode, int resultCode, const Want &resu void ExtensionImpl::SetLaunchParam(const AAFwk::LaunchParam &launchParam) { - HILOG_DEBUG("Called."); + TAG_LOGD(AAFwkTag::EXT, "called"); if (extension_ == nullptr) { - HILOG_ERROR("Extension is nullptr."); + TAG_LOGE(AAFwkTag::EXT, "Extension is nullptr."); return; } diff --git a/frameworks/native/ability/native/extension_module_loader.cpp b/frameworks/native/ability/native/extension_module_loader.cpp index 34f9397b3c..fa2b5d6c74 100644 --- a/frameworks/native/ability/native/extension_module_loader.cpp +++ b/frameworks/native/ability/native/extension_module_loader.cpp @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS::AbilityRuntime { namespace { diff --git a/frameworks/native/ability/native/fa_ability_thread.cpp b/frameworks/native/ability/native/fa_ability_thread.cpp index 36163011a5..b8595c955d 100644 --- a/frameworks/native/ability/native/fa_ability_thread.cpp +++ b/frameworks/native/ability/native/fa_ability_thread.cpp @@ -33,7 +33,6 @@ #endif // WITH_DLP #include "freeze_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "ohos_application.h" #ifdef SUPPORT_GRAPHICS @@ -1017,7 +1016,7 @@ std::vector FAAbilityThread::GetFileTypes(const Uri &uri, const std int FAAbilityThread::OpenFile(const Uri &uri, const std::string &mode) { - TAG_LOGD(AAFwkTag::FA, "Called."); + TAG_LOGD(AAFwkTag::FA, "called"); if (abilityImpl_ == nullptr) { TAG_LOGE(AAFwkTag::FA, "abilityImpl_ is nullptr"); return -1; @@ -1027,7 +1026,7 @@ int FAAbilityThread::OpenFile(const Uri &uri, const std::string &mode) int FAAbilityThread::OpenRawFile(const Uri &uri, const std::string &mode) { - TAG_LOGD(AAFwkTag::FA, "Called."); + TAG_LOGD(AAFwkTag::FA, "called"); if (abilityImpl_ == nullptr) { TAG_LOGE(AAFwkTag::FA, "abilityImpl_ is nullptr"); return -1; @@ -1038,7 +1037,7 @@ int FAAbilityThread::OpenRawFile(const Uri &uri, const std::string &mode) int FAAbilityThread::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) { - TAG_LOGD(AAFwkTag::FA, "Called."); + TAG_LOGD(AAFwkTag::FA, "called"); if (abilityImpl_ == nullptr) { TAG_LOGE(AAFwkTag::FA, "abilityImpl_ is nullptr"); return -1; @@ -1050,7 +1049,7 @@ int FAAbilityThread::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value std::shared_ptr FAAbilityThread::Call( const Uri &uri, const std::string &method, const std::string &arg, const AppExecFwk::PacMap &pacMap) { - TAG_LOGD(AAFwkTag::FA, "Called."); + TAG_LOGD(AAFwkTag::FA, "called"); if (abilityImpl_ == nullptr) { TAG_LOGE(AAFwkTag::FA, "abilityImpl_ is nullptr"); return nullptr; @@ -1062,7 +1061,7 @@ std::shared_ptr FAAbilityThread::Call( int FAAbilityThread::Update( const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { - TAG_LOGD(AAFwkTag::FA, "Called."); + TAG_LOGD(AAFwkTag::FA, "called"); if (abilityImpl_ == nullptr) { TAG_LOGE(AAFwkTag::FA, "abilityImpl_ is nullptr"); return -1; @@ -1073,7 +1072,7 @@ int FAAbilityThread::Update( int FAAbilityThread::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { - TAG_LOGD(AAFwkTag::FA, "Called."); + TAG_LOGD(AAFwkTag::FA, "called"); if (abilityImpl_ == nullptr) { TAG_LOGE(AAFwkTag::FA, "abilityImpl_ is nullptr"); return -1; @@ -1084,7 +1083,7 @@ int FAAbilityThread::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicat std::shared_ptr FAAbilityThread::Query( const Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) { - TAG_LOGD(AAFwkTag::FA, "Called."); + TAG_LOGD(AAFwkTag::FA, "called"); if (abilityImpl_ == nullptr) { TAG_LOGE(AAFwkTag::FA, "abilityImpl_ is nullptr"); return nullptr; @@ -1095,7 +1094,7 @@ std::shared_ptr FAAbilityThread::Query( std::string FAAbilityThread::GetType(const Uri &uri) { - TAG_LOGD(AAFwkTag::FA, "Called."); + TAG_LOGD(AAFwkTag::FA, "called"); std::string type; if (abilityImpl_ == nullptr) { TAG_LOGE(AAFwkTag::FA, "abilityImpl_ is nullptr"); @@ -1107,7 +1106,7 @@ std::string FAAbilityThread::GetType(const Uri &uri) bool FAAbilityThread::Reload(const Uri &uri, const AppExecFwk::PacMap &extras) { - TAG_LOGD(AAFwkTag::FA, "Called."); + TAG_LOGD(AAFwkTag::FA, "called"); if (abilityImpl_ == nullptr) { TAG_LOGE(AAFwkTag::FA, "abilityImpl_ is nullptr"); return false; @@ -1117,7 +1116,7 @@ bool FAAbilityThread::Reload(const Uri &uri, const AppExecFwk::PacMap &extras) int FAAbilityThread::BatchInsert(const Uri &uri, const std::vector &values) { - TAG_LOGD(AAFwkTag::FA, "Called."); + TAG_LOGD(AAFwkTag::FA, "called"); if (abilityImpl_ == nullptr) { TAG_LOGE(AAFwkTag::FA, "abilityImpl_ is nullptr"); return -1; diff --git a/frameworks/native/ability/native/form_extension.cpp b/frameworks/native/ability/native/form_extension.cpp index 61625dd97f..03c65238ef 100644 --- a/frameworks/native/ability/native/form_extension.cpp +++ b/frameworks/native/ability/native/form_extension.cpp @@ -19,7 +19,6 @@ #include "form_extension_context.h" #include "form_runtime/js_form_extension.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "runtime.h" namespace OHOS { diff --git a/frameworks/native/ability/native/form_extension_module_loader.cpp b/frameworks/native/ability/native/form_extension_module_loader.cpp index bdd8751868..86ce71fd94 100644 --- a/frameworks/native/ability/native/form_extension_module_loader.cpp +++ b/frameworks/native/ability/native/form_extension_module_loader.cpp @@ -17,7 +17,6 @@ #include "form_extension.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS::AbilityRuntime { FormExtensionModuleLoader::FormExtensionModuleLoader() = default; diff --git a/frameworks/native/ability/native/form_runtime/form_extension_provider_client.cpp b/frameworks/native/ability/native/form_runtime/form_extension_provider_client.cpp index eb6fdd23ae..c420b1aa54 100644 --- a/frameworks/native/ability/native/form_runtime/form_extension_provider_client.cpp +++ b/frameworks/native/ability/native/form_runtime/form_extension_provider_client.cpp @@ -25,7 +25,6 @@ #include "form_mgr_errors.h" #include "form_supply_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" namespace OHOS { @@ -35,7 +34,7 @@ using namespace OHOS::AppExecFwk; int FormExtensionProviderClient::AcquireProviderFormInfo(const AppExecFwk::FormJsInfo &formJsInfo, const Want &want, const sptr &callerToken) { - TAG_LOGI(AAFwkTag::FORM_EXT, "called."); + TAG_LOGI(AAFwkTag::FORM_EXT, "formId:%{public}" PRId64, formJsInfo.formId); sptr formSupplyClient = iface_cast(callerToken); if (formSupplyClient == nullptr) { TAG_LOGE(AAFwkTag::FORM_EXT, "IFormSupply is nullptr."); diff --git a/frameworks/native/ability/native/form_runtime/js_form_extension.cpp b/frameworks/native/ability/native/form_runtime/js_form_extension.cpp index ff0c9f6062..22e03bc3df 100644 --- a/frameworks/native/ability/native/form_runtime/js_form_extension.cpp +++ b/frameworks/native/ability/native/form_runtime/js_form_extension.cpp @@ -21,7 +21,6 @@ #include "form_runtime/form_extension_provider_client.h" #include "form_runtime/js_form_extension_context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_extension_context.h" #include "js_runtime.h" #include "js_runtime_utils.h" diff --git a/frameworks/native/ability/native/form_runtime/js_form_extension_context.cpp b/frameworks/native/ability/native/form_runtime/js_form_extension_context.cpp index 886c23b230..ab8e7acabc 100644 --- a/frameworks/native/ability/native/form_runtime/js_form_extension_context.cpp +++ b/frameworks/native/ability/native/form_runtime/js_form_extension_context.cpp @@ -19,8 +19,8 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "form_mgr_errors.h" +#include "ipc_skeleton.h" #include "js_extension_context.h" #include "js_error_utils.h" #include "js_runtime.h" @@ -31,6 +31,7 @@ #include "napi_common_want.h" #include "napi_remote_object.h" #include "napi_form_util.h" +#include "tokenid_kit.h" namespace OHOS { namespace AbilityRuntime { @@ -94,6 +95,12 @@ public: private: std::weak_ptr context_; + bool CheckCallerIsSystemApp() const + { + auto selfToken = IPCSkeleton::GetSelfTokenID(); + return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(selfToken); + } + napi_value OnUpdateForm(napi_env env, NapiCallbackInfo& info) { TAG_LOGI(AAFwkTag::FORM_EXT, "called."); @@ -197,6 +204,11 @@ private: napi_value OnConnectAbility(napi_env env, NapiCallbackInfo& info) { TAG_LOGD(AAFwkTag::FORM_EXT, "ConnectAbility called."); + if (!CheckCallerIsSystemApp()) { + TAG_LOGE(AAFwkTag::FORM_EXT, "ConnectAbility app is not system-app, can not use system-api"); + ThrowError(env, AbilityErrorCode::ERROR_CODE_NOT_SYSTEM_APP); + return CreateJsUndefined(env); + } // Check params count if (info.argc < ARGC_TWO) { TAG_LOGE(AAFwkTag::FORM_EXT, "Connect ability failed, not enough arguments."); @@ -239,6 +251,11 @@ private: napi_value OnDisconnectAbility(napi_env env, NapiCallbackInfo& info) { TAG_LOGI(AAFwkTag::FORM_EXT, "DisconnectAbility"); + if (!CheckCallerIsSystemApp()) { + TAG_LOGE(AAFwkTag::FORM_EXT, "DisconnectAbility app is not system-app, can not use system-api"); + ThrowError(env, AbilityErrorCode::ERROR_CODE_NOT_SYSTEM_APP); + return CreateJsUndefined(env); + } if (info.argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::FORM_EXT, "Disconnect ability failed, not enough parameters."); ThrowTooFewParametersError(env); diff --git a/frameworks/native/ability/native/free_install_observer_proxy.cpp b/frameworks/native/ability/native/free_install_observer_proxy.cpp index 097e807698..bd1d859caa 100644 --- a/frameworks/native/ability/native/free_install_observer_proxy.cpp +++ b/frameworks/native/ability/native/free_install_observer_proxy.cpp @@ -16,7 +16,6 @@ #include "free_install_observer_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { @@ -63,5 +62,35 @@ void FreeInstallObserverProxy::OnInstallFinished(const std::string &bundleName, return; } } + +void FreeInstallObserverProxy::OnInstallFinishedByUrl(const std::string &startTime, const std::string &url, + const int &resultCode) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + return; + } + + if (!data.WriteString(startTime) || !data.WriteString(url) || + !data.WriteInt32(resultCode)) { + TAG_LOGE(AAFwkTag::FREE_INSTALL, "params is wrong"); + return; + } + + sptr remote = Remote(); + if (remote == nullptr) { + TAG_LOGE(AAFwkTag::FREE_INSTALL, "Remote() is NULL"); + return; + } + int32_t ret = remote->SendRequest( + IFreeInstallObserver::ON_INSTALL_FINISHED_BY_URL, + data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGW(AAFwkTag::FREE_INSTALL, "SendRequest is failed, error code: %{public}d", ret); + return; + } +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/ability/native/free_install_observer_stub.cpp b/frameworks/native/ability/native/free_install_observer_stub.cpp index 68a4d08c19..e9e1635ef9 100644 --- a/frameworks/native/ability/native/free_install_observer_stub.cpp +++ b/frameworks/native/ability/native/free_install_observer_stub.cpp @@ -16,7 +16,6 @@ #include "free_install_observer_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" @@ -39,6 +38,16 @@ int FreeInstallObserverStub::OnInstallFinishedInner(MessageParcel &data, Message return NO_ERROR; } +int FreeInstallObserverStub::OnInstallFinishedByUrlInner(MessageParcel &data, MessageParcel &reply) +{ + std::string startTime = data.ReadString(); + std::string url = data.ReadString(); + int resultCode = data.ReadInt32(); + + OnInstallFinishedByUrl(startTime, url, resultCode); + return NO_ERROR; +} + int FreeInstallObserverStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -49,8 +58,11 @@ int FreeInstallObserverStub::OnRemoteRequest( return ERR_INVALID_STATE; } - if (code == IFreeInstallObserver::ON_INSTALL_FINISHED) { - return OnInstallFinishedInner(data, reply); + switch (code) { + case IFreeInstallObserver::ON_INSTALL_FINISHED: + return OnInstallFinishedInner(data, reply); + case IFreeInstallObserver::ON_INSTALL_FINISHED_BY_URL: + return OnInstallFinishedByUrlInner(data, reply); } return IPCObjectStub::OnRemoteRequest(code, data, reply, option); diff --git a/frameworks/native/ability/native/insight_intent_executor/insight_intent_executor.cpp b/frameworks/native/ability/native/insight_intent_executor/insight_intent_executor.cpp index 409b9f5a03..bafc7d6ddb 100644 --- a/frameworks/native/ability/native/insight_intent_executor/insight_intent_executor.cpp +++ b/frameworks/native/ability/native/insight_intent_executor/insight_intent_executor.cpp @@ -17,7 +17,6 @@ #include "js_insight_intent_executor.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "runtime.h" diff --git a/frameworks/native/ability/native/insight_intent_executor/insight_intent_executor_mgr.cpp b/frameworks/native/ability/native/insight_intent_executor/insight_intent_executor_mgr.cpp index 6b40704ecb..e77f28518c 100644 --- a/frameworks/native/ability/native/insight_intent_executor/insight_intent_executor_mgr.cpp +++ b/frameworks/native/ability/native/insight_intent_executor/insight_intent_executor_mgr.cpp @@ -17,7 +17,6 @@ #include "ability_business_error.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/ability/native/insight_intent_executor/js_insight_intent_executor.cpp b/frameworks/native/ability/native/insight_intent_executor/js_insight_intent_executor.cpp index fdf40935f6..2c79ecec4d 100644 --- a/frameworks/native/ability/native/insight_intent_executor/js_insight_intent_executor.cpp +++ b/frameworks/native/ability/native/insight_intent_executor/js_insight_intent_executor.cpp @@ -19,7 +19,6 @@ #include "ability_transaction_callback_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "insight_intent_constant.h" #include "insight_intent_execute_result.h" #include "js_insight_intent_context.h" diff --git a/frameworks/native/ability/native/insight_intent_host_client.cpp b/frameworks/native/ability/native/insight_intent_host_client.cpp index 8a27d6cf0d..b632cbee25 100644 --- a/frameworks/native/ability/native/insight_intent_host_client.cpp +++ b/frameworks/native/ability/native/insight_intent_host_client.cpp @@ -14,7 +14,6 @@ */ #include "insight_intent_host_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/ability/native/js_extension_common.cpp b/frameworks/native/ability/native/js_extension_common.cpp index 1e941d6f51..1c0d8ce55b 100644 --- a/frameworks/native/ability/native/js_extension_common.cpp +++ b/frameworks/native/ability/native/js_extension_common.cpp @@ -16,7 +16,6 @@ #include "js_extension_common.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_extension_context.h" #include "js_runtime.h" #include "js_runtime_utils.h" diff --git a/frameworks/native/ability/native/js_free_install_observer.cpp b/frameworks/native/ability/native/js_free_install_observer.cpp index 21b4e477fd..d5cdd7e256 100644 --- a/frameworks/native/ability/native/js_free_install_observer.cpp +++ b/frameworks/native/ability/native/js_free_install_observer.cpp @@ -16,7 +16,6 @@ #include "js_free_install_observer.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "js_error_utils.h" #include "js_runtime.h" @@ -48,6 +47,25 @@ void JsFreeInstallObserver::OnInstallFinished(const std::string &bundleName, con std::move(execute), std::move(complete))); } +void JsFreeInstallObserver::OnInstallFinishedByUrl(const std::string &startTime, const std::string& url, + const int &resultCode) +{ + TAG_LOGD(AAFwkTag::FREE_INSTALL, "call"); + wptr jsObserver = this; + std::unique_ptr complete = std::make_unique + ([jsObserver, startTime, url, resultCode](napi_env env, NapiAsyncTask &task, + int32_t status) { + sptr jsObserverSptr = jsObserver.promote(); + if (jsObserverSptr) { + jsObserverSptr->HandleOnInstallFinishedByUrl(startTime, url, resultCode); + } + }); + napi_ref callback = nullptr; + std::unique_ptr execute = nullptr; + NapiAsyncTask::Schedule("JsFreeInstallObserver::OnInstallFinished", env_, std::make_unique(callback, + std::move(execute), std::move(complete))); +} + void JsFreeInstallObserver::OnInstallFinished(const std::string &bundleName, const std::string &abilityName, const std::string &startTime, napi_value abilityResult) { @@ -82,27 +100,56 @@ void JsFreeInstallObserver::HandleOnInstallFinished(const std::string &bundleNam { TAG_LOGD(AAFwkTag::FREE_INSTALL, "call"); for (auto it = jsObserverObjectList_.begin(); it != jsObserverObjectList_.end();) { - if ((it->bundleName == bundleName) && (it->abilityName == abilityName) && (it->startTime == startTime)) { - if (it->callback == nullptr && it->deferred == nullptr) { - it++; - continue; - } - if (it->isAbilityResult && resultCode == ERR_OK) { - it++; - continue; - } - if (it->deferred != nullptr) { - CallPromise(it->deferred, resultCode); - } else { - CallCallback(it->callback, resultCode); - } - FinishAsyncTrace(HITRACE_TAG_ABILITY_MANAGER, "StartFreeInstall", atoi(startTime.c_str())); - it = jsObserverObjectList_.erase(it); - TAG_LOGD( - AAFwkTag::FREE_INSTALL, "the size of jsObserverObjectList_:%{public}zu", jsObserverObjectList_.size()); - } else { + if ((it->bundleName != bundleName) || (it->abilityName != abilityName) || (it->startTime != startTime)) { it++; + continue; } + if (it->callback == nullptr && it->deferred == nullptr) { + it++; + continue; + } + if (it->isAbilityResult && resultCode == ERR_OK) { + it++; + continue; + } + if (it->deferred != nullptr) { + CallPromise(it->deferred, resultCode); + } else { + CallCallback(it->callback, resultCode); + } + FinishAsyncTrace(HITRACE_TAG_ABILITY_MANAGER, "StartFreeInstall", atoi(startTime.c_str())); + it = jsObserverObjectList_.erase(it); + TAG_LOGD( + AAFwkTag::FREE_INSTALL, "the size of jsObserverObjectList_:%{public}zu", jsObserverObjectList_.size()); + } +} + +void JsFreeInstallObserver::HandleOnInstallFinishedByUrl(const std::string &startTime, const std::string& url, + const int &resultCode) +{ + TAG_LOGD(AAFwkTag::FREE_INSTALL, "call"); + for (auto it = jsObserverObjectList_.begin(); it != jsObserverObjectList_.end();) { + if ((it->startTime != startTime) || (it->url != url)) { + it++; + continue; + } + if (it->callback == nullptr && it->deferred == nullptr) { + it++; + continue; + } + if (it->isAbilityResult && resultCode == ERR_OK) { + it++; + continue; + } + if (it->deferred != nullptr) { + CallPromise(it->deferred, resultCode); + } else { + CallCallback(it->callback, resultCode); + } + FinishAsyncTrace(HITRACE_TAG_ABILITY_MANAGER, "StartFreeInstall", atoi(startTime.c_str())); + it = jsObserverObjectList_.erase(it); + TAG_LOGD( + AAFwkTag::FREE_INSTALL, "the size of jsObserverObjectList_:%{public}zu", jsObserverObjectList_.size()); } } @@ -182,6 +229,31 @@ void JsFreeInstallObserver::AddJsObserverObject(const std::string &bundleName, c object.bundleName = bundleName; object.abilityName = abilityName; object.startTime = startTime; + AddJsObserverCommon(object, jsObserverObject, result, isAbilityResult); +} + +void JsFreeInstallObserver::AddJsObserverObject(const std::string &startTime, const std::string &url, + napi_value jsObserverObject, napi_value* result, bool isAbilityResult) +{ + TAG_LOGD(AAFwkTag::FREE_INSTALL, "call"); + for (auto it = jsObserverObjectList_.begin(); it != jsObserverObjectList_.end(); ++it) { + if (it->startTime == startTime && it->url == url) { + TAG_LOGW(AAFwkTag::FREE_INSTALL, "The jsObject has been added."); + return; + } + } + + StartAsyncTrace(HITRACE_TAG_ABILITY_MANAGER, "StartFreeInstall", atoi(startTime.c_str())); + JsFreeInstallObserverObject object; + object.startTime = startTime; + object.url = url; + AddJsObserverCommon(object, jsObserverObject, result, isAbilityResult); +} + +void JsFreeInstallObserver::AddJsObserverCommon(JsFreeInstallObserverObject &object, + napi_value jsObserverObject, napi_value* result, bool isAbilityResult) +{ + TAG_LOGD(AAFwkTag::FREE_INSTALL, "call"); object.isAbilityResult = isAbilityResult; napi_valuetype type = napi_undefined; napi_typeof(env_, jsObserverObject, &type); diff --git a/frameworks/native/ability/native/js_service_extension.cpp b/frameworks/native/ability/native/js_service_extension.cpp index 2bd31f497b..e52ff87585 100644 --- a/frameworks/native/ability/native/js_service_extension.cpp +++ b/frameworks/native/ability/native/js_service_extension.cpp @@ -22,7 +22,6 @@ #include "configuration_utils.h" #include "hitrace_meter.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "insight_intent_execute_param.h" #include "insight_intent_execute_result.h" #include "insight_intent_executor_info.h" diff --git a/frameworks/native/ability/native/js_service_extension_context.cpp b/frameworks/native/ability/native/js_service_extension_context.cpp index 1b4feb27f6..9a0bb0a579 100644 --- a/frameworks/native/ability/native/js_service_extension_context.cpp +++ b/frameworks/native/ability/native/js_service_extension_context.cpp @@ -21,7 +21,6 @@ #include "ability_manager_client.h" #include "ability_runtime/js_caller_complex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_extension_context.h" #include "js_error_utils.h" #include "js_data_struct_converter.h" @@ -45,12 +44,14 @@ namespace { constexpr int32_t INDEX_ZERO = 0; constexpr int32_t INDEX_ONE = 1; constexpr int32_t INDEX_TWO = 2; +constexpr int32_t INDEX_THREE = 3; constexpr int32_t ERROR_CODE_ONE = 1; constexpr int32_t ERROR_CODE_TWO = 2; constexpr size_t ARGC_ZERO = 0; constexpr size_t ARGC_ONE = 1; constexpr size_t ARGC_TWO = 2; constexpr size_t ARGC_THREE = 3; +constexpr size_t ARGC_FOUR = 4; class StartAbilityByCallParameters { public: @@ -150,6 +151,11 @@ public: GET_NAPI_INFO_AND_CALL(env, info, JsServiceExtensionContext, OnStartExtensionAbility); } + static napi_value StartUIServiceExtensionAbility(napi_env env, napi_callback_info info) + { + GET_NAPI_INFO_AND_CALL(env, info, JsServiceExtensionContext, OnStartUIServiceExtension); + } + static napi_value StartServiceExtensionAbilityWithAccount(napi_env env, napi_callback_info info) { GET_NAPI_INFO_AND_CALL(env, info, JsServiceExtensionContext, OnStartExtensionAbilityWithAccount); @@ -170,6 +176,11 @@ public: GET_NAPI_INFO_AND_CALL(env, info, JsServiceExtensionContext, OnRequestModalUIExtension); } + static napi_value PreStartMission(napi_env env, napi_callback_info info) + { + GET_NAPI_INFO_AND_CALL(env, info, JsServiceExtensionContext, OnPreStartMission); + } + private: std::weak_ptr context_; sptr freeInstallObserver_ = nullptr; @@ -192,7 +203,12 @@ private: int ret = 0; if (freeInstallObserver_ == nullptr) { freeInstallObserver_ = new JsFreeInstallObserver(env); - ret = AAFwk::AbilityManagerClient::GetInstance()->AddFreeInstallObserver(freeInstallObserver_); + auto context = context_.lock(); + if (!context) { + TAG_LOGW(AAFwkTag::SERVICE_EXT, "context is released"); + return; + } + ret = context->AddFreeInstallObserver(freeInstallObserver_); } if (ret != ERR_OK) { @@ -301,7 +317,7 @@ private: napi_value OnOpenLink(napi_env env, NapiCallbackInfo& info) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGI(AAFwkTag::SERVICE_EXT, "OnOpenLink"); + TAG_LOGD(AAFwkTag::SERVICE_EXT, "OnOpenLink"); std::string linkValue(""); AAFwk::OpenLinkOptions openLinkOptions; @@ -315,7 +331,6 @@ private: return CreateJsUndefined(env); } - TAG_LOGI(AAFwkTag::SERVICE_EXT, "open link:%{public}s.", linkValue.c_str()); want.SetUri(linkValue); auto innerErrorCode = std::make_shared(ERR_OK); @@ -690,12 +705,12 @@ private: NapiAsyncTask::CompleteCallback complete = [connection, connectId, innerErrorCode](napi_env env, NapiAsyncTask& task, int32_t status) { if (*innerErrorCode == 0) { - HILOG_INFO("Connect ability success."); + TAG_LOGI(AAFwkTag::SERVICE_EXT, "Connect ability success."); task.ResolveWithNoError(env, CreateJsUndefined(env)); return; } - HILOG_ERROR("Connect ability failed."); + TAG_LOGE(AAFwkTag::SERVICE_EXT, "Connect ability failed."); int32_t errcode = static_cast(AbilityRuntime::GetJsErrorCodeByNativeError(*innerErrorCode)); if (errcode) { connection->CallJsFailed(errcode); @@ -889,6 +904,45 @@ private: return result; } + napi_value OnStartUIServiceExtension(napi_env env, NapiCallbackInfo& info) + { + TAG_LOGI(AAFwkTag::SERVICE_EXT, "OnStartUIServiceExtension is enter"); + if (info.argc StartUIServiceExtensionAbility(want); + if (errcode == 0) { + task.ResolveWithNoError(env, CreateJsUndefined(env)); + } else { + task.Reject(env, CreateJsErrorByNativeErr(env, errcode)); + } + }; + + napi_value lastParam = (info.argc > ARGC_ONE) ? info.argv[INDEX_ONE] : nullptr; + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("JsAbilityContext::OnStartUIServiceExtension", + env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + return result; + } + napi_value OnStartExtensionAbilityWithAccount(napi_env env, NapiCallbackInfo& info) { TAG_LOGI(AAFwkTag::SERVICE_EXT, "StartExtensionAbilityWithAccount"); @@ -1017,27 +1071,100 @@ private: ThrowInvalidParamError(env, "Parse param want failed, must be a Want."); return CreateJsUndefined(env); } - - NapiAsyncTask::CompleteCallback complete = - [weak = context_, want](napi_env env, NapiAsyncTask& task, int32_t status) { - auto context = weak.lock(); + + auto innerErrCode = std::make_shared(ERR_OK); + NapiAsyncTask::ExecuteCallback execute = [serviceContext = context_, want, innerErrCode]() { + auto context = serviceContext.lock(); if (!context) { - TAG_LOGW(AAFwkTag::SERVICE_EXT, "context is released"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + TAG_LOGE(AAFwkTag::APPKIT, "context is released"); + *innerErrCode = static_cast(AbilityErrorCode::ERROR_CODE_INNER); return; } - auto errcode = context->RequestModalUIExtension(want); - if (errcode == 0) { + *innerErrCode = AAFwk::AbilityManagerClient::GetInstance()->RequestModalUIExtension(want); + }; + NapiAsyncTask::CompleteCallback complete = [innerErrCode](napi_env env, NapiAsyncTask& task, int32_t status) { + if (*innerErrCode == ERR_OK) { task.Resolve(env, CreateJsUndefined(env)); } else { - task.Reject(env, CreateJsErrorByNativeErr(env, errcode)); + TAG_LOGE(AAFwkTag::APPKIT, "OnRequestModalUIExtension is failed %{public}d", *innerErrCode); + task.Reject(env, CreateJsErrorByNativeErr(env, *innerErrCode)); } }; napi_value lastParam = (info.argc > ARGC_ONE) ? info.argv[ARGC_ONE] : nullptr; napi_value result = nullptr; NapiAsyncTask::ScheduleHighQos("JSServiceExtensionContext::OnRequestModalUIExtension", - env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + env, CreateAsyncTaskWithLastParam(env, lastParam, std::move(execute), std::move(complete), &result)); + return result; + } + + bool ParsePreStartMissionArgs(const napi_env &env, const NapiCallbackInfo &info, std::string& bundleName, + std::string& moduleName, std::string& abilityName, std::string& startTime) + { + if (info.argc < ARGC_FOUR) { + TAG_LOGE(AAFwkTag::SERVICE_EXT, "wrong arguments num"); + ThrowTooFewParametersError(env); + return false; + } + + std::string args[ARGC_FOUR]; + for (size_t i = 0; i < ARGC_FOUR; i++) { + if (!CheckTypeForNapiValue(env, info.argv[i], napi_string)) { + TAG_LOGE(AAFwkTag::SERVICE_EXT, "param must be string"); + return false; + } + if (!ConvertFromJsValue(env, info.argv[i], args[i])) { + TAG_LOGE(AAFwkTag::SERVICE_EXT, "parameter invalid"); + return false; + } + } + + bundleName = args[INDEX_ZERO]; + moduleName = args[INDEX_ONE]; + abilityName = args[INDEX_TWO]; + startTime = args[INDEX_THREE]; + + return true; + } + + napi_value OnPreStartMission(napi_env env, NapiCallbackInfo& info) + { + TAG_LOGD(AAFwkTag::SERVICE_EXT, "called"); + if (info.argc < ARGC_FOUR) { + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + + std::string bundleName; + std::string moduleName; + std::string abilityName; + std::string startTime; + if (!ParsePreStartMissionArgs(env, info, bundleName, moduleName, abilityName, startTime)) { + TAG_LOGE(AAFwkTag::SERVICE_EXT, "parse preStartMission arguments failed"); + ThrowInvalidParamError(env, "Parse params failed, params must be strings."); + return CreateJsUndefined(env); + } + + NapiAsyncTask::CompleteCallback complete = + [weak = context_, bundleName, moduleName, abilityName, startTime]( + napi_env env, NapiAsyncTask& task, int32_t status) { + auto context = weak.lock(); + if (!context) { + TAG_LOGW(AAFwkTag::SERVICE_EXT, "context is released"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT)); + return; + } + auto errcode = context->PreStartMission(bundleName, moduleName, abilityName, startTime); + if (errcode == 0) { + task.ResolveWithNoError(env, CreateJsUndefined(env)); + return; + } + task.Reject(env, CreateJsErrorByNativeErr(env, errcode)); + }; + + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("JSServiceExtensionContext::OnPreStartMission", + env, CreateAsyncTaskWithLastParam(env, nullptr, nullptr, std::move(complete), &result)); return result; } @@ -1142,6 +1269,8 @@ napi_value CreateJsServiceExtensionContext(napi_env env, std::shared_ptrRequestFocus(want); - } - } else { - { - std::lock_guard lock(notifyForegroundLock_); - notifyForegroundByWindow_ = false; - } - Foreground(want); - std::lock_guard lock(notifyForegroundLock_); - ret = notifyForegroundByWindow_; - if (ret) { - notifyForegroundByWindow_ = false; - notifyForegroundByAbility_ = false; - } - } -#endif + ret = AbilityTransactionForeground(want, targetState); break; } case AAFwk::ABILITY_STATE_BACKGROUND_NEW: { @@ -164,5 +142,34 @@ bool NewAbilityImpl::AbilityTransaction(const Want &want, const AAFwk::LifeCycle TAG_LOGD(AAFwkTag::ABILITY, "NewAbilityImpl::AbilityTransaction end: retVal = %{public}d", static_cast(ret)); return ret; } + +bool NewAbilityImpl::AbilityTransactionForeground(const Want &want, const AAFwk::LifeCycleStateInfo &targetState) +{ + bool ret = true; + if (targetState.isNewWant) { + NewWant(want); + } +#ifdef SUPPORT_SCREEN + if (lifecycleState_ == AAFwk::ABILITY_STATE_FOREGROUND_NEW) { + if (ability_) { + ability_->RequestFocus(want); + } + } else { + { + std::lock_guard lock(notifyForegroundLock_); + notifyForegroundByWindow_ = false; + } + Foreground(want); + std::lock_guard lock(notifyForegroundLock_); + ret = notifyForegroundByWindow_; + if (ret) { + notifyForegroundByWindow_ = false; + notifyForegroundByAbility_ = false; + } + } +#endif + + return ret; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/native/ability/native/page_ability_impl.cpp b/frameworks/native/ability/native/page_ability_impl.cpp index 3946e8caec..8b2c8b6b5f 100644 --- a/frameworks/native/ability/native/page_ability_impl.cpp +++ b/frameworks/native/ability/native/page_ability_impl.cpp @@ -15,7 +15,6 @@ #include "page_ability_impl.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" namespace OHOS { @@ -110,20 +109,7 @@ bool PageAbilityImpl::AbilityTransaction(const Want &want, const AAFwk::LifeCycl break; } case AAFwk::ABILITY_STATE_FOREGROUND_NEW: { - if (targetState.isNewWant) { - NewWant(want); - } - SetUriString(targetState.caller.deviceId + "/" + targetState.caller.bundleName + "/" + - targetState.caller.abilityName); - - if (lifecycleState_ == AAFwk::ABILITY_STATE_BACKGROUND_NEW || - lifecycleState_ == AAFwk::ABILITY_STATE_BACKGROUND) { - Foreground(want); - } else { - if (ability_) { - ability_->RequestFocus(want); - } - } + AbilityTransactionForeground(want, targetState); break; } case AAFwk::ABILITY_STATE_ACTIVE: { @@ -151,6 +137,23 @@ bool PageAbilityImpl::AbilityTransaction(const Want &want, const AAFwk::LifeCycl return ret; } +void PageAbilityImpl::AbilityTransactionForeground(const Want &want, const AAFwk::LifeCycleStateInfo &targetState) +{ + if (targetState.isNewWant) { + NewWant(want); + } + SetUriString(targetState.caller.deviceId + "/" + targetState.caller.bundleName + "/" + + targetState.caller.abilityName); + if (lifecycleState_ == AAFwk::ABILITY_STATE_BACKGROUND_NEW || + lifecycleState_ == AAFwk::ABILITY_STATE_BACKGROUND) { + Foreground(want); + } else { + if (ability_) { + ability_->RequestFocus(want); + } + } +} + /** * @brief Execution the KeyDown callback of the ability * @param keyEvent Indicates the key-down event. diff --git a/frameworks/native/ability/native/photo_editor_extension_ability/photo_editor_extension_context.cpp b/frameworks/native/ability/native/photo_editor_extension_ability/photo_editor_extension_context.cpp index d7dc659220..1cdc3ba569 100644 --- a/frameworks/native/ability/native/photo_editor_extension_ability/photo_editor_extension_context.cpp +++ b/frameworks/native/ability/native/photo_editor_extension_ability/photo_editor_extension_context.cpp @@ -14,6 +14,7 @@ */ #include "photo_editor_extension_context.h" +#include #include #include "media_errors.h" #include "hilog_tag_wrapper.h" @@ -114,8 +115,14 @@ PhotoEditorErrorCode PhotoEditorExtensionContext::CopyImageToPanel(const std::st TAG_LOGD(AAFwkTag::UI_EXT, "ImageUri: %{public}s, panelPhysicalPath: %{public}s.", imageUri.c_str(), panelPhysicalPath.c_str()); + char imagePath[PATH_MAX] = {0}; + if (realpath(imageUri.c_str(), imagePath) == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "Realpath error, errno is %{public}d.", errno); + return PhotoEditorErrorCode::ERROR_CODE_IMAGE_INPUT_ERROR; + } + std::ifstream sourceFile; - sourceFile.open(imageUri, std::ios::binary); + sourceFile.open(imagePath, std::ios::binary); if (!sourceFile.is_open()) { TAG_LOGE(AAFwkTag::UI_EXT, "Can not open source file."); sourceFile.close(); @@ -143,8 +150,7 @@ PhotoEditorErrorCode PhotoEditorExtensionContext::CopyImageToPanel(const std::st while (sourceFile.read(buffer, sizeof(buffer))) { panelFile.write(buffer, sizeof(buffer)); } - size_t remainingBytes = sourceFile.gcount(); - panelFile.write(buffer, remainingBytes); + panelFile.write(buffer, sourceFile.gcount()); sourceFile.close(); panelFile.close(); diff --git a/frameworks/native/ability/native/photo_editor_extension_ability/photo_editor_extension_module_loader.cpp b/frameworks/native/ability/native/photo_editor_extension_ability/photo_editor_extension_module_loader.cpp index 13e47af9d2..97ea2b4939 100644 --- a/frameworks/native/ability/native/photo_editor_extension_ability/photo_editor_extension_module_loader.cpp +++ b/frameworks/native/ability/native/photo_editor_extension_ability/photo_editor_extension_module_loader.cpp @@ -24,7 +24,7 @@ PhotoEditorExtensionModuleLoader::~PhotoEditorExtensionModuleLoader() = default; Extension *PhotoEditorExtensionModuleLoader::Create(const std::unique_ptr &runtime) const { - TAG_LOGD(AAFwkTag::UI_EXT, "Called."); + TAG_LOGD(AAFwkTag::UI_EXT, "called"); return PhotoEditorExtension::Create(runtime); } diff --git a/frameworks/native/ability/native/recovery/ability_recovery.cpp b/frameworks/native/ability/native/recovery/ability_recovery.cpp index fb9512876a..585b064271 100644 --- a/frameworks/native/ability/native/recovery/ability_recovery.cpp +++ b/frameworks/native/ability/native/recovery/ability_recovery.cpp @@ -25,7 +25,6 @@ #include "context/application_context.h" #include "file_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "js_runtime.h" #include "js_runtime_utils.h" diff --git a/frameworks/native/ability/native/recovery/app_recovery.cpp b/frameworks/native/ability/native/recovery/app_recovery.cpp index 276bd19566..fedfc00bc2 100644 --- a/frameworks/native/ability/native/recovery/app_recovery.cpp +++ b/frameworks/native/ability/native/recovery/app_recovery.cpp @@ -30,7 +30,6 @@ #include "directory_ex.h" #include "file_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "js_runtime_utils.h" #include "js_ui_ability.h" diff --git a/frameworks/native/ability/native/resource_config_helper.cpp b/frameworks/native/ability/native/resource_config_helper.cpp index 71c7f8b5bf..dc9b7ebd86 100644 --- a/frameworks/native/ability/native/resource_config_helper.cpp +++ b/frameworks/native/ability/native/resource_config_helper.cpp @@ -14,7 +14,6 @@ */ #include "resource_config_helper.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "configuration_convertor.h" #include "hitrace_meter.h" diff --git a/frameworks/native/ability/native/service_ability_impl.cpp b/frameworks/native/ability/native/service_ability_impl.cpp index b313abfefa..c24f9f5c9f 100644 --- a/frameworks/native/ability/native/service_ability_impl.cpp +++ b/frameworks/native/ability/native/service_ability_impl.cpp @@ -15,7 +15,6 @@ #include "service_ability_impl.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/ability/native/service_extension.cpp b/frameworks/native/ability/native/service_extension.cpp index 1c5ec9c0cd..d9943a60b2 100644 --- a/frameworks/native/ability/native/service_extension.cpp +++ b/frameworks/native/ability/native/service_extension.cpp @@ -18,7 +18,6 @@ #include "configuration_utils.h" #include "connection_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_service_extension.h" #include "runtime.h" #include "service_extension_context.h" diff --git a/frameworks/native/ability/native/share_extension_ability/js_share_extension.cpp b/frameworks/native/ability/native/share_extension_ability/js_share_extension.cpp index e691c5a801..7ee3cdde08 100644 --- a/frameworks/native/ability/native/share_extension_ability/js_share_extension.cpp +++ b/frameworks/native/ability/native/share_extension_ability/js_share_extension.cpp @@ -16,7 +16,6 @@ #include "js_share_extension.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "js_ui_extension_base.h" @@ -35,7 +34,7 @@ JsShareExtension::JsShareExtension(const std::unique_ptr &runtime) JsShareExtension::~JsShareExtension() { - TAG_LOGD(AAFwkTag::SHARE_EXT, "destructor."); + TAG_LOGD(AAFwkTag::SHARE_EXT, "destructor"); } } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/ability/native/share_extension_ability/share_extension.cpp b/frameworks/native/ability/native/share_extension_ability/share_extension.cpp index eaf583ff37..ddc3d8d0f0 100644 --- a/frameworks/native/ability/native/share_extension_ability/share_extension.cpp +++ b/frameworks/native/ability/native/share_extension_ability/share_extension.cpp @@ -16,7 +16,6 @@ #include "share_extension.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_share_extension.h" #include "runtime.h" #include "ui_extension_context.h" @@ -25,7 +24,7 @@ namespace OHOS { namespace AbilityRuntime { ShareExtension *ShareExtension::Create(const std::unique_ptr &runtime) { - TAG_LOGD(AAFwkTag::SHARE_EXT, "called."); + TAG_LOGD(AAFwkTag::SHARE_EXT, "called"); if (!runtime) { return new ShareExtension(); } diff --git a/frameworks/native/ability/native/share_extension_ability/share_extension_module_loader.cpp b/frameworks/native/ability/native/share_extension_ability/share_extension_module_loader.cpp index e07a607a59..55271243a0 100644 --- a/frameworks/native/ability/native/share_extension_ability/share_extension_module_loader.cpp +++ b/frameworks/native/ability/native/share_extension_ability/share_extension_module_loader.cpp @@ -16,7 +16,6 @@ #include "share_extension_module_loader.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "share_extension.h" namespace OHOS { diff --git a/frameworks/native/ability/native/task_handler_client.cpp b/frameworks/native/ability/native/task_handler_client.cpp index 5b28043e4a..b8b84c0857 100644 --- a/frameworks/native/ability/native/task_handler_client.cpp +++ b/frameworks/native/ability/native/task_handler_client.cpp @@ -15,7 +15,6 @@ #include "task_handler_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/ability/native/ui_ability.cpp b/frameworks/native/ability/native/ui_ability.cpp index 01090dc632..86a95b1a03 100644 --- a/frameworks/native/ability/native/ui_ability.cpp +++ b/frameworks/native/ability/native/ui_ability.cpp @@ -20,7 +20,6 @@ #include "configuration_convertor.h" #include "event_report.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "js_ui_ability.h" #ifdef CJ_FRONTEND @@ -123,13 +122,13 @@ void UIAbility::Init(std::shared_ptr record, std::shared_ptr UIAbility::GetLifecycle() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); return lifecycle_; } void UIAbility::RegisterAbilityLifecycleObserver(const std::shared_ptr &observer) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (observer == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "register UIAbility lifecycle observer failed, observer is nullptr."); return; @@ -143,7 +142,7 @@ void UIAbility::RegisterAbilityLifecycleObserver(const std::shared_ptr &observer) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (observer == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "unregister UIAbility lifecycle observer failed, observer is nullptr."); return; @@ -235,12 +234,12 @@ void UIAbility::OnStop(AppExecFwk::AbilityTransactionCallbackInfo<> *callbackInf void UIAbility::OnStopCallback() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::DestroyInstance() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } bool UIAbility::IsRestoredInContinuation() const @@ -297,7 +296,7 @@ bool UIAbility::ShouldDefaultRecoverState(const AAFwk::Want &want) void UIAbility::NotifyContinuationResult(const AAFwk::Want &want, bool success) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); int sessionId = want.GetIntParam(DMS_SESSION_ID, DEFAULT_DMS_SESSION_ID); std::string originDeviceId = want.GetStringParam(DMS_ORIGIN_DEVICE_ID); @@ -362,7 +361,7 @@ void UIAbility::InitConfigurationProperties(const AppExecFwk::Configuration &cha void UIAbility::OnMemoryLevel(int level) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); #ifdef SUPPORT_SCREEN if (scene_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "WindowScene is null."); @@ -393,17 +392,17 @@ std::string UIAbility::GetModuleName() void UIAbility::OnAbilityResult(int requestCode, int resultCode, const AAFwk::Want &want) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::OnNewWant(const AAFwk::Want &want) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::OnRestoreAbilityState(const AppExecFwk::PacMap &inState) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::SetWant(const AAFwk::Want &want) @@ -418,17 +417,17 @@ std::shared_ptr UIAbility::GetWant() void UIAbility::OnConfigurationUpdated(const AppExecFwk::Configuration &configuration) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::Dump(const std::vector ¶ms, std::vector &info) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } AppExecFwk::AbilityLifecycleExecutor::LifecycleState UIAbility::GetState() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (abilityLifecycleExecutor_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "abilityLifecycleExecutor_ is nullptr."); return AppExecFwk::AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED; @@ -477,7 +476,7 @@ int32_t UIAbility::OnSaveState(int32_t reason, AAFwk::WantParams &wantParams) void UIAbility::OnCompleteContinuation(int result) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (continuationManager_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "Continuation manager is nullptr."); return; @@ -488,7 +487,7 @@ void UIAbility::OnCompleteContinuation(int result) void UIAbility::OnRemoteTerminated() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::DispatchLifecycleOnForeground(const AAFwk::Want &want) @@ -521,13 +520,13 @@ void UIAbility::HandleCreateAsRecovery(const AAFwk::Want &want) void UIAbility::SetStartAbilitySetting(std::shared_ptr setting) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); setting_ = setting; } void UIAbility::SetLaunchParam(const AAFwk::LaunchParam &launchParam) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); launchParam_ = launchParam; } @@ -580,22 +579,22 @@ void UIAbility::SetIsSilentForeground(bool isSilentForeground) #ifdef SUPPORT_SCREEN void UIAbility::OnSceneCreated() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::OnSceneRestored() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::OnSceneWillDestroy() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::onSceneDestroyed() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::OnForeground(const AAFwk::Want &want) @@ -664,13 +663,13 @@ void UIAbility::OnBackground() bool UIAbility::OnPrepareTerminate() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); return false; } const sptr UIAbility::GetWindow() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); return nullptr; } @@ -681,7 +680,7 @@ std::shared_ptr UIAbility::GetScene() void UIAbility::OnLeaveForeground() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } std::string UIAbility::GetContentInfo() @@ -721,12 +720,12 @@ void UIAbility::SetSceneListener(const sptr &listener) void UIAbility::DoOnForeground(const AAFwk::Want &want) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } int32_t UIAbility::GetCurrentWindowMode() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); auto windowMode = static_cast(Rosen::WindowMode::WINDOW_MODE_UNDEFINED); if (scene_ == nullptr) { return windowMode; @@ -740,7 +739,7 @@ int32_t UIAbility::GetCurrentWindowMode() ErrCode UIAbility::SetMissionLabel(const std::string &label) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (!abilityInfo_ || abilityInfo_->type != AppExecFwk::AbilityType::PAGE) { TAG_LOGE(AAFwkTag::UIABILITY, "Invalid ability info."); return ERR_INVALID_VALUE; @@ -765,7 +764,7 @@ ErrCode UIAbility::SetMissionLabel(const std::string &label) ErrCode UIAbility::SetMissionIcon(const std::shared_ptr &icon) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (!abilityInfo_ || abilityInfo_->type != AppExecFwk::AbilityType::PAGE) { TAG_LOGE(AAFwkTag::UIABILITY, "abilityInfo_ is nullptr or not page type."); return ERR_INVALID_VALUE; @@ -790,7 +789,7 @@ ErrCode UIAbility::SetMissionIcon(const std::shared_ptr & void UIAbility::GetWindowRect(int32_t &left, int32_t &top, int32_t &width, int32_t &height) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (scene_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "Scene is nullptr."); return; @@ -810,7 +809,7 @@ void UIAbility::GetWindowRect(int32_t &left, int32_t &top, int32_t &width, int32 Ace::UIContent *UIAbility::GetUIContent() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (scene_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "Get window scene failed."); return nullptr; @@ -825,12 +824,12 @@ Ace::UIContent *UIAbility::GetUIContent() void UIAbility::OnCreate(Rosen::DisplayId displayId) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::OnDestroy(Rosen::DisplayId displayId) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::OnDisplayInfoChange(const sptr& token, Rosen::DisplayId displayId, float density, @@ -943,7 +942,11 @@ void UIAbility::OnDisplayMove(Rosen::DisplayId from, Rosen::DisplayId to) "Density: %{public}f, Direction: %{public}d", resConfig->GetScreenDensity(), resConfig->GetDirection()); } } + UpdateConfiguration(to, density, width, height); +} +void UIAbility::UpdateConfiguration(Rosen::DisplayId to, float density, int32_t width, int32_t height) +{ AppExecFwk::Configuration newConfig; newConfig.AddItem(AppExecFwk::ConfigurationInner::APPLICATION_DISPLAYID, std::to_string(to)); newConfig.AddItem( @@ -978,12 +981,12 @@ void UIAbility::OnDisplayMove(Rosen::DisplayId from, Rosen::DisplayId to) void UIAbility::RequestFocus(const AAFwk::Want &want) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::InitWindow(int32_t displayId, sptr option) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } sptr UIAbility::GetWindowOption(const AAFwk::Want &want) @@ -1021,7 +1024,7 @@ sptr UIAbility::GetWindowOption(const AAFwk::Want &want) void UIAbility::ContinuationRestore(const AAFwk::Want &want) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); } void UIAbility::OnStartForSupportGraphics(const AAFwk::Want &want) diff --git a/frameworks/native/ability/native/ui_ability_impl.cpp b/frameworks/native/ability/native/ui_ability_impl.cpp index 8dcd664b32..d67057c246 100644 --- a/frameworks/native/ability/native/ui_ability_impl.cpp +++ b/frameworks/native/ability/native/ui_ability_impl.cpp @@ -20,7 +20,6 @@ #include "context/application_context.h" #include "freeze_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "js_ui_ability.h" #include "ohos_application.h" @@ -154,13 +153,13 @@ int32_t UIAbilityImpl::Share(AAFwk::WantParams &wantParam) void UIAbilityImpl::DispatchSaveAbilityState() { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); needSaveDate_ = true; } void UIAbilityImpl::DispatchRestoreAbilityState(const AppExecFwk::PacMap &inState) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); hasSaveData_ = true; restoreData_ = inState; } @@ -471,7 +470,7 @@ void UIAbilityImpl::WindowLifeCycleImpl::AfterForeground() void UIAbilityImpl::WindowLifeCycleImpl::AfterBackground() { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); FreezeUtil::LifecycleFlow flow = { token_, FreezeUtil::TimeoutState::BACKGROUND }; std::string entry = std::to_string(TimeUtil::SystemTimeMillisecond()) + "; UIAbilityImpl::WindowLifeCycleImpl::AfterBackground; the background lifecycle."; @@ -563,7 +562,7 @@ void UIAbilityImpl::Foreground(const AAFwk::Want &want) void UIAbilityImpl::WindowLifeCycleImpl::BackgroundFailed(int32_t type) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (type == static_cast(OHOS::Rosen::WMError::WM_DO_NOTHING)) { AppExecFwk::PacMap restoreData; AAFwk::AbilityManagerClient::GetInstance()->AbilityTransitionDone( @@ -593,18 +592,7 @@ bool UIAbilityImpl::AbilityTransaction(const AAFwk::Want &want, const AAFwk::Lif bool ret = true; switch (targetState.state) { case AAFwk::ABILITY_STATE_INITIAL: { -#ifdef SUPPORT_SCREEN - if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && - lifecycleState_ == AAFwk::ABILITY_STATE_FOREGROUND_NEW) { - Background(); - } -#endif - bool isAsyncCallback = false; - Stop(isAsyncCallback); - if (isAsyncCallback) { - // AbilityManagerService will be notified after async callback - ret = false; - } + HandleInitialState(ret); break; } case AAFwk::ABILITY_STATE_FOREGROUND_NEW: { @@ -644,6 +632,22 @@ bool UIAbilityImpl::AbilityTransaction(const AAFwk::Want &want, const AAFwk::Lif return ret; } +void UIAbilityImpl::HandleInitialState(bool &ret) +{ +#ifdef SUPPORT_SCREEN + if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && + lifecycleState_ == AAFwk::ABILITY_STATE_FOREGROUND_NEW) { + Background(); + } +#endif + bool isAsyncCallback = false; + Stop(isAsyncCallback); + if (isAsyncCallback) { + // AbilityManagerService will be notified after async callback + ret = false; + } +} + #ifdef SUPPORT_SCREEN void UIAbilityImpl::HandleForegroundNewState(const AAFwk::Want &want, bool &bflag) { diff --git a/frameworks/native/ability/native/ui_ability_thread.cpp b/frameworks/native/ability/native/ui_ability_thread.cpp index c8b7414b0f..51fd261d3b 100644 --- a/frameworks/native/ability/native/ui_ability_thread.cpp +++ b/frameworks/native/ability/native/ui_ability_thread.cpp @@ -24,7 +24,6 @@ #include "context_deal.h" #include "freeze_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "time_util.h" @@ -79,7 +78,7 @@ std::shared_ptr UIAbilityThread::CreateAndInitContextDe const std::shared_ptr &abilityRecord, const std::shared_ptr &abilityObject) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); std::shared_ptr contextDeal = nullptr; if (application == nullptr || abilityRecord == nullptr || abilityObject == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "Application or abilityRecord or abilityObject is nullptr."); @@ -507,7 +506,7 @@ std::shared_ptr UIAbilityThread::BuildAbilityContext( void UIAbilityThread::DumpAbilityInfo(const std::vector ¶ms, std::vector &info) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (token_ == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "token_ is nullptr."); return; @@ -562,7 +561,7 @@ void UIAbilityThread::DumpAbilityInfoInner(const std::vector ¶m #else void UIAbilityThread::DumpAbilityInfoInner(const std::vector ¶ms, std::vector &info) { - TAG_LOGD(AAFwkTag::UIABILITY, "Called."); + TAG_LOGD(AAFwkTag::UIABILITY, "called"); if (currentAbility_ != nullptr) { currentAbility_->Dump(params, info); } diff --git a/frameworks/native/ability/native/ui_extension_ability/js_embeddable_ui_ability_context.cpp b/frameworks/native/ability/native/ui_extension_ability/js_embeddable_ui_ability_context.cpp index d65cc503d7..5a330d5589 100644 --- a/frameworks/native/ability/native/ui_extension_ability/js_embeddable_ui_ability_context.cpp +++ b/frameworks/native/ability/native/ui_extension_ability/js_embeddable_ui_ability_context.cpp @@ -22,7 +22,6 @@ #include "ability_manager_client.h" #include "event_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_context_utils.h" #include "js_data_struct_converter.h" #include "js_error_utils.h" @@ -66,6 +65,11 @@ napi_value JsEmbeddableUIAbilityContext::StartAbility(napi_env env, napi_callbac GET_NAPI_INFO_AND_CALL(env, info, JsEmbeddableUIAbilityContext, OnStartAbility); } +napi_value JsEmbeddableUIAbilityContext::OpenLink(napi_env env, napi_callback_info info) +{ + GET_NAPI_INFO_AND_CALL(env, info, JsEmbeddableUIAbilityContext, OnOpenLink); +} + napi_value JsEmbeddableUIAbilityContext::StartAbilityForResult(napi_env env, napi_callback_info info) { GET_NAPI_INFO_AND_CALL(env, info, JsEmbeddableUIAbilityContext, OnStartAbilityForResult); @@ -187,6 +191,17 @@ napi_value JsEmbeddableUIAbilityContext::OnStartAbility(napi_env env, NapiCallba return jsAbilityContext_->OnStartAbility(env, info); } +napi_value JsEmbeddableUIAbilityContext::OnOpenLink(napi_env env, NapiCallbackInfo& info) +{ + if (screenMode_ == AAFwk::EMBEDDED_FULL_SCREEN_MODE) { + TAG_LOGI(AAFwkTag::UI_EXT, "Start openlink in embedded screen mode."); + CHECK_POINTER_RETURN(env, jsUIExtensionContext_); + return jsUIExtensionContext_->OnOpenLink(env, info); + } + CHECK_POINTER_RETURN(env, jsAbilityContext_); + return jsAbilityContext_->OnOpenLink(env, info); +} + napi_value JsEmbeddableUIAbilityContext::OnStartAbilityForResult(napi_env env, NapiCallbackInfo& info) { if (screenMode_ == AAFwk::EMBEDDED_FULL_SCREEN_MODE) { @@ -524,6 +539,7 @@ napi_value JsEmbeddableUIAbilityContext::CreateJsEmbeddableUIAbilityContext(napi const char* moduleName = "JsEmbeddableUIAbilityContext"; BindNativeFunction(env, objValue, "startAbility", moduleName, StartAbility); + BindNativeFunction(env, objValue, "openLink", moduleName, OpenLink); BindNativeFunction(env, objValue, "startAbilityForResult", moduleName, StartAbilityForResult); BindNativeFunction(env, objValue, "connectServiceExtensionAbility", moduleName, ConnectAbility); BindNativeFunction(env, objValue, "disconnectServiceExtensionAbility", moduleName, DisconnectAbility); 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 a4946e933c..91e21dd175 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 @@ -24,7 +24,6 @@ #include "context.h" #include "hitrace_meter.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "insight_intent_executor_info.h" #include "insight_intent_executor_mgr.h" #include "int_wrapper.h" @@ -708,6 +707,7 @@ sptr JsUIExtension::CreateUIWindow(const std::shared_ptrSetWindowType(Rosen::WindowType::WINDOW_TYPE_UI_EXTENSION); option->SetWindowSessionType(Rosen::WindowSessionType::EXTENSION_SESSION); option->SetParentId(sessionInfo->hostWindowId); + option->SetUIExtensionUsage(static_cast(sessionInfo->uiExtensionUsage)); return Rosen::Window::Create(option, GetContext(), sessionInfo->sessionToken); } diff --git a/frameworks/native/ability/native/ui_extension_ability/js_ui_extension_base.cpp b/frameworks/native/ability/native/ui_extension_ability/js_ui_extension_base.cpp index 556d3e7fac..c6b01b615e 100644 --- a/frameworks/native/ability/native/ui_extension_ability/js_ui_extension_base.cpp +++ b/frameworks/native/ability/native/ui_extension_ability/js_ui_extension_base.cpp @@ -22,7 +22,6 @@ #include "ability_manager_client.h" #include "configuration_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "insight_intent_executor_info.h" #include "insight_intent_executor_mgr.h" @@ -503,6 +502,7 @@ bool JsUIExtensionBase::HandleSessionCreate(const AAFwk::Want &want, const sptr< option->SetWindowType(Rosen::WindowType::WINDOW_TYPE_UI_EXTENSION); option->SetWindowSessionType(Rosen::WindowSessionType::EXTENSION_SESSION); option->SetParentId(sessionInfo->hostWindowId); + option->SetUIExtensionUsage(static_cast(sessionInfo->uiExtensionUsage)); auto uiWindow = Rosen::Window::Create(option, context_, sessionInfo->sessionToken); if (uiWindow == nullptr) { TAG_LOGE(AAFwkTag::UI_EXT, "create ui window error."); 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 e881135375..de4a59fdf6 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 @@ -19,7 +19,6 @@ #include "accesstoken_kit.h" #include "event_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "ipc_skeleton.h" #include "js_error_utils.h" @@ -831,8 +830,6 @@ 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; @@ -860,12 +857,14 @@ napi_value JsUIExtensionContentSession::OnStartAbilityByType(napi_env env, NapiC } #ifdef SUPPORT_SCREEN Ace::ModalUIExtensionCallbacks callback; - callback.onError = std::bind(&JsUIExtensionCallback::OnError, uiExtensionCallback, std::placeholders::_1); - callback.onRelease = std::bind(&JsUIExtensionCallback::OnRelease, - uiExtensionCallback, std::placeholders::_1); + callback.onError = [uiExtensionCallback](int arg, const std::string &str1, const std::string &str2) { + uiExtensionCallback->OnError(arg); + }; + callback.onRelease = [uiExtensionCallback](const auto &arg) { + uiExtensionCallback->OnRelease(arg); + }; Ace::ModalUIExtensionConfig config; auto uiContent = uiWindow->GetUIContent(); - int32_t sessionId = uiContent->CreateModalUIExtension(want, callback, config); if (sessionId == 0) { task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); @@ -1055,7 +1054,13 @@ void JsUIExtensionContentSession::AddFreeInstallObserver(napi_env env, int ret = 0; if (freeInstallObserver_ == nullptr) { freeInstallObserver_ = new JsFreeInstallObserver(env); - ret = AAFwk::AbilityManagerClient::GetInstance()->AddFreeInstallObserver(freeInstallObserver_); + auto context = context_.lock(); + if (!context) { + TAG_LOGE(AAFwkTag::CONTEXT, "context is nullptr."); + return; + } + ret = AAFwk::AbilityManagerClient::GetInstance()->AddFreeInstallObserver(context->GetToken(), + freeInstallObserver_); } if (ret != ERR_OK) { @@ -1080,11 +1085,11 @@ void JsUIExtensionContentSession::SetCallbackForTerminateWithResult(int32_t resu 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; + } else { + auto token = extensionContext->GetToken(); + AAFwk::AbilityManagerClient::GetInstance()->TransferAbilityResultForExtension(token, resultCode, want); } - 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)); 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 1182fabbee..fac6e158cb 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 @@ -18,14 +18,16 @@ #include #include "ability_manager_client.h" +#include "ability_manager_errors.h" #include "event_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_extension_context.h" #include "js_error_utils.h" #include "js_data_struct_converter.h" #include "js_runtime.h" #include "js_runtime_utils.h" +#include "js_uiservice_uiext_connection.h" +#include "js_ui_service_proxy.h" #include "napi/native_api.h" #include "napi_common_ability.h" #include "napi_common_want.h" @@ -37,6 +39,8 @@ #include "start_options.h" #include "hitrace_meter.h" #include "uri.h" +#include "ui_extension_servicehost_stub_impl.h" +#include "ui_service_extension_connection_constants.h" namespace OHOS { namespace AbilityRuntime { @@ -165,6 +169,21 @@ napi_value JsUIExtensionContext::OpenAtomicService(napi_env env, napi_callback_i GET_NAPI_INFO_AND_CALL(env, info, JsUIExtensionContext, OnOpenAtomicService); } +napi_value JsUIExtensionContext::StartUIServiceExtension(napi_env env, napi_callback_info info) +{ + GET_NAPI_INFO_AND_CALL(env, info, JsUIExtensionContext, OnStartUIServiceExtension); +} + +napi_value JsUIExtensionContext::ConnectUIServiceExtension(napi_env env, napi_callback_info info) +{ + GET_NAPI_INFO_AND_CALL(env, info, JsUIExtensionContext, OnConnectUIServiceExtension); +} + +napi_value JsUIExtensionContext::DisconnectUIServiceExtension(napi_env env, napi_callback_info info) +{ + GET_NAPI_INFO_AND_CALL(env, info, JsUIExtensionContext, OnDisconnectUIServiceExtension); +} + napi_value JsUIExtensionContext::OnStartAbility(napi_env env, NapiCallbackInfo& info) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); @@ -239,25 +258,34 @@ bool JsUIExtensionContext::CreateOpenLinkTask(const napi_env &env, const napi_va if (abilityResult == nullptr) { TAG_LOGW(AAFwkTag::UI_EXT, "wrap abilityResult error"); asyncTask->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); - } else { - if (isInner) { - asyncTask->Reject(env, CreateJsErrorByNativeErr(env, resultCode)); - } else { - asyncTask->ResolveWithNoError(env, abilityResult); - } + return; } + if (isInner) { + asyncTask->Reject(env, CreateJsErrorByNativeErr(env, resultCode)); + return; + } + asyncTask->ResolveWithNoError(env, abilityResult); }; auto context = context_.lock(); if (context == nullptr) { TAG_LOGW(AAFwkTag::UI_EXT, "context is released"); return false; - } else { - requestCode = context->GenerateCurRequestCode(); - context->InsertResultCallbackTask(requestCode, std::move(task)); } + requestCode = context->GenerateCurRequestCode(); + context->InsertResultCallbackTask(requestCode, std::move(task)); return true; } +void JsUIExtensionContext::RemoveOpenLinkTask(int requestCode) +{ + auto context = context_.lock(); + if (context == nullptr) { + TAG_LOGW(AAFwkTag::UI_EXT, "context is released"); + return; + } + context->RemoveResultCallbackTask(requestCode); +} + static bool ParseOpenLinkParams(const napi_env &env, const NapiCallbackInfo &info, std::string &linkValue, AAFwk::OpenLinkOptions &openLinkOptions, AAFwk::Want &want) { @@ -289,11 +317,10 @@ static bool ParseOpenLinkParams(const napi_env &env, const NapiCallbackInfo &inf napi_value JsUIExtensionContext::OnOpenLink(napi_env env, NapiCallbackInfo& info) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGI(AAFwkTag::UI_EXT, "OnOpenLink"); + TAG_LOGD(AAFwkTag::UI_EXT, "OnOpenLink"); std::string linkValue(""); AAFwk::OpenLinkOptions openLinkOptions; - napi_value lastParam = nullptr; AAFwk::Want want; want.SetParam(AppExecFwk::APP_LINKING_ONLY, false); @@ -304,37 +331,58 @@ napi_value JsUIExtensionContext::OnOpenLink(napi_env env, NapiCallbackInfo& info return CreateJsUndefined(env); } - TAG_LOGI(AAFwkTag::UI_EXT, "open link:%{public}s.", linkValue.c_str()); want.SetUri(linkValue); + std::string startTime = std::to_string(std::chrono::duration_cast(std::chrono:: + system_clock::now().time_since_epoch()).count()); + want.SetParam(Want::PARAM_RESV_START_TIME, startTime); + int requestCode = -1; if (CheckTypeForNapiValue(env, info.argv[INDEX_TWO], napi_function)) { TAG_LOGD(AAFwkTag::UI_EXT, "completionHandler is used."); - lastParam = info.argv[INDEX_TWO]; - CreateOpenLinkTask(env, lastParam, want, requestCode); + CreateOpenLinkTask(env, info.argv[INDEX_TWO], want, requestCode); } + return OnOpenLinkInner(env, want, requestCode, startTime, linkValue); +} - NapiAsyncTask::CompleteCallback complete = [weak = context_, want, requestCode](napi_env env, - NapiAsyncTask& task, int32_t status) { +napi_value JsUIExtensionContext::OnOpenLinkInner(napi_env env, const AAFwk::Want& want, + int requestCode, const std::string& startTime, const std::string& url) +{ + auto innerErrorCode = std::make_shared(ERR_OK); + NapiAsyncTask::ExecuteCallback execute = [weak = context_, want, innerErrorCode, requestCode]() { auto context = weak.lock(); if (!context) { TAG_LOGW(AAFwkTag::UI_EXT, "context is released"); - task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT)); + *innerErrorCode = static_cast(AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT); return; } - auto innerErrorCode = std::make_shared(ERR_OK); - *innerErrorCode = context->StartAbility(want, requestCode); + *innerErrorCode = context->OpenLink(want, requestCode); + }; + + NapiAsyncTask::CompleteCallback complete = [innerErrorCode, requestCode, startTime, url, this]( + napi_env env, NapiAsyncTask& task, int32_t status) { if (*innerErrorCode == 0) { - TAG_LOGI(AAFwkTag::UI_EXT, "OpenLink success."); - task.ResolveWithNoError(env, CreateJsUndefined(env)); - } else { - TAG_LOGI(AAFwkTag::UI_EXT, "OpenLink failed."); - task.Reject(env, CreateJsErrorByNativeErr(env, *innerErrorCode)); + TAG_LOGI(AAFwkTag::UI_EXT, "OpenLink succeeded."); + return; } + if (freeInstallObserver_ == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "freeInstallObserver_ is nullptr."); + RemoveOpenLinkTask(requestCode); + return; + } + if (*innerErrorCode == AAFwk::ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK) { + TAG_LOGI(AAFwkTag::UI_EXT, "start ability by default succeeded."); + freeInstallObserver_->OnInstallFinishedByUrl(startTime, url, ERR_OK); + return; + } + TAG_LOGI(AAFwkTag::UI_EXT, "OpenLink failed."); + freeInstallObserver_->OnInstallFinishedByUrl(startTime, url, *innerErrorCode); + RemoveOpenLinkTask(requestCode); }; napi_value result = nullptr; + AddFreeInstallObserver(env, want, nullptr, &result, false, true); NapiAsyncTask::ScheduleHighQos("JsUIExtensionContext::OnOpenLink", env, - CreateAsyncTaskWithLastParam(env, nullptr, nullptr, std::move(complete), &result)); + CreateAsyncTaskWithLastParam(env, nullptr, std::move(execute), std::move(complete), nullptr)); return result; } @@ -441,7 +489,7 @@ napi_value JsUIExtensionContext::OnTerminateSelfWithResult(napi_env env, NapiCal napi_value JsUIExtensionContext::OnStartAbilityForResultAsCaller(napi_env env, NapiCallbackInfo &info) { - TAG_LOGD(AAFwkTag::UI_EXT, "Called."); + TAG_LOGD(AAFwkTag::UI_EXT, "called"); if (info.argc == ARGC_ZERO) { ThrowTooFewParametersError(env); return CreateJsUndefined(env); @@ -578,6 +626,212 @@ napi_value JsUIExtensionContext::OnDisconnectAbility(napi_env env, NapiCallbackI return result; } +napi_value JsUIExtensionContext::OnStartUIServiceExtension(napi_env env, NapiCallbackInfo& info) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + TAG_LOGD(AAFwkTag::UI_EXT, "OnStartUIServiceExtension is called"); + if (info.argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::UI_EXT, "Start UIServiceExtension failed, not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + + size_t unwrapArgc = 0; + AAFwk::Want want; + AAFwk::StartOptions startOptions; + if (!CheckStartAbilityInputParam(env, info, want, startOptions, unwrapArgc)) { + TAG_LOGD(AAFwkTag::UI_EXT, "Failed, input param type invalid"); + ThrowInvalidParamError(env, "Parse param want failed, want must be Want."); + return CreateJsUndefined(env); + } + + NapiAsyncTask::CompleteCallback complete = + [weak = context_, want, startOptions, unwrapArgc](napi_env env, NapiAsyncTask& task, int32_t status) { + TAG_LOGD(AAFwkTag::UI_EXT, "StartUIServiceExtension begin"); + 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; + } + ErrCode innerErrorCode = ERR_OK; + innerErrorCode = context->StartUIServiceExtension(want); + if (innerErrorCode == 0) { + task.ResolveWithNoError(env, CreateJsUndefined(env)); + } else { + task.Reject(env, CreateJsErrorByNativeErr(env, innerErrorCode)); + } + }; + + napi_value lastParam = (info.argc == unwrapArgc) ? nullptr : info.argv[unwrapArgc]; + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("JSUIExtensionContext OnStartUIServiceExtension", + env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + return result; +} + +bool JsUIExtensionContext::UnwrapConnectUIServiceExtensionParam(napi_env env, NapiCallbackInfo& info, AAFwk::Want& want) +{ + if (info.argc < ARGC_TWO) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "failed, not enough params."); + ThrowTooFewParametersError(env); + return false; + } + bool unwrapResult = OHOS::AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want); + if (!unwrapResult) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "failed, UnwrapWant failed"); + ThrowInvalidParamError(env, "parse want error"); + return false; + } + TAG_LOGI(AAFwkTag::UISERVC_EXT, "callee:%{public}s.%{public}s", want.GetBundle().c_str(), + want.GetElement().GetAbilityName().c_str()); + if (!CheckTypeForNapiValue(env, info.argv[INDEX_ONE], napi_object)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "failed, callback type incorrect"); + ThrowInvalidParamError(env, "Incorrect parameter types"); + return false; + } + return true; +} + +bool JsUIExtensionContext::CheckConnectAlreadyExist(napi_env env, AAFwk::Want& want, napi_value callback, + napi_value& result) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + sptr connection = nullptr; + UIServiceConnection::FindUIServiceExtensionConnection(env, want, callback, connection); + if (connection == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "connection == nullptr"); + return false; + } + + std::unique_ptr uasyncTask = CreateAsyncTaskWithLastParam(env, nullptr, nullptr, nullptr, &result); + napi_value proxy = connection->GetProxyObject(); + if (proxy == nullptr) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "can't got proxy object, wait for duplicated connect finish"); + connection->AddDuplicatedPendingTask(uasyncTask); + } else { + TAG_LOGI(AAFwkTag::UISERVC_EXT, "Resolve, got proxy object"); + uasyncTask->ResolveWithNoError(env, proxy); + } + return true; +} + +napi_value JsUIExtensionContext::OnConnectUIServiceExtension(napi_env env, NapiCallbackInfo& info) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + AAFwk::Want want; + bool unwrapResult = UnwrapConnectUIServiceExtensionParam(env, info, want); + if (!unwrapResult) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "UnwrapConnectUIServiceExtensionParam failed"); + return CreateJsUndefined(env); + } + napi_value callbackObject = nullptr; + if (info.argc > ARGC_ONE) { + callbackObject = info.argv[INDEX_ONE]; + } + napi_value result = nullptr; + bool duplicated = CheckConnectAlreadyExist(env, want, callbackObject, result); + if (duplicated) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "duplicated"); + return result; + } + + sptr connection = sptr::MakeSptr(env); + sptr stub = connection->GetServiceHostStub(); + want.SetParam(UISERVICEHOSTPROXY_KEY, stub->AsObject()); + + result = nullptr; + std::unique_ptr uasyncTask = CreateAsyncTaskWithLastParam(env, nullptr, nullptr, nullptr, &result); + std::shared_ptr uasyncTaskShared = std::move(uasyncTask); + if (info.argc > ARGC_ONE) { + connection->SetJsConnectionObject(callbackObject); + } + connection->SetNapiAsyncTask(uasyncTaskShared); + UIServiceConnection::AddUIServiceExtensionConnection(want, connection); + std::unique_ptr complete = std::make_unique( + [weak = context_, want, uasyncTaskShared, connection]( + napi_env env, NapiAsyncTask& taskUseless, int32_t status) { + DoConnectUIServiceExtension(env, weak, connection, uasyncTaskShared, want); + }); + napi_ref callback = nullptr; + std::unique_ptr execute = nullptr; + NapiAsyncTask::ScheduleHighQos("JsUIExtensionContext::OnConnectUIServiceExtension", + env, std::make_unique(callback, std::move(execute), std::move(complete))); + return result; +} + +void JsUIExtensionContext::DoConnectUIServiceExtension(napi_env env, + std::weak_ptr weakContext, sptr connection, + std::shared_ptr uasyncTaskShared, const AAFwk::Want& want) +{ + if (uasyncTaskShared == nullptr) { + return; + } + + uint64_t connectId = connection->GetConnectionId(); + auto context = weakContext.lock(); + if (!context) { + TAG_LOGE(AAFwkTag::CONTEXT, "Connect ability failed, context is released."); + uasyncTaskShared->Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT)); + UIServiceConnection::RemoveUIServiceExtensionConnection(connectId); + return; + } + + auto innerErrorCode = context->ConnectAbility(want, connection); + AbilityErrorCode errcode = AbilityRuntime::GetJsErrorCodeByNativeError(innerErrorCode); + if (errcode != AbilityErrorCode::ERROR_OK) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "ConnectAbility failed, errcode is %{public}d.", errcode); + uasyncTaskShared->Reject(env, CreateJsError(env, errcode)); + UIServiceConnection::RemoveUIServiceExtensionConnection(connectId); + } +} + +napi_value JsUIExtensionContext::OnDisconnectUIServiceExtension(napi_env env, NapiCallbackInfo& info) +{ + if (info.argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "failed, not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + AAFwk::JsUIServiceProxy* proxy = nullptr; + napi_status status = napi_unwrap(env, info.argv[INDEX_ZERO], reinterpret_cast(&proxy)); + if (status != napi_ok || proxy == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "napi_unwrap err or proxy == nullptr"); + ThrowInvalidParamError(env, "Parameter verification failed"); + return CreateJsUndefined(env); + } + + int64_t connectId = proxy->GetConnectionId(); + AAFwk::Want want; + sptr connection = nullptr; + UIServiceConnection::FindUIServiceExtensionConnection(connectId, want, connection); + + TAG_LOGI(AAFwkTag::UISERVC_EXT, "connection:%{public}d.", static_cast(connectId)); + NapiAsyncTask::CompleteCallback complete = + [weak = context_, want, connectId, connection]( + napi_env env, NapiAsyncTask& task, int32_t status) { + auto context = weak.lock(); + if (!context) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "OnDisconnectUIServiceExtension context is released"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT)); + UIServiceConnection::RemoveUIServiceExtensionConnection(connectId); + } else if (!connection) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "connection nullptr"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INNER)); + UIServiceConnection::RemoveUIServiceExtensionConnection(connectId); + } else { + TAG_LOGI(AAFwkTag::UISERVC_EXT, "context->DisconnectAbility"); + context->DisconnectAbility(want, connection); + task.ResolveWithNoError(env, CreateJsUndefined(env)); + } + }; + + napi_value result = nullptr; + NapiAsyncTask::Schedule("JsUIExtensionContext::OnDisconnectUIServiceExtension", + env, CreateAsyncTaskWithLastParam(env, nullptr, nullptr, std::move(complete), &result)); + return result; +} + napi_value JsUIExtensionContext::OnReportDrawnCompleted(napi_env env, NapiCallbackInfo& info) { TAG_LOGD(AAFwkTag::UI_EXT, "called."); @@ -729,26 +983,34 @@ napi_value JsUIExtensionContext::OpenAtomicServiceInner(napi_env env, NapiCallba } void JsUIExtensionContext::AddFreeInstallObserver(napi_env env, const AAFwk::Want &want, napi_value callback, - napi_value *result, bool isAbilityResult) + napi_value *result, bool isAbilityResult, bool isOpenLink) { // adapter free install async return install and start result TAG_LOGD(AAFwkTag::UI_EXT, "ConvertWindowSize begin."); int ret = 0; if (freeInstallObserver_ == nullptr) { freeInstallObserver_ = new JsFreeInstallObserver(env); - ret = AAFwk::AbilityManagerClient::GetInstance()->AddFreeInstallObserver(freeInstallObserver_); + auto context = context_.lock(); + if (!context) { + TAG_LOGE(AAFwkTag::CONTEXT, "context is nullptr."); + return; + } + ret = context->AddFreeInstallObserver(freeInstallObserver_); } if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::UI_EXT, "AddFreeInstallObserver error."); - } else { + } + std::string startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME); + if (!isOpenLink) { TAG_LOGI(AAFwkTag::UI_EXT, "AddJsObserverObject"); std::string bundleName = want.GetElement().GetBundleName(); std::string abilityName = want.GetElement().GetAbilityName(); - std::string startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME); freeInstallObserver_->AddJsObserverObject( bundleName, abilityName, startTime, callback, result, isAbilityResult); } + std::string url = want.GetUriString(); + freeInstallObserver_->AddJsObserverObject(startTime, url, callback, result, isAbilityResult); } napi_value JsUIExtensionContext::CreateJsUIExtensionContext(napi_env env, @@ -775,6 +1037,9 @@ napi_value JsUIExtensionContext::CreateJsUIExtensionContext(napi_env env, BindNativeFunction(env, objValue, "disconnectServiceExtensionAbility", moduleName, DisconnectAbility); BindNativeFunction(env, objValue, "reportDrawnCompleted", moduleName, ReportDrawnCompleted); BindNativeFunction(env, objValue, "openAtomicService", moduleName, OpenAtomicService); + BindNativeFunction(env, objValue, "startUIServiceExtensionAbility", moduleName, StartUIServiceExtension); + BindNativeFunction(env, objValue, "connectUIServiceExtensionAbility", moduleName, ConnectUIServiceExtension); + BindNativeFunction(env, objValue, "disconnectUIServiceExtensionAbility", moduleName, DisconnectUIServiceExtension); return objValue; } @@ -805,41 +1070,53 @@ JSUIExtensionConnection::JSUIExtensionConnection(napi_env env) : env_(env) {} JSUIExtensionConnection::~JSUIExtensionConnection() { - if (jsConnectionObject_ == nullptr) { + ReleaseNativeReference(jsConnectionObject_.release()); +} + +void JSUIExtensionConnection::ReleaseNativeReference(NativeReference* ref) +{ + if (ref == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "ReleaseNativeReference: ref == nullptr"); return; } - uv_loop_t *loop = nullptr; napi_get_uv_event_loop(env_, &loop); if (loop == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "ReleaseNativeReference: failed to get uv loop."); + delete ref; return; } - uv_work_t *work = new (std::nothrow) uv_work_t; if (work == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "ReleaseNativeReference: failed to create work."); + delete ref; return; } - work->data = reinterpret_cast(jsConnectionObject_.release()); + work->data = reinterpret_cast(ref); int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { + [](uv_work_t *work, int status) { if (work == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "ReleaseNativeReference: work is nullptr."); return; } if (work->data == nullptr) { + TAG_LOGE(AAFwkTag::CONTEXT, "ReleaseNativeReference: data is nullptr."); delete work; work = nullptr; return; } - delete reinterpret_cast(work->data); - work->data = nullptr; + NativeReference *refPtr = reinterpret_cast(work->data); + delete refPtr; + refPtr = nullptr; delete work; work = nullptr; }); if (ret != 0) { - delete reinterpret_cast(work->data); - work->data = nullptr; - delete work; - work = nullptr; + delete ref; + if (work != nullptr) { + delete work; + work = nullptr; + } } } @@ -984,5 +1261,32 @@ void JSUIExtensionConnection::CallJsFailed(int32_t errorCode) TAG_LOGD(AAFwkTag::UI_EXT, "CallJsFailed end"); } +napi_value JSUIExtensionConnection::CallObjectMethod(const char* name, napi_value const *argv, size_t argc) +{ + TAG_LOGD(AAFwkTag::CONTEXT, "name:%{public}s", name); + if (!jsConnectionObject_) { + TAG_LOGW(AAFwkTag::CONTEXT, "Not found jsConnectionObject_"); + return nullptr; + } + + HandleScope handleScope(env_); + napi_value obj = jsConnectionObject_->GetNapiValue(); + if (!CheckTypeForNapiValue(env_, obj, napi_object)) { + TAG_LOGE(AAFwkTag::CONTEXT, "Failed to get jsConnectionObject_ object"); + return nullptr; + } + + napi_value method = nullptr; + napi_get_named_property(env_, obj, name, &method); + if (!CheckTypeForNapiValue(env_, method, napi_function)) { + TAG_LOGE(AAFwkTag::CONTEXT, "Failed to get '%{public}s' from jsConnectionObject_ object", name); + return nullptr; + } + napi_value result = nullptr; + napi_call_function(env_, obj, method, argc, argv, &result); + TAG_LOGD(AAFwkTag::CONTEXT, "CallFunction(%{public}s) ok", name); + return result; +} + } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/ability/native/ui_extension_ability/js_uiservice_uiext_connection.cpp b/frameworks/native/ability/native/ui_extension_ability/js_uiservice_uiext_connection.cpp new file mode 100644 index 0000000000..309ed4b4d4 --- /dev/null +++ b/frameworks/native/ability/native/ui_extension_ability/js_uiservice_uiext_connection.cpp @@ -0,0 +1,259 @@ +/* + * 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 "js_uiservice_uiext_connection.h" + +#include "ability_business_error.h" +#include "hilog_tag_wrapper.h" +#include "js_error_utils.h" +#include "js_ui_service_proxy.h" +#include "napi_common_want.h" +#include "ui_extension_servicehost_stub_impl.h" + +namespace OHOS { +namespace AbilityRuntime { +constexpr size_t ARGC_ONE = 1; + +namespace UIServiceConnection { +static std::map, key_compare> gUiServiceExtConnects; +static std::recursive_mutex gUiServiceExtConnectsLock; +static int64_t gUiServiceExtConnectSn = 0; + +void AddUIServiceExtensionConnection(AAFwk::Want& want, sptr& connection) +{ + std::lock_guard lock(gUiServiceExtConnectsLock); + UIExtensionConnectionKey key; + key.id = gUiServiceExtConnectSn; + key.want = want; + connection->SetConnectionId(key.id); + gUiServiceExtConnects.emplace(key, connection); + if (gUiServiceExtConnectSn < INT32_MAX) { + gUiServiceExtConnectSn++; + } else { + gUiServiceExtConnectSn = 0; + } +} + +void RemoveUIServiceExtensionConnection(const int64_t& connectId) +{ + std::lock_guard lock(gUiServiceExtConnectsLock); + auto item = std::find_if(gUiServiceExtConnects.begin(), gUiServiceExtConnects.end(), + [&connectId](const auto &obj) { + return connectId == obj.first.id; + }); + if (item != gUiServiceExtConnects.end()) { + TAG_LOGI(AAFwkTag::UI_EXT, "found, erase"); + gUiServiceExtConnects.erase(item); + } else { + TAG_LOGI(AAFwkTag::UI_EXT, "not found"); + } + TAG_LOGI(AAFwkTag::CONTEXT, "Connects new size:%{public}zu", gUiServiceExtConnects.size()); +} + +void FindUIServiceExtensionConnection(const int64_t& connectId, AAFwk::Want& want, + sptr& connection) +{ + std::lock_guard lock(gUiServiceExtConnectsLock); + TAG_LOGI(AAFwkTag::UI_EXT, "connection:%{public}d", static_cast(connectId)); + auto item = std::find_if(gUiServiceExtConnects.begin(), gUiServiceExtConnects.end(), + [&connectId](const auto &obj) { + return connectId == obj.first.id; + }); + if (item != gUiServiceExtConnects.end()) { + want = item->first.want; + connection = item->second; + TAG_LOGI(AAFwkTag::UI_EXT, "found"); + } else { + TAG_LOGI(AAFwkTag::UI_EXT, "not found"); + } +} + +void FindUIServiceExtensionConnection(napi_env env, AAFwk::Want& want, napi_value callback, + sptr& connection) +{ + std::lock_guard lock(gUiServiceExtConnectsLock); + auto item = std::find_if(gUiServiceExtConnects.begin(), gUiServiceExtConnects.end(), + [&want, env, callback](const auto &obj) { + bool wantEquals = (obj.first.want.GetElement() == want.GetElement()); + std::unique_ptr& tempCallbackPtr = obj.second->GetJsConnectionObject(); + bool callbackObjectEquals = + JSUIServiceUIExtConnection::IsJsCallbackObjectEquals(env, tempCallbackPtr, callback); + return wantEquals && callbackObjectEquals; + }); + if (item == gUiServiceExtConnects.end()) { + return; + } + connection = item->second; +} +} + +JSUIServiceUIExtConnection::JSUIServiceUIExtConnection(napi_env env) : JSUIExtensionConnection(env) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "JSUIServiceUIExtConnection"); + wptr weakthis = this; + serviceHostStub_ = sptr::MakeSptr(weakthis); +} + +JSUIServiceUIExtConnection::~JSUIServiceUIExtConnection() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "~JSUIServiceUIExtConnection"); + serviceHostStub_ = nullptr; + napiAsyncTask_.reset(); + ReleaseNativeReference(serviceProxyObject_.release()); +} + +void JSUIServiceUIExtConnection::HandleOnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + if (napiAsyncTask_ != nullptr) { + TAG_LOGI(AAFwkTag::UISERVC_EXT, "HandleOnAbilityConnectDone, CreateJsUIServiceProxy"); + sptr hostStub = GetServiceHostStub(); + sptr hostProxy = nullptr; + if (hostStub != nullptr) { + hostProxy = hostStub->AsObject(); + } + napi_value proxy = AAFwk::JsUIServiceProxy::CreateJsUIServiceProxy(env_, remoteObject, + connectionId_, hostProxy); + SetProxyObject(proxy); + napiAsyncTask_->ResolveWithNoError(env_, proxy); + + ResolveDuplicatedPendingTask(env_, proxy); + } else { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "HandleOnAbilityConnectDone, napiAsyncTask_ null"); + } + napiAsyncTask_.reset(); +} + +void JSUIServiceUIExtConnection::HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element, + int resultCode) +{ + if (napiAsyncTask_ != nullptr) { + napi_value innerError = CreateJsError(env_, AbilityErrorCode::ERROR_CODE_INNER); + napiAsyncTask_->Reject(env_, innerError); + RejectDuplicatedPendingTask(env_, innerError); + napiAsyncTask_ = nullptr; + } + CallJsOnDisconnect(); + SetProxyObject(nullptr); + RemoveConnectionObject(); + duplicatedPendingTaskList_.clear(); + UIServiceConnection::RemoveUIServiceExtensionConnection(connectionId_); +} + +void JSUIServiceUIExtConnection::SetNapiAsyncTask(std::shared_ptr& task) +{ + napiAsyncTask_ = task; +} + +void JSUIServiceUIExtConnection::AddDuplicatedPendingTask(std::unique_ptr& task) +{ + duplicatedPendingTaskList_.push_back(std::move(task)); +} + +void JSUIServiceUIExtConnection::ResolveDuplicatedPendingTask(napi_env env, napi_value proxy) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called, size %{public}zu", duplicatedPendingTaskList_.size()); + for (auto &task : duplicatedPendingTaskList_) { + if (task != nullptr) { + task->ResolveWithNoError(env, proxy); + } + } + duplicatedPendingTaskList_.clear(); +} + +void JSUIServiceUIExtConnection::RejectDuplicatedPendingTask(napi_env env, napi_value error) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called, size %{public}zu", duplicatedPendingTaskList_.size()); + for (auto &task : duplicatedPendingTaskList_) { + if (task != nullptr) { + task->Reject(env, error); + } + } + duplicatedPendingTaskList_.clear(); +} + +void JSUIServiceUIExtConnection::SetProxyObject(napi_value proxy) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "SetProxyObject"); + serviceProxyObject_.reset(); + if (proxy != nullptr) { + napi_ref ref = nullptr; + napi_create_reference(env_, proxy, 1, &ref); + serviceProxyObject_ = std::unique_ptr(reinterpret_cast(ref)); + } +} + +napi_value JSUIServiceUIExtConnection::GetProxyObject() +{ + if (serviceProxyObject_ == nullptr) { + return nullptr; + } + return serviceProxyObject_->GetNapiValue(); +} + +int32_t JSUIServiceUIExtConnection::OnSendData(OHOS::AAFwk::WantParams &data) +{ + wptr connection = this; + std::unique_ptr complete = std::make_unique + ([connection, wantParams = data](napi_env env, NapiAsyncTask &task, int32_t status) { + sptr connectionSptr = connection.promote(); + if (!connectionSptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "connectionSptr nullptr"); + return; + } + connectionSptr->HandleOnSendData(wantParams); + }); + + napi_ref callback = nullptr; + std::unique_ptr execute = nullptr; + NapiAsyncTask::Schedule("JSUIServiceUIExtConnection::SendData", + env_, std::make_unique(callback, std::move(execute), std::move(complete))); + + return static_cast(AbilityErrorCode::ERROR_OK); +} + +void JSUIServiceUIExtConnection::HandleOnSendData(const OHOS::AAFwk::WantParams &data) +{ + napi_value argv[] = { AppExecFwk::CreateJsWantParams(env_, data) }; + CallObjectMethod("onData", argv, ARGC_ONE); +} + +void JSUIServiceUIExtConnection::CallJsOnDisconnect() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + CallObjectMethod("onDisconnect", nullptr, 0); +} + +bool JSUIServiceUIExtConnection::IsJsCallbackObjectEquals(napi_env env, + std::unique_ptr &callback, napi_value value) +{ + if (value == nullptr || callback == nullptr) { + return callback.get() == reinterpret_cast(value); + } + auto object = callback->GetNapiValue(); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to get object."); + return false; + } + bool result = false; + if (napi_strict_equals(env, object, value, &result) != napi_ok) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Object does not match value."); + return false; + } + return result; +} + +} +} diff --git a/frameworks/native/ability/native/ui_extension_ability/ui_extension.cpp b/frameworks/native/ability/native/ui_extension_ability/ui_extension.cpp index 1d7711a9d6..7514c1d90d 100755 --- a/frameworks/native/ability/native/ui_extension_ability/ui_extension.cpp +++ b/frameworks/native/ability/native/ui_extension_ability/ui_extension.cpp @@ -16,7 +16,6 @@ #include "ui_extension.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_ui_extension.h" #include "runtime.h" #include "ui_extension_context.h" diff --git a/frameworks/native/ability/native/ui_extension_ability/ui_extension_context.cpp b/frameworks/native/ability/native/ui_extension_ability/ui_extension_context.cpp index 8eeffcf70b..df923fa2a9 100755 --- a/frameworks/native/ability/native/ui_extension_ability/ui_extension_context.cpp +++ b/frameworks/native/ability/native/ui_extension_ability/ui_extension_context.cpp @@ -18,7 +18,6 @@ #include "ability_manager_client.h" #include "connection_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" namespace OHOS { @@ -60,6 +59,18 @@ ErrCode UIExtensionContext::StartAbility(const AAFwk::Want &want, const AAFwk::S return err; } +ErrCode UIExtensionContext::StartUIServiceExtension(const AAFwk::Want& want, int32_t accountId) const +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + TAG_LOGD(AAFwkTag::UI_EXT, "Start UIServiceExtension begin"); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility( + want, token_, accountId, AppExecFwk::ExtensionAbilityType::UI_SERVICE); + if (err != ERR_OK) { + TAG_LOGE(AAFwkTag::UI_EXT, "StartUIServiceExtension is failed %{public}d", err); + } + return err; +} + ErrCode UIExtensionContext::TerminateSelf() { TAG_LOGD(AAFwkTag::UI_EXT, "TerminateSelf begin."); @@ -120,6 +131,15 @@ void UIExtensionContext::InsertResultCallbackTask(int requestCode, RuntimeTask & } } +void UIExtensionContext::RemoveResultCallbackTask(int requestCode) +{ + TAG_LOGD(AAFwkTag::UI_EXT, "called"); + { + std::lock_guard lock(mutexlock_); + resultCallbacks_.erase(requestCode); + } +} + ErrCode UIExtensionContext::StartAbilityForResult( const AAFwk::Want &want, const AAFwk::StartOptions &startOptions, int requestCode, RuntimeTask &&task) { @@ -139,7 +159,7 @@ ErrCode UIExtensionContext::StartAbilityForResult( ErrCode UIExtensionContext::StartAbilityForResultAsCaller(const AAFwk::Want &want, int requestCode, RuntimeTask &&task) { - TAG_LOGD(AAFwkTag::UI_EXT, "Called."); + TAG_LOGD(AAFwkTag::UI_EXT, "called"); { std::lock_guard lock(mutexlock_); resultCallbacks_.insert(make_pair(requestCode, std::move(task))); @@ -156,7 +176,7 @@ ErrCode UIExtensionContext::StartAbilityForResultAsCaller(const AAFwk::Want &wan ErrCode UIExtensionContext::StartAbilityForResultAsCaller( const AAFwk::Want &want, const AAFwk::StartOptions &startOptions, int requestCode, RuntimeTask &&task) { - TAG_LOGD(AAFwkTag::UI_EXT, "Called."); + TAG_LOGD(AAFwkTag::UI_EXT, "called"); { std::lock_guard lock(mutexlock_); resultCallbacks_.insert(make_pair(requestCode, std::move(task))); @@ -256,5 +276,20 @@ ErrCode UIExtensionContext::OpenAtomicService(AAFwk::Want& want, const AAFwk::St } return err; } + +ErrCode UIExtensionContext::OpenLink(const AAFwk::Want& want, int requestCode) +{ + TAG_LOGD(AAFwkTag::UI_EXT, "called"); + return AAFwk::AbilityManagerClient::GetInstance()->OpenLink(want, token_, -1, requestCode); +} + +ErrCode UIExtensionContext::AddFreeInstallObserver(const sptr &observer) +{ + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->AddFreeInstallObserver(token_, observer); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::CONTEXT, "AddFreeInstallObserver error, ret: %{public}d", ret); + } + return ret; +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/ability/native/ui_extension_ability/ui_extension_servicehost_stub_impl.cpp b/frameworks/native/ability/native/ui_extension_ability/ui_extension_servicehost_stub_impl.cpp new file mode 100644 index 0000000000..0f802d9858 --- /dev/null +++ b/frameworks/native/ability/native/ui_extension_ability/ui_extension_servicehost_stub_impl.cpp @@ -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. + */ + +#include "ui_extension_servicehost_stub_impl.h" + +#include "ability_business_error.h" +#include "js_uiservice_uiext_connection.h" + +namespace OHOS { +namespace AbilityRuntime { + +UIExtensionServiceHostStubImpl::UIExtensionServiceHostStubImpl(wptr conn) + :conn_(conn) +{ +} + +int32_t UIExtensionServiceHostStubImpl::SendData(OHOS::AAFwk::WantParams &data) +{ + sptr conn = conn_.promote(); + if (conn != nullptr) { + return conn->OnSendData(data); + } + + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); +} + +} +} diff --git a/frameworks/native/ability/native/ui_service_extension_ability/connection/js_ui_service_host_proxy.cpp b/frameworks/native/ability/native/ui_service_extension_ability/connection/js_ui_service_host_proxy.cpp new file mode 100644 index 0000000000..78258b96bb --- /dev/null +++ b/frameworks/native/ability/native/ui_service_extension_ability/connection/js_ui_service_host_proxy.cpp @@ -0,0 +1,127 @@ +/* + * 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 "js_ui_service_host_proxy.h" + +#include "ability_business_error.h" +#include "hilog_tag_wrapper.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "js_error_utils.h" +#include "napi_common_want.h" +#include "permission_constants.h" +#include "tokenid_kit.h" +#include "ui_service_host_proxy.h" + +namespace OHOS { +namespace AAFwk { +using namespace AbilityRuntime; + +static constexpr int32_t INDEX_ZERO = 0; +static constexpr int32_t ARGC_ONE = 1; + +napi_ref JsUIServiceHostProxy::CreateJsUIServiceHostProxy(napi_env env, const sptr& impl) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + napi_value object = nullptr; + napi_create_object(env, &object); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "napi_create_object, object is null"); + return nullptr; + } + + std::unique_ptr proxy = std::make_unique(impl); + napi_ref nref = nullptr; + napi_status status = napi_wrap(env, object, proxy.release(), JsUIServiceHostProxy::Finalizer, nullptr, &nref); + if (status != napi_ok) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "napi_wrap failed %{public}d", status); + } + const char *moduleName = "JsUIServiceHostProxy"; + BindNativeFunction(env, object, "sendData", moduleName, JsUIServiceHostProxy::SendData); + return nref; +} + +void JsUIServiceHostProxy::Finalizer(napi_env env, void* data, void* hint) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + std::unique_ptr(static_cast(data)); +} + +JsUIServiceHostProxy::JsUIServiceHostProxy(const sptr& impl) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + if (impl != nullptr) { + proxy_ = iface_cast(impl); + } + if (proxy_ == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "iface_cast return null"); + } +} + +JsUIServiceHostProxy::~JsUIServiceHostProxy() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + proxy_ = nullptr; +} + +bool JsUIServiceHostProxy::CheckCallerIsSystemApp() +{ + auto selfToken = IPCSkeleton::GetSelfTokenID(); + if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(selfToken)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Current app is not system app, not allow."); + return false; + } + return true; +} + +napi_value JsUIServiceHostProxy::SendData(napi_env env, napi_callback_info info) +{ + GET_NAPI_INFO_AND_CALL(env, info, JsUIServiceHostProxy, OnSendData); +} + +napi_value JsUIServiceHostProxy::OnSendData(napi_env env, NapiCallbackInfo& info) +{ + if (!CheckCallerIsSystemApp()) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "CheckCallerIsSystemApp failed"); + ThrowError(env, AbilityErrorCode::ERROR_CODE_NOT_SYSTEM_APP); + return CreateJsUndefined(env); + } + if (proxy_ == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "proxy_ is null"); + ThrowError(env, AbilityErrorCode::ERROR_CODE_INNER); + return CreateJsUndefined(env); + } + if (info.argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "failed, not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + AAFwk::WantParams params; + bool result = AppExecFwk::UnwrapWantParams(env, info.argv[INDEX_ZERO], params); + if (!result) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "UnwrapWantParams failed"); + ThrowError(env, static_cast(AbilityErrorCode::ERROR_CODE_INVALID_PARAM), "Data verification failed"); + return CreateJsUndefined(env); + } + + int32_t ret = proxy_->SendData(params); + if (ret != static_cast(AbilityErrorCode::ERROR_OK)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "SendData failed"); + ThrowError(env, AbilityErrorCode::ERROR_CODE_INNER); + } + return CreateJsUndefined(env); +} +} +} diff --git a/frameworks/native/ability/native/ui_service_extension_ability/connection/js_ui_service_proxy.cpp b/frameworks/native/ability/native/ui_service_extension_ability/connection/js_ui_service_proxy.cpp new file mode 100644 index 0000000000..633f81e73d --- /dev/null +++ b/frameworks/native/ability/native/ui_service_extension_ability/connection/js_ui_service_proxy.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 "js_ui_service_proxy.h" +#include "ability_business_error.h" +#include "hilog_tag_wrapper.h" +#include "js_error_utils.h" +#include "napi_common_want.h" + +namespace OHOS { +namespace AAFwk { +using namespace AbilityRuntime; + +static constexpr int32_t INDEX_ZERO = 0; +static constexpr int32_t ARGC_ONE = 1; + +napi_value JsUIServiceProxy::CreateJsUIServiceProxy(napi_env env, const sptr& impl, + int64_t connectionId, const sptr& hostProxy) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + napi_value object = nullptr; + napi_create_object(env, &object); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "napi_create_object, object is null"); + return CreateJsUndefined(env); + } + + std::unique_ptr proxy = std::make_unique(impl, hostProxy); + proxy->SetConnectionId(connectionId); + napi_wrap(env, object, proxy.release(), Finalizer, nullptr, nullptr); + + const char *moduleName = "JsUIServiceProxy"; + BindNativeFunction(env, object, "sendData", moduleName, JsUIServiceProxy::SendData); + return object; +} + +void JsUIServiceProxy::Finalizer(napi_env env, void* data, void* hint) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + std::unique_ptr(static_cast(data)); +} + +JsUIServiceProxy::JsUIServiceProxy(const sptr& impl, const sptr& hostProxy) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + proxy_ = iface_cast(impl); + hostProxy_ = hostProxy; + if (proxy_ == nullptr) { + TAG_LOGI(AAFwkTag::UISERVC_EXT, "iface_cast return null"); + } +} + +JsUIServiceProxy::~JsUIServiceProxy() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + proxy_ = nullptr; + hostProxy_ = nullptr; +} + +napi_value JsUIServiceProxy::SendData(napi_env env, napi_callback_info info) +{ + GET_NAPI_INFO_AND_CALL(env, info, JsUIServiceProxy, OnSendData); +} + +napi_value JsUIServiceProxy::OnSendData(napi_env env, NapiCallbackInfo& info) +{ + if (proxy_ == nullptr || hostProxy_ == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "proxy_ or hostProxy_ is null"); + ThrowError(env, AbilityErrorCode::ERROR_CODE_INNER); + return CreateJsUndefined(env); + } + if (info.argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "failed, not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + AAFwk::WantParams params; + bool result = AppExecFwk::UnwrapWantParams(env, info.argv[INDEX_ZERO], params); + if (!result) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "UnwrapWantParams failed"); + ThrowError(env, static_cast(AbilityErrorCode::ERROR_CODE_INVALID_PARAM), "Data verification failed"); + return CreateJsUndefined(env); + } + + int32_t ret = proxy_->SendData(hostProxy_, params); + if (ret != static_cast(AbilityErrorCode::ERROR_OK)) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "proxy_->SendData failed"); + ThrowError(env, AbilityErrorCode::ERROR_CODE_INNER); + } + return CreateJsUndefined(env); +} +} +} diff --git a/frameworks/native/ability/native/ui_service_extension_ability/connection/ui_service_host_proxy.cpp b/frameworks/native/ability/native/ui_service_extension_ability/connection/ui_service_host_proxy.cpp new file mode 100644 index 0000000000..e5599793f8 --- /dev/null +++ b/frameworks/native/ability/native/ui_service_extension_ability/connection/ui_service_host_proxy.cpp @@ -0,0 +1,64 @@ +/* + * 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 "ui_service_host_proxy.h" + +#include "ability_business_error.h" +#include "ability_manager_ipc_interface_code.h" +#include "ipc_types.h" +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace AAFwk { +using namespace AbilityRuntime; + +UIServiceHostProxy::UIServiceHostProxy(const sptr& impl) + :IRemoteProxy(impl) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); +} + +UIServiceHostProxy::~UIServiceHostProxy() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); +} + +int32_t UIServiceHostProxy::SendData(OHOS::AAFwk::WantParams &data) +{ + MessageParcel parcelData; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!parcelData.WriteInterfaceToken(UIServiceHostProxy::GetDescriptor())) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Write interface token failed."); + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); + } + if (!parcelData.WriteParcelable(&data)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Write data failed."); + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); + } + sptr remoteObject = Remote(); + if (remoteObject == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "remoteObject null"); + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); + } + auto error = remoteObject->SendRequest(static_cast(IUIServiceHost::SEND_DATA), parcelData, reply, option); + if (error != ERR_OK) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "SendRequest failed, error %{public}d", error); + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); + } + return ERR_OK; +} +} +} diff --git a/frameworks/native/ability/native/ui_service_extension_ability/connection/ui_service_host_stub.cpp b/frameworks/native/ability/native/ui_service_extension_ability/connection/ui_service_host_stub.cpp new file mode 100644 index 0000000000..cd41164693 --- /dev/null +++ b/frameworks/native/ability/native/ui_service_extension_ability/connection/ui_service_host_stub.cpp @@ -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. + */ + +#include "ui_service_host_stub.h" +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace AAFwk { + +UIServiceHostStub::UIServiceHostStub() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + requestFuncMap_[SEND_DATA] = &UIServiceHostStub::OnSendData; +} + +UIServiceHostStub::~UIServiceHostStub() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + requestFuncMap_.clear(); +} + +int UIServiceHostStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + std::u16string descriptor = UIServiceHostStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + return ERR_INVALID_STATE; + } + auto itFunc = requestFuncMap_.find(code); + if (itFunc != requestFuncMap_.end()) { + auto requestFunc = itFunc->second; + if (requestFunc != nullptr) { + return (this->*requestFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t UIServiceHostStub::OnSendData(MessageParcel& data, MessageParcel& reply) +{ + std::unique_ptr wantParams(data.ReadParcelable()); + if (wantParams == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "UIServiceHostStub::OnSendData, read WantParams failed"); + return ERR_INVALID_VALUE; + } + int32_t result = SendData(*wantParams); + if (!reply.WriteInt32(result)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "UIServiceHostStub::OnSendData, write result failed."); + return IPC_STUB_ERR; + } + return NO_ERROR; +} +} +} diff --git a/frameworks/native/ability/native/ui_service_extension_ability/connection/ui_service_proxy.cpp b/frameworks/native/ability/native/ui_service_extension_ability/connection/ui_service_proxy.cpp new file mode 100644 index 0000000000..0bceb7d366 --- /dev/null +++ b/frameworks/native/ability/native/ui_service_extension_ability/connection/ui_service_proxy.cpp @@ -0,0 +1,73 @@ +/* + * 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 "ui_service_proxy.h" + +#include "ability_business_error.h" +#include "ability_manager_ipc_interface_code.h" +#include "ipc_types.h" +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace AAFwk { +using namespace AbilityRuntime; + +UIServiceProxy::UIServiceProxy(const sptr& impl) + :IRemoteProxy(impl) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); +} + +UIServiceProxy::~UIServiceProxy() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); +} + +int32_t UIServiceProxy::SendData(sptr hostProxy, OHOS::AAFwk::WantParams &data) +{ + if (hostProxy == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "hostProxy == nullptr, SendData failed"); + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); + } + + MessageParcel parcelData; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!parcelData.WriteInterfaceToken(UIServiceProxy::GetDescriptor())) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Write interface token failed."); + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); + } + if (!parcelData.WriteRemoteObject(hostProxy)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Write hostProxy failed."); + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); + } + if (!parcelData.WriteParcelable(&data)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Write data failed."); + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); + } + sptr remoteObject = Remote(); + if (remoteObject == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "remoteObject null"); + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); + } + auto error = remoteObject->SendRequest(static_cast(IUIService::SEND_DATA), parcelData, reply, option); + if (error != ERR_OK) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "SendRequest failed, error %{public}d", error); + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); + } + return ERR_OK; +} +} +} diff --git a/frameworks/native/ability/native/ui_service_extension_ability/connection/ui_service_stub.cpp b/frameworks/native/ability/native/ui_service_extension_ability/connection/ui_service_stub.cpp new file mode 100644 index 0000000000..0784f87af0 --- /dev/null +++ b/frameworks/native/ability/native/ui_service_extension_ability/connection/ui_service_stub.cpp @@ -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. + */ + +#include "ui_service_stub.h" +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace AAFwk { + +UIServiceStub::UIServiceStub() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + requestFuncMap_[SEND_DATA] = &UIServiceStub::OnSendData; +} + +UIServiceStub::~UIServiceStub() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + requestFuncMap_.clear(); +} + +int32_t UIServiceStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, + MessageOption& option) +{ + std::u16string descriptor = UIServiceStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + return ERR_INVALID_STATE; + } + auto itFunc = requestFuncMap_.find(code); + if (itFunc != requestFuncMap_.end()) { + auto requestFunc = itFunc->second; + if (requestFunc != nullptr) { + return (this->*requestFunc)(data, reply); + } + } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t UIServiceStub::OnSendData(MessageParcel& data, MessageParcel& reply) +{ + sptr hostProxy = data.ReadRemoteObject(); + if (hostProxy == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "UIServiceStub::OnSendData, read hostProxy failed"); + return ERR_INVALID_VALUE; + } + std::unique_ptr wantParams(data.ReadParcelable()); + if (wantParams == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "UIServiceStub::OnSendData, read WantParams failed"); + return ERR_INVALID_VALUE; + } + int32_t result = SendData(hostProxy, *wantParams); + if (!reply.WriteInt32(result)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "UIServiceStub::OnSendData, write result failed."); + return IPC_STUB_ERR; + } + return NO_ERROR; +} +} +} diff --git a/frameworks/native/ability/native/ui_service_extension_ability/js_ui_service_extension.cpp b/frameworks/native/ability/native/ui_service_extension_ability/js_ui_service_extension.cpp new file mode 100644 index 0000000000..d19519ae89 --- /dev/null +++ b/frameworks/native/ability/native/ui_service_extension_ability/js_ui_service_extension.cpp @@ -0,0 +1,668 @@ +/* + * 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 "js_ui_service_extension.h" + +#include + +#include "ability_business_error.h" +#include "ability_handler.h" +#include "ability_info.h" +#include "ability.h" +#include "ability_manager_client.h" +#include "configuration_utils.h" +#include "hitrace_meter.h" +#include "hilog_tag_wrapper.h" +#include "js_extension_common.h" +#include "js_extension_context.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "js_ui_service_extension_context.h" +#include "js_window_stage.h" +#include "js_window.h" +#include "js_ui_service_host_proxy.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "napi_common_configuration.h" +#include "napi_common_want.h" +#include "napi_remote_object.h" +#include "scene_board_judgement.h" +#include "ability_context.h" +#include "session_info.h" +#include "ui_service_extension_connection_constants.h" +#include "window_scene.h" +#include "wm_common.h" +#include "window.h" +#ifdef SUPPORT_GRAPHICS +#include "iservice_registry.h" +#include "system_ability_definition.h" +#endif + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr size_t ARGC_ONE = 1; +constexpr size_t ARGC_TWO = 2; +} + +using namespace OHOS::AppExecFwk; + +UIServiceStubImpl::UIServiceStubImpl(std::weak_ptr& ext) + :extension_(ext) +{ +} + +UIServiceStubImpl::~UIServiceStubImpl() +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "~UIServiceStubImpl"); +} + +int32_t UIServiceStubImpl::SendData(sptr hostProxy, OHOS::AAFwk::WantParams &data) +{ + auto sptr = extension_.lock(); + if (sptr) { + return sptr->OnSendData(hostProxy, data); + } + + return static_cast(AbilityErrorCode::ERROR_CODE_INNER); +} + +napi_value AttachUIServiceExtensionContext(napi_env env, void *value, void *) +{ + if (value == nullptr) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "invalid parameter."); + return nullptr; + } + auto ptr = reinterpret_cast *>(value)->lock(); + if (ptr == nullptr) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "invalid context."); + return nullptr; + } + napi_value object = AbilityRuntime::CreateJsUIServiceExtensionContext(env, ptr); + auto sysModule = AbilityRuntime::JsRuntime::LoadSystemModuleByEngine(env, + "application.UIServiceExtensionContext", &object, 1); + if (sysModule == nullptr) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "load module failed."); + return nullptr; + } + auto contextObj = sysModule->GetNapiValue(); + napi_coerce_to_native_binding_object( + env, contextObj, AbilityRuntime::DetachCallbackFunc, AttachUIServiceExtensionContext, value, nullptr); + auto workContext = new (std::nothrow) std::weak_ptr(ptr); + napi_wrap(env, contextObj, workContext, + [](napi_env, void *data, void *) { + TAG_LOGD(AAFwkTag::UISERVC_EXT, "Finalizer for weak_ptr service extension context is called"); + delete static_cast *>(data); + }, + nullptr, nullptr); + return contextObj; +} + +JsUIServiceExtension* JsUIServiceExtension::Create(const std::unique_ptr& runtime) +{ + return new JsUIServiceExtension(static_cast(*runtime)); +} + +JsUIServiceExtension::JsUIServiceExtension(AbilityRuntime::JsRuntime& jsRuntime) : jsRuntime_(jsRuntime) {} + +JsUIServiceExtension::~JsUIServiceExtension() +{ + auto context = GetContext(); + if (context) { + context->Unbind(); + } + + jsRuntime_.FreeNativeReference(std::move(jsObj_)); + jsRuntime_.FreeNativeReference(std::move(shellContextRef_)); +} + +void JsUIServiceExtension::Init(const std::shared_ptr &record, + const std::shared_ptr &application, std::shared_ptr &handler, + const sptr &token) +{ + UIServiceExtension::Init(record, application, handler, token); + std::string srcPath = ""; + GetSrcPath(srcPath); + if (srcPath.empty()) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to get srcPath"); + return; + } + + std::string moduleName(Extension::abilityInfo_->moduleName); + moduleName.append("::").append(abilityInfo_->name); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "JsServiceExtension::Init moduleName:%{public}s,srcPath:%{public}s.", + moduleName.c_str(), srcPath.c_str()); + HandleScope handleScope(jsRuntime_); + auto env = jsRuntime_.GetNapiEnv(); + + jsObj_ = jsRuntime_.LoadModule( + moduleName, srcPath, abilityInfo_->hapPath, abilityInfo_->compileMode == CompileMode::ES_MODULE); + if (jsObj_ == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to get jsObj_"); + return; + } + + TAG_LOGD(AAFwkTag::UISERVC_EXT, "ConvertNativeValueTo."); + napi_value obj = jsObj_->GetNapiValue(); + if (!CheckTypeForNapiValue(env, obj, napi_object)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to get JsServiceExtension object"); + return; + } + + BindContext(env, obj); + + SetExtensionCommon(JsExtensionCommon::Create(jsRuntime_, static_cast(*jsObj_), shellContextRef_)); + + handler_ = handler; + auto context = GetContext(); + auto appContext = Context::GetApplicationContext(); + if (context != nullptr && appContext != nullptr) { + auto appConfig = appContext->GetConfiguration(); + if (appConfig != nullptr) { + TAG_LOGD(AAFwkTag::UISERVC_EXT, "Original config dump: %{public}s", appConfig->GetName().c_str()); + context->SetConfiguration(std::make_shared(*appConfig)); + } + } + ListenWMS(); +} + +void JsUIServiceExtension::SystemAbilityStatusChangeListener::OnAddSystemAbility(int32_t systemAbilityId, + const std::string& deviceId) +{ + TAG_LOGD(AAFwkTag::UISERVC_EXT, "systemAbilityId: %{public}d add", systemAbilityId); + if (systemAbilityId == WINDOW_MANAGER_SERVICE_ID) { + Rosen::DisplayManager::GetInstance().RegisterDisplayListener(tmpDisplayListener_); + } +} + +void JsUIServiceExtension::BindContext(napi_env env, napi_value obj) +{ + auto context = GetContext(); + if (context == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to get context"); + return; + } + TAG_LOGD(AAFwkTag::UISERVC_EXT, "call"); + napi_value contextObj = CreateJsUIServiceExtensionContext(env, context); + shellContextRef_ = JsRuntime::LoadSystemModuleByEngine(env, "application.UIServiceExtensionContext", + &contextObj, ARGC_ONE); + if (shellContextRef_ == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to load module"); + return; + } + contextObj = shellContextRef_->GetNapiValue(); + if (!CheckTypeForNapiValue(env, contextObj, napi_object)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "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, AttachUIServiceExtensionContext, workContext, nullptr); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "Bind."); + context->Bind(jsRuntime_, shellContextRef_.get()); + napi_set_named_property(env, obj, "context", contextObj); + + napi_wrap(env, contextObj, workContext, + [](napi_env, void* data, void*) { + delete static_cast*>(data); + }, + nullptr, nullptr); + + TAG_LOGD(AAFwkTag::UISERVC_EXT, "end."); +} + +void JsUIServiceExtension::OnStart(const AAFwk::Want &want) +{ + Extension::OnStart(want); + TAG_LOGE(AAFwkTag::UISERVC_EXT, "call"); + + auto context = GetContext(); + if (context != nullptr) { + int32_t displayId = static_cast(Rosen::DisplayManager::GetInstance().GetDefaultDisplayId()); + displayId = want.GetIntParam(Want::PARAM_RESV_DISPLAY_ID, displayId); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "displayId %{public}d", displayId); + auto configUtils = std::make_shared(); + configUtils->InitDisplayConfig(displayId, context->GetConfiguration(), context->GetResourceManager()); + } + + HandleScope handleScope(jsRuntime_); + napi_env env = jsRuntime_.GetNapiEnv(); + + // display config has changed, need update context.config + if (context != nullptr) { + JsExtensionContext::ConfigurationUpdated(env, shellContextRef_, context->GetConfiguration()); + } + + napi_value napiWant = OHOS::AppExecFwk::WrapWant(env, want); + napi_value argv[] = {napiWant}; + CallObjectMethod("onCreate", argv, ARGC_ONE); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "ok"); +} + +void JsUIServiceExtension::OnStart(const AAFwk::Want &want, sptr sessionInfo) +{ + Extension::OnStart(want, sessionInfo); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "call"); + + auto context = GetContext(); + if (context != nullptr) { + int32_t displayId = static_cast(Rosen::DisplayManager::GetInstance().GetDefaultDisplayId()); + displayId = want.GetIntParam(Want::PARAM_RESV_DISPLAY_ID, displayId); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "displayId %{public}d", displayId); + auto configUtils = std::make_shared(); + configUtils->InitDisplayConfig(displayId, context->GetConfiguration(), context->GetResourceManager()); + } + + HandleScope handleScope(jsRuntime_); + napi_env env = jsRuntime_.GetNapiEnv(); + + // display config has changed, need update context.config + if (context != nullptr) { + JsExtensionContext::ConfigurationUpdated(env, shellContextRef_, context->GetConfiguration()); + } + + napi_value napiWant = OHOS::AppExecFwk::WrapWant(env, want); + napi_value argv[] = {napiWant}; + CallObjectMethod("onCreate", argv, ARGC_ONE); +#ifdef SUPPORT_GRAPHICS + auto extensionWindowConfig = std::make_shared(); + OnSceneWillCreated(extensionWindowConfig); + auto option = GetWindowOption(want, extensionWindowConfig, sessionInfo); + sptr extensionWindow = Rosen::Window::Create(extensionWindowConfig->windowName, option, context); + if (extensionWindow != nullptr) { + OnSceneDidCreated(extensionWindow); + context->SetWindow(extensionWindow); + } else { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "extensionWindow is nullptr"); + } +#endif + TAG_LOGD(AAFwkTag::UISERVC_EXT, "ok"); +} + +void JsUIServiceExtension::OnStop() +{ + Extension::OnStop(); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "call"); + CallObjectMethod("onDestroy"); + bool ret = ConnectionManager::GetInstance().DisconnectCaller(GetContext()->GetToken()); + if (ret) { + ConnectionManager::GetInstance().ReportConnectionLeakEvent(getpid(), gettid()); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "The service extension connection is not disconnected."); + } + Rosen::DisplayManager::GetInstance().UnregisterDisplayListener(displayListener_); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "ok"); +} + +sptr JsUIServiceExtension::OnConnect(const AAFwk::Want &want, + AppExecFwk::AbilityTransactionCallbackInfo> *callbackInfo, bool &isAsyncCallback) +{ + HandleScope handleScope(jsRuntime_); + sptr result = CallOnConnect(want); + return result; +} + +void JsUIServiceExtension::OnDisconnect(const AAFwk::Want &want, + AppExecFwk::AbilityTransactionCallbackInfo<> *callbackInfo, bool &isAsyncCallback) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + HandleScope handleScope(jsRuntime_); + Extension::OnDisconnect(want); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "begin."); + CallOnDisconnect(want); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "end."); +} + +void JsUIServiceExtension::OnCommand(const AAFwk::Want &want, bool restart, int startId) +{ + Extension::OnCommand(want, restart, startId); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "restart=%{public}s,startId=%{public}d.", + restart ? "true" : "false", + startId); + // wrap want + HandleScope handleScope(jsRuntime_); + napi_env env = jsRuntime_.GetNapiEnv(); + napi_value napiWant = OHOS::AppExecFwk::WrapWant(env, want); + // wrap startId + napi_value napiStartId = nullptr; + napi_create_int32(env, startId, &napiStartId); + napi_value argv[] = {napiWant, napiStartId}; + CallObjectMethod("onRequest", argv, ARGC_TWO); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "ok"); +} + +sptr JsUIServiceExtension::CallOnConnect(const AAFwk::Want &want) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + Extension::OnConnect(want); + TAG_LOGI(AAFwkTag::UISERVC_EXT, "call"); + napi_env env = jsRuntime_.GetNapiEnv(); + sptr hostProxy = GetHostProxyFromWant(want); + if (hostProxy == nullptr) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "hostProxy nullptr"); + return nullptr; + } + napi_value napiWant = WrapWant(env, want); + if (napiWant == nullptr) { + return nullptr; + } + SetupServiceStub(); + sptr stubObject = extensionStub_->AsObject(); + if (hostProxyMap_.find(hostProxy) != hostProxyMap_.end()) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "alread exist hostproxy record"); + return stubObject; + } + napi_ref hostProxyNref = AAFwk::JsUIServiceHostProxy::CreateJsUIServiceHostProxy(env, hostProxy); + if (hostProxyNref == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to CreateJsUIServiceHostProxy"); + return nullptr; + } + napi_value jsHostProxy = reinterpret_cast(hostProxyNref)->GetNapiValue(); + hostProxyMap_[hostProxy] = std::unique_ptr(reinterpret_cast(hostProxyNref)); + + napi_value argv[] = {napiWant, jsHostProxy}; + CallObjectMethod("onConnect", argv, ARGC_TWO); + return stubObject; +} + +napi_value JsUIServiceExtension::CallOnDisconnect(const AAFwk::Want &want) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "call"); + HandleEscape handleEscape(jsRuntime_); + napi_env env = jsRuntime_.GetNapiEnv(); + sptr hostProxy = GetHostProxyFromWant(want); + if (hostProxy == nullptr) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "hostProxy nullptr"); + return nullptr; + } + napi_value napiWant = WrapWant(env, want); + if (napiWant == nullptr) { + return nullptr; + } + napi_value jsHostProxy = nullptr; + auto iter = hostProxyMap_.find(hostProxy); + if (iter != hostProxyMap_.end()) { + jsHostProxy = iter->second->GetNapiValue(); + } else { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "jsHostProxy null"); + return nullptr; + } + napi_value argv[] = { napiWant, jsHostProxy }; + CallObjectMethod("onDisconnect", argv, ARGC_TWO); + hostProxyMap_.erase(iter); + return nullptr; +} + +napi_value JsUIServiceExtension::WrapWant(napi_env env, const AAFwk::Want &want) +{ + AAFwk::Want jsWant = want; + jsWant.RemoveParam(UISERVICEHOSTPROXY_KEY); + napi_value napiWant = OHOS::AppExecFwk::WrapWant(env, jsWant); + return napiWant; +} + +int32_t JsUIServiceExtension::OnSendData(sptr hostProxy, OHOS::AAFwk::WantParams &data) +{ + napi_env env = jsRuntime_.GetNapiEnv(); + std::unique_ptr complete = std::make_unique + ([weak = weak_from_this(), hostProxy, wantParams = data](napi_env env, NapiAsyncTask &task, int32_t status) { + auto extensionSptr = weak.lock(); + if (!extensionSptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "extensionSptr nullptr"); + return; + } + auto sptrThis = std::static_pointer_cast(extensionSptr); + if (!sptrThis) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "sptrThis nullptr"); + return; + } + sptrThis->HandleSendData(hostProxy, wantParams); + }); + + napi_ref callback = nullptr; + std::unique_ptr execute = nullptr; + NapiAsyncTask::Schedule("JsUIServiceExtension::SendData", + env, std::make_unique(callback, std::move(execute), std::move(complete))); + return static_cast(AbilityErrorCode::ERROR_OK); +} + +void JsUIServiceExtension::HandleSendData(sptr hostProxy, const OHOS::AAFwk::WantParams &data) +{ + if (hostProxy == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "hostProxy null"); + return; + } + napi_value jsHostProxy = nullptr; + auto iter = hostProxyMap_.find(hostProxy); + if (iter != hostProxyMap_.end()) { + jsHostProxy = iter->second->GetNapiValue(); + } + if (jsHostProxy == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "jsHostProxy = nullptr"); + return; + } + + napi_env env = jsRuntime_.GetNapiEnv(); + napi_value argv[] = {jsHostProxy, AppExecFwk::CreateJsWantParams(env, data)}; + CallObjectMethod("onData", argv, ARGC_TWO); +} + +void JsUIServiceExtension::SetupServiceStub() +{ + if (extensionStub_ != nullptr) { + return; + } + TAG_LOGI(AAFwkTag::UISERVC_EXT, "called"); + std::weak_ptr weakThis = std::static_pointer_cast(shared_from_this()); + extensionStub_ = sptr::MakeSptr(weakThis); +} + +sptr JsUIServiceExtension::GetHostProxyFromWant(const AAFwk::Want &want) +{ + sptr hostProxy = nullptr; + if (!want.HasParameter(UISERVICEHOSTPROXY_KEY)) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "Not found UISERVICEHOSTPROXY_KEY"); + return hostProxy; + } + hostProxy = want.GetRemoteObject(UISERVICEHOSTPROXY_KEY); + return hostProxy; +} + +napi_value JsUIServiceExtension::CallObjectMethod(const char* name, napi_value const* argv, size_t argc) +{ + TAG_LOGD(AAFwkTag::UISERVC_EXT, "name:%{public}s", name); + + if (!jsObj_) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "Not found ServiceExtension.js"); + return nullptr; + } + + HandleScope handleScope(jsRuntime_); + napi_env env = jsRuntime_.GetNapiEnv(); + + napi_value obj = jsObj_->GetNapiValue(); + if (!CheckTypeForNapiValue(env, obj, napi_object)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to get ServiceExtension object"); + return nullptr; + } + + napi_value method = nullptr; + napi_get_named_property(env, obj, name, &method); + if (!CheckTypeForNapiValue(env, method, napi_function)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to get '%{public}s' from ServiceExtension object", name); + return nullptr; + } + TAG_LOGD(AAFwkTag::UISERVC_EXT, "CallFunction(%{public}s) ok", name); + napi_value result = nullptr; + napi_call_function(env, obj, method, argc, argv, &result); + return result; +} + +void JsUIServiceExtension::GetSrcPath(std::string &srcPath) +{ + TAG_LOGD(AAFwkTag::UISERVC_EXT, "GetSrcPath start."); + if (!Extension::abilityInfo_->srcEntrance.empty()) { + srcPath.append(Extension::abilityInfo_->moduleName + "/"); + srcPath.append(Extension::abilityInfo_->srcEntrance); + srcPath.erase(srcPath.rfind('.')); + srcPath.append(".abc"); + } +} + +void JsUIServiceExtension::OnConfigurationUpdated(const AppExecFwk::Configuration& configuration) +{ + UIServiceExtension::OnConfigurationUpdated(configuration); + TAG_LOGD(AAFwkTag::UISERVC_EXT, "call"); + auto context = GetContext(); + if (context == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Context is invalid."); + return; + } + + auto contextConfig = context->GetConfiguration(); + if (contextConfig != nullptr) { + TAG_LOGD(AAFwkTag::UISERVC_EXT, "Config dump: %{public}s", contextConfig->GetName().c_str()); + std::vector changeKeyV; + contextConfig->CompareDifferent(changeKeyV, configuration); + if (!changeKeyV.empty()) { + contextConfig->Merge(changeKeyV, configuration); + } + TAG_LOGD(AAFwkTag::UISERVC_EXT, "Config dump after merge: %{public}s", contextConfig->GetName().c_str()); + } + ConfigurationUpdated(); +} + +void JsUIServiceExtension::ConfigurationUpdated() +{ + TAG_LOGD(AAFwkTag::UISERVC_EXT, "called."); + HandleScope handleScope(jsRuntime_); + napi_env env = jsRuntime_.GetNapiEnv(); + + // Notify extension context + auto fullConfig = GetContext()->GetConfiguration(); + if (!fullConfig) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "configuration is nullptr."); + return; + } + + napi_value napiConfiguration = OHOS::AppExecFwk::WrapConfiguration(env, *fullConfig); + CallObjectMethod("onConfigurationUpdate", &napiConfiguration, ARGC_ONE); + JsExtensionContext::ConfigurationUpdated(env, shellContextRef_, fullConfig); +} + +void JsUIServiceExtension::ListenWMS() +{ +#ifdef SUPPORT_GRAPHICS + TAG_LOGD(AAFwkTag::UISERVC_EXT, "RegisterDisplayListener"); + auto abilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (abilityManager == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to get SaMgr."); + return; + } + + auto jsUIServiceExtension = std::static_pointer_cast(shared_from_this()); + displayListener_ = sptr::MakeSptr(jsUIServiceExtension); + if (displayListener_ == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to create display listener."); + return; + } + + auto listener = sptr::MakeSptr(displayListener_); + if (listener == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to create status change listener."); + return; + } + + auto ret = abilityManager->SubscribeSystemAbility(WINDOW_MANAGER_SERVICE_ID, listener); + if (ret != 0) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "subscribe system ability failed, ret = %{public}d.", ret); + } +#endif +} + +#ifdef SUPPORT_GRAPHICS +void JsUIServiceExtension::OnCreate(Rosen::DisplayId displayId) +{ + TAG_LOGD(AAFwkTag::UISERVC_EXT, "enter."); +} + +void JsUIServiceExtension::OnDestroy(Rosen::DisplayId displayId) +{ + TAG_LOGD(AAFwkTag::UISERVC_EXT, "exit."); +} + +void JsUIServiceExtension::OnChange(Rosen::DisplayId displayId) +{ + TAG_LOGD(AAFwkTag::UISERVC_EXT, "displayId: %{public}" PRIu64"", displayId); + auto context = GetContext(); + if (context == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Context is invalid."); + return; + } + + auto contextConfig = context->GetConfiguration(); + if (contextConfig == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Configuration is invalid."); + return; + } + + TAG_LOGD(AAFwkTag::UISERVC_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::UISERVC_EXT, "Config dump after update: %{public}s", contextConfig->GetName().c_str()); + + if (configChanged) { + auto jsUIServiceExtension = std::static_pointer_cast(shared_from_this()); + auto task = [jsUIServiceExtension]() { + if (jsUIServiceExtension) { + jsUIServiceExtension->ConfigurationUpdated(); + } + }; + if (handler_ != nullptr) { + handler_->PostTask(task, "JsServiceExtension:OnChange"); + } + } + + TAG_LOGD(AAFwkTag::UISERVC_EXT, "finished."); +} + +void JsUIServiceExtension::OnSceneWillCreated(std::shared_ptr extensionWindowConfig) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "OnSceneWillCreated call"); + HandleScope handleScope(jsRuntime_); + auto env = jsRuntime_.GetNapiEnv(); + auto jsExtensionWindowConfig = CreateJsExtensionWindowConfig(env, extensionWindowConfig); + if (jsExtensionWindowConfig == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Failed to create jsExtensionWindowConfig object."); + return; + } + napi_value argv[] = {jsExtensionWindowConfig}; + CallObjectMethod("onWindowWillCreate", argv, ArraySize(argv)); + TAG_LOGI(AAFwkTag::UISERVC_EXT, "End OnSceneWillCreated."); +} + +void JsUIServiceExtension::OnSceneDidCreated(sptr& window) +{ + TAG_LOGI(AAFwkTag::UISERVC_EXT, "OnSceneDidCreated call"); + HandleScope handleScope(jsRuntime_); + auto env = jsRuntime_.GetNapiEnv(); + napi_value jsWindow = Rosen::CreateJsWindowObject(env, window); + napi_value argv[] = {jsWindow}; + CallObjectMethod("onWindowDidCreate", argv, ArraySize(argv)); + TAG_LOGI(AAFwkTag::UISERVC_EXT, "End OnSceneDidCreated."); +} +#endif +} +} // OHOS diff --git a/frameworks/native/ability/native/ui_service_extension_ability/js_ui_service_extension_context.cpp b/frameworks/native/ability/native/ui_service_extension_ability/js_ui_service_extension_context.cpp new file mode 100644 index 0000000000..63ae5a8bc0 --- /dev/null +++ b/frameworks/native/ability/native/ui_service_extension_ability/js_ui_service_extension_context.cpp @@ -0,0 +1,246 @@ +/* + * 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 "js_ui_service_extension_context.h" + +#include +#include + +#include "ability_manager_client.h" +#include "ability_runtime/js_caller_complex.h" +#include "ui_service_extension.h" +#include "hilog_tag_wrapper.h" +#include "js_extension_context.h" +#include "js_error_utils.h" +#include "js_data_struct_converter.h" +#include "js_runtime.h" +#include "js_runtime_utils.h" +#include "napi/native_api.h" +#include "napi_common_ability.h" +#include "napi_common_want.h" +#include "napi_common_util.h" +#include "napi_remote_object.h" +#include "napi_common_start_options.h" +#include "start_options.h" +#include "hitrace_meter.h" +#include "js_free_install_observer.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr int32_t INDEX_ZERO = 0; +constexpr int32_t INDEX_ONE = 1; +constexpr int32_t INDEX_TWO = 2; +constexpr int32_t ERROR_CODE_ONE = 1; +constexpr size_t ARGC_ZERO = 0; +constexpr size_t ARGC_ONE = 1; +constexpr size_t ARGC_THREE = 3; + +class JSUIServiceExtensionContext final { +public: + explicit JSUIServiceExtensionContext( + const std::shared_ptr& context) : context_(context) {} + ~JSUIServiceExtensionContext() = default; + + static void Finalizer(napi_env env, void* data, void* hint) + { + TAG_LOGD(AAFwkTag::UISERVC_EXT, "JsAbilityContext::Finalizer is called"); + std::unique_ptr(static_cast(data)); + } + + static napi_value StartAbility(napi_env env, napi_callback_info info) + { + GET_NAPI_INFO_AND_CALL(env, info, JSUIServiceExtensionContext, OnStartAbility); + } + + static napi_value TerminateSelf(napi_env env, napi_callback_info info) + { + GET_NAPI_INFO_AND_CALL(env, info, JSUIServiceExtensionContext, OnTerminateSelf); + } + + static napi_value StartAbilityByType(napi_env env, napi_callback_info info) + { + GET_NAPI_INFO_AND_CALL(env, info, JSUIServiceExtensionContext, OnStartAbilityByType); + } +private: + std::weak_ptr context_; + + napi_value OnStartAbility(napi_env env, NapiCallbackInfo& info) + { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + TAG_LOGI(AAFwkTag::UISERVC_EXT, "Call"); + if (info.argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "Start ability failed, not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + + size_t unwrapArgc = 0; + AAFwk::Want want; + AAFwk::StartOptions startOptions; + if (!CheckStartAbilityInputParam(env, info, want, startOptions, unwrapArgc)) { + ThrowInvalidParamError(env, "Parse param want failed, want must be Want."); + return CreateJsUndefined(env); + } + + NapiAsyncTask::CompleteCallback complete = + [weak = context_, want, startOptions, unwrapArgc](napi_env env, NapiAsyncTask& task, int32_t status) { + TAG_LOGD(AAFwkTag::UI_EXT, "JSUIServiceExtensionContext OnStartAbility"); + auto context = weak.lock(); + if (!context) { + TAG_LOGE(AAFwkTag::UI_EXT, "JSUIServiceExtensionContext context is released"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT)); + return; + } + + ErrCode innerErrorCode = ERR_OK; + innerErrorCode = context->StartAbility(want, startOptions); + if (innerErrorCode == 0) { + task.ResolveWithNoError(env, CreateJsUndefined(env)); + } else { + task.Reject(env, CreateJsErrorByNativeErr(env, innerErrorCode)); + } + }; + + napi_value lastParam = nullptr; + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("JSUIServiceExtensionContext OnStartAbility", + env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + return result; +} + + bool CheckStartAbilityInputParam(napi_env env, NapiCallbackInfo& info, + AAFwk::Want& want, AAFwk::StartOptions& startOptions, size_t& unwrapArgc) const + { + if (info.argc < ARGC_ONE) { + return false; + } + unwrapArgc = ARGC_ZERO; + // Check input want + if (!AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want)) { + return false; + } + ++unwrapArgc; + if (info.argc > ARGC_ONE && CheckTypeForNapiValue(env, info.argv[1], napi_object)) { + TAG_LOGD(AAFwkTag::UISERVC_EXT, "OnStartAbility start options is used."); + AppExecFwk::UnwrapStartOptions(env, info.argv[1], startOptions); + unwrapArgc++; + } + return true; + } + + napi_value OnTerminateSelf(napi_env env, NapiCallbackInfo& info) + { + TAG_LOGI(AAFwkTag::UISERVC_EXT, "Call"); + + NapiAsyncTask::CompleteCallback complete = + [weak = context_](napi_env env, NapiAsyncTask& task, int32_t status) { + auto context = weak.lock(); + if (!context) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "context is released"); + task.Reject(env, CreateJsError(env, ERROR_CODE_ONE, "Context is released")); + return; + } + + TAG_LOGD(AAFwkTag::UISERVC_EXT, "JSUIServiceExtensionContext OnTerminateSelf"); + ErrCode innerErrorCode = context->TerminateSelf(); + if (innerErrorCode == 0) { + task.Resolve(env, CreateJsUndefined(env)); + } else { + task.Reject(env, CreateJsErrorByNativeErr(env, innerErrorCode)); + } + }; + + napi_value lastParam = nullptr; + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("JSUIServiceExtensionContext::OnTerminateSelf", + env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + napi_value OnStartAbilityByType(napi_env env, NapiCallbackInfo& info) + { + TAG_LOGI(AAFwkTag::UISERVC_EXT, "Call"); + if (info.argc < ARGC_THREE) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "OnStartAbilityByType, Not enough params"); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + + std::string type; + if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], type)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "OnStartAbilityByType, parse type failed."); + ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + return CreateJsUndefined(env); + } + + AAFwk::WantParams wantParam; + if (!AppExecFwk::UnwrapWantParams(env, info.argv[INDEX_ONE], wantParam)) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "OnStartAbilityByType, parse wantParam failed."); + ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + return CreateJsUndefined(env); + } + + std::shared_ptr callback = std::make_shared(env); + callback->SetJsCallbackObject(info.argv[INDEX_TWO]); + NapiAsyncTask::CompleteCallback complete = + [weak = context_, type, wantParam, callback](napi_env env, NapiAsyncTask& task, int32_t status) mutable { + auto context = weak.lock(); + if (!context) { + TAG_LOGW(AAFwkTag::UISERVC_EXT, "OnStartAbilityByType context is released"); + task.Reject(env, CreateJsError(env, AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT)); + return; + } + + TAG_LOGD(AAFwkTag::UISERVC_EXT, "JSUIServiceExtensionContext OnStartAbilityByType"); + auto errcode = context->StartAbilityByType(type, wantParam, callback); + if (errcode != 0) { + task.Reject(env, CreateJsErrorByNativeErr(env, errcode)); + } else { + task.ResolveWithNoError(env, CreateJsUndefined(env)); + } + }; + + napi_value lastParam = nullptr; + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("JSUIServiceExtensionContext::OnStartAbilityByType", + env, CreateAsyncTaskWithLastParam(env, lastParam, nullptr, std::move(complete), &result)); + return result; + } +}; +} // namespace + +napi_value CreateJsUIServiceExtensionContext(napi_env env, std::shared_ptr context) +{ + TAG_LOGD(AAFwkTag::UISERVC_EXT, "Call"); + std::shared_ptr abilityInfo = nullptr; + if (context) { + abilityInfo = context->GetAbilityInfo(); + } + napi_value object = CreateJsExtensionContext(env, context, abilityInfo); + + std::unique_ptr jsUIContext = + std::make_unique(context); + napi_wrap(env, object, jsUIContext.release(), JSUIServiceExtensionContext::Finalizer, nullptr, nullptr); + + const char *moduleName = "JsUIServiceExtensionContext"; + BindNativeFunction(env, object, "startAbility", moduleName, JSUIServiceExtensionContext::StartAbility); + BindNativeFunction(env, object, "terminateSelf", moduleName, JSUIServiceExtensionContext::TerminateSelf); + BindNativeFunction(env, object, "startAbilityByType", moduleName, + JSUIServiceExtensionContext::StartAbilityByType); + return object; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/ability/native/ui_service_extension_ability/ui_service_extension.cpp b/frameworks/native/ability/native/ui_service_extension_ability/ui_service_extension.cpp new file mode 100644 index 0000000000..a3d61e17b9 --- /dev/null +++ b/frameworks/native/ability/native/ui_service_extension_ability/ui_service_extension.cpp @@ -0,0 +1,116 @@ +/* + * 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 "ui_service_extension.h" + +#include +#include + +#include "hilog_tag_wrapper.h" +#include "hitrace_meter.h" +#include "ability_delegator_registry.h" +#include "napi_common_util.h" +#include "runtime.h" +#include "js_runtime_utils.h" +#include "js_ui_service_extension.h" +#include "napi_common_configuration.h" +#include "napi_common_want.h" +#include "napi_remote_object.h" +#include "ui_service_extension_context.h" +#include "time_util.h" + + +namespace OHOS { +namespace AbilityRuntime { +using namespace OHOS::AppExecFwk; + +UIServiceExtension* UIServiceExtension::Create(const std::unique_ptr& runtime) +{ + if (!runtime) { + return new UIServiceExtension(); + } + TAG_LOGD(AAFwkTag::UISERVC_EXT, "UIServiceExtension Create runtime"); + switch (runtime->GetLanguage()) { + case Runtime::Language::JS: + return JsUIServiceExtension::Create(runtime); + + default: + return new UIServiceExtension(); + } +} + +void UIServiceExtension::Init(const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) +{ + TAG_LOGD(AAFwkTag::UISERVC_EXT, "UIExtension begin init"); + ExtensionBase::Init(record, application, handler, token); +} + +std::shared_ptr UIServiceExtension::CreateAndInitContext( + const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) +{ + std::shared_ptr context = + ExtensionBase::CreateAndInitContext(record, application, handler, token); + if (context == nullptr) { + TAG_LOGE(AAFwkTag::UISERVC_EXT, "UIServiceExtension CreateAndInitContext context is nullptr"); + return context; + } + return context; +} + +#ifdef SUPPORT_GRAPHICS +sptr UIServiceExtension::GetWindowOption(const AAFwk::Want &want, + const std::shared_ptr< Rosen::ExtensionWindowConfig>& extensionWindowConfig, + const sptr& sessionInfo) +{ + auto option = sptr::MakeSptr(); + if (option == nullptr) { + TAG_LOGE(AAFwkTag::UIABILITY, "Option is null."); + return nullptr; + } + if (extensionWindowConfig->windowAttribute == Rosen::ExtensionWindowAttribute::SUB_WINDOW) { + option->SetWindowType(Rosen::WindowType::WINDOW_TYPE_APP_SUB_WINDOW); + option->SetParentId(sessionInfo->hostWindowId); + option->SetExtensionTag(true); + option->SetSubWindowTitle(extensionWindowConfig->subWindowOptions.title); + option->SetSubWindowDecorEnable(extensionWindowConfig->subWindowOptions.decorEnabled); + if (extensionWindowConfig->subWindowOptions.isModal) { + option->AddWindowFlag(Rosen::WindowFlag::WINDOW_FLAG_IS_MODAL); + if (extensionWindowConfig->subWindowOptions.isTopmost) { + option->SetWindowTopmost(true); + } + } + } else if (extensionWindowConfig->windowAttribute == Rosen::ExtensionWindowAttribute::SYSTEM_WINDOW) { + Rosen::WindowType winType; + if (Rosen::ParseSystemWindowTypeForApiWindowType( + extensionWindowConfig->systemWindowOptions.windowType, winType)) { + option->SetWindowType(winType); + } else { + TAG_LOGE(AAFwkTag::UIABILITY, "ParseSystemWindowTypeForApiWindowType error"); + return nullptr; + } + } + option->SetWindowMode(Rosen::WindowMode::WINDOW_MODE_FLOATING); + option->SetWindowRect(extensionWindowConfig->windowRect); + return option; +} +#endif +} +} diff --git a/frameworks/native/ability/native/ui_service_extension_ability/ui_service_extension_module_loader.cpp b/frameworks/native/ability/native/ui_service_extension_ability/ui_service_extension_module_loader.cpp new file mode 100644 index 0000000000..780dfa010a --- /dev/null +++ b/frameworks/native/ability/native/ui_service_extension_ability/ui_service_extension_module_loader.cpp @@ -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. + */ + +#include "ui_service_extension_module_loader.h" +#include "ui_service_extension.h" + +namespace OHOS::AbilityRuntime { +UIServiceExtensionModuleLoader::UIServiceExtensionModuleLoader() = default; +UIServiceExtensionModuleLoader::~UIServiceExtensionModuleLoader() = default; + +Extension *UIServiceExtensionModuleLoader::Create(const std::unique_ptr& runtime) const +{ + return UIServiceExtension::Create(runtime); +} + +std::map UIServiceExtensionModuleLoader::GetParams() +{ + std::map params; + // type means extension type in ExtensionAbilityType of extension_ability_info.h, 269 means uiService. + params.insert(std::pair("type", "269")); + // extension name + params.insert(std::pair("name", "UIServiceExtensionAbility")); + return params; +} + +extern "C" __attribute__((visibility("default"))) void* OHOS_EXTENSION_GetExtensionModule() +{ + return &UIServiceExtensionModuleLoader::GetInstance(); +} +} // namespace OHOS::AbilityRuntime diff --git a/frameworks/native/appkit/BUILD.gn b/frameworks/native/appkit/BUILD.gn index 3e8fef309b..0dd3de6410 100644 --- a/frameworks/native/appkit/BUILD.gn +++ b/frameworks/native/appkit/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") import("//build/templates/abc/ohos_abc.gni") import("//commonlibrary/memory_utils/purgeable_mem_config.gni") @@ -120,6 +120,7 @@ ohos_shared_library("appkit_native") { "${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/dump_runtime_helper.cpp", "${ability_runtime_native_path}/appkit/app/extension_plugin_info.cpp", "${ability_runtime_native_path}/appkit/app/idle_time.cpp", "${ability_runtime_native_path}/appkit/app/main_thread.cpp", @@ -171,10 +172,12 @@ ohos_shared_library("appkit_native") { "ability_base:extractresourcemanager", "ability_base:string_utils", "ability_base:want", + "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "ets_runtime:libark_jsruntime", "eventhandler:libeventhandler", "faultloggerd:libbacktrace_local", "faultloggerd:libdfx_procinfo", @@ -239,11 +242,6 @@ ohos_shared_library("appkit_native") { defines += [ "CJ_FRONTEND" ] - deps += [ - "${ability_runtime_path}/cj_environment/frameworks/cj_environment:cj_environment", - "${ability_runtime_path}/frameworks/cj/ffi:cj_ability_ffi", - ] - external_deps += [ "bundle_framework:appexecfwk_base", "napi:cj_bind_ffi", @@ -275,6 +273,7 @@ ohos_shared_library("app_context") { sources = [ "${ability_runtime_native_path}/appkit/ability_runtime/context/ability_lifecycle_callback.cpp", + "${ability_runtime_native_path}/appkit/ability_runtime/context/ability_stage_context.cpp", "${ability_runtime_native_path}/appkit/ability_runtime/context/application_context.cpp", "${ability_runtime_native_path}/appkit/ability_runtime/context/application_state_change_callback.cpp", "${ability_runtime_native_path}/appkit/ability_runtime/context/context_impl.cpp", @@ -298,7 +297,6 @@ ohos_shared_library("app_context") { external_deps = [ "ability_base:extractortool", "ability_base:session_info", - "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", @@ -314,6 +312,7 @@ ohos_shared_library("app_context") { public_external_deps = [ "ability_base:configuration", "ability_base:want", + "bundle_framework:appexecfwk_base", ] if (ability_runtime_graphics) { @@ -453,6 +452,9 @@ ohos_shared_library("appkit_delegator") { "${ability_runtime_native_path}/appkit/ability_delegator/runner_runtime/cj_test_runner_object.cpp", ] + include_dirs += + [ "${ability_runtime_path}/cj_environment/interfaces/inner_api" ] + defines = [ "CJ_FRONTEND" ] } if (ability_runtime_graphics) { 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 ac21209083..5871f802d0 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 @@ -18,7 +18,6 @@ #include "bundle_mgr_service_death_recipient.h" #include "global_constant.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "iservice_registry.h" #include "system_ability_definition.h" @@ -36,7 +35,7 @@ BundleMgrHelper::~BundleMgrHelper() ErrCode BundleMgrHelper::GetNameForUid(const int32_t uid, std::string &name) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -50,7 +49,7 @@ ErrCode BundleMgrHelper::GetNameForUid(const int32_t uid, std::string &name) bool BundleMgrHelper::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -64,7 +63,7 @@ bool BundleMgrHelper::GetBundleInfo(const std::string &bundleName, const BundleF ErrCode BundleMgrHelper::InstallSandboxApp(const std::string &bundleName, int32_t dlpType, int32_t userId, int32_t &appIndex) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); if (bundleName.empty()) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "The bundleName is empty."); return ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR; @@ -81,7 +80,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."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); 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; @@ -98,7 +97,7 @@ ErrCode BundleMgrHelper::UninstallSandboxApp(const std::string &bundleName, int3 ErrCode BundleMgrHelper::GetUninstalledBundleInfo(const std::string bundleName, BundleInfo &bundleInfo) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -112,7 +111,7 @@ ErrCode BundleMgrHelper::GetUninstalledBundleInfo(const std::string bundleName, ErrCode BundleMgrHelper::GetSandboxBundleInfo( const std::string &bundleName, int32_t appIndex, int32_t userId, BundleInfo &info) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); 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 +129,7 @@ ErrCode BundleMgrHelper::GetSandboxBundleInfo( ErrCode BundleMgrHelper::GetSandboxAbilityInfo(const Want &want, int32_t appIndex, int32_t flags, int32_t userId, AbilityInfo &abilityInfo) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); 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 +150,7 @@ ErrCode BundleMgrHelper::GetSandboxAbilityInfo(const Want &want, int32_t appInde ErrCode BundleMgrHelper::GetSandboxExtAbilityInfos(const Want &want, int32_t appIndex, int32_t flags, int32_t userId, std::vector &extensionInfos) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); 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 +168,7 @@ ErrCode BundleMgrHelper::GetSandboxExtAbilityInfos(const Want &want, int32_t app ErrCode BundleMgrHelper::GetSandboxHapModuleInfo(const AbilityInfo &abilityInfo, int32_t appIndex, int32_t userId, HapModuleInfo &hapModuleInfo) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); if (appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "The params are invalid."); return ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR; @@ -187,7 +186,7 @@ ErrCode BundleMgrHelper::GetSandboxHapModuleInfo(const AbilityInfo &abilityInfo, sptr BundleMgrHelper::Connect() { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); std::lock_guard lock(mutex_); if (bundleMgr_ == nullptr) { sptr systemAbilityManager = @@ -226,7 +225,7 @@ sptr BundleMgrHelper::Connect() sptr BundleMgrHelper::ConnectBundleInstaller() { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); { std::lock_guard lock(mutex_); if (bundleInstaller_ != nullptr) { @@ -252,7 +251,7 @@ sptr BundleMgrHelper::ConnectBundleInstaller() void BundleMgrHelper::OnDeath() { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); std::lock_guard lock(mutex_); if (bundleMgr_ == nullptr || bundleMgr_->AsObject() == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "bundleMgr_ is nullptr."); @@ -266,7 +265,7 @@ void BundleMgrHelper::OnDeath() bool BundleMgrHelper::GetBundleInfo(const std::string &bundleName, int32_t flags, BundleInfo &bundleInfo, int32_t userId) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -279,7 +278,7 @@ bool BundleMgrHelper::GetBundleInfo(const std::string &bundleName, int32_t flags bool BundleMgrHelper::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -292,7 +291,7 @@ bool BundleMgrHelper::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModule std::string BundleMgrHelper::GetAbilityLabel(const std::string &bundleName, const std::string &abilityName) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -305,7 +304,7 @@ std::string BundleMgrHelper::GetAbilityLabel(const std::string &bundleName, cons std::string BundleMgrHelper::GetAppType(const std::string &bundleName) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -320,7 +319,7 @@ ErrCode BundleMgrHelper::GetBaseSharedBundleInfos( const std::string &bundleName, std::vector &baseSharedBundleInfos, GetDependentBundleInfoFlag flag) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -333,7 +332,7 @@ ErrCode BundleMgrHelper::GetBaseSharedBundleInfos( ErrCode BundleMgrHelper::GetBundleInfoForSelf(int32_t flags, BundleInfo &bundleInfo) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -347,7 +346,7 @@ ErrCode BundleMgrHelper::GetBundleInfoForSelf(int32_t flags, BundleInfo &bundleI ErrCode BundleMgrHelper::GetDependentBundleInfo(const std::string &sharedBundleName, BundleInfo &sharedBundleInfo, GetDependentBundleInfoFlag flag) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -360,7 +359,7 @@ ErrCode BundleMgrHelper::GetDependentBundleInfo(const std::string &sharedBundleN bool BundleMgrHelper::GetGroupDir(const std::string &dataGroupId, std::string &dir) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -373,7 +372,7 @@ bool BundleMgrHelper::GetGroupDir(const std::string &dataGroupId, std::string &d sptr BundleMgrHelper::GetOverlayManagerProxy() { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -386,7 +385,7 @@ sptr BundleMgrHelper::GetOverlayManagerProxy() bool BundleMgrHelper::QueryAbilityInfo(const Want &want, AbilityInfo &abilityInfo) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -401,7 +400,7 @@ bool BundleMgrHelper::QueryAbilityInfo(const Want &want, AbilityInfo &abilityInf bool BundleMgrHelper::QueryAbilityInfo(const Want &want, int32_t flags, int32_t userId, AbilityInfo &abilityInfo) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -416,7 +415,7 @@ bool BundleMgrHelper::QueryAbilityInfo(const Want &want, int32_t flags, int32_t bool BundleMgrHelper::GetBundleInfos(int32_t flags, std::vector &bundleInfos, int32_t userId) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -429,7 +428,7 @@ bool BundleMgrHelper::GetBundleInfos(int32_t flags, std::vector &bun bool BundleMgrHelper::GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos, int32_t userId) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -442,7 +441,7 @@ bool BundleMgrHelper::GetBundleInfos(const BundleFlag flag, std::vector BundleMgrHelper::GetQuickFixManagerProxy() { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -455,7 +454,7 @@ sptr BundleMgrHelper::GetQuickFixManagerProxy() bool BundleMgrHelper::ProcessPreload(const Want &want) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -470,7 +469,7 @@ bool BundleMgrHelper::ProcessPreload(const Want &want) sptr BundleMgrHelper::GetAppControlProxy() { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -484,7 +483,7 @@ sptr BundleMgrHelper::GetAppControlProxy() bool BundleMgrHelper::QueryExtensionAbilityInfos(const Want &want, const int32_t &flag, const int32_t &userId, std::vector &extensionInfos) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -500,7 +499,7 @@ bool BundleMgrHelper::QueryExtensionAbilityInfos(const Want &want, const int32_t ErrCode BundleMgrHelper::GetBundleInfoV9( const std::string &bundleName, int32_t flags, BundleInfo &bundleInfo, int32_t userId) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -514,7 +513,7 @@ ErrCode BundleMgrHelper::GetBundleInfoV9( bool BundleMgrHelper::GetApplicationInfo( const std::string &appName, const ApplicationFlag flag, const int32_t userId, ApplicationInfo &appInfo) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -528,7 +527,7 @@ bool BundleMgrHelper::GetApplicationInfo( bool BundleMgrHelper::GetApplicationInfo( const std::string &appName, int32_t flags, int32_t userId, ApplicationInfo &appInfo) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -578,7 +577,7 @@ bool BundleMgrHelper::GetApplicationInfoWithAppIndex( bool BundleMgrHelper::UnregisterBundleEventCallback(const sptr &bundleEventCallback) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); if (bundleEventCallback == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "The bundleEventCallback is nullptr."); return false; @@ -597,7 +596,7 @@ bool BundleMgrHelper::UnregisterBundleEventCallback(const sptr &callBack) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -654,7 +653,7 @@ bool BundleMgrHelper::QueryAbilityInfo( void BundleMgrHelper::UpgradeAtomicService(const Want &want, int32_t userId) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -668,9 +667,9 @@ void BundleMgrHelper::UpgradeAtomicService(const Want &want, int32_t userId) } bool BundleMgrHelper::ImplicitQueryInfos(const Want &want, int32_t flags, int32_t userId, bool withDefault, - std::vector &abilityInfos, std::vector &extensionInfos) + std::vector &abilityInfos, std::vector &extensionInfos, bool &findDefaultApp) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -680,7 +679,6 @@ bool BundleMgrHelper::ImplicitQueryInfos(const Want &want, int32_t flags, int32_ AAFwk::Want newWant = want; newWant.RemoveAllFd(); HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - bool findDefaultApp = false; bool ret = bundleMgr->ImplicitQueryInfos(newWant, flags, userId, withDefault, abilityInfos, extensionInfos, findDefaultApp); TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "findDefaultApp is %{public}d.", findDefaultApp); @@ -689,7 +687,7 @@ bool BundleMgrHelper::ImplicitQueryInfos(const Want &want, int32_t flags, int32_ bool BundleMgrHelper::CleanBundleDataFiles(const std::string &bundleName, int32_t userId, int32_t appCloneIndex) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -703,7 +701,7 @@ bool BundleMgrHelper::CleanBundleDataFiles(const std::string &bundleName, int32_ bool BundleMgrHelper::QueryDataGroupInfos( const std::string &bundleName, int32_t userId, std::vector &infos) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -714,22 +712,9 @@ bool BundleMgrHelper::QueryDataGroupInfos( return bundleMgr->QueryDataGroupInfos(bundleName, userId, infos); } -bool BundleMgrHelper::GetBundleGidsByUid(const std::string &bundleName, const int32_t &uid, std::vector &gids) -{ - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); - auto bundleMgr = Connect(); - if (bundleMgr == nullptr) { - TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); - return false; - } - - HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - return bundleMgr->GetBundleGidsByUid(bundleName, uid, gids); -} - bool BundleMgrHelper::RegisterBundleEventCallback(const sptr &bundleEventCallback) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); if (bundleEventCallback == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "The bundleEventCallback is nullptr."); return false; @@ -747,7 +732,7 @@ bool BundleMgrHelper::RegisterBundleEventCallback(const sptr &extensionInfos) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -800,7 +785,7 @@ ErrCode BundleMgrHelper::QueryExtensionAbilityInfosOnlyWithTypeName(const std::s sptr BundleMgrHelper::GetDefaultAppProxy() { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -814,7 +799,7 @@ sptr BundleMgrHelper::GetDefaultAppProxy() ErrCode BundleMgrHelper::GetJsonProfile(ProfileType profileType, const std::string &bundleName, const std::string &moduleName, std::string &profile, int32_t userId) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -827,7 +812,7 @@ ErrCode BundleMgrHelper::GetJsonProfile(ProfileType profileType, const std::stri ErrCode BundleMgrHelper::GetLaunchWantForBundle(const std::string &bundleName, Want &want, int32_t userId) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -842,7 +827,7 @@ ErrCode BundleMgrHelper::GetLaunchWantForBundle(const std::string &bundleName, W ErrCode BundleMgrHelper::QueryCloneAbilityInfo(const ElementName &element, int32_t flags, int32_t appCloneIndex, AbilityInfo &abilityInfo, int32_t userId) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -856,7 +841,7 @@ ErrCode BundleMgrHelper::QueryCloneAbilityInfo(const ElementName &element, int32 ErrCode BundleMgrHelper::GetCloneBundleInfo(const std::string &bundleName, int32_t flags, int32_t appCloneIndex, BundleInfo &bundleInfo, int32_t userId) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -870,7 +855,7 @@ ErrCode BundleMgrHelper::GetCloneBundleInfo(const std::string &bundleName, int32 ErrCode BundleMgrHelper::QueryCloneExtensionAbilityInfoWithAppIndex(const ElementName &element, int32_t flags, int32_t appCloneIndex, ExtensionAbilityInfo &extensionInfo, int32_t userId) { - TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); + TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "called"); auto bundleMgr = Connect(); if (bundleMgr == nullptr) { TAG_LOGE(AAFwkTag::BUNDLEMGRHELPER, "Failed to connect."); @@ -881,5 +866,19 @@ ErrCode BundleMgrHelper::QueryCloneExtensionAbilityInfoWithAppIndex(const Elemen return bundleMgr->QueryCloneExtensionAbilityInfoWithAppIndex(element, flags, appCloneIndex, extensionInfo, userId); } +ErrCode BundleMgrHelper::GetCloneAppIndexes(const std::string &bundleName, std::vector &appIndexes, + 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; + } + + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + return bundleMgr->GetCloneAppIndexes(bundleName, appIndexes, userId); +} + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/appkit/ability_delegator/ability_delegator.cpp b/frameworks/native/appkit/ability_delegator/ability_delegator.cpp index dccebff688..ac7c433e22 100644 --- a/frameworks/native/appkit/ability_delegator/ability_delegator.cpp +++ b/frameworks/native/appkit/ability_delegator/ability_delegator.cpp @@ -16,7 +16,6 @@ #include "ability_delegator.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ohos_application.h" #include "ability_manager_client.h" #include "ability_delegator_registry.h" diff --git a/frameworks/native/appkit/ability_delegator/delegator_thread.cpp b/frameworks/native/appkit/ability_delegator/delegator_thread.cpp index 521403d6ff..0728b655da 100644 --- a/frameworks/native/appkit/ability_delegator/delegator_thread.cpp +++ b/frameworks/native/appkit/ability_delegator/delegator_thread.cpp @@ -15,7 +15,6 @@ #include "delegator_thread.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/appkit/ability_delegator/iability_monitor.cpp b/frameworks/native/appkit/ability_delegator/iability_monitor.cpp index b9cfe2d15a..0690980603 100644 --- a/frameworks/native/appkit/ability_delegator/iability_monitor.cpp +++ b/frameworks/native/appkit/ability_delegator/iability_monitor.cpp @@ -14,7 +14,6 @@ */ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iability_monitor.h" using namespace std::chrono_literals; diff --git a/frameworks/native/appkit/ability_delegator/iability_stage_monitor.cpp b/frameworks/native/appkit/ability_delegator/iability_stage_monitor.cpp index 232784f26b..9f21501c50 100644 --- a/frameworks/native/appkit/ability_delegator/iability_stage_monitor.cpp +++ b/frameworks/native/appkit/ability_delegator/iability_stage_monitor.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iability_stage_monitor.h" namespace OHOS { 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 index 2033a5f95f..59478ab38a 100644 --- a/frameworks/native/appkit/ability_delegator/runner_runtime/cj_test_runner.cpp +++ b/frameworks/native/appkit/ability_delegator/runner_runtime/cj_test_runner.cpp @@ -18,7 +18,7 @@ #include #include "ability_delegator_registry.h" -#include "hilog_wrapper.h" +#include "hilog_tag_wrapper.h" #include "runner_runtime/cj_test_runner_object.h" namespace OHOS { @@ -27,26 +27,26 @@ 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."); + TAG_LOGI(AAFwkTag::DELEGATOR, "CJTestRunner::Create start."); if (!runtime) { - HILOG_ERROR("Invalid runtime"); + TAG_LOGE(AAFwkTag::DELEGATOR, "Invalid runtime"); return nullptr; } auto cjRuntime = static_cast(runtime.get()); if (!cjRuntime->IsAppLibLoaded()) { - HILOG_ERROR("CJTestRunner: AppLib Not Loaded"); + TAG_LOGE(AAFwkTag::DELEGATOR, "CJTestRunner: AppLib Not Loaded"); return nullptr; } if (!args) { - HILOG_ERROR("Invalid ability delegator args"); + TAG_LOGE(AAFwkTag::DELEGATOR, "Invalid ability delegator args"); return nullptr; } auto pTestRunner = new (std::nothrow) CJTestRunner(*cjRuntime, args, bundleInfo); if (!pTestRunner) { - HILOG_ERROR("Failed to create test runner"); + TAG_LOGE(AAFwkTag::DELEGATOR, "Failed to create test runner"); return nullptr; } @@ -65,11 +65,11 @@ CJTestRunner::~CJTestRunner() = default; bool CJTestRunner::Initialize() { if (!cjRuntime_.IsAppLibLoaded()) { - HILOG_ERROR("CJTestRunner: AppLib Not Loaded"); + TAG_LOGE(AAFwkTag::DELEGATOR, "CJTestRunner: AppLib Not Loaded"); return false; } if (!cjTestRunnerObj_) { - HILOG_ERROR("CJTestRunnerObj does not exist, Initialize failed."); + TAG_LOGE(AAFwkTag::DELEGATOR, "CJTestRunnerObj does not exist, Initialize failed."); return false; } return true; @@ -77,34 +77,34 @@ bool CJTestRunner::Initialize() void CJTestRunner::Prepare() { - HILOG_INFO("Enter"); + TAG_LOGI(AAFwkTag::DELEGATOR, "Enter"); TestRunner::Prepare(); if (!cjTestRunnerObj_) { - HILOG_ERROR("CJTestRunnerObj does not exist, Prepare failed."); + TAG_LOGE(AAFwkTag::DELEGATOR, "CJTestRunnerObj does not exist, Prepare failed."); return; } cjTestRunnerObj_->OnPrepare(); - HILOG_INFO("End"); + TAG_LOGI(AAFwkTag::DELEGATOR, "End"); } void CJTestRunner::Run() { - HILOG_INFO("Enter"); + TAG_LOGI(AAFwkTag::DELEGATOR, "Enter"); TestRunner::Run(); if (!cjTestRunnerObj_) { - HILOG_ERROR("CJTestRunnerObj does not exist, OnRun failed."); + TAG_LOGE(AAFwkTag::DELEGATOR, "CJTestRunnerObj does not exist, OnRun failed."); return; } cjTestRunnerObj_->OnRun(); - HILOG_INFO("End"); + TAG_LOGI(AAFwkTag::DELEGATOR, "End"); } void CJTestRunner::ReportFinished(const std::string &msg) { - HILOG_INFO("Enter"); + TAG_LOGI(AAFwkTag::DELEGATOR, "Enter"); auto delegator = AbilityDelegatorRegistry::GetAbilityDelegator(); if (!delegator) { - HILOG_ERROR("delegator is null."); + TAG_LOGE(AAFwkTag::DELEGATOR, "delegator is null."); return; } @@ -113,10 +113,10 @@ void CJTestRunner::ReportFinished(const std::string &msg) void CJTestRunner::ReportStatus(const std::string &msg) { - HILOG_INFO("Enter"); + TAG_LOGI(AAFwkTag::DELEGATOR, "Enter"); auto delegator = AbilityDelegatorRegistry::GetAbilityDelegator(); if (!delegator) { - HILOG_ERROR("delegator is null."); + TAG_LOGE(AAFwkTag::DELEGATOR, "delegator is null."); return; } 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 index 68ea89ca09..b3fc0acc42 100644 --- 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 @@ -17,7 +17,7 @@ #include -#include "hilog_wrapper.h" +#include "hilog_tag_wrapper.h" namespace { // g_cjTestRunnerFuncs is used to save cj functions. @@ -28,20 +28,20 @@ CJTestRunnerFuncs* g_cjTestRunnerFuncs = nullptr; void RegisterCJTestRunnerFuncs(void (*registerFunc)(CJTestRunnerFuncs*)) { - HILOG_INFO("RegisterCJTestRunnerFuncs start."); + TAG_LOGI(AAFwkTag::DELEGATOR, "RegisterCJTestRunnerFuncs start."); if (g_cjTestRunnerFuncs != nullptr) { - HILOG_ERROR("Repeated registration for cj functions of CJTestRunner."); + TAG_LOGE(AAFwkTag::DELEGATOR, "Repeated registration for cj functions of CJTestRunner."); return; } if (registerFunc == nullptr) { - HILOG_ERROR("RegisterCJTestRunnerFuncs failed, registerFunc is nullptr."); + TAG_LOGE(AAFwkTag::DELEGATOR, "RegisterCJTestRunnerFuncs failed, registerFunc is nullptr."); return; } g_cjTestRunnerFuncs = new CJTestRunnerFuncs(); registerFunc(g_cjTestRunnerFuncs); - HILOG_INFO("RegisterCJTestRunnerFuncs end."); + TAG_LOGI(AAFwkTag::DELEGATOR, "RegisterCJTestRunnerFuncs end."); } namespace OHOS { @@ -49,12 +49,12 @@ namespace RunnerRuntime { std::shared_ptr CJTestRunnerObject::LoadModule(const std::string& name) { if (g_cjTestRunnerFuncs == nullptr) { - HILOG_ERROR("cj functions for CJTestRunner are not registered"); + TAG_LOGE(AAFwkTag::DELEGATOR, "cj functions for CJTestRunner are not registered"); return nullptr; } auto id = g_cjTestRunnerFuncs->cjTestRunnerCreate(name.c_str()); if (id == 0) { - HILOG_ERROR( + TAG_LOGE(AAFwkTag::DELEGATOR, "Failed to invoke CJTestRunnerObject::LoadModule. Ability: %{public}s is not registered.", name.c_str()); return nullptr; } @@ -70,7 +70,7 @@ CJTestRunnerObject::~CJTestRunnerObject() void CJTestRunnerObject::OnRun() const { if (g_cjTestRunnerFuncs == nullptr) { - HILOG_ERROR("cj functions for CJTestRunner are not registered"); + TAG_LOGE(AAFwkTag::DELEGATOR, "cj functions for CJTestRunner are not registered"); return; } g_cjTestRunnerFuncs->cjTestRunnerOnRun(id_); @@ -79,7 +79,7 @@ void CJTestRunnerObject::OnRun() const void CJTestRunnerObject::OnPrepare() const { if (g_cjTestRunnerFuncs == nullptr) { - HILOG_ERROR("cj functions for CJTestRunner are not registered"); + TAG_LOGE(AAFwkTag::DELEGATOR, "cj functions for CJTestRunner are not registered"); return; } g_cjTestRunnerFuncs->cjTestRunnerOnPrepare(id_); diff --git a/frameworks/native/appkit/ability_delegator/runner_runtime/js_test_runner.cpp b/frameworks/native/appkit/ability_delegator/runner_runtime/js_test_runner.cpp index 9fe6c1ff5c..1a5566fe55 100644 --- a/frameworks/native/appkit/ability_delegator/runner_runtime/js_test_runner.cpp +++ b/frameworks/native/appkit/ability_delegator/runner_runtime/js_test_runner.cpp @@ -17,7 +17,6 @@ #include "ability_delegator_registry.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" #include "runner_runtime/js_test_runner.h" diff --git a/frameworks/native/appkit/ability_delegator/test_runner.cpp b/frameworks/native/appkit/ability_delegator/test_runner.cpp index 8f02aa5f12..7b3c637542 100644 --- a/frameworks/native/appkit/ability_delegator/test_runner.cpp +++ b/frameworks/native/appkit/ability_delegator/test_runner.cpp @@ -16,7 +16,6 @@ #include "bundle_mgr_helper.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #ifdef CJ_FRONTEND #include "runner_runtime/cj_test_runner.h" #endif diff --git a/frameworks/native/appkit/ability_runtime/app/ability_stage.cpp b/frameworks/native/appkit/ability_runtime/app/ability_stage.cpp index 197e6849b1..988f93da79 100644 --- a/frameworks/native/appkit/ability_runtime/app/ability_stage.cpp +++ b/frameworks/native/appkit/ability_runtime/app/ability_stage.cpp @@ -17,7 +17,6 @@ #include "ability_runtime/context/context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #ifdef CJ_FRONTEND #include "cj_ability_stage.h" diff --git a/frameworks/native/appkit/ability_runtime/app/cj_ability_stage.cpp b/frameworks/native/appkit/ability_runtime/app/cj_ability_stage.cpp index d5b269c86f..9eca40a43d 100644 --- a/frameworks/native/appkit/ability_runtime/app/cj_ability_stage.cpp +++ b/frameworks/native/appkit/ability_runtime/app/cj_ability_stage.cpp @@ -16,13 +16,33 @@ #include "cj_ability_stage.h" #include "cj_ability_stage_context.h" #include "cj_runtime.h" -#include "cj_utils_ffi.h" #include "context_impl.h" -#include "hilog_wrapper.h" #include "hilog_tag_wrapper.h" - +#include "securec.h" using namespace OHOS::AbilityRuntime; + +namespace { +char* CreateCStringFromString(const std::string& source) +{ + if (source.size() == 0) { + return nullptr; + } + size_t length = source.size() + 1; + auto res = static_cast(malloc(length)); + if (res == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "fail to mallc string."); + return nullptr; + } + if (strcpy_s(res, length, source.c_str()) != 0) { + free(res); + TAG_LOGE(AAFwkTag::APPKIT, "fail to strcpy source."); + return nullptr; + } + return res; +} +} + extern "C" { CJ_EXPORT CurrentHapModuleInfo* FFICJCurrentHapModuleInfo(int64_t id) { @@ -80,34 +100,45 @@ std::shared_ptr CJAbilityStage::Create( const std::unique_ptr& runtime, const AppExecFwk::HapModuleInfo& hapModuleInfo) { if (!runtime) { - HILOG_ERROR("Runtime does not exist."); + TAG_LOGE(AAFwkTag::APPKIT, "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."); + TAG_LOGE(AAFwkTag::APPKIT, "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."); + TAG_LOGE(AAFwkTag::APPKIT, "Failed to create CJAbilityStage."); return nullptr; } return std::make_shared(cjAbilityStageObject); } +void CJAbilityStage::Init(const std::shared_ptr &context, + const std::weak_ptr application) +{ + AbilityStage::Init(context, application); + if (!cjAbilityStageObject_) { + TAG_LOGE(AAFwkTag::APPKIT, "Failed to create CJAbilityStage."); + return; + } + cjAbilityStageObject_->Init(this); +} + void CJAbilityStage::OnCreate(const AAFwk::Want& want) const { AbilityStage::OnCreate(want); if (!cjAbilityStageObject_) { - HILOG_ERROR("CJAbilityStage is not loaded."); + TAG_LOGE(AAFwkTag::APPKIT, "CJAbilityStage is not loaded."); return; } - HILOG_DEBUG("CJAbilityStage::OnCreate"); + TAG_LOGD(AAFwkTag::APPKIT, "CJAbilityStage::OnCreate"); cjAbilityStageObject_->OnCreate(); } @@ -115,7 +146,7 @@ std::string CJAbilityStage::OnAcceptWant(const AAFwk::Want& want) { AbilityStage::OnAcceptWant(want); if (!cjAbilityStageObject_) { - HILOG_ERROR("CJAbilityStage is not loaded."); + TAG_LOGE(AAFwkTag::APPKIT, "CJAbilityStage is not loaded."); return ""; } return cjAbilityStageObject_->OnAcceptWant(want); @@ -126,12 +157,12 @@ void CJAbilityStage::OnConfigurationUpdated(const AppExecFwk::Configuration& con AbilityStage::OnConfigurationUpdated(configuration); auto fullConfig = GetContext()->GetConfiguration(); if (!fullConfig) { - HILOG_ERROR("configuration is nullptr."); + TAG_LOGE(AAFwkTag::APPKIT, "configuration is nullptr."); return; } if (!cjAbilityStageObject_) { - HILOG_ERROR("CJAbilityStage is not loaded."); + TAG_LOGE(AAFwkTag::APPKIT, "CJAbilityStage is not loaded."); return; } cjAbilityStageObject_->OnConfigurationUpdated(fullConfig); @@ -141,7 +172,7 @@ void CJAbilityStage::OnMemoryLevel(int level) { AbilityStage::OnMemoryLevel(level); if (!cjAbilityStageObject_) { - HILOG_ERROR("CJAbilityStage is not loaded."); + TAG_LOGE(AAFwkTag::APPKIT, "CJAbilityStage is not loaded."); return; } cjAbilityStageObject_->OnMemoryLevel(level); diff --git a/frameworks/native/appkit/ability_runtime/app/cj_ability_stage_context.cpp b/frameworks/native/appkit/ability_runtime/app/cj_ability_stage_context.cpp index e89338a309..8e7f3a5134 100644 --- a/frameworks/native/appkit/ability_runtime/app/cj_ability_stage_context.cpp +++ b/frameworks/native/appkit/ability_runtime/app/cj_ability_stage_context.cpp @@ -18,7 +18,6 @@ #include "hap_module_info.h" #include "ability_runtime/context/context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { 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 index 3eb0669d0d..acd8d18d3e 100644 --- a/frameworks/native/appkit/ability_runtime/app/cj_ability_stage_object.cpp +++ b/frameworks/native/appkit/ability_runtime/app/cj_ability_stage_object.cpp @@ -15,7 +15,6 @@ #include "cj_ability_stage_object.h" -#include "hilog_wrapper.h" #include "hilog_tag_wrapper.h" using namespace OHOS::AbilityRuntime; @@ -67,6 +66,15 @@ CJAbilityStageObject::~CJAbilityStageObject() id_ = 0; } +void CJAbilityStageObject::Init(AbilityStageHandle abilityStage) const +{ + if (g_cjAbilityStageFuncs == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "cj functions for CJAbilityStage are not registered"); + return; + } + g_cjAbilityStageFuncs->AbilityStageInit(id_, abilityStage); +} + void CJAbilityStageObject::OnCreate() const { if (g_cjAbilityStageFuncs == nullptr) { 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 f9b4fb504a..4be33507d9 100644 --- a/frameworks/native/appkit/ability_runtime/app/js_ability_stage.cpp +++ b/frameworks/native/appkit/ability_runtime/app/js_ability_stage.cpp @@ -17,7 +17,6 @@ #include "ability_delegator_registry.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_ability_stage_context.h" #include "js_context_utils.h" #include "js_runtime.h" @@ -48,9 +47,9 @@ constexpr const char* EXCLUDE_FROM_AUTO_START = "excludeFromAutoStart"; 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_LOWER = "taskpool"; + napi_value AttachAbilityStageContext(napi_env env, void *value, void *) { TAG_LOGD(AAFwkTag::APPKIT, "AttachAbilityStageContext"); @@ -63,7 +62,7 @@ napi_value AttachAbilityStageContext(napi_env env, void *value, void *) TAG_LOGW(AAFwkTag::APPKIT, "invalid context."); return nullptr; } - napi_value object = CreateJsAbilityStageContext(env, ptr, nullptr, nullptr); + napi_value object = CreateJsAbilityStageContext(env, ptr); auto systemModule = JsRuntime::LoadSystemModuleByEngine(env, "application.AbilityStageContext", &object, 1); if (systemModule == nullptr) { TAG_LOGW(AAFwkTag::APPKIT, "invalid systemModule."); @@ -169,7 +168,7 @@ void JsAbilityStage::Init(const std::shared_ptr &context, TAG_LOGE(AAFwkTag::APPKIT, "stage is nullptr"); return; } - + SetJsAbilityStage(context); } @@ -415,12 +414,12 @@ int32_t JsAbilityStage::RegisterStartupTaskFromProfile(std::vector TAG_LOGE(AAFwkTag::APPKIT, "context is nullptr."); return false; } - + auto resMgr = context->GetResourceManager(); if (!resMgr) { TAG_LOGE(AAFwkTag::APPKIT, "resMgr is nullptr."); return false; } - + auto hapModuleInfo = context->GetHapModuleInfo(); if (!hapModuleInfo) { TAG_LOGE(AAFwkTag::APPKIT, "hapModuleInfo is nullptr."); return false; } - + jsRuntime_.UpdateModuleNameAndAssetPath(hapModuleInfo->moduleName); bool isCompressed = !hapModuleInfo->hapPath.empty(); std::string appStartup = hapModuleInfo->appStartup; @@ -452,7 +451,7 @@ bool JsAbilityStage::GetProfileInfoFromResourceManager(std::vector TAG_LOGE(AAFwkTag::APPKIT, "appStartup invalid."); return false; } - + GetResFromResMgr(appStartup, resMgr, isCompressed, profileInfo); if (profileInfo.empty()) { TAG_LOGE(AAFwkTag::APPKIT, "appStartup config not exist."); @@ -482,17 +481,17 @@ std::unique_ptr JsAbilityStage::LoadJsSrcEntry(const std::strin bool esmodule = hapModuleInfo->compileMode == AppExecFwk::CompileMode::ES_MODULE; std::string moduleName(hapModuleInfo->moduleName); std::string srcPath(moduleName + "/" + srcEntry); - + auto pos = srcPath.rfind('.'); if (pos == std::string::npos) { return nullptr; } srcPath.erase(pos); srcPath.append(".abc"); - + std::unique_ptr jsCode( jsRuntime_.LoadModule(moduleName, srcPath, hapModuleInfo->hapPath, esmodule)); - + return jsCode; } @@ -544,15 +543,13 @@ void JsAbilityStage::SetOptionalParameters( if (module.contains(RUN_ON_THREAD) && module[RUN_ON_THREAD].is_string()) { std::string profileName = module.at(RUN_ON_THREAD).get(); - if (profileName == MAIN_THREAD) { - jsStartupTask.SetCallCreateOnMainThread(true); - } else if (profileName == TASKPOOL) { + if (profileName == TASKPOOL || profileName == TASKPOOL_LOWER) { jsStartupTask.SetCallCreateOnMainThread(false); } else { - TAG_LOGW(AAFwkTag::APPKIT, "RunOnThread configuration is invalid."); + jsStartupTask.SetCallCreateOnMainThread(true); } } - + if (module.contains(WAIT_ON_MAIN_THREAD) && module[WAIT_ON_MAIN_THREAD].is_boolean()) { jsStartupTask.SetWaitOnMainThread(module.at(WAIT_ON_MAIN_THREAD).get()); } else { @@ -598,7 +595,7 @@ bool JsAbilityStage::AnalyzeProfileInfoAndRegisterStartupTask(const std::vector< TAG_LOGE(AAFwkTag::APPKIT, "Invalid module data."); return false; } - + std::unique_ptr startupJsRef = LoadJsSrcEntry(module.at(SRC_ENTRY).get()); if (startupJsRef == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "load js appStartup tasks failed."); @@ -730,7 +727,7 @@ bool JsAbilityStage::GetResFromResMgr( TAG_LOGE(AAFwkTag::APPKIT, "res name is empty."); return false; } - + size_t pos = resName.rfind(PROFILE_FILE_PREFIX); if ((pos == std::string::npos) || (pos == resName.length() - strlen(PROFILE_FILE_PREFIX))) { TAG_LOGE(AAFwkTag::APPKIT, "res name %{public}s is invalid.", resName.c_str()); @@ -781,10 +778,10 @@ void JsAbilityStage::SetJsAbilityStage(const std::shared_ptr &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(); @@ -793,8 +790,8 @@ void JsAbilityStage::SetJsAbilityStage(const std::shared_ptr &context) return; } } - - napi_value contextObj = CreateJsAbilityStageContext(env, context, nullptr, nullptr); + + napi_value contextObj = CreateJsAbilityStageContext(env, context); shellContextRef_ = JsRuntime::LoadSystemModuleByEngine(env, "application.AbilityStageContext", &contextObj, 1); if (shellContextRef_ == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "Failed to get LoadSystemModuleByEngine"); @@ -809,7 +806,7 @@ void JsAbilityStage::SetJsAbilityStage(const std::shared_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); } diff --git a/frameworks/native/appkit/ability_runtime/app/js_ability_stage_context.cpp b/frameworks/native/appkit/ability_runtime/app/js_ability_stage_context.cpp index 0c6dc28d79..860fac6fc0 100644 --- a/frameworks/native/appkit/ability_runtime/app/js_ability_stage_context.cpp +++ b/frameworks/native/appkit/ability_runtime/app/js_ability_stage_context.cpp @@ -17,7 +17,6 @@ #include "ability_runtime/context/context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_context_utils.h" #include "js_data_struct_converter.h" #include "js_runtime.h" @@ -52,8 +51,7 @@ void JsAbilityStageContext::ConfigurationUpdated(napi_env env, std::shared_ptr context, DetachCallback detach, NapiAttachCallback attach) +napi_value CreateJsAbilityStageContext(napi_env env, std::shared_ptr context) { TAG_LOGD(AAFwkTag::APPKIT, "called."); napi_value objValue = CreateJsBaseContext(env, context); diff --git a/frameworks/native/appkit/ability_runtime/context/ability_lifecycle_callback.cpp b/frameworks/native/appkit/ability_runtime/context/ability_lifecycle_callback.cpp index d01f096843..f6d0555ae5 100644 --- a/frameworks/native/appkit/ability_runtime/context/ability_lifecycle_callback.cpp +++ b/frameworks/native/appkit/ability_runtime/context/ability_lifecycle_callback.cpp @@ -16,7 +16,6 @@ #include "ability_lifecycle_callback.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" namespace OHOS { @@ -149,6 +148,33 @@ void JsAbilityLifecycleCallback::OnAbilityContinue(const std::shared_ptr &ability) +{ + CallJsMethod("onAbilityWillContinue", ability); +} + +void JsAbilityLifecycleCallback::OnWindowStageWillRestore(const std::shared_ptr &ability, + const std::shared_ptr &windowStage) +{ + CallWindowStageJsMethod("onWindowStageWillRestore", ability, windowStage); +} + +void JsAbilityLifecycleCallback::OnWindowStageRestore(const std::shared_ptr &ability, + const std::shared_ptr &windowStage) +{ + CallWindowStageJsMethod("onWindowStageRestore", ability, windowStage); +} + +void JsAbilityLifecycleCallback::OnAbilityWillSaveState(const std::shared_ptr &ability) +{ + CallJsMethod("onAbilityWillSaveState", ability); +} + +void JsAbilityLifecycleCallback::OnAbilitySaveState(const std::shared_ptr &ability) +{ + CallJsMethod("onAbilitySaveState", ability); +} + int32_t JsAbilityLifecycleCallback::Register(napi_value jsCallback, bool isSync) { TAG_LOGD(AAFwkTag::APPKIT, "enter"); diff --git a/frameworks/native/appkit/ability_runtime/context/ability_stage_context.cpp b/frameworks/native/appkit/ability_runtime/context/ability_stage_context.cpp new file mode 100755 index 0000000000..2f604fa11a --- /dev/null +++ b/frameworks/native/appkit/ability_runtime/context/ability_stage_context.cpp @@ -0,0 +1,396 @@ +/* + * 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 "ability_stage_context.h" + +#include "context.h" +#include "context_impl.h" +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace AbilityRuntime { +const size_t AbilityStageContext::CONTEXT_TYPE_ID(std::hash {} ("AbilityStageContext")); + +AbilityStageContext::AbilityStageContext() +{ + TAG_LOGD(AAFwkTag::APPKIT, "Constructor."); + contextImpl_ = std::make_shared(); +} + +void AbilityStageContext::SetParentContext(const std::shared_ptr &context) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return; + } + + contextImpl_->SetParentContext(context); +} + +void AbilityStageContext::InitHapModuleInfo(const std::shared_ptr &abilityInfo) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return; + } + + contextImpl_->InitHapModuleInfo(abilityInfo); +} + +void AbilityStageContext::InitHapModuleInfo(const AppExecFwk::HapModuleInfo &hapModuleInfo) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return; + } + + contextImpl_->InitHapModuleInfo(hapModuleInfo); +} + +std::shared_ptr AbilityStageContext::GetHapModuleInfo() const +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return nullptr; + } + + return contextImpl_->GetHapModuleInfo(); +} + +void AbilityStageContext::SetConfiguration(const std::shared_ptr &config) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return; + } + + contextImpl_->SetConfiguration(config); +} + +std::shared_ptr AbilityStageContext::GetConfiguration() const +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return nullptr; + } + + return contextImpl_->GetConfiguration(); +} + +void AbilityStageContext::SetResourceManager(const std::shared_ptr &resourceManager) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return; + } + + contextImpl_->SetResourceManager(resourceManager); +} + +std::shared_ptr AbilityStageContext::GetResourceManager() const +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return nullptr; + } + + return contextImpl_->GetResourceManager(); +} + +std::string AbilityStageContext::GetBundleName() const +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetBundleName(); +} + +std::shared_ptr AbilityStageContext::GetApplicationInfo() const +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return nullptr; + } + + return contextImpl_->GetApplicationInfo(); +} + +std::shared_ptr AbilityStageContext::CreateBundleContext(const std::string &bundleName) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return nullptr; + } + + return contextImpl_->CreateBundleContext(bundleName); +} + +std::shared_ptr AbilityStageContext::CreateModuleContext(const std::string &moduleName) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return nullptr; + } + + return contextImpl_->CreateModuleContext(moduleName); +} + +std::shared_ptr AbilityStageContext::CreateModuleContext(const std::string &bundleName, + const std::string &moduleName) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return nullptr; + } + + return contextImpl_->CreateModuleContext(bundleName, moduleName); +} + +std::shared_ptr AbilityStageContext::CreateModuleResourceManager( + const std::string &bundleName, const std::string &moduleName) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return nullptr; + } + + return contextImpl_->CreateModuleResourceManager(bundleName, moduleName); +} + +int32_t AbilityStageContext::CreateSystemHspModuleResourceManager(const std::string &bundleName, + const std::string &moduleName, std::shared_ptr &resourceManager) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return ERR_INVALID_VALUE; + } + + return contextImpl_->CreateSystemHspModuleResourceManager(bundleName, moduleName, resourceManager); +} + +std::string AbilityStageContext::GetBundleCodePath() const +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetBundleCodePath(); +} + +std::string AbilityStageContext::GetBundleCodeDir() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetBundleCodeDir(); +} + +std::string AbilityStageContext::GetCacheDir() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetCacheDir(); +} + +std::string AbilityStageContext::GetTempDir() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetTempDir(); +} + +std::string AbilityStageContext::GetFilesDir() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetFilesDir(); +} + +std::string AbilityStageContext::GetResourceDir() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetResourceDir(); +} + +std::string AbilityStageContext::GetDatabaseDir() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetDatabaseDir(); +} + +std::string AbilityStageContext::GetPreferencesDir() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetPreferencesDir(); +} + +std::string AbilityStageContext::GetGroupDir(std::string groupId) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetGroupDir(groupId); +} + +int32_t AbilityStageContext::GetSystemDatabaseDir(const std::string &groupId, bool checkExist, std::string &databaseDir) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return ERR_INVALID_VALUE; + } + + return contextImpl_->GetSystemDatabaseDir(groupId, checkExist, databaseDir); +} + +int32_t AbilityStageContext::GetSystemPreferencesDir(const std::string &groupId, bool checkExist, + std::string &preferencesDir) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return ERR_INVALID_VALUE; + } + + return contextImpl_->GetSystemPreferencesDir(groupId, checkExist, preferencesDir); +} + +std::string AbilityStageContext::GetDistributedFilesDir() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetDistributedFilesDir(); +} + +std::string AbilityStageContext::GetCloudFileDir() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetCloudFileDir(); +} + +std::string AbilityStageContext::GetBaseDir() const +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return {}; + } + + return contextImpl_->GetBaseDir(); +} + +bool AbilityStageContext::IsUpdatingConfigurations() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return false; + } + + return contextImpl_->IsUpdatingConfigurations(); +} + +bool AbilityStageContext::PrintDrawnCompleted() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return false; + } + + return contextImpl_->PrintDrawnCompleted(); +} + +sptr AbilityStageContext::GetToken() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return nullptr; + } + + return contextImpl_->GetToken(); +} + +void AbilityStageContext::SetToken(const sptr &token) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return; + } + + contextImpl_->SetToken(token); +} + +void AbilityStageContext::SwitchArea(int mode) +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return; + } + + contextImpl_->SwitchArea(mode); +} + +int AbilityStageContext::GetArea() +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return ContextImpl::EL_DEFAULT; + } + + return contextImpl_->GetArea(); +} + +Global::Resource::DeviceType AbilityStageContext::GetDeviceType() const +{ + if (contextImpl_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Invalid contextImpl."); + return Global::Resource::DeviceType::DEVICE_PHONE; + } + + return contextImpl_->GetDeviceType(); +} +} // 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 b9f37fb133..cb10a3767f 100644 --- a/frameworks/native/appkit/ability_runtime/context/application_context.cpp +++ b/frameworks/native/appkit/ability_runtime/context/application_context.cpp @@ -20,12 +20,12 @@ #include "ability_manager_errors.h" #include "configuration_convertor.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "running_process_info.h" namespace OHOS { namespace AbilityRuntime { +const size_t ApplicationContext::CONTEXT_TYPE_ID(std::hash {} ("ApplicationContext")); std::vector> ApplicationContext::callbacks_; std::vector> ApplicationContext::envCallbacks_; std::vector> ApplicationContext::applicationStateCallback_; @@ -235,6 +235,88 @@ void ApplicationContext::DispatchOnAbilityContinue(const std::shared_ptr &ability) +{ + TAG_LOGD(AAFwkTag::APPKIT, "Dispatch onAbilityWillContinue."); + if (ability == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Parameters invalid, ability is nullptr."); + return; + } + + std::lock_guard lock(callbackLock_); + for (auto callback : callbacks_) { + if (callback != nullptr) { + callback->OnAbilityWillContinue(ability); + } + } +} + +void ApplicationContext::DispatchOnWindowStageWillRestore(const std::shared_ptr &ability, + const std::shared_ptr &windowStage) +{ + TAG_LOGD(AAFwkTag::APPKIT, "Dispatch onWindowStageWillRestore."); + if (ability == nullptr || windowStage == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Parameters invalid, ability or windowStage is null."); + return; + } + + std::lock_guard lock(callbackLock_); + for (auto callback : callbacks_) { + if (callback != nullptr) { + callback->OnWindowStageWillRestore(ability, windowStage); + } + } +} + +void ApplicationContext::DispatchOnWindowStageRestore(const std::shared_ptr &ability, + const std::shared_ptr &windowStage) +{ + TAG_LOGD(AAFwkTag::APPKIT, "Dispatch onWindowStageRestore."); + if (ability == nullptr || windowStage == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Parameters invalid, ability or windowStage is null."); + return; + } + + std::lock_guard lock(callbackLock_); + for (auto callback : callbacks_) { + if (callback != nullptr) { + callback->OnWindowStageRestore(ability, windowStage); + } + } +} + +void ApplicationContext::DispatchOnAbilityWillSaveState(const std::shared_ptr &ability) +{ + TAG_LOGD(AAFwkTag::APPKIT, "Dispatch onAbilityWillSaveState."); + if (ability == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Parameters invalid, ability is nullptr."); + return; + } + + std::lock_guard lock(callbackLock_); + for (auto callback : callbacks_) { + if (callback != nullptr) { + callback->OnAbilityWillSaveState(ability); + } + } +} + +void ApplicationContext::DispatchOnAbilitySaveState(const std::shared_ptr &ability) +{ + TAG_LOGD(AAFwkTag::APPKIT, "Dispatch onAbilitySaveState."); + if (ability == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Parameters invalid, ability is nullptr."); + return; + } + + std::lock_guard lock(callbackLock_); + for (auto callback : callbacks_) { + if (callback != nullptr) { + callback->OnAbilitySaveState(ability); + } + } +} + void ApplicationContext::DispatchConfigurationUpdated(const AppExecFwk::Configuration &config) { std::lock_guard lock(envCallbacksLock_); @@ -635,6 +717,20 @@ void ApplicationContext::SetFont(const std::string &font) #endif } +void ApplicationContext::SetMcc(const std::string &mcc) +{ + if (contextImpl_ != nullptr) { + contextImpl_->SetMcc(mcc); + } +} + +void ApplicationContext::SetMnc(const std::string &mnc) +{ + if (contextImpl_ != nullptr) { + contextImpl_->SetMnc(mnc); + } +} + void ApplicationContext::ClearUpApplicationData() { if (contextImpl_ != nullptr) { diff --git a/frameworks/native/appkit/ability_runtime/context/application_state_change_callback.cpp b/frameworks/native/appkit/ability_runtime/context/application_state_change_callback.cpp index a478d4ea48..e683a3a881 100755 --- a/frameworks/native/appkit/ability_runtime/context/application_state_change_callback.cpp +++ b/frameworks/native/appkit/ability_runtime/context/application_state_change_callback.cpp @@ -16,7 +16,6 @@ #include "application_state_change_callback.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_data_struct_converter.h" #include "js_runtime_utils.h" diff --git a/frameworks/native/appkit/ability_runtime/context/context_impl.cpp b/frameworks/native/appkit/ability_runtime/context/context_impl.cpp index cc2aec0eee..eda497be8f 100644 --- a/frameworks/native/appkit/ability_runtime/context/context_impl.cpp +++ b/frameworks/native/appkit/ability_runtime/context/context_impl.cpp @@ -29,8 +29,8 @@ #include "directory_ex.h" #include "file_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" +#include "ipc_object_proxy.h" #include "ipc_singleton.h" #include "js_runtime_utils.h" #ifdef SUPPORT_SCREEN @@ -361,6 +361,22 @@ void ContextImpl::SwitchArea(int mode) TAG_LOGD(AAFwkTag::APPKIT, "currArea:%{public}s.", currArea_.c_str()); } +void ContextImpl::SetMcc(std::string mcc) +{ + TAG_LOGD(AAFwkTag::APPKIT, "mcc:%{public}s.", mcc.c_str()); + if (config_) { + config_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_MCC, mcc); + } +} + +void ContextImpl::SetMnc(std::string mnc) +{ + TAG_LOGD(AAFwkTag::APPKIT, "mnc:%{public}s.", mnc.c_str()); + if (config_) { + config_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_MNC, mnc); + } +} + std::shared_ptr ContextImpl::CreateModuleContext(const std::string &moduleName) { return CreateModuleContext(GetBundleName(), moduleName); @@ -788,57 +804,87 @@ std::shared_ptr ContextImpl::InitResourceMana } TAG_LOGD(AAFwkTag::APPKIT, "loadPath: %{public}s", loadPath.c_str()); - // getOverlayPath - std::vector overlayModuleInfos; - auto res = GetOverlayModuleInfos(bundleInfo.name, hapModuleInfo.moduleName, overlayModuleInfos); - if (res != ERR_OK) { - TAG_LOGD(AAFwkTag::APPKIT, "Get overlay paths from bms failed."); - } - if (overlayModuleInfos.size() == 0) { - if (!resourceManager->AddResource(loadPath.c_str())) { - TAG_LOGE(AAFwkTag::APPKIT, "AddResource fail, moduleResPath: %{public}s", loadPath.c_str()); - } - } else { - std::vector overlayPaths; - for (auto it : overlayModuleInfos) { - if (std::regex_search(it.hapPath, std::regex(GetBundleName()))) { - it.hapPath = std::regex_replace(it.hapPath, inner_pattern, LOCAL_CODE_PATH); - } else { - it.hapPath = std::regex_replace(it.hapPath, outer_pattern, LOCAL_BUNDLES); - } - if (it.state == AppExecFwk::OverlayState::OVERLAY_ENABLE) { - TAG_LOGD(AAFwkTag::APPKIT, "hapPath: %{public}s", it.hapPath.c_str()); - overlayPaths.emplace_back(it.hapPath); - } - } - TAG_LOGD(AAFwkTag::APPKIT, "OverlayPaths size:%{public}zu.", overlayPaths.size()); - if (!resourceManager->AddResource(loadPath, overlayPaths)) { - TAG_LOGE(AAFwkTag::APPKIT, "AddResource failed"); - } - - if (currentBundle) { - // add listen overlay change - overlayModuleInfos_ = overlayModuleInfos; - EventFwk::MatchingSkills matchingSkills; - matchingSkills.AddEvent(OVERLAY_STATE_CHANGED); - EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); - subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); - auto callback = [this, resourceManager, bundleName = bundleInfo.name, moduleName = - hapModuleInfo.moduleName, loadPath](const EventFwk::CommonEventData &data) { - TAG_LOGI(AAFwkTag::APPKIT, "On overlay changed."); - this->OnOverlayChanged(data, resourceManager, bundleName, moduleName, loadPath); - }; - auto subscriber = std::make_shared(subscribeInfo, callback); - bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber); - TAG_LOGI(AAFwkTag::APPKIT, "Overlay event subscriber register result is %{public}d", subResult); - } - } + GetOverlayPath(resourceManager, bundleInfo.name, hapModuleInfo.moduleName, loadPath, currentBundle); + AddPatchResource(resourceManager, loadPath, hapModuleInfo.hqfInfo.hqfFilePath, + bundleInfo.applicationInfo.debug); } } } return resourceManager; } +void ContextImpl::AddPatchResource(std::shared_ptr &resourceManager, + const std::string &loadPath, const std::string &hqfPath, bool isDebug) +{ + std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + GetBundleName()); + if (!hqfPath.empty() && isDebug) { + std::string realHqfPath = std::regex_replace(hqfPath, pattern, LOCAL_CODE_PATH); + TAG_LOGI(AAFwkTag::APPKIT, "AddPatchResource hapPath:%{public}s, patchPath:%{public}s", + loadPath.c_str(), realHqfPath.c_str()); + if (!resourceManager->AddPatchResource(loadPath.c_str(), realHqfPath.c_str())) { + TAG_LOGE(AAFwkTag::APPKIT, "AddPatchResource failed"); + } + } +} + +void ContextImpl::GetOverlayPath(std::shared_ptr &resourceManager, + const std::string &bundleName, const std::string &moduleName, std::string &loadPath, bool currentBundle) +{ + // getOverlayPath + std::vector overlayModuleInfos; + auto res = GetOverlayModuleInfos(bundleName, moduleName, overlayModuleInfos); + if (res != ERR_OK) { + TAG_LOGD(AAFwkTag::APPKIT, "Get overlay paths from bms failed."); + } + if (overlayModuleInfos.size() == 0) { + if (!resourceManager->AddResource(loadPath.c_str())) { + TAG_LOGE(AAFwkTag::APPKIT, "AddResource fail, moduleResPath: %{public}s", loadPath.c_str()); + } + } else { + std::vector overlayPaths; + for (auto it : overlayModuleInfos) { + if (std::regex_search(it.hapPath, std::regex(GetBundleName()))) { + it.hapPath = std::regex_replace(it.hapPath, std::regex(std::string(ABS_CODE_PATH) + + std::string(FILE_SEPARATOR) + GetBundleName()), LOCAL_CODE_PATH); + } else { + it.hapPath = std::regex_replace(it.hapPath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES); + } + if (it.state == AppExecFwk::OverlayState::OVERLAY_ENABLE) { + TAG_LOGD(AAFwkTag::APPKIT, "hapPath: %{public}s", it.hapPath.c_str()); + overlayPaths.emplace_back(it.hapPath); + } + } + TAG_LOGD(AAFwkTag::APPKIT, "OverlayPaths size:%{public}zu.", overlayPaths.size()); + if (!resourceManager->AddResource(loadPath, overlayPaths)) { + TAG_LOGE(AAFwkTag::APPKIT, "AddResource failed"); + } + + if (currentBundle) { + SubscribeToOverlayEvents(resourceManager, bundleName, moduleName, loadPath, overlayModuleInfos); + } + } +} + +void ContextImpl::SubscribeToOverlayEvents(std::shared_ptr &resourceManager, + const std::string &name, const std::string &hapModuleName, std::string &loadPath, + std::vector overlayModuleInfos) +{ + // add listen overlay change + overlayModuleInfos_ = overlayModuleInfos; + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(OVERLAY_STATE_CHANGED); + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); + auto callback = [this, resourceManager, bundleName = name, moduleName = + hapModuleName, loadPath](const EventFwk::CommonEventData &data) { + TAG_LOGI(AAFwkTag::APPKIT, "On overlay changed."); + this->OnOverlayChanged(data, resourceManager, bundleName, moduleName, loadPath); + }; + auto subscriber = std::make_shared(subscribeInfo, callback); + bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber); + TAG_LOGI(AAFwkTag::APPKIT, "Overlay event subscriber register result is %{public}d", subResult); +} + void ContextImpl::UpdateResConfig(std::shared_ptr &resourceManager) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); @@ -876,6 +922,14 @@ void ContextImpl::UpdateResConfig(std::shared_ptrSetDeviceType(GetDeviceType()); + std::string mcc = config_->GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_MCC); + std::string mnc = config_->GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_MNC); + try { + resConfig->SetMcc(static_cast(std::stoi(mcc))); + resConfig->SetMnc(static_cast(std::stoi(mnc))); + } catch (...) { + TAG_LOGW(AAFwkTag::APPKIT, "Set mcc,mnc failed mcc:%{public}s mnc:%{public}s.", mcc.c_str(), mnc.c_str()); + } resourceManager->UpdateResConfig(*resConfig); } @@ -1000,6 +1054,9 @@ void ContextImpl::SetToken(const sptr &token) return; } token_ = token; + if (GetBundleName() == "com.ohos.callui") { + PrintTokenInfo(); + } } sptr ContextImpl::GetToken() @@ -1248,5 +1305,23 @@ int32_t ContextImpl::SetSupportedProcessCacheSelf(bool isSupport) } return appMgrClient->SetSupportedProcessCacheSelf(isSupport); } + +void ContextImpl::PrintTokenInfo() const +{ + if (token_ == nullptr) { + TAG_LOGI(AAFwkTag::EXT, "com.ohos.callui.ServiceAbility token is null"); + return; + } + if (!token_->IsProxyObject()) { + TAG_LOGI(AAFwkTag::EXT, "com.ohos.callui.ServiceAbility token is not proxy"); + return; + } + IPCObjectProxy *tokenProxyObject = reinterpret_cast(token_.GetRefPtr()); + if (tokenProxyObject != nullptr) { + std::string remoteDescriptor = Str16ToStr8(tokenProxyObject->GetInterfaceDescriptor()); + TAG_LOGI(AAFwkTag::EXT, "com.ohos.callui.ServiceAbility handle: %{public}d, descriptor: %{public}s", + tokenProxyObject->GetHandle(), remoteDescriptor.c_str()); + } +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/appkit/ability_runtime/context/environment_callback.cpp b/frameworks/native/appkit/ability_runtime/context/environment_callback.cpp index 7b325cc761..f0867dd701 100755 --- a/frameworks/native/appkit/ability_runtime/context/environment_callback.cpp +++ b/frameworks/native/appkit/ability_runtime/context/environment_callback.cpp @@ -16,7 +16,6 @@ #include "environment_callback.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "js_data_struct_converter.h" #include "js_runtime_utils.h" 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 7625adeb80..c2ebdb917f 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 @@ -25,7 +25,6 @@ #include "application_info.h" #include "application_context_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "js_ability_auto_startup_callback.h" #include "js_ability_auto_startup_manager_utils.h" @@ -208,7 +207,11 @@ napi_value JsApplicationContextUtils::OnCreateModuleContext(napi_env env, NapiCa AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); return CreateJsUndefined(env); } + return CreateJsModuleContext(env, moduleContext); +} +napi_value JsApplicationContextUtils::CreateJsModuleContext(napi_env env, const std::shared_ptr& moduleContext) +{ napi_value value = CreateJsBaseContext(env, moduleContext, true); auto systemModule = JsRuntime::LoadSystemModuleByEngine(env, "application.Context", &value, 1); if (systemModule == nullptr) { @@ -431,7 +434,7 @@ napi_value JsApplicationContextUtils::OnGetCloudFileDir(napi_env env, NapiCallba { auto applicationContext = applicationContext_.lock(); if (!applicationContext) { - HILOG_WARN("applicationContext is already released"); + TAG_LOGW(AAFwkTag::APPKIT, "applicationContext is already released"); return CreateJsUndefined(env); } std::string path = applicationContext->GetCloudFileDir(); @@ -711,7 +714,7 @@ napi_value JsApplicationContextUtils::PreloadUIExtensionAbility(napi_env env, na napi_value JsApplicationContextUtils::OnPreloadUIExtensionAbility(napi_env env, NapiCallbackInfo& info) { - HILOG_DEBUG("called"); + TAG_LOGD(AAFwkTag::APPKIT, "called"); if (info.argc < ARGC_ONE) { TAG_LOGW(AAFwkTag::APPKIT, "Params error!"); ThrowTooFewParametersError(env); @@ -1480,11 +1483,6 @@ napi_value JsApplicationContextUtils::OnSetSupportedProcessCacheSelf(napi_env en { TAG_LOGD(AAFwkTag::APPKIT, "called"); - if (!CheckCallerIsSystemApp()) { - TAG_LOGE(AAFwkTag::APPKIT, "This application is not system-app, can not use system-api."); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_NOT_SYSTEM_APP); - return CreateJsUndefined(env); - } // only support one params if (info.argc == ARGC_ZERO) { TAG_LOGE(AAFwkTag::APPKIT, "Not enough params"); @@ -1507,12 +1505,9 @@ napi_value JsApplicationContextUtils::OnSetSupportedProcessCacheSelf(napi_env en } int32_t errCode = applicationContext->SetSupportedProcessCacheSelf(isSupport); - if (errCode == AAFwk::CHECK_PERMISSION_FAILED) { - TAG_LOGE(AAFwkTag::APPKIT, "check permission failed"); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_NO_ACCESS_PERMISSION); - } else if (errCode == AAFwk::ERR_SET_SUPPORTED_PROCESS_CACHE_AGAIN) { - TAG_LOGE(AAFwkTag::APPKIT, "cannot set more than once"); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_SET_SUPPORTED_PROCESS_CACHE_AGAIN); + if (errCode == AAFwk::ERR_CAPABILITY_NOT_SUPPORT) { + TAG_LOGE(AAFwkTag::APPKIT, "process cache feature is disabled."); + AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_NO_SUCH_SYSCAP); } else if (errCode != ERR_OK) { TAG_LOGE(AAFwkTag::APPKIT, "set failed"); AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INTERNAL_ERROR); diff --git a/frameworks/native/appkit/ability_runtime/context/js_context_utils.cpp b/frameworks/native/appkit/ability_runtime/context/js_context_utils.cpp index 20acd7c2ed..9c586942ce 100644 --- a/frameworks/native/appkit/ability_runtime/context/js_context_utils.cpp +++ b/frameworks/native/appkit/ability_runtime/context/js_context_utils.cpp @@ -19,7 +19,6 @@ #include "application_context.h" #include "application_context_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "js_application_context_utils.h" #include "js_data_struct_converter.h" @@ -78,10 +77,13 @@ protected: private: napi_value OnCreateBundleContext(napi_env env, NapiCallbackInfo& info); + napi_value CreateJsBundleContext(napi_env env, const std::shared_ptr& bundleContext); napi_value OnGetApplicationContext(napi_env env, NapiCallbackInfo& info); + napi_value CreateJSApplicationContext(napi_env env, const std::shared_ptr applicationContext); napi_value OnSwitchArea(napi_env env, NapiCallbackInfo& info); napi_value OnGetArea(napi_env env, NapiCallbackInfo& info); napi_value OnCreateModuleContext(napi_env env, NapiCallbackInfo& info); + napi_value CreateJsModuleContext(napi_env env, const std::shared_ptr& moduleContext); napi_value OnCreateSystemHspModuleResourceManager(napi_env env, NapiCallbackInfo& info); napi_value OnCreateModuleResourceManager(napi_env env, NapiCallbackInfo& info); bool CheckCallerIsSystemApp(); @@ -194,7 +196,11 @@ napi_value JsBaseContext::OnCreateModuleContext(napi_env env, NapiCallbackInfo& AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); return CreateJsUndefined(env); } + return CreateJsModuleContext(env, moduleContext); +} +napi_value JsBaseContext::CreateJsModuleContext(napi_env env, const std::shared_ptr& moduleContext) +{ napi_value value = CreateJsBaseContext(env, moduleContext, true); auto systemModule = JsRuntime::LoadSystemModuleByEngine(env, "application.Context", &value, 1); if (systemModule == nullptr) { @@ -509,7 +515,7 @@ napi_value JsBaseContext::OnGetCloudFileDir(napi_env env, NapiCallbackInfo& info { auto context = context_.lock(); if (!context) { - HILOG_WARN("context is already released"); + TAG_LOGW(AAFwkTag::APPKIT, "context is already released"); return CreateJsUndefined(env); } std::string path = context->GetCloudFileDir(); @@ -550,7 +556,11 @@ napi_value JsBaseContext::OnCreateBundleContext(napi_env env, NapiCallbackInfo& AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); return CreateJsUndefined(env); } + return CreateJsBundleContext(env, bundleContext); +} +napi_value JsBaseContext::CreateJsBundleContext(napi_env env, const std::shared_ptr& bundleContext) +{ napi_value value = CreateJsBaseContext(env, bundleContext, true); auto systemModule = JsRuntime::LoadSystemModuleByEngine(env, "application.Context", &value, 1); if (systemModule == nullptr) { @@ -600,7 +610,12 @@ napi_value JsBaseContext::OnGetApplicationContext(napi_env env, NapiCallbackInfo return objValue; } } + return CreateJSApplicationContext(env, applicationContext); +} +napi_value JsBaseContext::CreateJSApplicationContext(napi_env env, + const std::shared_ptr applicationContext) +{ napi_value value = JsApplicationContextUtils::CreateJsApplicationContext(env); auto systemModule = JsRuntime::LoadSystemModuleByEngine(env, "application.ApplicationContext", &value, 1); if (systemModule == nullptr) { diff --git a/frameworks/native/appkit/ability_runtime/extension_context.cpp b/frameworks/native/appkit/ability_runtime/extension_context.cpp index 15407dd6fd..3f7ac8f6d4 100644 --- a/frameworks/native/appkit/ability_runtime/extension_context.cpp +++ b/frameworks/native/appkit/ability_runtime/extension_context.cpp @@ -16,7 +16,6 @@ #include "extension_context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/appkit/ability_runtime/form_extension_context.cpp b/frameworks/native/appkit/ability_runtime/form_extension_context.cpp index c664ade993..8378973a76 100644 --- a/frameworks/native/appkit/ability_runtime/form_extension_context.cpp +++ b/frameworks/native/appkit/ability_runtime/form_extension_context.cpp @@ -21,7 +21,6 @@ #include "form_mgr.h" #include "form_mgr_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" namespace OHOS { diff --git a/frameworks/native/appkit/ability_runtime/service_extension_context.cpp b/frameworks/native/appkit/ability_runtime/service_extension_context.cpp index e3649d0694..4036ab70b2 100644 --- a/frameworks/native/appkit/ability_runtime/service_extension_context.cpp +++ b/frameworks/native/appkit/ability_runtime/service_extension_context.cpp @@ -18,7 +18,6 @@ #include "ability_connection.h" #include "ability_manager_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" namespace OHOS { @@ -132,6 +131,9 @@ ErrCode ServiceExtensionContext::StartAbilityWithAccount(const AAFwk::Want &want 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); + if (callerName == "com.ohos.callui.ServiceAbility") { + PrintTokenInfo(); + } ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility( want, token_, ILLEGAL_REQUEST_CODE, accountId); TAG_LOGD(AAFwkTag::APPKIT, "%{public}s. End calling StartAbilityWithAccount. ret=%{public}d", __func__, err); @@ -166,6 +168,17 @@ ErrCode ServiceExtensionContext::StartServiceExtensionAbility(const AAFwk::Want return err; } +ErrCode ServiceExtensionContext::StartUIServiceExtensionAbility(const AAFwk::Want &want, int32_t accountId) const +{ + TAG_LOGD(AAFwkTag::APPKIT, "begin."); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility( + want, token_, accountId, AppExecFwk::ExtensionAbilityType::UI_SERVICE); + if (err != ERR_OK) { + TAG_LOGE(AAFwkTag::APPKIT, "ServiceContext::StartServiceExtensionAbility is failed %{public}d", err); + } + return err; +} + ErrCode ServiceExtensionContext::StopServiceExtensionAbility(const AAFwk::Want& want, int32_t accountId) const { TAG_LOGD(AAFwkTag::APPKIT, "%{public}s begin.", __func__); @@ -232,5 +245,27 @@ AppExecFwk::AbilityType ServiceExtensionContext::GetAbilityInfoType() const return info->type; } + +ErrCode ServiceExtensionContext::PreStartMission(const std::string& bundleName, const std::string& moduleName, + const std::string& abilityName, const std::string& startTime) +{ + TAG_LOGI(AAFwkTag::APPKIT, "called"); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->PreStartMission( + bundleName, moduleName, abilityName, startTime); + if (err != ERR_OK) { + TAG_LOGE(AAFwkTag::APPKIT, "ServiceExtensionContext::PreStartMission is failed %{public}d", err); + } + TAG_LOGI(AAFwkTag::APPKIT, "End."); + return err; +} + +ErrCode ServiceExtensionContext::AddFreeInstallObserver(const sptr &observer) +{ + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->AddFreeInstallObserver(token_, observer); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::APPKIT, "AddFreeInstallObserver error, ret: %{public}d", ret); + } + return ret; +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/appkit/ability_runtime/ui_service_extension_context.cpp b/frameworks/native/appkit/ability_runtime/ui_service_extension_context.cpp new file mode 100644 index 0000000000..af24afb171 --- /dev/null +++ b/frameworks/native/appkit/ability_runtime/ui_service_extension_context.cpp @@ -0,0 +1,123 @@ +/* + * 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 "ui_service_extension_context.h" + +#include "ability_connection.h" +#include "ability_manager_client.h" +#include "hilog_tag_wrapper.h" +#include "hitrace_meter.h" +#include +#include "ui_content.h" +#include "connection_manager.h" +#include "string_wrapper.h" +#include "want_params_wrapper.h" + +namespace OHOS { +namespace AbilityRuntime { +const size_t UIServiceExtensionContext::CONTEXT_TYPE_ID(std::hash {} ("UIServiceExtensionContext")); +const std::string UIEXTENSION_TARGET_TYPE_KEY = "ability.want.params.uiExtensionTargetType"; +const std::string FLAG_AUTH_READ_URI_PERMISSION = "ability.want.params.uriPermissionFlag"; + +int32_t UIServiceExtensionContext::ILLEGAL_REQUEST_CODE(-1); + +ErrCode UIServiceExtensionContext::StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + TAG_LOGD(AAFwkTag::APPKIT, "Start ability begin, ability:%{public}s.", want.GetElement().GetAbilityName().c_str()); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, startOptions, token_, + ILLEGAL_REQUEST_CODE); + if (err != ERR_OK) { + TAG_LOGE(AAFwkTag::APPKIT, "UIServiceExtensionContext::StartAbility is failed %{public}d", err); + } + return err; +} + +ErrCode UIServiceExtensionContext::TerminateSelf() +{ + TAG_LOGI(AAFwkTag::APPKIT, "begin."); + ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->TerminateAbility(token_, -1, nullptr); + if (err != ERR_OK) { + TAG_LOGE(AAFwkTag::APPKIT, "UIServiceExtensionContext::TerminateAbility is failed %{public}d", err); + } + TAG_LOGI(AAFwkTag::APPKIT, "%{public}s end.", __func__); + return err; +} + +void UIServiceExtensionContext::SetWindow(sptr window) +{ + window_ = window; +} + +sptr UIServiceExtensionContext::GetWindow() +{ + return window_; +} + +Ace::UIContent* UIServiceExtensionContext::GetUIContent() +{ + TAG_LOGI(AAFwkTag::UI_EXT, "called"); + if (window_ == nullptr) { + TAG_LOGD(AAFwkTag::APPKIT, "window_ is nullptr"); + return nullptr; + } + return window_->GetUIContent(); +} + +ErrCode UIServiceExtensionContext::StartAbilityByType(const std::string &type, + AAFwk::WantParams &wantParam, const std::shared_ptr &uiExtensionCallbacks) +{ + TAG_LOGD(AAFwkTag::APPKIT, "StartAbilityByType begin."); + if (uiExtensionCallbacks == nullptr) { + TAG_LOGD(AAFwkTag::APPKIT, "uiExtensionCallbacks is nullptr."); + return ERR_INVALID_VALUE; + } + auto uiContent = GetUIContent(); + if (uiContent == nullptr) { + TAG_LOGD(AAFwkTag::APPKIT, "uiContent is nullptr."); + return ERR_INVALID_VALUE; + } + wantParam.SetParam(UIEXTENSION_TARGET_TYPE_KEY, AAFwk::String::Box(type)); + AAFwk::Want want; + want.SetParams(wantParam); + if (wantParam.HasParam(FLAG_AUTH_READ_URI_PERMISSION)) { + int32_t flag = wantParam.GetIntParam(FLAG_AUTH_READ_URI_PERMISSION, 0); + want.SetFlags(flag); + wantParam.Remove(FLAG_AUTH_READ_URI_PERMISSION); + } + + OHOS::Ace::ModalUIExtensionCallbacks callback; + OHOS::Ace::ModalUIExtensionConfig config; + callback.onError = [uiExtensionCallbacks](int32_t arg, const std::string &str1, const std::string &str2) { + uiExtensionCallbacks->OnError(arg); + }; + callback.onRelease = [uiExtensionCallbacks](int32_t arg) { + uiExtensionCallbacks->OnRelease(arg); + }; + callback.onResult = [uiExtensionCallbacks](int32_t arg1, const OHOS::AAFwk::Want arg2) { + uiExtensionCallbacks->OnResult(arg1, arg2); + }; + + int32_t sessionId = uiContent->CreateModalUIExtension(want, callback, config); + if (sessionId == 0) { + TAG_LOGD(AAFwkTag::APPKIT, "CreateModalUIExtension is failed"); + return ERR_INVALID_VALUE; + } + uiExtensionCallbacks->SetUIContent(uiContent); + uiExtensionCallbacks->SetSessionId(sessionId); + return ERR_OK; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/frameworks/native/appkit/app/ability_manager.cpp b/frameworks/native/appkit/app/ability_manager.cpp index 6fd240910e..3c0240681d 100644 --- a/frameworks/native/appkit/app/ability_manager.cpp +++ b/frameworks/native/appkit/app/ability_manager.cpp @@ -15,7 +15,6 @@ #include "ability_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "singleton.h" #include "sys_mgr_client.h" diff --git a/frameworks/native/appkit/app/ability_record_mgr.cpp b/frameworks/native/appkit/app/ability_record_mgr.cpp index b732b34bae..99c2375089 100644 --- a/frameworks/native/appkit/app/ability_record_mgr.cpp +++ b/frameworks/native/appkit/app/ability_record_mgr.cpp @@ -15,7 +15,6 @@ #include "ability_record_mgr.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/appkit/app/app_context.cpp b/frameworks/native/appkit/app/app_context.cpp index 9e7ff3f852..b64fdf43f2 100644 --- a/frameworks/native/appkit/app/app_context.cpp +++ b/frameworks/native/appkit/app/app_context.cpp @@ -14,7 +14,6 @@ */ #include "app_context.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/appkit/app/app_loader.cpp b/frameworks/native/appkit/app/app_loader.cpp index 94cfa35c42..0b45eb3c91 100644 --- a/frameworks/native/appkit/app/app_loader.cpp +++ b/frameworks/native/appkit/app/app_loader.cpp @@ -15,7 +15,6 @@ #include "app_loader.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/appkit/app/application_cleaner.cpp b/frameworks/native/appkit/app/application_cleaner.cpp index 502dc8af36..31b31ee211 100644 --- a/frameworks/native/appkit/app/application_cleaner.cpp +++ b/frameworks/native/appkit/app/application_cleaner.cpp @@ -25,7 +25,6 @@ #include "directory_ex.h" #include "ffrt.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "os_account_manager_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/appkit/app/application_data_manager.cpp b/frameworks/native/appkit/app/application_data_manager.cpp index d07e612adf..ae6f6ad83e 100644 --- a/frameworks/native/appkit/app/application_data_manager.cpp +++ b/frameworks/native/appkit/app/application_data_manager.cpp @@ -17,7 +17,6 @@ #include "app_recovery.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/native/appkit/app/application_impl.cpp b/frameworks/native/appkit/app/application_impl.cpp index 018d74bbf8..35d3622ec9 100644 --- a/frameworks/native/appkit/app/application_impl.cpp +++ b/frameworks/native/appkit/app/application_impl.cpp @@ -16,7 +16,6 @@ #include "application_impl.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "ohos_application.h" #include "uri_permission_manager_client.h" diff --git a/frameworks/native/appkit/app/assert_fault_callback.cpp b/frameworks/native/appkit/app/assert_fault_callback.cpp index 6ab7b744bb..8abef1d6c0 100644 --- a/frameworks/native/appkit/app/assert_fault_callback.cpp +++ b/frameworks/native/appkit/app/assert_fault_callback.cpp @@ -16,7 +16,6 @@ #include "assert_fault_callback.h" #include "assert_fault_task_thread.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/appkit/app/assert_fault_task_thread.cpp b/frameworks/native/appkit/app/assert_fault_task_thread.cpp index c75d11e160..44ced3a7d6 100644 --- a/frameworks/native/appkit/app/assert_fault_task_thread.cpp +++ b/frameworks/native/appkit/app/assert_fault_task_thread.cpp @@ -21,7 +21,6 @@ #include "assert_fault_task_thread.h" #include "assert_fault_callback.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "main_thread.h" #include "string_wrapper.h" @@ -72,7 +71,7 @@ Assert_Status ConvertAssertResult(AAFwk::UserStatus status) static Assert_Status AssertCallback(AssertFailureInfo assertFail) { - TAG_LOGD(AAFwkTag::APPKIT, "Called."); + TAG_LOGD(AAFwkTag::APPKIT, "called"); auto instance = DelayedSingleton::GetInstance(); if (instance == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "Invalid Instance."); diff --git a/frameworks/native/appkit/app/child_main_thread.cpp b/frameworks/native/appkit/app/child_main_thread.cpp index 3fdb069d36..1276ea2ddf 100644 --- a/frameworks/native/appkit/app/child_main_thread.cpp +++ b/frameworks/native/appkit/app/child_main_thread.cpp @@ -19,7 +19,6 @@ #include "child_process_manager.h" #include "constants.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "sys_mgr_client.h" #include "system_ability_definition.h" @@ -30,6 +29,7 @@ using namespace OHOS::AbilityBase::Constants; using OHOS::AbilityRuntime::ChildProcessManager; ChildMainThread::ChildMainThread() { + processArgs_ = std::make_shared(); TAG_LOGD(AAFwkTag::APPKIT, "ChildMainThread constructor called"); } @@ -38,14 +38,22 @@ ChildMainThread::~ChildMainThread() TAG_LOGD(AAFwkTag::APPKIT, "ChildMainThread deconstructor called"); } -void ChildMainThread::Start(const ChildProcessInfo &processInfo) +void ChildMainThread::Start(const std::map &fds) { TAG_LOGI(AAFwkTag::APPKIT, "ChildMainThread start."); + ChildProcessInfo processInfo; + auto ret = GetChildProcessInfo(processInfo); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::APPKIT, "GetChildProcessInfo failed, ret:%{public}d.", ret); + return; + } + sptr thread = sptr(new (std::nothrow) ChildMainThread()); if (thread == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "New ChildMainThread failed."); return; } + thread->SetFds(fds); std::shared_ptr runner = EventRunner::GetMainEventRunner(); if (runner == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "runner is null."); @@ -60,7 +68,7 @@ void ChildMainThread::Start(const ChildProcessInfo &processInfo) return; } - auto ret = runner->Run(); + ret = runner->Run(); if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::APPKIT, "ChildMainThread runner->Run failed ret = %{public}d", ret); } @@ -68,6 +76,31 @@ void ChildMainThread::Start(const ChildProcessInfo &processInfo) TAG_LOGD(AAFwkTag::APPKIT, "ChildMainThread end."); } +int32_t ChildMainThread::GetChildProcessInfo(ChildProcessInfo &info) +{ + TAG_LOGD(AAFwkTag::APPKIT, "GetChildProcessInfo called."); + auto object = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "failed to get app manager service"); + return ERR_INVALID_VALUE; + } + auto appMgr = iface_cast(object); + if (appMgr == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "failed to iface_cast object to appMgr"); + return ERR_INVALID_VALUE; + } + return appMgr->GetChildProcessInfoForSelf(info); +} + +void ChildMainThread::SetFds(const std::map &fds) +{ + if (!processArgs_) { + TAG_LOGE(AAFwkTag::APPKIT, "processArgs_ is nullptr."); + return; + } + processArgs_->fds = fds; +} + bool ChildMainThread::Init(const std::shared_ptr &runner, const ChildProcessInfo &processInfo) { TAG_LOGD(AAFwkTag::APPKIT, "ChildMainThread:Init called."); @@ -116,14 +149,23 @@ bool ChildMainThread::ScheduleLoadJs() TAG_LOGE(AAFwkTag::APPKIT, "mainHandler_ is null"); return false; } + if (!processInfo_) { + TAG_LOGE(AAFwkTag::APPKIT, "processInfo is nullptr."); + return false; + } + auto childProcessType = processInfo_->childProcessType; wptr weak = this; - auto task = [weak]() { + auto task = [weak, childProcessType]() { auto childMainThread = weak.promote(); if (childMainThread == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "childMainThread is nullptr, ScheduleLoadJs failed."); return; } - childMainThread->HandleLoadJs(); + if (childProcessType == CHILD_PROCESS_TYPE_ARK) { + childMainThread->HandleLoadArkTs(); + } else { + childMainThread->HandleLoadJs(); + } }; if (!mainHandler_->PostTask(task, "ChildMainThread::HandleLoadJs")) { TAG_LOGE(AAFwkTag::APPKIT, "ChildMainThread::ScheduleLoadJs PostTask task failed."); @@ -134,7 +176,7 @@ bool ChildMainThread::ScheduleLoadJs() void ChildMainThread::HandleLoadJs() { - TAG_LOGD(AAFwkTag::APPKIT, "called."); + TAG_LOGD(AAFwkTag::APPKIT, "HandleLoadJs called."); if (!processInfo_ || !bundleInfo_) { TAG_LOGE(AAFwkTag::APPKIT, "processInfo or bundleInfo_ is null."); return; @@ -142,8 +184,8 @@ void ChildMainThread::HandleLoadJs() ChildProcessManager &childProcessManager = ChildProcessManager::GetInstance(); HapModuleInfo hapModuleInfo; BundleInfo bundleInfoCopy = *bundleInfo_; - if (!childProcessManager.GetHapModuleInfo(bundleInfoCopy, hapModuleInfo)) { - TAG_LOGE(AAFwkTag::APPKIT, "GetHapModuleInfo failed."); + if (!childProcessManager.GetEntryHapModuleInfo(bundleInfoCopy, hapModuleInfo)) { + TAG_LOGE(AAFwkTag::APPKIT, "GetEntryHapModuleInfo failed."); return; } @@ -153,19 +195,59 @@ void ChildMainThread::HandleLoadJs() return; } AbilityRuntime::Runtime::DebugOption debugOption; - debugOption.isStartWithDebug = processInfo_->isStartWithDebug; - debugOption.processName = processInfo_->processName; - debugOption.isDebugApp = processInfo_->isDebugApp; - debugOption.isStartWithNative = processInfo_->isStartWithNative; + childProcessManager.SetAppSpawnForkDebugOption(debugOption, processInfo_); TAG_LOGD(AAFwkTag::APPKIT, "StartDebugMode, isStartWithDebug is %{public}d, processName is %{public}s, " "isDebugApp is %{public}d, isStartWithNative is %{public}d.", processInfo_->isStartWithDebug, processInfo_->processName.c_str(), processInfo_->isDebugApp, processInfo_->isStartWithNative); runtime_->StartDebugMode(debugOption); - childProcessManager.LoadJsFile(processInfo_->srcEntry, hapModuleInfo, runtime_); + std::string srcPath; + srcPath.append(hapModuleInfo.moduleName).append("/").append(processInfo_->srcEntry); + childProcessManager.LoadJsFile(srcPath, hapModuleInfo, runtime_); TAG_LOGD(AAFwkTag::APPKIT, "ChildMainThread::HandleLoadJs end."); ExitProcessSafely(); } +void ChildMainThread::HandleLoadArkTs() +{ + TAG_LOGD(AAFwkTag::APPKIT, "HandleLoadArkTs called."); + if (!processInfo_ || !bundleInfo_) { + TAG_LOGE(AAFwkTag::APPKIT, "processInfo or bundleInfo_ is null."); + return; + } + if (!processArgs_) { + TAG_LOGE(AAFwkTag::APPKIT, "processArgs_ is nullptr."); + return; + } + auto &srcEntry = processInfo_->srcEntry; + ChildProcessManager &childProcessManager = ChildProcessManager::GetInstance(); + std::string moduleName = childProcessManager.GetModuleNameFromSrcEntry(srcEntry); + if (moduleName.empty()) { + TAG_LOGE(AAFwkTag::APPKIT, "Can't find module name from srcEntry, srcEntry is %{private}s.", srcEntry.c_str()); + return; + } + HapModuleInfo hapModuleInfo; + if (!childProcessManager.GetHapModuleInfo(*bundleInfo_, moduleName, hapModuleInfo)) { + TAG_LOGE(AAFwkTag::APPKIT, "GetHapModuleInfo failed, can't find module:%{public}s.", moduleName.c_str()); + return; + } + + runtime_ = childProcessManager.CreateRuntime(*bundleInfo_, hapModuleInfo, true, processInfo_->jitEnabled); + if (!runtime_) { + TAG_LOGE(AAFwkTag::APPKIT, "Failed to create child process runtime"); + return; + } + AbilityRuntime::Runtime::DebugOption debugOption; + childProcessManager.SetAppSpawnForkDebugOption(debugOption, processInfo_); + TAG_LOGD(AAFwkTag::APPKIT, "StartDebugMode, isStartWithDebug is %{public}d, processName is %{public}s, " + "isDebugApp is %{public}d, isStartWithNative is %{public}d.", processInfo_->isStartWithDebug, + processInfo_->processName.c_str(), processInfo_->isDebugApp, processInfo_->isStartWithNative); + runtime_->StartDebugMode(debugOption); + + processArgs_->entryParams = processInfo_->entryParams; + childProcessManager.LoadJsFile(srcEntry, hapModuleInfo, runtime_, processArgs_); + TAG_LOGD(AAFwkTag::APPKIT, "HandleLoadArkTs end."); +} + void ChildMainThread::InitNativeLib(const BundleInfo &bundleInfo) { AppLibPathMap appLibPaths {}; @@ -173,7 +255,7 @@ void ChildMainThread::InitNativeLib(const BundleInfo &bundleInfo) bool isSystemApp = bundleInfo.applicationInfo.isSystemApp; TAG_LOGD(AAFwkTag::APPKIT, "the application isSystemApp: %{public}d", isSystemApp); - if (processInfo_->processType != CHILD_PROCESS_TYPE_NATIVE) { + if (processInfo_->childProcessType != CHILD_PROCESS_TYPE_NATIVE) { AbilityRuntime::JsRuntime::SetAppLibPath(appLibPaths, isSystemApp); } else { UpdateNativeChildLibModuleName(appLibPaths, isSystemApp); diff --git a/frameworks/native/appkit/app/context_container.cpp b/frameworks/native/appkit/app/context_container.cpp index c8072f3ca3..f315017888 100644 --- a/frameworks/native/appkit/app/context_container.cpp +++ b/frameworks/native/appkit/app/context_container.cpp @@ -23,7 +23,6 @@ #include "bundle_mgr_helper.h" #include "constants.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parameters.h" namespace OHOS { @@ -320,7 +319,13 @@ void ContextContainer::InitResourceManager(BundleInfo &bundleInfo, std::shared_p TAG_LOGE(AAFwkTag::APPKIT, "ContextContainer::InitResourceManager create resourceManager failed"); return; } + LoadResources(bundleInfo, resourceManager, resConfig, deal); +} +void ContextContainer::LoadResources(BundleInfo &bundleInfo, + std::shared_ptr &resourceManager, + std::unique_ptr &resConfig, std::shared_ptr &deal) +{ TAG_LOGD(AAFwkTag::APPKIT, "ContextContainer::InitResourceManager hapModuleInfos count: %{public}zu", bundleInfo.hapModuleInfos.size()); std::regex pattern(AbilityBase::Constants::ABS_CODE_PATH); diff --git a/frameworks/native/appkit/app/context_deal.cpp b/frameworks/native/appkit/app/context_deal.cpp index 9cedb20ee9..76051119f1 100644 --- a/frameworks/native/appkit/app/context_deal.cpp +++ b/frameworks/native/appkit/app/context_deal.cpp @@ -25,7 +25,6 @@ #include "directory_ex.h" #include "file_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iservice_registry.h" #include "os_account_manager_wrapper.h" #include "sys_mgr_client.h" diff --git a/frameworks/native/appkit/app/dump_runtime_helper.cpp b/frameworks/native/appkit/app/dump_runtime_helper.cpp new file mode 100644 index 0000000000..447a8fe428 --- /dev/null +++ b/frameworks/native/appkit/app/dump_runtime_helper.cpp @@ -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. + */ + +#include "dump_runtime_helper.h" + +#include "app_mgr_client.h" +#include "hilog_tag_wrapper.h" +#include "js_runtime.h" +#include "singleton.h" +#include "dfx_jsnapi.h" + +namespace OHOS { +namespace AppExecFwk { +DumpRuntimeHelper::DumpRuntimeHelper(const std::shared_ptr &application) + : application_(application) +{} + +void DumpRuntimeHelper::SetAppFreezeFilterCallback() +{ + if (application_ == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "SetAppFreezeFilterCallback OHOSApplication is nullptr"); + return; + } + auto& runtime = application_->GetRuntime(); + if (runtime == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "SetAppFreezeFilterCallback GetRuntime is nullptr"); + return; + } + auto appfreezeFilterCallback = [] (const int32_t pid) -> bool { + auto client = DelayedSingleton::GetInstance(); + if (client == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "SetAppFreezeFilterCallback client is nullptr"); + return false; + } + return client->SetAppFreezeFilter(pid); + }; + auto vm = (static_cast(*runtime)).GetEcmaVm(); + panda::DFXJSNApi::SetAppFreezeFilterCallback(vm, appfreezeFilterCallback); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/frameworks/native/appkit/app/extension_plugin_info.cpp b/frameworks/native/appkit/app/extension_plugin_info.cpp index 983673ccc3..e17fec869c 100755 --- a/frameworks/native/appkit/app/extension_plugin_info.cpp +++ b/frameworks/native/appkit/app/extension_plugin_info.cpp @@ -22,7 +22,6 @@ #include "extension_module_loader.h" #include "file_path_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/appkit/app/idle_time.cpp b/frameworks/native/appkit/app/idle_time.cpp index f1878c8813..d2c92620ba 100644 --- a/frameworks/native/appkit/app/idle_time.cpp +++ b/frameworks/native/appkit/app/idle_time.cpp @@ -16,7 +16,6 @@ #include "idle_time.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #ifdef SUPPORT_SCREEN #include "transaction/rs_interfaces.h" #endif // SUPPORT_SCREEN diff --git a/frameworks/native/appkit/app/main_thread.cpp b/frameworks/native/appkit/app/main_thread.cpp index a58c4c277f..757f2499c3 100644 --- a/frameworks/native/appkit/app/main_thread.cpp +++ b/frameworks/native/appkit/app/main_thread.cpp @@ -31,9 +31,7 @@ #include "ability_thread.h" #include "ability_util.h" #include "app_loader.h" -#include "ability_manager_client.h" #include "app_recovery.h" -#include "app_utils.h" #include "appfreeze_inner.h" #include "appfreeze_state.h" #include "application_data_manager.h" @@ -49,6 +47,7 @@ #include "context_impl.h" #include "dump_ffrt_helper.h" #include "dump_ipc_helper.h" +#include "dump_runtime_helper.h" #include "exit_reason.h" #include "extension_ability_info.h" #include "extension_module_loader.h" @@ -75,6 +74,7 @@ #ifdef CJ_FRONTEND #include "cj_runtime.h" #endif +#include "nlohmann/json.hpp" #include "ohos_application.h" #include "overlay_module_info.h" #include "parameters.h" @@ -157,7 +157,9 @@ const std::string SIGNAL_HANDLER = "OS_SignalHandler"; constexpr uint32_t CHECK_MAIN_THREAD_IS_ALIVE = 1; const std::string OVERLAY_STATE_CHANGED = "usual.event.OVERLAY_STATE_CHANGED"; - +const std::string JSON_KEY_APP_FONT_SIZE_SCALE = "fontSizeScale"; +const std::string JSON_KEY_APP_FONT_MAX_SCALE = "fontSizeMaxScale"; +const std::string JSON_KEY_APP_CONFIGURATION = "configuration"; const int32_t TYPE_RESERVE = 1; const int32_t TYPE_OTHERS = 2; @@ -496,12 +498,13 @@ void MainThread::ScheduleForegroundApplication() if (!mainHandler_->PostTask(task, "MainThread:ForegroundApplication")) { TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed"); } - - if (watchdog_ == nullptr) { + auto tmpWatchdog = watchdog_; + if (tmpWatchdog == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "Watch dog is nullptr."); return; } - watchdog_->SetBackgroundStatus(false); + tmpWatchdog->SetBackgroundStatus(false); + tmpWatchdog = nullptr; } /** @@ -511,7 +514,8 @@ void MainThread::ScheduleForegroundApplication() */ void MainThread::ScheduleBackgroundApplication() { - TAG_LOGD(AAFwkTag::APPKIT, "called"); + TAG_LOGI(AAFwkTag::APPKIT, "called"); + HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); wptr weak = this; auto task = [weak]() { auto appThread = weak.promote(); @@ -525,11 +529,13 @@ void MainThread::ScheduleBackgroundApplication() TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed"); } - if (watchdog_ == nullptr) { + auto tmpWatchdog = watchdog_; + if (tmpWatchdog == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "Watch dog is nullptr."); return; } - watchdog_->SetBackgroundStatus(true); + tmpWatchdog->SetBackgroundStatus(true); + tmpWatchdog = nullptr; } /** @@ -789,8 +795,10 @@ void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr(abilityInfo, token); abilityRecord->SetWant(want); abilityRecord->SetAbilityRecordId(abilityRecordId); - if (watchdog_ != nullptr) { - watchdog_->SetBgWorkingThreadStatus(IsBgWorkingThread(info)); + auto tmpWatchdog = watchdog_; + if (tmpWatchdog != nullptr) { + tmpWatchdog->SetBgWorkingThreadStatus(IsBgWorkingThread(info)); + tmpWatchdog = nullptr; } FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::LOAD }; std::string entry = std::to_string(AbilityRuntime::TimeUtil::SystemTimeMillisecond()) + @@ -1045,66 +1053,14 @@ bool MainThread::CheckForHandleLaunchApplication(const AppLaunchData &appLaunchD bool MainThread::InitResourceManager(std::shared_ptr &resourceManager, const AppExecFwk::HapModuleInfo &entryHapModuleInfo, const std::string &bundleName, - bool multiProjects, const Configuration &config) + const Configuration &config, const ApplicationInfo &appInfo) { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); bool isStageBased = entryHapModuleInfo.isStageBasedModel; - if (isStageBased && multiProjects) { + if (isStageBased && appInfo.multiProjects) { TAG_LOGI(AAFwkTag::APPKIT, "multiProjects"); } else { - std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + bundleName); - std::string loadPath = - (!entryHapModuleInfo.hapPath.empty()) ? entryHapModuleInfo.hapPath : entryHapModuleInfo.resourcePath; - if (!loadPath.empty()) { - loadPath = std::regex_replace(loadPath, pattern, std::string(LOCAL_CODE_PATH)); - TAG_LOGD(AAFwkTag::APPKIT, "ModuleResPath: %{public}s", loadPath.c_str()); - // getOverlayPath - auto res = GetOverlayModuleInfos(bundleName, entryHapModuleInfo.moduleName, overlayModuleInfos_); - if (res != ERR_OK) { - TAG_LOGW(AAFwkTag::APPKIT, "getOverlayPath failed."); - } - if (overlayModuleInfos_.size() == 0) { - if (!resourceManager->AddResource(loadPath.c_str())) { - TAG_LOGE(AAFwkTag::APPKIT, "AddResource failed"); - } - } else { - std::vector overlayPaths; - for (auto it : overlayModuleInfos_) { - if (std::regex_search(it.hapPath, std::regex(bundleName))) { - it.hapPath = std::regex_replace(it.hapPath, pattern, std::string(LOCAL_CODE_PATH)); - } else { - it.hapPath = std::regex_replace(it.hapPath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES); - } - if (it.state == OverlayState::OVERLAY_ENABLE) { - TAG_LOGD(AAFwkTag::APPKIT, "hapPath: %{public}s", it.hapPath.c_str()); - overlayPaths.emplace_back(it.hapPath); - } - } - TAG_LOGD(AAFwkTag::APPKIT, "OverlayPaths size:%{public}zu.", overlayPaths.size()); - if (!resourceManager->AddResource(loadPath, overlayPaths)) { - TAG_LOGE(AAFwkTag::APPKIT, "AddResource failed"); - } - // add listen overlay change - EventFwk::MatchingSkills matchingSkills; - matchingSkills.AddEvent(OVERLAY_STATE_CHANGED); - EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); - subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); - wptr weak = this; - auto callback = [weak, resourceManager, bundleName, moduleName = entryHapModuleInfo.moduleName, - loadPath](const EventFwk::CommonEventData &data) { - TAG_LOGD(AAFwkTag::APPKIT, "On overlay changed."); - auto appThread = weak.promote(); - if (appThread == nullptr) { - TAG_LOGE(AAFwkTag::APPKIT, "abilityThread is nullptr, SetRunnerStarted failed."); - return; - } - appThread->OnOverlayChanged(data, resourceManager, bundleName, moduleName, loadPath); - }; - auto subscriber = std::make_shared(subscribeInfo, callback); - bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber); - TAG_LOGD(AAFwkTag::APPKIT, "Overlay event subscriber register result is %{public}d", subResult); - } - } + OnStartAbility(bundleName, resourceManager, entryHapModuleInfo, appInfo.debug); } std::unique_ptr resConfig(Global::Resource::CreateResConfig()); @@ -1149,6 +1105,89 @@ bool MainThread::InitResourceManager(std::shared_ptr &resourceManager, + const AppExecFwk::HapModuleInfo &entryHapModuleInfo, const bool isDebugApp) +{ + std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + bundleName); + std::string loadPath = + (!entryHapModuleInfo.hapPath.empty()) ? entryHapModuleInfo.hapPath : entryHapModuleInfo.resourcePath; + if (!loadPath.empty()) { + loadPath = std::regex_replace(loadPath, pattern, std::string(LOCAL_CODE_PATH)); + TAG_LOGD(AAFwkTag::APPKIT, "ModuleResPath: %{public}s", loadPath.c_str()); + // getOverlayPath + auto res = GetOverlayModuleInfos(bundleName, entryHapModuleInfo.moduleName, overlayModuleInfos_); + if (res != ERR_OK) { + TAG_LOGW(AAFwkTag::APPKIT, "getOverlayPath failed."); + } + if (overlayModuleInfos_.size() == 0) { + if (!resourceManager->AddResource(loadPath.c_str())) { + TAG_LOGE(AAFwkTag::APPKIT, "AddResource failed"); + } + } else { + std::vector overlayPaths = GetOverlayPaths(bundleName, overlayModuleInfos_); + TAG_LOGD(AAFwkTag::APPKIT, "OverlayPaths size:%{public}zu.", overlayPaths.size()); + if (!resourceManager->AddResource(loadPath, overlayPaths)) { + TAG_LOGE(AAFwkTag::APPKIT, "AddResource failed"); + } + SubscribeOverlayChange(bundleName, loadPath, resourceManager, entryHapModuleInfo); + } + std::string hqfPath = entryHapModuleInfo.hqfInfo.hqfFilePath; + if (!hqfPath.empty() && isDebugApp) { + hqfPath = std::regex_replace(hqfPath, pattern, std::string(LOCAL_CODE_PATH)); + TAG_LOGI(AAFwkTag::APPKIT, "AddPatchResource hapPath:%{public}s, patchPath:%{public}s", + loadPath.c_str(), hqfPath.c_str()); + if (!resourceManager->AddPatchResource(loadPath.c_str(), hqfPath.c_str())) { + TAG_LOGE(AAFwkTag::APPKIT, "AddPatchResource failed"); + } + } + } +} + +std::vector MainThread::GetOverlayPaths(const std::string &bundleName, + const std::vector &overlayModuleInfos) +{ + std::vector overlayPaths; + for (auto it : overlayModuleInfos_) { + if (std::regex_search(it.hapPath, std::regex(bundleName))) { + it.hapPath = std::regex_replace(it.hapPath, std::regex(std::string(ABS_CODE_PATH) + + std::string(FILE_SEPARATOR) + bundleName), std::string(LOCAL_CODE_PATH)); + } else { + it.hapPath = std::regex_replace(it.hapPath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES); + } + if (it.state == OverlayState::OVERLAY_ENABLE) { + TAG_LOGD(AAFwkTag::APPKIT, "hapPath: %{public}s", it.hapPath.c_str()); + overlayPaths.emplace_back(it.hapPath); + } + } + return overlayPaths; +} + +void MainThread::SubscribeOverlayChange(const std::string &bundleName, const std::string &loadPath, + std::shared_ptr &resourceManager, + const AppExecFwk::HapModuleInfo &entryHapModuleInfo) +{ + // add listen overlay change + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(OVERLAY_STATE_CHANGED); + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); + wptr weak = this; + auto callback = [weak, resourceManager, bundleName, moduleName = entryHapModuleInfo.moduleName, + loadPath](const EventFwk::CommonEventData &data) { + TAG_LOGD(AAFwkTag::APPKIT, "On overlay changed."); + auto appThread = weak.promote(); + if (appThread == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "abilityThread is nullptr, SetRunnerStarted failed."); + return; + } + appThread->OnOverlayChanged(data, resourceManager, bundleName, moduleName, loadPath); + }; + auto subscriber = std::make_shared(subscribeInfo, callback); + bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber); + TAG_LOGD(AAFwkTag::APPKIT, "Overlay event subscriber register result is %{public}d", subResult); +} + void MainThread::OnOverlayChanged(const EventFwk::CommonEventData &data, const std::shared_ptr &resourceManager, const std::string &bundleName, const std::string &moduleName, const std::string &loadPath) @@ -1273,8 +1312,8 @@ CJUncaughtExceptionInfo MainThread::CreateCjExceptionInfo(const std::string &bun time_t timet; time(&timet); std::string errName = errorObj.name ? errorObj.name : "[none]"; - std::string errMsg = errorObj.name ? errorObj.message : "[none]"; - std::string errStack = errorObj.name ? errorObj.stack : "[none]"; + std::string errMsg = errorObj.message ? errorObj.message : "[none]"; + std::string errStack = errorObj.stack ? errorObj.stack : "[none]"; HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, "CJ_ERROR", OHOS::HiviewDFX::HiSysEvent::EventType::FAULT, EVENT_KEY_PACKAGE_NAME, bundleName, @@ -1347,7 +1386,11 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con } auto bundleName = appInfo.bundleName; - watchdog_->SetBundleInfo(bundleName, appInfo.versionName); + auto tmpWatchdog = watchdog_; + if (tmpWatchdog != nullptr) { + tmpWatchdog->SetBundleInfo(bundleName, appInfo.versionName); + tmpWatchdog = nullptr; + } BundleInfo bundleInfo; if (!GetBundleForLaunchApplication(bundleMgrHelper, bundleName, appLaunchData.GetAppIndex(), bundleInfo)) { TAG_LOGE(AAFwkTag::APPKIT, "Failed to get bundle info."); @@ -1375,7 +1418,7 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con } #ifdef CJ_FRONTEND if (!entryHapModuleInfo.abilityInfos.empty()) { - isCJApp = IsCJAbility(entryHapModuleInfo.abilityInfos.front().srcEntrance); + isCJApp = AbilityRuntime::CJRuntime::IsCJAbility(entryHapModuleInfo.abilityInfos.front().srcEntrance); } #endif moduelJson = entryHapModuleInfo.isModuleJson; @@ -1463,6 +1506,11 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con #ifdef CJ_FRONTEND if (isCJApp) { AbilityRuntime::CJRuntime::SetAppLibPath(appLibPaths); + if (appInfo.asanEnabled) { + AbilityRuntime::CJRuntime::SetAsanVersion(); + } else if (appInfo.tsanEnabled) { + AbilityRuntime::CJRuntime::SetTsanVersion(); + } } else { #endif AbilityRuntime::JsRuntime::SetAppLibPath(appLibPaths, isSystemApp); @@ -1493,6 +1541,9 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con if (applicationInfo_->appProvisionType == Constants::APP_PROVISION_TYPE_DEBUG) { TAG_LOGD(AAFwkTag::JSRUNTIME, "Start Multi-Thread Mode: %{public}d.", appLaunchData.GetMultiThread()); options.isMultiThread = appLaunchData.GetMultiThread(); + TAG_LOGD(AAFwkTag::JSRUNTIME, "Start Error-Info-Enhance Mode: %{public}d.", + appLaunchData.GetErrorInfoEnhance()); + options.isErrorInfoEnhance = appLaunchData.GetErrorInfoEnhance(); } options.jitEnabled = appLaunchData.IsJITEnabled(); AbilityRuntime::ChildProcessManager::GetInstance().SetForkProcessJITEnabled(appLaunchData.IsJITEnabled()); @@ -1601,7 +1652,7 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con TAG_LOGI(AAFwkTag::APPKIT, "hisysevent write result=%{public}d, send event [FRAMEWORK,PROCESS_KILL]," " pid=%{public}d, processName=%{public}s, msg=%{public}s", result, pid, processName.c_str(), KILL_REASON); - + if (ApplicationDataManager::GetInstance().NotifyUnhandledException(summary) && ApplicationDataManager::GetInstance().NotifyExceptionObject(appExecErrorObj)) { return; @@ -1661,6 +1712,9 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con IdleNotifyStatusCallback cb = idleTime_->GetIdleNotifyFunc(); jsEngine.NotifyIdleStatusControl(cb); + + auto helper = std::make_shared(application_); + helper->SetAppFreezeFilterCallback(); } #ifdef CJ_FRONTEND } @@ -1705,8 +1759,11 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con return; } + Configuration appConfig = config; + ParseAppConfigurationParams(bundleInfo.applicationInfo.configuration, appConfig); + if (!InitResourceManager(resourceManager, entryHapModuleInfo, bundleInfo.name, - bundleInfo.applicationInfo.multiProjects, config)) { + appConfig, bundleInfo.applicationInfo)) { TAG_LOGE(AAFwkTag::APPKIT, "InitResourceManager failed"); return; } @@ -1717,7 +1774,7 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con contextDeal->SetApplicationContext(application_); application_->AttachBaseContext(contextDeal); application_->SetAbilityRecordMgr(abilityRecordMgr_); - application_->SetConfiguration(config); + application_->SetConfiguration(appConfig); contextImpl->SetConfiguration(application_->GetConfiguration()); applicationImpl_->SetRecordId(appLaunchData.GetRecordId()); @@ -2197,7 +2254,7 @@ void MainThread::HandleCleanAbility(const sptr &token, bool isCac void MainThread::HandleForegroundApplication() { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::APPKIT, "called."); + TAG_LOGI(AAFwkTag::APPKIT, "called."); if ((application_ == nullptr) || (appMgr_ == nullptr)) { TAG_LOGE(AAFwkTag::APPKIT, "MainThread::handleForegroundApplication error!"); return; @@ -2224,7 +2281,7 @@ void MainThread::HandleForegroundApplication() void MainThread::HandleBackgroundApplication() { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::APPKIT, "start."); + TAG_LOGI(AAFwkTag::APPKIT, "start."); if ((application_ == nullptr) || (appMgr_ == nullptr)) { TAG_LOGE(AAFwkTag::APPKIT, "error!"); @@ -2400,38 +2457,37 @@ void MainThread::HandleSignal(int signal, [[maybe_unused]] siginfo_t *siginfo, v } switch (static_cast(siginfo->si_value.sival_int)) { case SignalType::SIGNAL_JSHEAP_OLD: { - auto heapFunc = std::bind(&MainThread::HandleDumpHeap, false); + auto heapFunc = []() { return MainThread::HandleDumpHeap(false); }; mainHandler_->PostTask(heapFunc, "MainThread::SIGNAL_JSHEAP_OLD"); - break; } case SignalType::SIGNAL_JSHEAP: { - auto heapFunc = std::bind(&MainThread::HandleDumpHeap, false); + auto heapFunc = []() { return MainThread::HandleDumpHeap(false); }; mainHandler_->PostTask(heapFunc, "MainThread::SIGNAL_JSHEAP"); break; } case SignalType::SIGNAL_JSHEAP_PRIV: { - auto privateHeapFunc = std::bind(&MainThread::HandleDumpHeap, true); + auto privateHeapFunc = []() { return MainThread::HandleDumpHeap(true); }; mainHandler_->PostTask(privateHeapFunc, "MainThread:SIGNAL_JSHEAP_PRIV"); break; } case SignalType::SIGNAL_NO_TRIGGERID: { - auto heapFunc = std::bind(&MainThread::HandleDumpHeap, false); + auto heapFunc = []() { return MainThread::HandleDumpHeap(false); }; mainHandler_->PostTask(heapFunc, "MainThread::SIGNAL_JSHEAP"); - auto noTriggerIdFunc = std::bind(&MainThread::DestroyHeapProfiler); + auto noTriggerIdFunc = []() { MainThread::DestroyHeapProfiler(); }; mainHandler_->PostTask(noTriggerIdFunc, "MainThread::SIGNAL_NO_TRIGGERID"); break; } case SignalType::SIGNAL_NO_TRIGGERID_PRIV: { - auto privateHeapFunc = std::bind(&MainThread::HandleDumpHeap, true); + auto privateHeapFunc = []() { return MainThread::HandleDumpHeap(true); }; mainHandler_->PostTask(privateHeapFunc, "MainThread:SIGNAL_JSHEAP_PRIV"); - auto noTriggerIdFunc = std::bind(&MainThread::DestroyHeapProfiler); + auto noTriggerIdFunc = []() { MainThread::DestroyHeapProfiler(); }; mainHandler_->PostTask(noTriggerIdFunc, "MainThread::SIGNAL_NO_TRIGGERID_PRIV"); break; } case SignalType::SIGNAL_FORCE_FULLGC: { - auto forceFullGCFunc = std::bind(&MainThread::ForceFullGC); + auto forceFullGCFunc = []() { MainThread::ForceFullGC(); }; ffrt::submit(forceFullGCFunc); break; } @@ -2512,7 +2568,7 @@ void MainThread::HandleDumpHeap(bool isPrivate) }; ffrt::submit(taskFork, {}, {}, ffrt::task_attr().qos(ffrt::qos_user_initiated)); - runtime->DumpCpuProfile(isPrivate); + runtime->DumpCpuProfile(); } void MainThread::DestroyHeapProfiler() @@ -2558,15 +2614,6 @@ void MainThread::Start() HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::APPKIT, "App main thread create, pid:%{public}d.", getprocpid()); - if (AAFwk::AppUtils::GetInstance().IsMultiProcessModel()) { - ChildProcessInfo info; - if (IsStartChild(info)) { - ChildMainThread::Start(info); - TAG_LOGD(AAFwkTag::APPKIT, "MainThread::ChildMainThread end."); - return; - } - } - std::shared_ptr runner = EventRunner::GetMainEventRunner(); if (runner == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "runner is nullptr"); @@ -2596,20 +2643,11 @@ void MainThread::Start() thread->RemoveAppMgrDeathRecipient(); } -bool MainThread::IsStartChild(ChildProcessInfo &info) +void MainThread::StartChild(const std::map &fds) { - TAG_LOGD(AAFwkTag::APPKIT, "called."); - auto object = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID); - if (object == nullptr) { - TAG_LOGE(AAFwkTag::APPKIT, "failed to get app manager service"); - return false; - } - auto appMgr = iface_cast(object); - if (appMgr == nullptr) { - TAG_LOGE(AAFwkTag::APPKIT, "failed to iface_cast object to appMgr"); - return false; - } - return appMgr->GetChildProcessInfoForSelf(info) == ERR_OK; + TAG_LOGI(AAFwkTag::APPKIT, "MainThread StartChild, fds size:%{public}zu", fds.size()); + ChildMainThread::Start(fds); + TAG_LOGD(AAFwkTag::APPKIT, "MainThread::ChildMainThread end."); } void MainThread::PreloadExtensionPlugin() @@ -2671,15 +2709,7 @@ void MainThread::LoadAbilityLibrary(const std::vector &libraryPaths #ifdef ABILITY_LIBRARY_LOADER TAG_LOGD(AAFwkTag::APPKIT, "start."); #ifdef SUPPORT_SCREEN - void *AceAbilityLib = nullptr; - const char *path = Ace::AceForwardCompatibility::GetAceLibName(); - AceAbilityLib = dlopen(path, RTLD_NOW | RTLD_LOCAL); - if (AceAbilityLib == nullptr) { - TAG_LOGE(AAFwkTag::APPKIT, "Fail to dlopen %{public}s, [%{public}s]", path, dlerror()); - } else { - TAG_LOGD(AAFwkTag::APPKIT, "Success to dlopen %{public}s", path); - handleAbilityLib_.emplace_back(AceAbilityLib); - } + LoadAceAbilityLibrary(); #endif size_t size = libraryPaths.size(); for (size_t index = 0; index < size; index++) { @@ -2722,6 +2752,19 @@ void MainThread::LoadAbilityLibrary(const std::vector &libraryPaths #endif // ABILITY_LIBRARY_LOADER } +void MainThread::LoadAceAbilityLibrary() +{ + void *AceAbilityLib = nullptr; + const char *path = Ace::AceForwardCompatibility::GetAceLibName(); + AceAbilityLib = dlopen(path, RTLD_NOW | RTLD_LOCAL); + if (AceAbilityLib == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "Fail to dlopen %{public}s, [%{public}s]", path, dlerror()); + } else { + TAG_LOGD(AAFwkTag::APPKIT, "Success to dlopen %{public}s", path); + handleAbilityLib_.emplace_back(AceAbilityLib); + } +} + void MainThread::LoadAppLibrary() { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); @@ -2907,13 +2950,15 @@ void MainThread::ScheduleNewProcessRequest(const AAFwk::Want &want, const std::s void MainThread::CheckMainThreadIsAlive() { - if (watchdog_ == nullptr) { + auto tmpWatchdog = watchdog_; + if (tmpWatchdog == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "Watch dog is nullptr."); return; } - watchdog_->SetAppMainThreadState(true); - watchdog_->AllowReportEvent(); + tmpWatchdog->SetAppMainThreadState(true); + tmpWatchdog->AllowReportEvent(); + tmpWatchdog = nullptr; } #endif // ABILITY_LIBRARY_LOADER @@ -3233,19 +3278,19 @@ int32_t MainThread::ChangeAppGcState(int32_t state) void MainThread::AttachAppDebug() { - TAG_LOGD(AAFwkTag::APPKIT, "Called."); + TAG_LOGD(AAFwkTag::APPKIT, "called"); SetAppDebug(AbilityRuntime::AppFreezeState::AppFreezeFlag::ATTACH_DEBUG_MODE, true); } void MainThread::DetachAppDebug() { - TAG_LOGD(AAFwkTag::APPKIT, "Called."); + TAG_LOGD(AAFwkTag::APPKIT, "called"); SetAppDebug(AbilityRuntime::AppFreezeState::AppFreezeFlag::ATTACH_DEBUG_MODE, false); } bool MainThread::NotifyDeviceDisConnect() { - TAG_LOGD(AAFwkTag::APPKIT, "Called."); + TAG_LOGD(AAFwkTag::APPKIT, "called"); bool isLastProcess = appMgr_->IsFinalAppProcess(); ScheduleTerminateApplication(isLastProcess); return true; @@ -3253,7 +3298,7 @@ bool MainThread::NotifyDeviceDisConnect() void MainThread::AssertFaultPauseMainThreadDetection() { - TAG_LOGD(AAFwkTag::APPKIT, "Called."); + TAG_LOGD(AAFwkTag::APPKIT, "called"); SetAppDebug(AbilityRuntime::AppFreezeState::AppFreezeFlag::ASSERT_DEBUG_MODE, true); if (appMgr_ == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "appMgr is nullptr."); @@ -3264,7 +3309,7 @@ void MainThread::AssertFaultPauseMainThreadDetection() void MainThread::AssertFaultResumeMainThreadDetection() { - TAG_LOGD(AAFwkTag::APPKIT, "Called."); + TAG_LOGD(AAFwkTag::APPKIT, "called"); SetAppDebug(AbilityRuntime::AppFreezeState::AppFreezeFlag::ASSERT_DEBUG_MODE, false); if (appMgr_ == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "appMgr is nullptr."); @@ -3298,7 +3343,7 @@ void MainThread::HandleInitAssertFaultTask(bool isDebugModule, bool isDebugApp) void MainThread::SetAppDebug(uint32_t modeFlag, bool isDebug) { - TAG_LOGD(AAFwkTag::APPKIT, "Called."); + TAG_LOGD(AAFwkTag::APPKIT, "called"); auto state = DelayedSingleton::GetInstance(); if (state == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "Get app freeze state instance is nullptr."); @@ -3378,6 +3423,43 @@ void MainThread::ScheduleCacheProcess() } } +void MainThread::ParseAppConfigurationParams(const std::string configuration, Configuration &appConfig) +{ + TAG_LOGD(AAFwkTag::APPKIT, "start"); + if (configuration.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "the configuration is empty"); + return; + } + nlohmann::json configurationJson = nlohmann::json::parse(configuration, nullptr, false); + if (configurationJson.is_discarded()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "json discarded error"); + return; + } + if (!configurationJson.contains(JSON_KEY_APP_CONFIGURATION)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "app configuration is not exist"); + return; + } + nlohmann::json jsonObject = configurationJson.at(JSON_KEY_APP_CONFIGURATION).get(); + if (jsonObject.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "app configuration is null"); + return; + } + if (jsonObject.contains(JSON_KEY_APP_FONT_SIZE_SCALE) + && jsonObject[JSON_KEY_APP_FONT_SIZE_SCALE].is_string()) { + appConfig.AddItem(AAFwk::GlobalConfigurationKey::APP_FONT_SIZE_SCALE, + jsonObject.at(JSON_KEY_APP_FONT_SIZE_SCALE).get()); + } + if (jsonObject.contains(JSON_KEY_APP_FONT_MAX_SCALE) + && jsonObject[JSON_KEY_APP_FONT_MAX_SCALE].is_string()) { + std::string appFontMaxScale = jsonObject.at(JSON_KEY_APP_FONT_MAX_SCALE).get(); + const std::regex INTEGER_REGEX("^[-+]?([0-9]+)([.]([0-9]+))?$"); + if (std::regex_match(appFontMaxScale, INTEGER_REGEX)) { + appConfig.AddItem(AAFwk::GlobalConfigurationKey::APP_FONT_MAX_SCALE, appFontMaxScale); + } + } + TAG_LOGD(AAFwkTag::APPKIT, "configuration_: %{public}s", appConfig.GetName().c_str()); +} + /** * * @brief Notify application to prepare for process caching. diff --git a/frameworks/native/appkit/app/ohos_application.cpp b/frameworks/native/appkit/app/ohos_application.cpp index a2c5fd3fd9..fc8a969b40 100644 --- a/frameworks/native/appkit/app/ohos_application.cpp +++ b/frameworks/native/appkit/app/ohos_application.cpp @@ -23,6 +23,7 @@ #include "ability.h" #include "ability_record_mgr.h" +#include "ability_stage_context.h" #include "ability_thread.h" #include "app_loader.h" #include "application_context.h" @@ -32,7 +33,6 @@ #include "configuration_utils.h" #include "context_impl.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "iservice_registry.h" #include "runtime.h" @@ -445,6 +445,8 @@ void OHOSApplication::OnConfigurationUpdated(Configuration config) } std::string language = config.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE); std::string colorMode = config.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE); + std::string fontSizeScal = config.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_FONT_SIZE_SCALE); + std::string fontWeightScale = config.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_FONT_WEIGHT_SCALE); std::string languageIsSetByApp = config.GetItem(AAFwk::GlobalConfigurationKey::LANGUAGE_IS_SET_BY_APP); std::string colorModeIsSetByApp = @@ -462,7 +464,9 @@ void OHOSApplication::OnConfigurationUpdated(Configuration config) configuration_->GetItem(AAFwk::GlobalConfigurationKey::COLORMODE_IS_SET_BY_APP); std::string globalColorModeIsSetBySa = configuration_->GetItem(AAFwk::GlobalConfigurationKey::COLORMODE_IS_SET_BY_SA); - if (colorMode.compare(ConfigurationInner::COLOR_MODE_AUTO) == 0) { + std::string globalFontFollowSysteme = + configuration_->GetItem(AAFwk::GlobalConfigurationKey::APP_FONT_SIZE_SCALE); + if (colorMode.compare(ConfigurationInner::COLOR_MODE_AUTO) == 0 && globalColorModeIsSetBySa.empty()) { TAG_LOGD(AAFwkTag::APPKIT, "colorMode is auto"); constexpr int buffSize = 64; char valueGet[buffSize] = { 0 }; @@ -474,14 +478,21 @@ void OHOSApplication::OnConfigurationUpdated(Configuration config) config.AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, valueGet); } if (!colorMode.empty() && colorModeIsSetByApp.empty() && colorModeIsSetBySa.empty()) { - if ((!globalColorModeIsSetByApp.empty() || !globalColorModeIsSetBySa.empty()) && - globalColorMode.compare(ConfigurationInner::COLOR_MODE_AUTO) != 0) { + if ((!globalColorModeIsSetByApp.empty() && globalColorMode.compare(ConfigurationInner::COLOR_MODE_AUTO) != 0) || + !globalColorModeIsSetBySa.empty()) { TAG_LOGD(AAFwkTag::APPKIT, "colormode has been set by app or sa"); return; } } + if (!fontSizeScal.empty() || !fontWeightScale.empty()) { + if (!globalFontFollowSysteme.empty() + && globalFontFollowSysteme.compare(ConfigurationInner::IS_APP_FONT_FOLLOW_SYSTEM) != 0) { + TAG_LOGW(AAFwkTag::APPKIT, "the font configured for the app does not take effect with the system"); + return; + } + } if (!colorModeIsSetBySa.empty() && colorModeIsSetByApp.empty()) { - if (!globalColorModeIsSetByApp.empty()) { + if (!globalColorModeIsSetByApp.empty() && globalColorMode.compare(ConfigurationInner::COLOR_MODE_AUTO) != 0) { TAG_LOGD(AAFwkTag::APPKIT, "colormode has been set by app"); return; } @@ -490,12 +501,6 @@ void OHOSApplication::OnConfigurationUpdated(Configuration config) TAG_LOGD(AAFwkTag::APPKIT, "language has been set by app"); return; } - // When display move happened, need to remove SA key, so setting can update colormode success after display move. - if (!colorModeNeedRemoveIsSetBySa.empty() && !globalColorModeIsSetBySa.empty()) { - configuration_->RemoveItem(AAFwk::GlobalConfigurationKey::COLORMODE_IS_SET_BY_SA); - config.RemoveItem(AAFwk::GlobalConfigurationKey::COLORMODE_NEED_REMOVE_SET_BY_SA); - config.RemoveItem(AAFwk::GlobalConfigurationKey::COLORMODE_IS_SET_BY_SA); - } std::vector changeKeyV; { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "configuration_->CompareDifferent"); @@ -539,11 +544,20 @@ void OHOSApplication::OnConfigurationUpdated(Configuration config) } abilityRuntimeContext_->DispatchConfigurationUpdated(*configuration_); + abilityRuntimeContext_->SetMcc(configuration_->GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_MCC)); + abilityRuntimeContext_->SetMnc(configuration_->GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_MNC)); - if (colorMode.compare(ConfigurationInner::COLOR_MODE_AUTO) == 0 - || (globalColorMode.compare(ConfigurationInner::COLOR_MODE_AUTO) == 0 && colorModeIsSetByApp.empty())) { + if (colorMode.compare(ConfigurationInner::COLOR_MODE_AUTO) == 0 || + (globalColorMode.compare(ConfigurationInner::COLOR_MODE_AUTO) == 0 && (colorModeIsSetByApp.empty() || + !colorModeIsSetBySa.empty()))) { configuration_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, ConfigurationInner::COLOR_MODE_AUTO); } + + // When display move happened, need to remove SA key, so setting can update colormode success after display move. + if (!colorModeNeedRemoveIsSetBySa.empty() && !globalColorModeIsSetBySa.empty()) { + configuration_->RemoveItem(AAFwk::GlobalConfigurationKey::COLORMODE_IS_SET_BY_SA); + configuration_->RemoveItem(AAFwk::GlobalConfigurationKey::COLORMODE_NEED_REMOVE_SET_BY_SA); + } } /** @@ -670,7 +684,7 @@ std::shared_ptr OHOSApplication::AddAbilityStage( std::shared_ptr abilityStage; auto iterator = abilityStages_.find(moduleName); if (iterator == abilityStages_.end()) { - std::shared_ptr stageContext = std::make_shared(); + auto stageContext = std::make_shared(); stageContext->SetParentContext(abilityRuntimeContext_); stageContext->InitHapModuleInfo(abilityInfo); stageContext->SetConfiguration(GetConfiguration()); @@ -789,7 +803,7 @@ bool OHOSApplication::AddAbilityStage(const AppExecFwk::HapModuleInfo &hapModule return false; } - auto stageContext = std::make_shared(); + auto stageContext = std::make_shared(); stageContext->SetParentContext(abilityRuntimeContext_); stageContext->InitHapModuleInfo(hapModuleInfo); stageContext->SetConfiguration(GetConfiguration()); diff --git a/frameworks/native/appkit/app/overlay_event_subscriber.cpp b/frameworks/native/appkit/app/overlay_event_subscriber.cpp index cf3336c7f1..7c2f5ed926 100644 --- a/frameworks/native/appkit/app/overlay_event_subscriber.cpp +++ b/frameworks/native/appkit/app/overlay_event_subscriber.cpp @@ -17,7 +17,6 @@ #include "bundle_mgr_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "overlay_module_info.h" namespace OHOS { diff --git a/frameworks/native/appkit/app/sys_mgr_client.cpp b/frameworks/native/appkit/app/sys_mgr_client.cpp index 95c0982374..125fe6f1cf 100644 --- a/frameworks/native/appkit/app/sys_mgr_client.cpp +++ b/frameworks/native/appkit/app/sys_mgr_client.cpp @@ -16,7 +16,6 @@ #include "sys_mgr_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" diff --git a/frameworks/native/appkit/app_startup/js_startup_config.cpp b/frameworks/native/appkit/app_startup/js_startup_config.cpp index 9dd117a28b..3968109d86 100644 --- a/frameworks/native/appkit/app_startup/js_startup_config.cpp +++ b/frameworks/native/appkit/app_startup/js_startup_config.cpp @@ -16,7 +16,6 @@ #include "js_startup_config.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" namespace OHOS { diff --git a/frameworks/native/appkit/app_startup/js_startup_task.cpp b/frameworks/native/appkit/app_startup/js_startup_task.cpp index c0dfdd5876..b183456987 100644 --- a/frameworks/native/appkit/app_startup/js_startup_task.cpp +++ b/frameworks/native/appkit/app_startup/js_startup_task.cpp @@ -16,7 +16,6 @@ #include "js_startup_task.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" namespace { @@ -82,7 +81,7 @@ int32_t JsStartupTask::RunTaskInit(std::unique_ptr ca int32_t JsStartupTask::LoadJsAsyncTaskExcutor() { - TAG_LOGD(AAFwkTag::STARTUP, "Called."); + TAG_LOGD(AAFwkTag::STARTUP, "called"); HandleScope handleScope(jsRuntime_); auto env = jsRuntime_.GetNapiEnv(); @@ -100,7 +99,7 @@ int32_t JsStartupTask::LoadJsAsyncTaskExcutor() void JsStartupTask::LoadJsAsyncTaskCallback() { - TAG_LOGD(AAFwkTag::STARTUP, "Called."); + TAG_LOGD(AAFwkTag::STARTUP, "called"); HandleScope handleScope(jsRuntime_); auto env = jsRuntime_.GetNapiEnv(); @@ -122,7 +121,7 @@ void JsStartupTask::LoadJsAsyncTaskCallback() void JsStartupTask::OnAsyncTaskCompleted(const std::shared_ptr &result) { - TAG_LOGD(AAFwkTag::STARTUP, "Called."); + TAG_LOGD(AAFwkTag::STARTUP, "called"); if (startupTaskResultCallback_ == nullptr) { TAG_LOGE(AAFwkTag::STARTUP, "Startup task result callback object is nullptr."); return; @@ -188,7 +187,7 @@ 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."); + TAG_LOGD(AAFwkTag::STARTUP, "called"); size_t argc = ARGC_TWO; napi_value argv[ARGC_TWO] = { nullptr }; napi_value thisVar = nullptr; @@ -223,7 +222,7 @@ napi_value AsyncTaskCallBack::AsyncTaskCompleted(napi_env env, napi_callback_inf napi_value AsyncTaskCallBack::Constructor(napi_env env, napi_callback_info cbinfo) { - TAG_LOGD(AAFwkTag::STARTUP, "Called."); + TAG_LOGD(AAFwkTag::STARTUP, "called"); return CreateJsUndefined(env); } } // namespace AbilityRuntime 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 e4bb365e22..365ce14c78 100644 --- a/frameworks/native/appkit/app_startup/js_startup_task_executor.cpp +++ b/frameworks/native/appkit/app_startup/js_startup_task_executor.cpp @@ -16,7 +16,6 @@ #include "js_startup_task_executor.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" #include "js_startup_task_result.h" @@ -49,7 +48,7 @@ int32_t JsStartupTaskExecutor::RunOnTaskPool( const std::unique_ptr &asyncTaskCallback, const std::string &startupName) { - TAG_LOGD(AAFwkTag::STARTUP, "Called."); + TAG_LOGD(AAFwkTag::STARTUP, "called"); HandleScope handleScope(jsRuntime); auto env = jsRuntime.GetNapiEnv(); diff --git a/frameworks/native/appkit/app_startup/startup_manager.cpp b/frameworks/native/appkit/app_startup/startup_manager.cpp index 3cc7f822ca..6f9107116e 100644 --- a/frameworks/native/appkit/app_startup/startup_manager.cpp +++ b/frameworks/native/appkit/app_startup/startup_manager.cpp @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/appkit/app_startup/startup_task.cpp b/frameworks/native/appkit/app_startup/startup_task.cpp index 00203dcc5a..0ea2a9250a 100644 --- a/frameworks/native/appkit/app_startup/startup_task.cpp +++ b/frameworks/native/appkit/app_startup/startup_task.cpp @@ -15,7 +15,6 @@ #include "startup_task.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/appkit/app_startup/startup_task_dispatcher.cpp b/frameworks/native/appkit/app_startup/startup_task_dispatcher.cpp index 4d7d3e750f..e7d87dd611 100644 --- a/frameworks/native/appkit/app_startup/startup_task_dispatcher.cpp +++ b/frameworks/native/appkit/app_startup/startup_task_dispatcher.cpp @@ -17,7 +17,6 @@ #include "event_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "startup_manager.h" namespace OHOS { diff --git a/frameworks/native/appkit/app_startup/startup_task_manager.cpp b/frameworks/native/appkit/app_startup/startup_task_manager.cpp index b7b3203ef7..38e5b1b5b1 100644 --- a/frameworks/native/appkit/app_startup/startup_task_manager.cpp +++ b/frameworks/native/appkit/app_startup/startup_task_manager.cpp @@ -16,7 +16,6 @@ #include "startup_task_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "startup_manager.h" #include "startup_topologysort.h" diff --git a/frameworks/native/appkit/app_startup/startup_task_result.cpp b/frameworks/native/appkit/app_startup/startup_task_result.cpp index a378faf843..d5f85e5748 100644 --- a/frameworks/native/appkit/app_startup/startup_task_result.cpp +++ b/frameworks/native/appkit/app_startup/startup_task_result.cpp @@ -16,7 +16,6 @@ #include "startup_task_result.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/appkit/dfr/appfreeze_inner.cpp b/frameworks/native/appkit/dfr/appfreeze_inner.cpp index 32b2af337d..3f8f1c9639 100644 --- a/frameworks/native/appkit/dfr/appfreeze_inner.cpp +++ b/frameworks/native/appkit/dfr/appfreeze_inner.cpp @@ -24,7 +24,6 @@ #include "ffrt.h" #include "freeze_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "hisysevent.h" #include "parameter.h" @@ -170,6 +169,7 @@ int AppfreezeInner::AcquireStack(const FaultData& info, bool onlyMainThread) faultData.notifyApp = false; faultData.waitSaveState = false; faultData.forceExit = false; + faultData.eventId = it->eventId; bool isExit = IsExitApp(it->errorObject.name); if (isExit) { faultData.forceExit = true; diff --git a/frameworks/native/appkit/dfr/appfreeze_state.cpp b/frameworks/native/appkit/dfr/appfreeze_state.cpp index 35eb37b9c5..1164784d5c 100644 --- a/frameworks/native/appkit/dfr/appfreeze_state.cpp +++ b/frameworks/native/appkit/dfr/appfreeze_state.cpp @@ -16,7 +16,6 @@ #include "appfreeze_inner.h" #include "appfreeze_state.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/appkit/dfr/watchdog.cpp b/frameworks/native/appkit/dfr/watchdog.cpp index 3e7adeeb3a..8447c963f8 100644 --- a/frameworks/native/appkit/dfr/watchdog.cpp +++ b/frameworks/native/appkit/dfr/watchdog.cpp @@ -23,7 +23,6 @@ #include "appfreeze_inner.h" #include "hisysevent.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "xcollie/watchdog.h" namespace OHOS { @@ -61,7 +60,7 @@ void Watchdog::Init(const std::shared_ptr mainHandler) appMainHandler_->SendEvent(CHECK_MAIN_THREAD_IS_ALIVE, 0, EventQueue::Priority::HIGH); } lastWatchTime_ = 0; - auto watchdogTask = std::bind(&Watchdog::Timer, this); + auto watchdogTask = [this] { this->Timer(); }; OHOS::HiviewDFX::Watchdog::GetInstance().RunPeriodicalTask("AppkitWatchdog", watchdogTask, CHECK_INTERVAL_TIME, INI_TIMER_FIRST_SECOND); } diff --git a/frameworks/native/child_process/src/native_child_callback.cpp b/frameworks/native/child_process/src/native_child_callback.cpp index 1102c8b3fb..9356d455ad 100644 --- a/frameworks/native/child_process/src/native_child_callback.cpp +++ b/frameworks/native/child_process/src/native_child_callback.cpp @@ -15,7 +15,6 @@ #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" diff --git a/frameworks/native/child_process/src/native_child_process.cpp b/frameworks/native/child_process/src/native_child_process.cpp index f87e4a8562..d976d29332 100644 --- a/frameworks/native/child_process/src/native_child_process.cpp +++ b/frameworks/native/child_process/src/native_child_process.cpp @@ -17,7 +17,6 @@ #include #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "native_child_callback.h" #include "child_process_manager.h" diff --git a/frameworks/native/insight_intent/insight_intent_context/insight_intent_context.cpp b/frameworks/native/insight_intent/insight_intent_context/insight_intent_context.cpp index 198b810f3f..6862356a2b 100644 --- a/frameworks/native/insight_intent/insight_intent_context/insight_intent_context.cpp +++ b/frameworks/native/insight_intent/insight_intent_context/insight_intent_context.cpp @@ -17,7 +17,6 @@ #include "ability_manager_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" namespace OHOS { diff --git a/frameworks/native/insight_intent/insight_intent_context/js_insight_intent_context.cpp b/frameworks/native/insight_intent/insight_intent_context/js_insight_intent_context.cpp index 2bcef8817b..a3361c2f2c 100644 --- a/frameworks/native/insight_intent/insight_intent_context/js_insight_intent_context.cpp +++ b/frameworks/native/insight_intent/insight_intent_context/js_insight_intent_context.cpp @@ -17,7 +17,6 @@ #include "ability_window_configuration.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "js_error_utils.h" #include "napi_common_want.h" @@ -118,7 +117,7 @@ napi_value CreateJsInsightIntentContext(napi_env env, const std::shared_ptr #include #include +#include -#include "cj_environment.h" -#include "hilog_wrapper.h" +#include "cj_envsetup.h" +#include "hilog_tag_wrapper.h" #include "hdc_register.h" #include "connect_server_manager.h" @@ -35,6 +36,27 @@ const std::string CJ_SYSLIB_PATH = "/system/lib64:/system/lib64/platformsdk:/sys const std::string CJ_CHIPSDK_PATH = "/system/lib64/chipset-pub-sdk"; } // namespace +#define LIB_NAME "libcj_environment.z.so" +#define GET_ENV_INS_NAME "OHOS_GetCJEnvInstance" + +namespace OHOS { +CJEnvMethods* CJEnv::LoadInstance() +{ + auto handle = dlopen(LIB_NAME, RTLD_NOW); + if (!handle) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "dlopen failed %{public}s, %{public}s", LIB_NAME, dlerror()); + return nullptr; + } + auto symbol = dlsym(handle, GET_ENV_INS_NAME); + if (!symbol) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "dlsym failed %{public}s, %{public}s", GET_ENV_INS_NAME, dlerror()); + dlclose(handle); + return nullptr; + } + auto func = reinterpret_cast(symbol); + return func(); +} +} AppLibPathVec CJRuntime::appLibPaths_; std::unique_ptr CJRuntime::Create(const Options& options) @@ -51,33 +73,43 @@ 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()); + TAG_LOGD(AAFwkTag::CJRUNTIME, "SetCJAppLibPath: %{public}s.", libPath.c_str()); CJRuntime::appLibPaths_.emplace_back(libPath); appPath += appPath.empty() ? libPath : ":" + libPath; } } - CJEnvironment::GetInstance()->InitCJChipSDKNS(CJ_CHIPSDK_PATH); - CJEnvironment::GetInstance()->InitCJAppNS(appPath); - CJEnvironment::GetInstance()->InitCJSDKNS(CJ_RT_PATH + ":" + CJ_LIB_PATH); - CJEnvironment::GetInstance()->InitCJSysNS(CJ_SYSLIB_PATH); + auto cjEnv = OHOS::CJEnv::LoadInstance(); + if (cjEnv == nullptr) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "CJEnv LoadInstance failed."); + return; + } + cjEnv->initCJChipSDKNS(CJ_CHIPSDK_PATH); + cjEnv->initCJAppNS(appPath); + cjEnv->initCJSDKNS(CJ_RT_PATH + ":" + CJ_LIB_PATH); + cjEnv->initCJSysNS(CJ_SYSLIB_PATH); } bool CJRuntime::Initialize(const Options& options) { if (options.lang != GetLanguage()) { - HILOG_ERROR("CJRuntime Initialize fail, language mismatch"); + TAG_LOGE(AAFwkTag::CJRUNTIME, "CJRuntime Initialize fail, language mismatch"); return false; } - if (!OHOS::CJEnvironment::GetInstance()->StartRuntime()) { - HILOG_ERROR("start cj runtime failed"); + auto cjEnv = OHOS::CJEnv::LoadInstance(); + if (cjEnv == nullptr) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "CJEnv LoadInstance failed."); return false; } - if (!OHOS::CJEnvironment::GetInstance()->StartUIScheduler()) { - HILOG_ERROR("start cj ui context failed"); + if (!cjEnv->startRuntime()) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "start cj runtime failed"); + return false; + } + if (!cjEnv->startUIScheduler()) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "start cj ui context failed"); return false; } if (!LoadCJAppLibrary(CJRuntime::appLibPaths_)) { - HILOG_ERROR("CJRuntime::Initialize fail, load app library fail."); + TAG_LOGE(AAFwkTag::CJRUNTIME, "CJRuntime::Initialize fail, load app library fail."); return false; } bundleName_ = options.bundleName; @@ -87,11 +119,28 @@ bool CJRuntime::Initialize(const Options& options) void CJRuntime::RegisterUncaughtExceptionHandler(const CJUncaughtExceptionInfo& uncaughtExceptionInfo) { - HILOG_INFO("RegisterUncaughtExceptionHandler not support yet"); + auto cjEnv = OHOS::CJEnv::LoadInstance(); + if (cjEnv == nullptr) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "CJEnv LoadInstance failed."); + return; + } + cjEnv->registerCJUncaughtExceptionHandler(uncaughtExceptionInfo); +} + +bool CJRuntime::IsCJAbility(const std::string& info) +{ + // in cj application, the srcEntry format should be packageName.AbilityClassName. + std::string pattern = "^([a-zA-Z0-9_]+\\.)+[a-zA-Z0-9_]+$"; + return std::regex_match(info, std::regex(pattern)); } bool CJRuntime::LoadCJAppLibrary(const AppLibPathVec& appLibPaths) { + auto cjEnv = OHOS::CJEnv::LoadInstance(); + if (cjEnv == nullptr) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "CJEnv LoadInstance failed."); + return false; + } void* handle = nullptr; for (const auto& libPath : appLibPaths) { for (auto& itor : std::filesystem::directory_iterator(libPath)) { @@ -99,10 +148,10 @@ bool CJRuntime::LoadCJAppLibrary(const AppLibPathVec& appLibPaths) if (itor.path().string().find("ohos_app_cangjie") == std::string::npos) { continue; } - handle = OHOS::CJEnvironment::GetInstance()->LoadCJLibrary(itor.path().c_str()); + handle = cjEnv->loadCJLibrary(itor.path().c_str()); if (handle == nullptr) { char* errMsg = dlerror(); - HILOG_ERROR( + TAG_LOGE(AAFwkTag::CJRUNTIME, "Failed to load %{public}s : reason: %{public}s.", itor.path().c_str(), errMsg ? errMsg : "null"); return false; } @@ -112,10 +161,40 @@ bool CJRuntime::LoadCJAppLibrary(const AppLibPathVec& appLibPaths) return true; } +void CJRuntime::SetAsanVersion() +{ + auto cjEnv = OHOS::CJEnv::LoadInstance(); + if (cjEnv == nullptr) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "CJEnv LoadInstance failed."); + return; + } + cjEnv->setSanitizerKindRuntimeVersion(SanitizerKind::ASAN); +} + +void CJRuntime::SetTsanVersion() +{ + auto cjEnv = OHOS::CJEnv::LoadInstance(); + if (cjEnv == nullptr) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "CJEnv LoadInstance failed."); + return; + } + cjEnv->setSanitizerKindRuntimeVersion(SanitizerKind::TSAN); +} + +void CJRuntime::SetHWAsanVersion() +{ + auto cjEnv = OHOS::CJEnv::LoadInstance(); + if (cjEnv == nullptr) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "CJEnv LoadInstance failed."); + return; + } + cjEnv->setSanitizerKindRuntimeVersion(SanitizerKind::HWASAN); +} + void CJRuntime::StartDebugMode(const DebugOption dOption) { if (debugModel_) { - HILOG_INFO("Already in debug mode"); + TAG_LOGI(AAFwkTag::CJRUNTIME, "Already in debug mode"); return; } @@ -124,12 +203,13 @@ void CJRuntime::StartDebugMode(const DebugOption dOption) const std::string bundleName = bundleName_; std::string inputProcessName = bundleName_ != dOption.processName ? dOption.processName : ""; - HILOG_INFO("StartDebugMode %{public}s", bundleName_.c_str()); + TAG_LOGI(AAFwkTag::CJRUNTIME, "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()); + TAG_LOGI(AAFwkTag::CJRUNTIME, + "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); @@ -137,7 +217,7 @@ void CJRuntime::StartDebugMode(const DebugOption dOption) ConnectServerManager::Get().SendDebuggerInfo(isStartWithDebug, isDebugApp); ConnectServerManager::Get().StartConnectServer(bundleName, socketFd, false); } else { - HILOG_ERROR("debugger service unexpected option: %{public}s", option.c_str()); + TAG_LOGE(AAFwkTag::CJRUNTIME, "debugger service unexpected option: %{public}s", option.c_str()); } }); if (isDebugApp) { @@ -150,10 +230,15 @@ void CJRuntime::StartDebugMode(const DebugOption dOption) bool CJRuntime::StartDebugger() { - return CJEnvironment::GetInstance()->StartDebugger(); + auto cjEnv = OHOS::CJEnv::LoadInstance(); + if (cjEnv == nullptr) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "CJEnv LoadInstance failed."); + return false; + } + return cjEnv->startDebugger(); } void CJRuntime::UnLoadCJAppLibrary() { - HILOG_INFO("UnLoadCJAppLibrary not support yet"); + TAG_LOGI(AAFwkTag::CJRUNTIME, "UnLoadCJAppLibrary not support yet"); } diff --git a/frameworks/native/runtime/connect_server_manager.cpp b/frameworks/native/runtime/connect_server_manager.cpp index 696c52bd92..3921125fde 100644 --- a/frameworks/native/runtime/connect_server_manager.cpp +++ b/frameworks/native/runtime/connect_server_manager.cpp @@ -19,7 +19,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS::AbilityRuntime { namespace { @@ -173,17 +172,13 @@ void ConnectServerManager::SendDebuggerInfo(bool needBreakPoint, bool isDebugApp panda::EcmaVM* vm = reinterpret_cast(g_debuggerInfo[tid].first); std::lock_guard lock(g_debuggerMutex); - const auto &debuggerPoskTask = g_debuggerInfo[tid].second; - if (!debuggerPoskTask) { + const auto &debuggerPostTask = g_debuggerInfo[tid].second; + if (!debuggerPostTask) { continue; } ConnectServerManager::Get().SendInstanceMessage(tid, instanceId, instanceName); - auto storeDebugInfoTask = [needBreakPoint, isDebugApp, instanceId, vm, debuggerPoskTask, instanceName]() { - panda::JSNApi::DebugOption debugOption = {ARK_DEBUGGER_LIB_PATH, isDebugApp ? needBreakPoint : false}; - panda::JSNApi::StoreDebugInfo(getproctid(), vm, debugOption, debuggerPoskTask, isDebugApp); - }; - - debuggerPoskTask(storeDebugInfoTask); + panda::JSNApi::DebugOption debugOption = {ARK_DEBUGGER_LIB_PATH, isDebugApp ? needBreakPoint : false}; + panda::JSNApi::StoreDebugInfo(tid, vm, debugOption, debuggerPostTask, isDebugApp); } } @@ -204,33 +199,15 @@ void ConnectServerManager::SetConnectedCallback() }); } -bool ConnectServerManager::SendInstanceMessage(int32_t tid, int32_t instanceId, const std::string& instanceName) +void ConnectServerManager::SetSwitchCallback(int32_t instanceId) { - TAG_LOGI(AAFwkTag::JSRUNTIME, "ConnectServerManager::SendInstanceMessage Add instance to connect server"); LoadConnectServerDebuggerSo(); - auto setSwitchCallBack = reinterpret_cast( - dlsym(handlerConnectServerSo_, "SetSwitchCallBack")); + dlsym(handlerConnectServerSo_, "SetSwitchCallBack")); if (setSwitchCallBack == nullptr) { - TAG_LOGI( - AAFwkTag::JSRUNTIME, "ConnectServerManager::SendInstanceMessage failed to find symbol 'setSwitchCallBack'"); - return false; + TAG_LOGE(AAFwkTag::JSRUNTIME, "ConnectServerManager::AddInstance failed to find symbol 'setSwitchCallBack'"); + return; } - - auto storeMessage = reinterpret_cast(dlsym(handlerConnectServerSo_, "StoreMessage")); - if (storeMessage == nullptr) { - TAG_LOGE(AAFwkTag::JSRUNTIME, "ConnectServerManager::SendInstanceMessage failed to find symbol 'StoreMessage'"); - return false; - } - - auto setProfilerCallback = reinterpret_cast( - dlsym(handlerConnectServerSo_, "SetProfilerCallback")); - if (setProfilerCallback == nullptr) { - TAG_LOGI(AAFwkTag::JSRUNTIME, - "ConnectServerManager::SendInstanceMessage failed to find symbol 'setProfilerCallback'"); - return false; - } - setSwitchCallBack( [this](bool status) { if (setStatus_ != nullptr) { @@ -246,7 +223,18 @@ bool ConnectServerManager::SendInstanceMessage(int32_t tid, int32_t instanceId, TAG_LOGE(AAFwkTag::JSRUNTIME, "ConnectServerManager::createLayoutInfo_ is nullptr"); } }, instanceId); - +} + +void ConnectServerManager::SetProfilerCallBack() +{ + LoadConnectServerDebuggerSo(); + auto setProfilerCallback = reinterpret_cast( + dlsym(handlerConnectServerSo_, "SetProfilerCallback")); + if (setProfilerCallback == nullptr) { + TAG_LOGE(AAFwkTag::JSRUNTIME, + "ConnectServerManager::AddInstance failed to find symbol 'setProfilerCallback'"); + return; + } setProfilerCallback([this](bool status) { if (setArkUIStateProfilerStatus_ != nullptr) { setArkUIStateProfilerStatus_(status); @@ -254,14 +242,25 @@ bool ConnectServerManager::SendInstanceMessage(int32_t tid, int32_t instanceId, TAG_LOGE(AAFwkTag::JSRUNTIME, "ConnectServerManager::setArkUIStateProfilerStatus_ is nullptr"); } }); +} +bool ConnectServerManager::SendInstanceMessage(int32_t tid, int32_t instanceId, const std::string& instanceName) +{ + TAG_LOGI(AAFwkTag::JSRUNTIME, "ConnectServerManager::SendInstanceMessage Add instance to connect server"); + ConnectServerManager::Get().SetSwitchCallback(instanceId); + ConnectServerManager::Get().SetProfilerCallBack(); std::string message = GetInstanceMapMessage("addInstance", instanceId, instanceName, tid); + LoadConnectServerDebuggerSo(); + auto storeMessage = reinterpret_cast(dlsym(handlerConnectServerSo_, "StoreMessage")); + if (storeMessage == nullptr) { + TAG_LOGE(AAFwkTag::JSRUNTIME, "ConnectServerManager::SendInstanceMessage failed to find symbol 'StoreMessage'"); + return false; + } storeMessage(instanceId, message); - return true; } - + bool ConnectServerManager::AddInstance(int32_t tid, int32_t instanceId, const std::string& instanceName) { { @@ -280,46 +279,10 @@ bool ConnectServerManager::AddInstance(int32_t tid, int32_t instanceId, const st } TAG_LOGD(AAFwkTag::JSRUNTIME, "ConnectServerManager::AddInstance Add instance to connect server"); + + ConnectServerManager::Get().SetSwitchCallback(instanceId); + ConnectServerManager::Get().SetProfilerCallBack(); LoadConnectServerDebuggerSo(); - - auto setSwitchCallBack = reinterpret_cast( - dlsym(handlerConnectServerSo_, "SetSwitchCallBack")); - if (setSwitchCallBack == nullptr) { - TAG_LOGE(AAFwkTag::JSRUNTIME, "ConnectServerManager::AddInstance failed to find symbol 'setSwitchCallBack'"); - return false; - } - setSwitchCallBack( - [this](bool status) { - if (setStatus_ != nullptr) { - setStatus_(status); - } else { - TAG_LOGE(AAFwkTag::JSRUNTIME, "ConnectServerManager::setStatus_ is nullptr"); - } - }, - [this](int32_t containerId) { - if (createLayoutInfo_ != nullptr) { - createLayoutInfo_(containerId); - } else { - TAG_LOGE(AAFwkTag::JSRUNTIME, "ConnectServerManager::createLayoutInfo_ is nullptr"); - } - }, instanceId); - - auto setProfilerCallback = reinterpret_cast( - dlsym(handlerConnectServerSo_, "SetProfilerCallback")); - if (setProfilerCallback == nullptr) { - TAG_LOGE(AAFwkTag::JSRUNTIME, - "ConnectServerManager::AddInstance failed to find symbol 'setProfilerCallback'"); - return false; - } - - setProfilerCallback([this](bool status) { - if (setArkUIStateProfilerStatus_ != nullptr) { - setArkUIStateProfilerStatus_(status); - } else { - TAG_LOGE(AAFwkTag::JSRUNTIME, "ConnectServerManager::setArkUIStateProfilerStatus_ is nullptr"); - } - }); - // Get the message including information of new instance, which will be send to IDE. std::string message = GetInstanceMapMessage("addInstance", instanceId, instanceName, tid); diff --git a/frameworks/native/runtime/connect_server_manager.h b/frameworks/native/runtime/connect_server_manager.h index a4dd6a9a4d..0601c4b125 100644 --- a/frameworks/native/runtime/connect_server_manager.h +++ b/frameworks/native/runtime/connect_server_manager.h @@ -53,6 +53,8 @@ public: void SendDebuggerInfo(bool needBreakPoint, bool isDebugApp); void LoadConnectServerDebuggerSo(); DebuggerPostTask GetDebuggerPostTask(int32_t tid); + void SetSwitchCallback(int32_t instanceId); + void SetProfilerCallBack(); private: ConnectServerManager() = default; diff --git a/frameworks/native/runtime/hdc_register.cpp b/frameworks/native/runtime/hdc_register.cpp index 609e7ddc3e..81c1f7cd0e 100644 --- a/frameworks/native/runtime/hdc_register.cpp +++ b/frameworks/native/runtime/hdc_register.cpp @@ -19,7 +19,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS::AbilityRuntime { using StartRegister = void (*)(const std::string& processName, const std::string& pkgName, bool isDebug, diff --git a/frameworks/native/runtime/js_data_struct_converter.cpp b/frameworks/native/runtime/js_data_struct_converter.cpp index e00e571ce1..78fc7d1796 100644 --- a/frameworks/native/runtime/js_data_struct_converter.cpp +++ b/frameworks/native/runtime/js_data_struct_converter.cpp @@ -18,7 +18,6 @@ #include "common_func.h" #include "configuration_convertor.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "js_runtime_utils.h" @@ -118,6 +117,13 @@ napi_value CreateJsConfiguration(napi_env env, const AppExecFwk::Configuration& std::string fontWeightScale = configuration.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_FONT_WEIGHT_SCALE); napi_set_named_property(env, object, "fontWeightScale", CreateJsValue(env, fontWeightScale == "" ? 1.0 : std::stod(fontWeightScale))); + + napi_set_named_property(env, object, "mcc", CreateJsValue(env, + configuration.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_MCC))); + + napi_set_named_property(env, object, "mnc", CreateJsValue(env, + configuration.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_MNC))); + return object; } diff --git a/frameworks/native/runtime/js_module_reader.cpp b/frameworks/native/runtime/js_module_reader.cpp index b521508e84..bac2bb2f02 100755 --- a/frameworks/native/runtime/js_module_reader.cpp +++ b/frameworks/native/runtime/js_module_reader.cpp @@ -20,7 +20,6 @@ #include "bundle_mgr_proxy.h" #include "file_path_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "iservice_registry.h" #include "js_runtime_utils.h" diff --git a/frameworks/native/runtime/js_module_searcher.cpp b/frameworks/native/runtime/js_module_searcher.cpp index 1d0aec536a..651cc3b52c 100644 --- a/frameworks/native/runtime/js_module_searcher.cpp +++ b/frameworks/native/runtime/js_module_searcher.cpp @@ -16,7 +16,6 @@ #include "js_module_searcher.h" #include "file_path_utils.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/native/runtime/js_quickfix_callback.cpp b/frameworks/native/runtime/js_quickfix_callback.cpp index 4bae9675fe..097e0d83aa 100644 --- a/frameworks/native/runtime/js_quickfix_callback.cpp +++ b/frameworks/native/runtime/js_quickfix_callback.cpp @@ -17,7 +17,6 @@ #include "file_path_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" namespace OHOS { diff --git a/frameworks/native/runtime/js_runtime.cpp b/frameworks/native/runtime/js_runtime.cpp index 0c9bd45850..cee9c32079 100644 --- a/frameworks/native/runtime/js_runtime.cpp +++ b/frameworks/native/runtime/js_runtime.cpp @@ -36,7 +36,6 @@ #include "file_path_utils.h" #include "hdc_register.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "ipc_skeleton.h" #include "iservice_registry.h" @@ -103,6 +102,7 @@ const std::string MODULE_NAME = "moduleName"; const std::string VERSION = "version"; const std::string ENTRY_PATH = "entryPath"; const std::string IS_SO = "isSO"; +constexpr char DEVELOPER_MODE_STATE[] = "const.security.developermode.state"; const std::string DEPENDENCY_ALIAS = "dependencyAlias"; static auto PermissionCheckFunc = []() { @@ -247,6 +247,10 @@ std::unique_ptr JsRuntime::Create(const Options& options) void JsRuntime::StartDebugMode(const DebugOption dOption) { + if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) { + TAG_LOGE(AAFwkTag::JSRUNTIME, "Developer Mode is false."); + return; + } CHECK_POINTER(jsEnv_); if (jsEnv_->GetDebugMode()) { TAG_LOGI(AAFwkTag::JSRUNTIME, "Already in debug mode"); @@ -283,15 +287,18 @@ void JsRuntime::StartDebugMode(const DebugOption dOption) if (isDebugApp) { weak->StopDebugger(option); } - int32_t tid = weak->ParseHdcRegisterOption(option); - const auto &debuggerPostTask = ConnectServerManager::Get().GetDebuggerPostTask(tid); - weak->StartDebugger(option, socketFd, isDebugApp, debuggerPostTask); + weak->StartDebugger(option, socketFd, isDebugApp); } }); if (isDebugApp) { ConnectServerManager::Get().StartConnectServer(bundleName_, -1, true); } + DebuggerConnectionHandler(isDebugApp, isStartWithDebug); +} + +void JsRuntime::DebuggerConnectionHandler(bool isDebugApp, bool isStartWithDebug) +{ ConnectServerManager::Get().StoreInstanceMessage(getproctid(), instanceId_); EcmaVM* vm = GetEcmaVm(); auto dTask = jsEnv_->GetDebuggerPostTask(); @@ -382,6 +389,10 @@ int32_t JsRuntime::JsperfProfilerCommandParse(const std::string &command, int32_ void JsRuntime::StartProfiler(const DebugOption dOption) { + if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) { + TAG_LOGE(AAFwkTag::JSRUNTIME, "Developer Mode is false."); + return; + } CHECK_POINTER(jsEnv_); if (JsRuntime::hasInstance.exchange(true, std::memory_order_relaxed)) { instanceId_ = static_cast(getproctid()); @@ -411,11 +422,15 @@ void JsRuntime::StartProfiler(const DebugOption dOption) if (isDebugApp) { weak->StopDebugger(option); } - int32_t tid = weak->ParseHdcRegisterOption(option); - const auto &debuggerPostTask = ConnectServerManager::Get().GetDebuggerPostTask(tid); - weak->StartDebugger(option, socketFd, isDebugApp, debuggerPostTask); + weak->StartDebugger(option, socketFd, isDebugApp); } }); + + DebuggerConnectionManager(isDebugApp, isStartWithDebug, dOption); +} + +void JsRuntime::DebuggerConnectionManager(bool isDebugApp, bool isStartWithDebug, const DebugOption dOption) +{ if (isDebugApp) { ConnectServerManager::Get().StartConnectServer(bundleName_, 0, true); } @@ -634,6 +649,10 @@ void JsRuntime::PostPreload(const Options& options) TAG_LOGD(AAFwkTag::JSRUNTIME, "Start Multi-Thread Mode: %{public}d.", options.isMultiThread); panda::JSNApi::SetMultiThreadCheck(); } + if (options.isErrorInfoEnhance) { + TAG_LOGD(AAFwkTag::JSRUNTIME, "Start Error-Info-Enhance Mode: %{public}d.", options.isErrorInfoEnhance); + panda::JSNApi::SetErrorInfoEnhance(); + } bool profileEnabled = OHOS::system::GetBoolParameter("ark.profile", false); postOption.SetEnableProfile(profileEnabled); TAG_LOGD(AAFwkTag::JSRUNTIME, "ASMM JIT Verify PostFork, jitEnabled: %{public}d", options.jitEnabled); @@ -814,6 +833,11 @@ bool JsRuntime::CreateJsEnv(const Options& options) panda::JSNApi::SetMultiThreadCheck(); } + if (options.isErrorInfoEnhance) { + TAG_LOGD(AAFwkTag::JSRUNTIME, "Start Error Info Enhance Mode: %{public}d.", options.isErrorInfoEnhance); + panda::JSNApi::SetErrorInfoEnhance(); + } + if (IsUseAbilityRuntime(options)) { // aot related bool aotEnabled = OHOS::system::GetBoolParameter("persist.ark.aot", true); @@ -1191,11 +1215,11 @@ void JsRuntime::RemoveTask(const std::string& name) jsEnv_->RemoveTask(name); } -void JsRuntime::DumpCpuProfile(bool isPrivate) +void JsRuntime::DumpCpuProfile() { auto nativeEngine = GetNativeEnginePointer(); CHECK_POINTER(nativeEngine); - nativeEngine->DumpCpuProfile(true, DumpFormat::JSON, isPrivate, false); + nativeEngine->DumpCpuProfile(); } void JsRuntime::DumpHeapSnapshot(bool isPrivate) @@ -1209,7 +1233,14 @@ void JsRuntime::DumpHeapSnapshot(uint32_t tid, bool isFullGC) { auto vm = GetEcmaVm(); CHECK_POINTER(vm); - DFXJSNApi::DumpHeapSnapshot(vm, 0, true, false, false, isFullGC, tid); + panda::ecmascript::DumpSnapShotOption dumpOption; + dumpOption.dumpFormat = panda::ecmascript::DumpFormat::JSON; + dumpOption.isVmMode = true; + dumpOption.isPrivate = false; + dumpOption.captureNumericValue = false; + dumpOption.isFullGC = isFullGC; + dumpOption.isSync = false; + DFXJSNApi::DumpHeapSnapshot(vm, dumpOption, tid); } void JsRuntime::ForceFullGC(uint32_t tid) diff --git a/frameworks/native/runtime/js_runtime_utils.cpp b/frameworks/native/runtime/js_runtime_utils.cpp index 7e32d09d60..811099fe18 100644 --- a/frameworks/native/runtime/js_runtime_utils.cpp +++ b/frameworks/native/runtime/js_runtime_utils.cpp @@ -16,7 +16,6 @@ #include "js_runtime_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "napi/native_api.h" @@ -452,5 +451,23 @@ std::unique_ptr CreateAsyncTaskWithLastParam(napi_env env, napi_v return CreateAsyncTaskWithLastParam(env, lastParam, std::unique_ptr(), std::unique_ptr(), result); } + +std::unique_ptr CreateEmptyAsyncTask(napi_env env, napi_value lastParam, napi_value* result) +{ + napi_valuetype type = napi_undefined; + napi_typeof(env, lastParam, &type); + if (lastParam == nullptr || type != napi_function) { + napi_deferred nativeDeferred = nullptr; + napi_create_promise(env, &nativeDeferred, result); + return std::make_unique(nativeDeferred, std::unique_ptr(), + std::unique_ptr()); + } else { + napi_get_undefined(env, result); + napi_ref callbackRef = nullptr; + napi_create_reference(env, lastParam, 1, &callbackRef); + return std::make_unique(callbackRef, std::unique_ptr(), + std::unique_ptr()); + } +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/runtime/js_worker.cpp b/frameworks/native/runtime/js_worker.cpp index fad54284f3..1696949612 100644 --- a/frameworks/native/runtime/js_worker.cpp +++ b/frameworks/native/runtime/js_worker.cpp @@ -22,9 +22,11 @@ #include #include +#include "bundle_info.h" #include "bundle_mgr_helper.h" +#include "bundle_mgr_proxy.h" #include "connect_server_manager.h" -#include "commonlibrary/c_utils/base/include/refbase.h" +#include "console.h" #ifdef SUPPORT_SCREEN #include "core/common/container_scope.h" #include "declarative_module_preloader.h" @@ -32,18 +34,15 @@ #include "extractor.h" #include "file_mapper.h" -#include "foundation/bundlemanager/bundle_framework/interfaces/inner_api/appexecfwk_base/include/bundle_info.h" -#include "foundation/bundlemanager/bundle_framework/interfaces/inner_api/appexecfwk_core/include/bundlemgr/bundle_mgr_proxy.h" -#include "foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy/include/iservice_registry.h" -#include "foundation/communication/ipc/interfaces/innerkits/ipc_core/include/iremote_object.h" -#include "singleton.h" -#include "system_ability_definition.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" +#include "iremote_object.h" +#include "iservice_registry.h" #include "js_runtime_utils.h" #include "native_engine/impl/ark/ark_native_engine.h" -#include "commonlibrary/ets_utils/js_sys_module/console/console.h" +#include "refbase.h" +#include "singleton.h" #include "syscap_ts.h" +#include "system_ability_definition.h" #ifdef SUPPORT_SCREEN using OHOS::Ace::ContainerScope; #endif @@ -100,7 +99,7 @@ void InitWorkerFunc(NativeEngine* nativeEngine) } if (g_debugMode) { - auto instanceId = getproctid(); + auto instanceId = DFXJSNApi::GetCurrentThreadId(); std::string instanceName = "workerThread_" + std::to_string(instanceId); bool needBreakPoint = ConnectServerManager::Get().AddInstance(instanceId, instanceId, instanceName); if (g_nativeStart) { @@ -128,7 +127,7 @@ void OffWorkerFunc(NativeEngine* nativeEngine) } if (g_debugMode) { - auto instanceId = getproctid(); + auto instanceId = DFXJSNApi::GetCurrentThreadId(); ConnectServerManager::Get().RemoveInstance(instanceId); auto arkNativeEngine = static_cast(nativeEngine); auto vm = const_cast(arkNativeEngine->GetEcmaVm()); diff --git a/frameworks/native/runtime/native_runtime_impl.cpp b/frameworks/native/runtime/native_runtime_impl.cpp index 1eccd3c66c..95221ad491 100644 --- a/frameworks/native/runtime/native_runtime_impl.cpp +++ b/frameworks/native/runtime/native_runtime_impl.cpp @@ -19,7 +19,6 @@ #include "bundle_mgr_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iservice_registry.h" #include "js_environment.h" #include "js_module_reader.h" diff --git a/frameworks/native/runtime/ohos_js_environment_impl.cpp b/frameworks/native/runtime/ohos_js_environment_impl.cpp index 1936f15a87..23c754faf7 100644 --- a/frameworks/native/runtime/ohos_js_environment_impl.cpp +++ b/frameworks/native/runtime/ohos_js_environment_impl.cpp @@ -18,7 +18,6 @@ #include "commonlibrary/ets_utils/js_sys_module/console/console.h" #include "commonlibrary/ets_utils/js_sys_module/timer/timer.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_utils.h" #include "js_worker.h" #include "ohos_loop_handler.h" diff --git a/frameworks/native/runtime/ohos_loop_handler.h b/frameworks/native/runtime/ohos_loop_handler.h index cc49db7226..c2d30c1fb6 100644 --- a/frameworks/native/runtime/ohos_loop_handler.h +++ b/frameworks/native/runtime/ohos_loop_handler.h @@ -18,7 +18,6 @@ #include #include "event_handler.h" -#include "hilog_wrapper.h" #include "native_engine/native_engine.h" namespace OHOS { diff --git a/frameworks/simulator/BUILD.gn b/frameworks/simulator/BUILD.gn index 959b40c99e..e031635253 100644 --- a/frameworks/simulator/BUILD.gn +++ b/frameworks/simulator/BUILD.gn @@ -73,6 +73,8 @@ ohos_copy("ability_simulator_copy_app_ability_modules") { sources = [] napi_modules = [ + "napi_module/embeddable_ui_ability:embeddableuiability_napi", + "napi_module/embeddable_ui_ability_context:embeddeduiextensionability_napi", "napi_module/uiability:uiability", "napi_module/ability_stage:abilitystage", "napi_module/ability_constant:abilityconstant", diff --git a/frameworks/simulator/ability_simulator/BUILD.gn b/frameworks/simulator/ability_simulator/BUILD.gn index 0671f9f18f..6526957a6a 100644 --- a/frameworks/simulator/ability_simulator/BUILD.gn +++ b/frameworks/simulator/ability_simulator/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") import("//foundation/ability/ability_runtime/ability_runtime.gni") import("//foundation/arkui/ace_engine/build/ace_gen_obj.gni") @@ -68,7 +68,6 @@ ohos_shared_library("ability_simulator_inner") { "${windowmanager_path}/interfaces/innerkits/wm", "${windowmanager_path}/interfaces/kits/napi/window_runtime/window_stage_napi", "include/bundle_parser", - "//third_party/json/include", ] sources = [ @@ -113,6 +112,7 @@ ohos_shared_library("ability_simulator_inner") { "ets_utils:console", "ets_utils:timer", "hilog:libhilog", + "json:nlohmann_json_static", "jsoncpp:jsoncpp_static", "napi:ace_napi", ] diff --git a/frameworks/simulator/ability_simulator/include/bundle_parser/json_util.h b/frameworks/simulator/ability_simulator/include/bundle_parser/json_util.h index c0cb33258c..72b3e52b47 100644 --- a/frameworks/simulator/ability_simulator/include/bundle_parser/json_util.h +++ b/frameworks/simulator/ability_simulator/include/bundle_parser/json_util.h @@ -21,7 +21,6 @@ #include "appexecfwk_errors.h" #include "bundle_constants.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "json_serializer.h" namespace OHOS { diff --git a/frameworks/simulator/ability_simulator/include/simulator.h b/frameworks/simulator/ability_simulator/include/simulator.h index bf8d78e5e6..d1cfb0bf2d 100644 --- a/frameworks/simulator/ability_simulator/include/simulator.h +++ b/frameworks/simulator/ability_simulator/include/simulator.h @@ -43,7 +43,7 @@ public: * * @param options The simulator options. */ - static std::unique_ptr Create(const Options &options); + static std::shared_ptr Create(const Options &options); virtual ~Simulator() = default; diff --git a/frameworks/simulator/ability_simulator/src/ability_context.cpp b/frameworks/simulator/ability_simulator/src/ability_context.cpp index b3fbdba0c0..a84bf082d4 100644 --- a/frameworks/simulator/ability_simulator/src/ability_context.cpp +++ b/frameworks/simulator/ability_simulator/src/ability_context.cpp @@ -17,7 +17,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/simulator/ability_simulator/src/ability_stage_context.cpp b/frameworks/simulator/ability_simulator/src/ability_stage_context.cpp index ca90bfb1cb..ca58a3e279 100644 --- a/frameworks/simulator/ability_simulator/src/ability_stage_context.cpp +++ b/frameworks/simulator/ability_simulator/src/ability_stage_context.cpp @@ -17,7 +17,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/frameworks/simulator/ability_simulator/src/bundle_parser/ability_info.cpp b/frameworks/simulator/ability_simulator/src/bundle_parser/ability_info.cpp index 0721fe1fa5..c784e4bf75 100644 --- a/frameworks/simulator/ability_simulator/src/bundle_parser/ability_info.cpp +++ b/frameworks/simulator/ability_simulator/src/bundle_parser/ability_info.cpp @@ -22,7 +22,6 @@ #include "bundle_constants.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "json_util.h" #include "nlohmann/json.hpp" #include "string_ex.h" diff --git a/frameworks/simulator/ability_simulator/src/bundle_parser/application_info.cpp b/frameworks/simulator/ability_simulator/src/bundle_parser/application_info.cpp index 33440e25ab..f864522494 100644 --- a/frameworks/simulator/ability_simulator/src/bundle_parser/application_info.cpp +++ b/frameworks/simulator/ability_simulator/src/bundle_parser/application_info.cpp @@ -23,7 +23,6 @@ #include "bundle_constants.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "json_serializer.h" #include "json_util.h" #include "nlohmann/json.hpp" diff --git a/frameworks/simulator/ability_simulator/src/bundle_parser/bundle_container.cpp b/frameworks/simulator/ability_simulator/src/bundle_parser/bundle_container.cpp index e344212bab..0d062d33b0 100644 --- a/frameworks/simulator/ability_simulator/src/bundle_parser/bundle_container.cpp +++ b/frameworks/simulator/ability_simulator/src/bundle_parser/bundle_container.cpp @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "json_serializer.h" #include "module_profile.h" diff --git a/frameworks/simulator/ability_simulator/src/bundle_parser/extension_ability_info.cpp b/frameworks/simulator/ability_simulator/src/bundle_parser/extension_ability_info.cpp index 0ced11ac6a..3527702504 100644 --- a/frameworks/simulator/ability_simulator/src/bundle_parser/extension_ability_info.cpp +++ b/frameworks/simulator/ability_simulator/src/bundle_parser/extension_ability_info.cpp @@ -21,7 +21,6 @@ #include "bundle_constants.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "json_util.h" #include "nlohmann/json.hpp" #include "string_ex.h" diff --git a/frameworks/simulator/ability_simulator/src/bundle_parser/hap_module_info.cpp b/frameworks/simulator/ability_simulator/src/bundle_parser/hap_module_info.cpp index 7ff3eb6e12..6c7665d319 100644 --- a/frameworks/simulator/ability_simulator/src/bundle_parser/hap_module_info.cpp +++ b/frameworks/simulator/ability_simulator/src/bundle_parser/hap_module_info.cpp @@ -17,7 +17,6 @@ #include "bundle_constants.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "json_util.h" #include "nlohmann/json.hpp" #include "string_ex.h" diff --git a/frameworks/simulator/ability_simulator/src/bundle_parser/module_info.cpp b/frameworks/simulator/ability_simulator/src/bundle_parser/module_info.cpp index bad5141d60..b486236860 100644 --- a/frameworks/simulator/ability_simulator/src/bundle_parser/module_info.cpp +++ b/frameworks/simulator/ability_simulator/src/bundle_parser/module_info.cpp @@ -16,7 +16,6 @@ #include "module_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "json_util.h" #include "nlohmann/json.hpp" #include "string_ex.h" diff --git a/frameworks/simulator/ability_simulator/src/common_func.cpp b/frameworks/simulator/ability_simulator/src/common_func.cpp index d09643b287..85b17e6019 100644 --- a/frameworks/simulator/ability_simulator/src/common_func.cpp +++ b/frameworks/simulator/ability_simulator/src/common_func.cpp @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" diff --git a/frameworks/simulator/ability_simulator/src/js_ability_context.cpp b/frameworks/simulator/ability_simulator/src/js_ability_context.cpp index 9d31e9031b..f51f54f591 100644 --- a/frameworks/simulator/ability_simulator/src/js_ability_context.cpp +++ b/frameworks/simulator/ability_simulator/src/js_ability_context.cpp @@ -17,7 +17,6 @@ #include "ability_business_error.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_context_utils.h" #include "js_data_converter.h" #include "js_resource_manager_utils.h" diff --git a/frameworks/simulator/ability_simulator/src/js_ability_stage_context.cpp b/frameworks/simulator/ability_simulator/src/js_ability_stage_context.cpp index 0131e03073..b5e6f60603 100644 --- a/frameworks/simulator/ability_simulator/src/js_ability_stage_context.cpp +++ b/frameworks/simulator/ability_simulator/src/js_ability_stage_context.cpp @@ -16,7 +16,6 @@ #include "js_ability_stage_context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_context_utils.h" #include "js_data_converter.h" #include "js_runtime_utils.h" diff --git a/frameworks/simulator/ability_simulator/src/js_application_context_utils.cpp b/frameworks/simulator/ability_simulator/src/js_application_context_utils.cpp index ec74fcc551..dfe5d59735 100644 --- a/frameworks/simulator/ability_simulator/src/js_application_context_utils.cpp +++ b/frameworks/simulator/ability_simulator/src/js_application_context_utils.cpp @@ -17,7 +17,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_context_utils.h" #include "js_data_converter.h" #include "js_runtime_utils.h" @@ -227,7 +226,7 @@ napi_value JsApplicationContextUtils::OnGetCloudFileDir(napi_env env, NapiCallba { auto context = context_.lock(); if (!context) { - HILOG_WARN("context is already released"); + TAG_LOGW(AAFwkTag::ABILITY_SIM, "context is already released"); return CreateJsUndefined(env); } std::string path = context->GetCloudFileDir(); diff --git a/frameworks/simulator/ability_simulator/src/js_console_log.cpp b/frameworks/simulator/ability_simulator/src/js_console_log.cpp index 3135be714f..9aaf2ceb8c 100644 --- a/frameworks/simulator/ability_simulator/src/js_console_log.cpp +++ b/frameworks/simulator/ability_simulator/src/js_console_log.cpp @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime_utils.h" namespace OHOS { diff --git a/frameworks/simulator/ability_simulator/src/js_context_utils.cpp b/frameworks/simulator/ability_simulator/src/js_context_utils.cpp index 7d2610f5f6..2a4d3583f9 100644 --- a/frameworks/simulator/ability_simulator/src/js_context_utils.cpp +++ b/frameworks/simulator/ability_simulator/src/js_context_utils.cpp @@ -17,7 +17,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_application_context_utils.h" #include "js_data_converter.h" #include "js_runtime_utils.h" @@ -289,7 +288,7 @@ napi_value JsBaseContext::OnGetCloudFileDir(napi_env env, NapiCallbackInfo &info { auto context = context_.lock(); if (!context) { - HILOG_WARN("context is already released"); + TAG_LOGW(AAFwkTag::ABILITY_SIM, "context is already released"); return CreateJsUndefined(env); } std::string path = context->GetCloudFileDir(); diff --git a/frameworks/simulator/ability_simulator/src/js_data_converter.cpp b/frameworks/simulator/ability_simulator/src/js_data_converter.cpp index c4c70e7921..2b7455c989 100644 --- a/frameworks/simulator/ability_simulator/src/js_data_converter.cpp +++ b/frameworks/simulator/ability_simulator/src/js_data_converter.cpp @@ -17,7 +17,6 @@ #include "common_func.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "js_runtime_utils.h" diff --git a/frameworks/simulator/ability_simulator/src/js_runtime_utils.cpp b/frameworks/simulator/ability_simulator/src/js_runtime_utils.cpp index df9e345c84..2c042c7b9b 100644 --- a/frameworks/simulator/ability_simulator/src/js_runtime_utils.cpp +++ b/frameworks/simulator/ability_simulator/src/js_runtime_utils.cpp @@ -16,7 +16,6 @@ #include "js_runtime_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" namespace OHOS { @@ -319,6 +318,24 @@ std::unique_ptr CreateAsyncTaskWithLastParam(napi_env env, napi_v std::unique_ptr(), result); } +std::unique_ptr CreateEmptyAsyncTask(napi_env env, napi_value lastParam, napi_value* result) +{ + napi_valuetype type = napi_undefined; + napi_typeof(env, lastParam, &type); + if (lastParam == nullptr || type != napi_function) { + napi_deferred nativeDeferred = nullptr; + napi_create_promise(env, &nativeDeferred, result); + return std::make_unique(nativeDeferred, std::unique_ptr(), + std::unique_ptr()); + } else { + napi_get_undefined(env, result); + napi_ref callbackRef = nullptr; + napi_create_reference(env, lastParam, 1, &callbackRef); + return std::make_unique(callbackRef, std::unique_ptr(), + std::unique_ptr()); + } +} + std::unique_ptr JsRuntime::LoadSystemModuleByEngine(napi_env env, const std::string &moduleName, napi_value const *argv, size_t argc) { diff --git a/frameworks/simulator/ability_simulator/src/js_timer.cpp b/frameworks/simulator/ability_simulator/src/js_timer.cpp index 4c558f04ff..2eb9a9f23a 100644 --- a/frameworks/simulator/ability_simulator/src/js_timer.cpp +++ b/frameworks/simulator/ability_simulator/src/js_timer.cpp @@ -23,7 +23,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "js_runtime_utils.h" diff --git a/frameworks/simulator/ability_simulator/src/simulator.cpp b/frameworks/simulator/ability_simulator/src/simulator.cpp index 19c438535e..57702bc5d1 100644 --- a/frameworks/simulator/ability_simulator/src/simulator.cpp +++ b/frameworks/simulator/ability_simulator/src/simulator.cpp @@ -28,7 +28,6 @@ #include "commonlibrary/ets_utils/js_sys_module/timer/timer.h" #include "commonlibrary/ets_utils/js_sys_module/console/console.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_ability_context.h" #include "js_ability_stage_context.h" #include "js_console_log.h" @@ -124,6 +123,8 @@ private: static napi_value RequireNapi(napi_env env, napi_callback_info info); inline void SetHostResolveBufferTracker(); void LoadJsMock(const std::string &fileName); + void ReportJsError(napi_value obj); + std::string GetNativeStrFromJsTaggedObj(napi_value obj, const char* key); panda::ecmascript::EcmaVM *CreateJSVM(); Options options_; @@ -689,8 +690,9 @@ bool SimulatorImpl::OnInit() } panda::JSNApi::DebugOption debugOption = {ARK_DEBUGGER_LIB_PATH, (options_.debugPort != 0), options_.debugPort}; - panda::JSNApi::StartDebugger(vm_, debugOption, 0, - std::bind(&DebuggerTask::OnPostTask, &debuggerTask_, std::placeholders::_1)); + panda::JSNApi::StartDebugger(vm_, debugOption, 0, [this](std::function &&arg) { + debuggerTask_.OnPostTask(std::move(arg)); + }); auto nativeEngine = new (std::nothrow) ArkNativeEngine(vm_, nullptr); if (nativeEngine == nullptr) { @@ -705,6 +707,7 @@ bool SimulatorImpl::OnInit() TAG_LOGE(AAFwkTag::ABILITY_SIM, "SimulatorImpl is nullptr."); return; } + self->ReportJsError(value); if (self->terminateCallback_ == nullptr) { TAG_LOGE(AAFwkTag::ABILITY_SIM, "terminateCallback is nullptr."); return; @@ -835,9 +838,9 @@ void SimulatorImpl::Run() } } -std::unique_ptr Simulator::Create(const Options &options) +std::shared_ptr Simulator::Create(const Options &options) { - auto simulator = std::make_unique(); + auto simulator = std::make_shared(); if (simulator->Initialize(options)) { return simulator; } @@ -934,5 +937,53 @@ void SimulatorImpl::GetPkgContextInfoListInner(nlohmann::json &itemObject, std:: } } } + +std::string SimulatorImpl::GetNativeStrFromJsTaggedObj(napi_value obj, const char* key) +{ + if (obj == nullptr) { + TAG_LOGE(AAFwkTag::ABILITY_SIM, "Failed to get value from key."); + return ""; + } + + napi_value valueStr = nullptr; + napi_get_named_property(nativeEngine_, obj, key, &valueStr); + napi_valuetype valueType = napi_undefined; + napi_typeof(nativeEngine_, valueStr, &valueType); + if (valueType != napi_string) { + TAG_LOGE(AAFwkTag::ABILITY_SIM, "Failed to convert value from key."); + return ""; + } + + size_t valueStrBufLength = 0; + napi_get_value_string_utf8(nativeEngine_, valueStr, nullptr, 0, &valueStrBufLength); + auto valueCStr = std::make_unique(valueStrBufLength + 1); + size_t valueStrLength = 0; + napi_get_value_string_utf8(nativeEngine_, valueStr, valueCStr.get(), valueStrBufLength + 1, &valueStrLength); + std::string ret(valueCStr.get(), valueStrLength); + TAG_LOGD(AAFwkTag::ABILITY_SIM, "GetNativeStrFromJsTaggedObj Success."); + return ret; +} + +void SimulatorImpl::ReportJsError(napi_value obj) +{ + std::string errorMsg = GetNativeStrFromJsTaggedObj(obj, "message"); + std::string errorName = GetNativeStrFromJsTaggedObj(obj, "name"); + std::string errorStack = GetNativeStrFromJsTaggedObj(obj, "stack"); + std::string topStack = GetNativeStrFromJsTaggedObj(obj, "topstack"); + std::string summary = "Simulator error name:" + errorName + "\n"; + summary += "Simulator error message:" + errorMsg + "\n"; + bool hasProperty = false; + napi_has_named_property(nativeEngine_, obj, "code", &hasProperty); + if (hasProperty) { + std::string errorCode = GetNativeStrFromJsTaggedObj(obj, "code"); + summary += "Simulator error code:" + errorCode + "\n"; + } + if (errorStack.empty()) { + TAG_LOGE(AAFwkTag::ABILITY_SIM, "errorStack is empty"); + return; + } + summary += "Stacktrace:\n" + errorStack; + TAG_LOGE(AAFwkTag::ABILITY_SIM, "summary: \n%{public}s", summary.c_str()); +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/simulator/build/ability_simulator.gni b/frameworks/simulator/build/ability_simulator.gni index 140603c7eb..e7f52af639 100644 --- a/frameworks/simulator/build/ability_simulator.gni +++ b/frameworks/simulator/build/ability_simulator.gni @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") import("//foundation/arkui/ace_engine/build/ace_gen_obj.gni") diff --git a/frameworks/simulator/napi_module/ability_constant/ability_constant_module.cpp b/frameworks/simulator/napi_module/ability_constant/ability_constant_module.cpp index 805fb48b11..70132844b2 100644 --- a/frameworks/simulator/napi_module/ability_constant/ability_constant_module.cpp +++ b/frameworks/simulator/napi_module/ability_constant/ability_constant_module.cpp @@ -15,7 +15,6 @@ #include "ability_window_configuration.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "launch_param.h" #include "napi/native_api.h" #include "napi/native_common.h" diff --git a/frameworks/simulator/napi_module/embeddable_ui_ability/BUILD.gn b/frameworks/simulator/napi_module/embeddable_ui_ability/BUILD.gn new file mode 100644 index 0000000000..ab430a396b --- /dev/null +++ b/frameworks/simulator/napi_module/embeddable_ui_ability/BUILD.gn @@ -0,0 +1,39 @@ +# 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("../../build/ability_simulator.gni") + +gen_js_src_binary("embeddable_ui_ability") { + js_source = "${ability_runtime_napi_path}/embeddable_ui_ability/embeddable_ui_ability.js" +} + +ohos_shared_library("embeddableuiability_napi") { + if (is_mingw) { + defines = [ "WINDOWS_PLATFORM" ] + } else { + defines = [ "MAC_PLATFORM" ] + } + + sources = [ "${ability_runtime_napi_path}/embeddable_ui_ability/embeddable_ui_ability_module.cpp" ] + + deps = [ + ":gen_obj_src_embeddable_ui_ability_abc", + ":gen_obj_src_embeddable_ui_ability_js", + ] + external_deps = [ "napi:ace_napi" ] + + part_name = "ability_runtime" + subsystem_name = "ability" +} diff --git a/frameworks/simulator/napi_module/embeddable_ui_ability_context/BUILD.gn b/frameworks/simulator/napi_module/embeddable_ui_ability_context/BUILD.gn new file mode 100644 index 0000000000..7dd5205e2e --- /dev/null +++ b/frameworks/simulator/napi_module/embeddable_ui_ability_context/BUILD.gn @@ -0,0 +1,39 @@ +# 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("../../build/ability_simulator.gni") + +gen_js_src_binary("embeddable_ui_ability_context") { + js_source = "${ability_runtime_napi_path}/embeddable_ui_ability_context/embeddable_ui_ability_context.js" +} + +ohos_shared_library("embeddeduiextensionability_napi") { + if (is_mingw) { + defines = [ "WINDOWS_PLATFORM" ] + } else { + defines = [ "MAC_PLATFORM" ] + } + + sources = [ "${ability_runtime_napi_path}/embeddable_ui_ability_context/embeddable_ui_ability_context_module.cpp" ] + + deps = [ + ":gen_obj_src_embeddable_ui_ability_context_abc", + ":gen_obj_src_embeddable_ui_ability_context_js", + ] + external_deps = [ "napi:ace_napi" ] + + part_name = "ability_runtime" + subsystem_name = "ability" +} diff --git a/interfaces/inner_api/ability_manager/BUILD.gn b/interfaces/inner_api/ability_manager/BUILD.gn index c066d6a600..d987116005 100644 --- a/interfaces/inner_api/ability_manager/BUILD.gn +++ b/interfaces/inner_api/ability_manager/BUILD.gn @@ -27,8 +27,11 @@ config("ability_manager_public_config") { "include/", "include/status_bar_delegate", "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/interfaces/kits/native/ability/ability_runtime", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", "${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", "${ability_runtime_path}/interfaces/kits/native/appkit/app", @@ -57,112 +60,6 @@ config("ability_manager_public_config") { } } -ohos_shared_library("ability_manager_base") { - 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 = [ - "${ability_runtime_innerkits_path}/ability_manager/include", - "${ability_runtime_innerkits_path}/ability_manager/include/status_bar_delegate", - "${ability_runtime_path}/interfaces/kits/native/ability/native", - "${ability_runtime_services_path}/abilitymgr/include", - "${ability_runtime_services_path}/common/include", - ] - - defines = [] - - if (ability_command_for_test) { - defines += [ "ABILITY_COMMAND_FOR_TEST" ] - } - - if (ability_runtime_graphics) { - defines += [ - "SUPPORT_GRAPHICS", - "SUPPORT_SCREEN", - ] - } - - cflags = [] - if (target_cpu == "arm") { - cflags += [ "-DBINDER_IPC_32BIT" ] - } - - sources = [ - "${ability_runtime_native_path}/ability/native/data_ability_operation.cpp", - "${ability_runtime_native_path}/ability/native/data_ability_operation_builder.cpp", - "${ability_runtime_native_path}/ability/native/data_ability_result.cpp", - "${ability_runtime_services_path}/abilitymgr/src/ability_running_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/acquire_share_data_callback_proxy.cpp", - "${ability_runtime_services_path}/abilitymgr/src/auto_startup_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/caller_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/dialog_session_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/exit_reason.cpp", - "${ability_runtime_services_path}/abilitymgr/src/extension_running_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_callback_proxy.cpp", - "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_param.cpp", - "${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_info.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/remote_on_listener_proxy.cpp", - "${ability_runtime_services_path}/abilitymgr/src/sender_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/ui_extension_ability_connect_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/ui_extension_host_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/user_callback_proxy.cpp", - "${ability_runtime_services_path}/abilitymgr/src/want_sender_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/wants_info.cpp", - "src/status_bar_delegate/status_bar_delegate_proxy.cpp", - ] - - if (ability_runtime_graphics) { - sources += [ - "src/ability_first_frame_state_data.cpp", - "src/ability_first_frame_state_observer_proxy.cpp", - ] - } - - deps = [ - ":ability_start_options", - ":ability_start_setting", - ] - - external_deps = [ - "ability_base:base", - "bundle_framework:appexecfwk_base", - "bundle_framework:libappexecfwk_common", - "c_utils:utils", - "hilog:libhilog", - "hitrace:hitrace_meter", - "ipc:ipc_core", - ] - - public_external_deps = [ - "ability_base:configuration", - "ability_base:want", - "ability_base:zuri", - "bundle_framework:appexecfwk_core", - "relational_store:native_dataability", - "relational_store:native_rdb", - ] - - innerapi_tags = [ - "platformsdk", - "sasdk", - ] - subsystem_name = "ability" - part_name = "ability_runtime" -} - ohos_shared_library("ability_manager") { sources = [ "${ability_runtime_native_path}/ability/native/data_ability_operation.cpp", @@ -175,12 +72,14 @@ ohos_shared_library("ability_manager") { "${ability_runtime_services_path}/abilitymgr/src/ability_manager_proxy.cpp", "${ability_runtime_services_path}/abilitymgr/src/ability_running_info.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", "${ability_runtime_services_path}/abilitymgr/src/auto_startup_info.cpp", "${ability_runtime_services_path}/abilitymgr/src/caller_info.cpp", - "${ability_runtime_services_path}/abilitymgr/src/dialog_session_info.cpp", + "${ability_runtime_services_path}/abilitymgr/src/dialog_session/dialog_session_info.cpp", "${ability_runtime_services_path}/abilitymgr/src/exit_reason.cpp", "${ability_runtime_services_path}/abilitymgr/src/extension_running_info.cpp", + "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_callback_proxy.cpp", "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_callback_stub.cpp", "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_param.cpp", "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_result.cpp", @@ -188,6 +87,7 @@ ohos_shared_library("ability_manager") { "${ability_runtime_services_path}/abilitymgr/src/lifecycle_state_info.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_stub.cpp", "${ability_runtime_services_path}/abilitymgr/src/remote_on_listener_proxy.cpp", @@ -196,6 +96,7 @@ ohos_shared_library("ability_manager") { "${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", + "${ability_runtime_services_path}/abilitymgr/src/ui_extension_session_info.cpp", "${ability_runtime_services_path}/abilitymgr/src/user_callback_proxy.cpp", "${ability_runtime_services_path}/abilitymgr/src/user_callback_stub.cpp", "${ability_runtime_services_path}/abilitymgr/src/want_receiver_stub.cpp", @@ -203,6 +104,7 @@ 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", + "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", "src/window_manager_service_handler_stub.cpp", @@ -211,6 +113,7 @@ ohos_shared_library("ability_manager") { if (ability_runtime_graphics) { sources += [ "src/ability_first_frame_state_data.cpp", + "src/ability_first_frame_state_observer_proxy.cpp", "src/ability_first_frame_state_observer_stub.cpp", ] } @@ -233,7 +136,6 @@ ohos_shared_library("ability_manager") { external_deps = [ "ability_base:base", "ability_base:session_info", - "bundle_framework:appexecfwk_base", "bundle_framework:libappexecfwk_common", "c_utils:utils", "common_event_service:cesfwk_innerkits", @@ -243,9 +145,11 @@ ohos_shared_library("ability_manager") { "hitrace:hitrace_meter", "ipc:ipc_core", "relational_store:native_dataability", - "relational_store:native_rdb", "samgr:samgr_proxy", ] + if (host_cpu != "arm64") { + external_deps += [ "relational_store:native_rdb" ] + } public_external_deps = [ "ability_base:configuration", @@ -264,7 +168,6 @@ ohos_shared_library("ability_manager") { deps += [] external_deps += [ "ability_base:session_info", - "graphic_2d:color_manager", "image_framework:image_native", "window_manager:libwsutils", "window_manager:session_manager_lite", @@ -385,6 +288,7 @@ ohos_shared_library("ability_start_setting") { "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "jsoncpp:jsoncpp", + "napi:ace_napi", ] if (ability_runtime_graphics) { public_external_deps += [ "graphic_2d:color_manager" ] diff --git a/interfaces/inner_api/ability_manager/include/ability_first_frame_state_data.h b/interfaces/inner_api/ability_manager/include/ability_first_frame_state_data.h index 59f86d7d68..f1b32351c6 100644 --- a/interfaces/inner_api/ability_manager/include/ability_first_frame_state_data.h +++ b/interfaces/inner_api/ability_manager/include/ability_first_frame_state_data.h @@ -20,6 +20,7 @@ #include #include "parcel.h" +#include "app_mgr_constants.h" #include "iremote_object.h" namespace OHOS { diff --git a/interfaces/inner_api/ability_manager/include/ability_first_frame_state_observer_stub.h b/interfaces/inner_api/ability_manager/include/ability_first_frame_state_observer_stub.h index 3c0fca6575..ab3494fe51 100644 --- a/interfaces/inner_api/ability_manager/include/ability_first_frame_state_observer_stub.h +++ b/interfaces/inner_api/ability_manager/include/ability_first_frame_state_observer_stub.h @@ -35,9 +35,6 @@ public: private: int32_t HandleOnAbilityFirstFrameStateChanged(MessageParcel &data, MessageParcel &reply); - using AbilityFirstFrameStateObserverFunc = int32_t (AbilityFirstFrameStateObserverStub::*)( - MessageParcel &data, MessageParcel &reply); - std::map memberFuncMap_; static std::mutex callbackMutex_; DISALLOW_COPY_AND_MOVE(AbilityFirstFrameStateObserverStub); 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 771ad19a4d..b889cc7a45 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_client.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_client.h @@ -1009,7 +1009,8 @@ public: * @param handler Indidate handler of WindowManagerService. * @return ErrCode Returns ERR_OK on success, others on failure. */ - ErrCode RegisterWindowManagerServiceHandler(sptr handler); + ErrCode RegisterWindowManagerServiceHandler(sptr handler, + bool animationEnabled = true); /** * WindowManager notification AbilityManager after the first frame is drawn. @@ -1033,8 +1034,8 @@ public: void UpdateMissionSnapShot(sptr token, std::shared_ptr pixelMap); - ErrCode GetDialogSessionInfo(const std::string dialogSessionId, sptr &info); - ErrCode SendDialogResult(const Want &want, const std::string dialogSessionId, bool isAllow); + ErrCode GetDialogSessionInfo(const std::string &dialogSessionId, sptr &info); + ErrCode SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllow); #endif /** @@ -1180,10 +1181,12 @@ public: /** * @brief Add free install observer. * + * @param callerToken The caller ability token. * @param observer Free install observer. * @return Returns ERR_OK on success, others on failure. */ - ErrCode AddFreeInstallObserver(sptr observer); + ErrCode AddFreeInstallObserver(const sptr callToken, + const sptr observer); /** * Called to verify that the MissionId is valid. @@ -1408,6 +1411,17 @@ public: ErrCode GetUIExtensionRootHostInfo(const sptr token, UIExtensionHostInfo &hostInfo, int32_t userId = DEFAULT_INVAL_VALUE); + /** + * @brief Get ui extension session info + * + * @param token The ability token. + * @param uiExtensionSessionInfo The ui extension session info. + * @param userId The user id. + * @return int32_t Returns ERR_OK on success, others on failure. + */ + ErrCode GetUIExtensionSessionInfo(const sptr token, UIExtensionSessionInfo &uiExtensionSessionInfo, + int32_t userId = DEFAULT_INVAL_VALUE); + /** * @brief Restart app self. * @param want The ability type must be UIAbility. @@ -1498,6 +1512,29 @@ public: */ void NotifyFrozenProcessByRSS(const std::vector &pidList, int32_t uid); + /** + * Open atomic service window prior to finishing free install. + * + * @param bundleName, the bundle name of the atomic service. + * @param moduleName, the module name of the atomic service. + * @param abilityName, the ability name of the atomic service. + * @param startTime, the starting time of the free install task. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t PreStartMission(const std::string& bundleName, const std::string& moduleName, + const std::string& abilityName, const std::string& startTime); + + /** + * Open link of ability and atomic service. + * + * @param want Ability want. + * @param callerToken Caller ability token. + * @param userId User ID. + * @param requestCode Ability request code. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t OpenLink(const Want& want, sptr callerToken, int32_t userId, int requestCode); + private: AbilityManagerClient(); DISALLOW_COPY_AND_MOVE(AbilityManagerClient); @@ -1517,6 +1554,7 @@ private: static std::once_flag singletonFlag_; std::recursive_mutex mutex_; + std::mutex topAbilityMutex_; static std::shared_ptr instance_; sptr proxy_; sptr deathRecipient_; 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 531e2a7c6b..2fda501886 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_errors.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_errors.h @@ -550,6 +550,16 @@ enum { */ ERR_BUNDLE_NOT_EXIST, + /* + * Result(2097259) for open link start abilty default ok. + */ + ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK = 2097259, + + /* + * Result (2097260) for target free install task does not exist. + */ + ERR_FREE_INSTALL_TASK_NOT_EXIST = 2097260, + /** * Native error(3000000) for target bundle not exist. */ 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 9f8c65e778..d1d5f4f3f5 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_interface.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_interface.h @@ -53,6 +53,7 @@ #include "system_memory_attr.h" #include "ui_extension_ability_connect_info.h" #include "ui_extension_host_info.h" +#include "ui_extension_session_info.h" #include "ui_extension_window_command.h" #include "uri.h" #include "want.h" @@ -76,6 +77,7 @@ using InsightIntentExecuteParam = AppExecFwk::InsightIntentExecuteParam; using InsightIntentExecuteResult = AppExecFwk::InsightIntentExecuteResult; using UIExtensionAbilityConnectInfo = AbilityRuntime::UIExtensionAbilityConnectInfo; using UIExtensionHostInfo = AbilityRuntime::UIExtensionHostInfo; +using UIExtensionSessionInfo = AbilityRuntime::UIExtensionSessionInfo; #ifdef SUPPORT_SCREEN using IAbilityFirstFrameStateObserver = AppExecFwk::IAbilityFirstFrameStateObserver; #endif @@ -201,8 +203,7 @@ public: const sptr &callerToken, sptr asCallerSourceToken, int32_t userId = DEFAULT_INVAL_VALUE, - int requestCode = DEFAULT_INVAL_VALUE, - bool isSendDialogResult = false) + int requestCode = DEFAULT_INVAL_VALUE) { return 0; } @@ -723,7 +724,23 @@ public: * @param uid uid of bundle. * @return Returns ERR_OK on success, others on failure. */ - virtual int UninstallApp(const std::string &bundleName, int32_t uid) = 0; + virtual int UninstallApp(const std::string &bundleName, int32_t uid) + { + return 0; + } + + /** + * Uninstall app + * + * @param bundleName bundle name of uninstalling app. + * @param uid uid of bundle. + * @param appIndex the app index of app clone. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t UninstallApp(const std::string &bundleName, int32_t uid, int32_t appIndex) + { + return 0; + } /** * Upgrade app, record exit reason and kill application @@ -731,9 +748,11 @@ public: * @param bundleName bundle name of upgrading app. * @param uid uid of bundle. * @param exitMsg the exit reason message. + * @param appIndex the app index of app clone. * @return Returns ERR_OK on success, others on failure. */ - virtual int32_t UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg) + virtual int32_t UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg, + int32_t appIndex = 0) { return 0; } @@ -884,7 +903,11 @@ public: * @param handler Indidate handler of WindowManagerService. * @return ErrCode Returns ERR_OK on success, others on failure. */ - virtual int RegisterWindowManagerServiceHandler(const sptr& handler) = 0; + virtual int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled) + { + return 0; + } /** * WindowManager notification AbilityManager after the first frame is drawn. @@ -913,12 +936,12 @@ public: return 0; } - virtual int GetDialogSessionInfo(const std::string dialogSessionId, sptr &dialogSessionInfo) + virtual int GetDialogSessionInfo(const std::string &dialogSessionId, sptr &dialogSessionInfo) { return 0; } - virtual int SendDialogResult(const Want &want, const std::string dialogSessionId, bool isAllow) + virtual int SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllow) { return 0; } @@ -1127,10 +1150,12 @@ public: /** * Add free install observer. * - * @param observer, the observer of the ability to free install start. + * @param callerToken, The caller ability token. + * @param observer, The observer of the ability to free install start. * @return Returns ERR_OK on success, others on failure. */ - virtual int AddFreeInstallObserver(const sptr &observer) + virtual int AddFreeInstallObserver(const sptr &callerToken, + const sptr &observer) { return 0; } @@ -1493,6 +1518,20 @@ public: return 0; } + /** + * @brief Get ui extension session info + * + * @param token The ability token. + * @param uiExtensionSessionInfo The ui extension session info. + * @param userId The user id. + * @return int32_t Returns ERR_OK on success, others on failure. + */ + virtual int32_t GetUIExtensionSessionInfo(const sptr token, + UIExtensionSessionInfo &uiExtensionSessionInfo, int32_t userId = DEFAULT_INVAL_VALUE) + { + return 0; + } + /** * @brief Restart app self. * @param want The ability type must be UIAbility. @@ -1503,6 +1542,21 @@ public: return 0; } + /** + * Open link of ability and atomic service. + * + * @param want Ability want. + * @param callerToken Caller ability token. + * @param userId User ID. + * @param requestCode Ability request code. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t OpenLink(const Want& want, sptr callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = DEFAULT_INVAL_VALUE) + { + return 0; + } + /** * @brief Pop-up launch of full-screen atomic service. * @param want The want with parameters. @@ -1610,6 +1664,21 @@ public: { return; } + + /** + * Open atomic service window prior to finishing free install. + * + * @param bundleName, the bundle name of the atomic service. + * @param moduleName, the module name of the atomic service. + * @param abilityName, the ability name of the atomic service. + * @param startTime, the starting time of the free install task. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t PreStartMission(const std::string& bundleName, const std::string& moduleName, + const std::string& abilityName, const std::string& startTime) + { + 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 ac9f5fd75b..0b09132c0b 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 @@ -395,8 +395,14 @@ enum class AbilityManagerInterfaceCode { // ipc id for preload UIExtension ability by want PRELOAD_UIEXTENSION_ABILITY = 1062, - // ipc id for start UIExtension ability non—modal - START_UI_EXTENSION_ABILITY_NON_MODAL = 1063, + // ipc id for start UIExtension ability embedded + START_UI_EXTENSION_ABILITY_EMBEDDED = 1063, + + // ipc id for start UIExtension ability constrained embedded + START_UI_EXTENSION_CONSTRAINED_EMBEDDED = 1064, + + // get ui extension session info + GET_UI_EXTENSION_SESSION_INFO = 1065, // ipc id for continue ability(1101) START_CONTINUATION = 1101, @@ -444,6 +450,12 @@ enum class AbilityManagerInterfaceCode { // ipc for notify frozen process by RSS NOTIFY_FROZEN_PROCESS_BY_RSS = 1130, + // ipc id for pre-start mission + PRE_START_MISSION = 1135, + + // ipc for open link + OPEN_LINK = 1140, + // ipc id 2001-3000 for tools // ipc id for dumping state (2001) DUMP_STATE = 2001, diff --git a/interfaces/inner_api/ability_manager/include/acquire_share_data_callback_stub.h b/interfaces/inner_api/ability_manager/include/acquire_share_data_callback_stub.h index 83aa9b0f4d..f661afb6ed 100644 --- a/interfaces/inner_api/ability_manager/include/acquire_share_data_callback_stub.h +++ b/interfaces/inner_api/ability_manager/include/acquire_share_data_callback_stub.h @@ -42,8 +42,6 @@ private: ShareRuntimeTask shareRuntimeTask_; std::shared_ptr handler_; - using StubFunc = int32_t (AcquireShareDataCallbackStub::*)(MessageParcel &data, MessageParcel &reply); - std::vector vecMemberFunc_; }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/ability_manager/include/atomic_service_status_callback_interface.h b/interfaces/inner_api/ability_manager/include/atomic_service_status_callback_interface.h index f41a8b3248..2b44322052 100644 --- a/interfaces/inner_api/ability_manager/include/atomic_service_status_callback_interface.h +++ b/interfaces/inner_api/ability_manager/include/atomic_service_status_callback_interface.h @@ -49,19 +49,11 @@ public: * @param userId, user`s id. */ virtual void OnRemoteInstallFinished(int resultCode, const Want &want, int32_t userId) = 0; - - /** - * OnRemoveTimeoutTask, BMS has connected AG. - * - * @param want, the want of the ability to free install. - */ - virtual void OnRemoveTimeoutTask(const Want &want) = 0; protected: enum IAtomicServiceStatusCallbackCmd { ON_FREE_INSTALL_DONE = 0, ON_REMOTE_FREE_INSTALL_DONE, - ON_REMOVE_TIMEOUT_TASK, CMD_MAX, }; }; diff --git a/interfaces/inner_api/ability_manager/include/atomic_service_status_callback_proxy.h b/interfaces/inner_api/ability_manager/include/atomic_service_status_callback_proxy.h index 1694a06a75..cf30700726 100644 --- a/interfaces/inner_api/ability_manager/include/atomic_service_status_callback_proxy.h +++ b/interfaces/inner_api/ability_manager/include/atomic_service_status_callback_proxy.h @@ -52,13 +52,6 @@ public: */ void OnRemoteInstallFinished(int resultCode, const Want &want, int32_t userId) override; - /** - * OnRemoveTimeoutTask, BMS has connected AG. - * - * @param want, installed ability - */ - void OnRemoveTimeoutTask(const Want &want) override; - private: int32_t SendTransactCmd(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); static inline BrokerDelegator delegator_; diff --git a/interfaces/inner_api/ability_manager/include/atomic_service_status_callback_stub.h b/interfaces/inner_api/ability_manager/include/atomic_service_status_callback_stub.h index a2b4f4db21..a995c2423d 100644 --- a/interfaces/inner_api/ability_manager/include/atomic_service_status_callback_stub.h +++ b/interfaces/inner_api/ability_manager/include/atomic_service_status_callback_stub.h @@ -41,9 +41,6 @@ private: int OnInstallFinishedInner(MessageParcel &data, MessageParcel &reply); int OnRemoteInstallFinishedInner(MessageParcel &data, MessageParcel &reply); int OnRemoveTimeoutTaskInner(MessageParcel &data, MessageParcel &replay); - using AtomicServiceStatusCallbackFunc = int (AtomicServiceStatusCallbackStub::*)(MessageParcel &data, - MessageParcel &reply); - std::vector vecMemberFunc_; }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/ability_manager/include/auto_startup_callback_stub.h b/interfaces/inner_api/ability_manager/include/auto_startup_callback_stub.h index 76effeea02..74cc2fc1fb 100644 --- a/interfaces/inner_api/ability_manager/include/auto_startup_callback_stub.h +++ b/interfaces/inner_api/ability_manager/include/auto_startup_callback_stub.h @@ -41,8 +41,6 @@ private: int32_t OnAutoStartupOnInner(MessageParcel &data, MessageParcel &reply); int32_t OnAutoStartupOffInner(MessageParcel &data, MessageParcel &reply); - using RequestFuncType = int (AutoStartupCallBackStub::*)(MessageParcel &data, MessageParcel &reply); - std::map requestFuncMap_; DISALLOW_COPY_AND_MOVE(AutoStartupCallBackStub); }; } // namespace AbilityRuntime diff --git a/interfaces/inner_api/ability_manager/include/auto_startup_info.h b/interfaces/inner_api/ability_manager/include/auto_startup_info.h index 5a3b28cffc..f39b6f0e73 100644 --- a/interfaces/inner_api/ability_manager/include/auto_startup_info.h +++ b/interfaces/inner_api/ability_manager/include/auto_startup_info.h @@ -33,7 +33,7 @@ public: std::string moduleName; std::string abilityTypeName; std::string accessTokenId; - int32_t appCloneIndex = -1; + int32_t appCloneIndex = 0; int32_t userId = -1; bool ReadFromParcel(Parcel &parcel); 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 fc6f550944..af2b7303cf 100644 --- a/interfaces/inner_api/ability_manager/include/dialog_session_info.h +++ b/interfaces/inner_api/ability_manager/include/dialog_session_info.h @@ -19,6 +19,7 @@ #include #include +#include "application_info.h" #include "json_serializer.h" #include "parcel.h" #include "refbase.h" @@ -35,6 +36,8 @@ struct DialogAbilityInfo { int32_t abilityIconId = 0; int32_t abilityLabelId = 0; bool visible = true; + int32_t appIndex = 0; + AppExecFwk::MultiAppModeData multiAppMode; std::string GetURI() const; bool ParseURI(const std::string &uri); diff --git a/interfaces/inner_api/ability_manager/include/free_install_observer_interface.h b/interfaces/inner_api/ability_manager/include/free_install_observer_interface.h index 33de6df6b0..80b5a6923e 100644 --- a/interfaces/inner_api/ability_manager/include/free_install_observer_interface.h +++ b/interfaces/inner_api/ability_manager/include/free_install_observer_interface.h @@ -36,8 +36,19 @@ public: virtual void OnInstallFinished(const std::string &bundleName, const std::string &abilityName, const std::string &startTime, const int &resultCode) = 0; + /** + * OnInstallFinishedByUrl, return free install result. + * + * @param startTime Free install start request time. + * @param url Free install url. + * @param resultCode The result of this free install. + */ + virtual void OnInstallFinishedByUrl(const std::string &startTime, const std::string &url, + const int &resultCode) = 0; + enum { ON_INSTALL_FINISHED = 1, + ON_INSTALL_FINISHED_BY_URL = 2, }; }; } // namespace AbilityRuntime diff --git a/interfaces/inner_api/ability_manager/include/insight_intent_execute_callback_stub.h b/interfaces/inner_api/ability_manager/include/insight_intent_execute_callback_stub.h index 9c6e7d2768..816a2bb0c2 100644 --- a/interfaces/inner_api/ability_manager/include/insight_intent_execute_callback_stub.h +++ b/interfaces/inner_api/ability_manager/include/insight_intent_execute_callback_stub.h @@ -33,8 +33,6 @@ private: int32_t OnExecuteDoneInner(MessageParcel &data, MessageParcel &reply); std::shared_ptr handler_; - using StubFunc = int (InsightIntentExecuteCallbackStub::*)(MessageParcel &data, MessageParcel &reply); - std::map requestFuncMap_; }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/ability_manager/include/launch_param.h b/interfaces/inner_api/ability_manager/include/launch_param.h index 1d788c66d1..243a1f87ac 100644 --- a/interfaces/inner_api/ability_manager/include/launch_param.h +++ b/interfaces/inner_api/ability_manager/include/launch_param.h @@ -36,7 +36,8 @@ enum LaunchReason { LAUNCHREASON_START_EXTENSION, LAUNCHREASON_CONNECT_EXTENSION, LAUNCHREASON_AUTO_STARTUP, - LAUNCHREASON_INSIGHT_INTENT + LAUNCHREASON_INSIGHT_INTENT, + LAUNCHREASON_PREPARE_CONTINUATION }; /** diff --git a/interfaces/inner_api/ability_manager/include/mission_listener_stub.h b/interfaces/inner_api/ability_manager/include/mission_listener_stub.h index 129f130ff5..e9cde518cd 100644 --- a/interfaces/inner_api/ability_manager/include/mission_listener_stub.h +++ b/interfaces/inner_api/ability_manager/include/mission_listener_stub.h @@ -49,9 +49,6 @@ private: int OnMissionLabelUpdatedInner(MessageParcel &data, MessageParcel &reply); int OnMissionFocusedInner(MessageParcel &data, MessageParcel &reply); int OnMissionUnfocusedInner(MessageParcel &data, MessageParcel &reply); - - using MissionListenerFunc = int (MissionListenerStub::*)(MessageParcel &data, MessageParcel &reply); - std::vector vecMemberFunc_; }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/ability_manager/include/prepare_terminate_callback_stub.h b/interfaces/inner_api/ability_manager/include/prepare_terminate_callback_stub.h index 81d0e5c7ed..7706d8aa6e 100644 --- a/interfaces/inner_api/ability_manager/include/prepare_terminate_callback_stub.h +++ b/interfaces/inner_api/ability_manager/include/prepare_terminate_callback_stub.h @@ -33,8 +33,6 @@ public: private: int DoPrepareTerminateInner(MessageParcel &data, MessageParcel &reply); - using RequestFuncType = int (PrepareTerminateCallbackStub::*)(MessageParcel &data, MessageParcel &reply); - std::map requestFuncMap_; }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/ability_manager/include/status_bar_delegate/status_bar_delegate_stub.h b/interfaces/inner_api/ability_manager/include/status_bar_delegate/status_bar_delegate_stub.h index 6752c1f40c..9f32cd34c5 100644 --- a/interfaces/inner_api/ability_manager/include/status_bar_delegate/status_bar_delegate_stub.h +++ b/interfaces/inner_api/ability_manager/include/status_bar_delegate/status_bar_delegate_stub.h @@ -38,9 +38,6 @@ private: int32_t HandleCheckIfStatusBarItemExists(MessageParcel &data, MessageParcel &reply); int32_t HandleAttachPidToStatusBarItem(MessageParcel &data, MessageParcel &reply); - - using StatusBarDelegateStubFunc = int (StatusBarDelegateStub::*)(MessageParcel &data, MessageParcel &reply); - std::vector vecMemberFunc_; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/interfaces/inner_api/ability_manager/include/ui_extension_session_info.h b/interfaces/inner_api/ability_manager/include/ui_extension_session_info.h new file mode 100755 index 0000000000..9201916b32 --- /dev/null +++ b/interfaces/inner_api/ability_manager/include/ui_extension_session_info.h @@ -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. + */ + +#ifndef OHOS_ABILITY_RUNTIME_UI_EXTENSION_SESSION_INFO_H +#define OHOS_ABILITY_RUNTIME_UI_EXTENSION_SESSION_INFO_H + +#include "parcel.h" +#include "session_info_constants.h" + +namespace OHOS { +namespace AbilityRuntime { +class UIExtensionSessionInfo : public Parcelable { +public: + UIExtensionSessionInfo() = default; + virtual ~UIExtensionSessionInfo() = default; + + bool Marshalling(Parcel &parcel) const override; + static UIExtensionSessionInfo *Unmarshalling(Parcel &parcel); + + int32_t persistentId = 0; + uint32_t hostWindowId = 0; + AAFwk::UIExtensionUsage uiExtensionUsage = AAFwk::UIExtensionUsage::MODAL; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_UI_EXTENSION_SESSION_INFO_H diff --git a/interfaces/inner_api/ability_manager/include/user_callback_stub.h b/interfaces/inner_api/ability_manager/include/user_callback_stub.h index 5e2945ef71..40656e025c 100644 --- a/interfaces/inner_api/ability_manager/include/user_callback_stub.h +++ b/interfaces/inner_api/ability_manager/include/user_callback_stub.h @@ -42,9 +42,6 @@ private: int OnStopUserDoneInner(MessageParcel &data, MessageParcel &reply); int OnStartUserDoneInner(MessageParcel &data, MessageParcel &reply); - - using UserCallbackFunc = int (UserCallbackStub::*)(MessageParcel &data, MessageParcel &reply); - std::vector vecMemberFunc_; }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/ability_manager/include/window_manager_service_handler_stub.h b/interfaces/inner_api/ability_manager/include/window_manager_service_handler_stub.h index 5b7aab098e..485d4df325 100644 --- a/interfaces/inner_api/ability_manager/include/window_manager_service_handler_stub.h +++ b/interfaces/inner_api/ability_manager/include/window_manager_service_handler_stub.h @@ -44,9 +44,6 @@ private: int NotifyAnimationAbilityDiedInner(MessageParcel &data, MessageParcel &reply); int MoveMissionsToForegroundInner(MessageParcel &data, MessageParcel &reply); int MoveMissionsToBackgroundInner(MessageParcel &data, MessageParcel &reply); - - using RequestFuncType = int (WindowManagerServiceHandlerStub::*)(MessageParcel &data, MessageParcel &reply); - std::map requestFuncMap_; }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/ability_manager/src/ability_first_frame_state_observer_stub.cpp b/interfaces/inner_api/ability_manager/src/ability_first_frame_state_observer_stub.cpp index 07311ae6e8..a5e5ca1cd8 100644 --- a/interfaces/inner_api/ability_manager/src/ability_first_frame_state_observer_stub.cpp +++ b/interfaces/inner_api/ability_manager/src/ability_first_frame_state_observer_stub.cpp @@ -25,21 +25,14 @@ namespace OHOS { namespace AppExecFwk { -AbilityFirstFrameStateObserverStub::AbilityFirstFrameStateObserverStub() -{ - memberFuncMap_[static_cast(IAbilityFirstFrameStateObserver::Message::ON_ABILITY_FIRST_FRAME_STATE)] = - &AbilityFirstFrameStateObserverStub::HandleOnAbilityFirstFrameStateChanged; -} +AbilityFirstFrameStateObserverStub::AbilityFirstFrameStateObserverStub() {} -AbilityFirstFrameStateObserverStub::~AbilityFirstFrameStateObserverStub() -{ - memberFuncMap_.clear(); -} +AbilityFirstFrameStateObserverStub::~AbilityFirstFrameStateObserverStub() {} int32_t AbilityFirstFrameStateObserverStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); std::u16string descriptor = AbilityFirstFrameStateObserverStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { @@ -47,12 +40,8 @@ int32_t AbilityFirstFrameStateObserverStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + if (code == static_cast(IAbilityFirstFrameStateObserver::Message::ON_ABILITY_FIRST_FRAME_STATE)) { + return HandleOnAbilityFirstFrameStateChanged(data, reply); } return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/interfaces/inner_api/ability_manager/src/ability_foreground_state_observer_proxy.cpp b/interfaces/inner_api/ability_manager/src/ability_foreground_state_observer_proxy.cpp index 6465c6f166..1ba31e5c6f 100644 --- a/interfaces/inner_api/ability_manager/src/ability_foreground_state_observer_proxy.cpp +++ b/interfaces/inner_api/ability_manager/src/ability_foreground_state_observer_proxy.cpp @@ -16,7 +16,6 @@ #include "ability_foreground_state_observer_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { diff --git a/interfaces/inner_api/ability_manager/src/ability_foreground_state_observer_stub.cpp b/interfaces/inner_api/ability_manager/src/ability_foreground_state_observer_stub.cpp index 8ac11d348e..b9d123ebe6 100644 --- a/interfaces/inner_api/ability_manager/src/ability_foreground_state_observer_stub.cpp +++ b/interfaces/inner_api/ability_manager/src/ability_foreground_state_observer_stub.cpp @@ -17,27 +17,19 @@ #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" namespace OHOS { namespace AppExecFwk { -AbilityForegroundStateObserverStub::AbilityForegroundStateObserverStub() -{ - memberFuncMap_[static_cast(IAbilityForegroundStateObserver::Message::ON_ABILITY_STATE_CHANGED)] = - &AbilityForegroundStateObserverStub::HandleOnAbilityStateChanged; -} +AbilityForegroundStateObserverStub::AbilityForegroundStateObserverStub() {} -AbilityForegroundStateObserverStub::~AbilityForegroundStateObserverStub() -{ - memberFuncMap_.clear(); -} +AbilityForegroundStateObserverStub::~AbilityForegroundStateObserverStub() {} int32_t AbilityForegroundStateObserverStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); std::u16string descriptor = AbilityForegroundStateObserverStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { @@ -45,12 +37,8 @@ int32_t AbilityForegroundStateObserverStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + if (code == static_cast(IAbilityForegroundStateObserver::Message::ON_ABILITY_STATE_CHANGED)) { + return HandleOnAbilityStateChanged(data, reply); } return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/interfaces/inner_api/ability_manager/src/status_bar_delegate/status_bar_delegate_stub.cpp b/interfaces/inner_api/ability_manager/src/status_bar_delegate/status_bar_delegate_stub.cpp index 59421e5124..e4dedb4067 100644 --- a/interfaces/inner_api/ability_manager/src/status_bar_delegate/status_bar_delegate_stub.cpp +++ b/interfaces/inner_api/ability_manager/src/status_bar_delegate/status_bar_delegate_stub.cpp @@ -21,14 +21,7 @@ namespace OHOS { namespace AbilityRuntime { -StatusBarDelegateStub::StatusBarDelegateStub() -{ - vecMemberFunc_.resize(static_cast(StatusBarDelegateCmd::END)); - vecMemberFunc_[static_cast(StatusBarDelegateCmd::CHECK_IF_STATUS_BAR_ITEM_EXISTS)] = - &StatusBarDelegateStub::HandleCheckIfStatusBarItemExists; - vecMemberFunc_[static_cast(StatusBarDelegateCmd::ATTACH_PID_TO_STATUS_BAR_ITEM)] = - &StatusBarDelegateStub::HandleAttachPidToStatusBarItem; -} +StatusBarDelegateStub::StatusBarDelegateStub() {} int32_t StatusBarDelegateStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -41,8 +34,12 @@ int32_t StatusBarDelegateStub::OnRemoteRequest( } if (code < static_cast(StatusBarDelegateCmd::END)) { - auto memberFunc = vecMemberFunc_[code]; - return (this->*memberFunc)(data, reply); + switch (code) { + case static_cast(StatusBarDelegateCmd::CHECK_IF_STATUS_BAR_ITEM_EXISTS): + return HandleCheckIfStatusBarItemExists(data, reply); + case static_cast(StatusBarDelegateCmd::ATTACH_PID_TO_STATUS_BAR_ITEM): + return HandleAttachPidToStatusBarItem(data, reply); + } } return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/interfaces/inner_api/ability_manager/src/window_manager_service_handler_proxy.cpp b/interfaces/inner_api/ability_manager/src/window_manager_service_handler_proxy.cpp index 3e73bb0f98..152c2b8344 100644 --- a/interfaces/inner_api/ability_manager/src/window_manager_service_handler_proxy.cpp +++ b/interfaces/inner_api/ability_manager/src/window_manager_service_handler_proxy.cpp @@ -18,7 +18,6 @@ #include "ability_manager_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parcel.h" namespace OHOS { diff --git a/interfaces/inner_api/ability_manager/src/window_manager_service_handler_stub.cpp b/interfaces/inner_api/ability_manager/src/window_manager_service_handler_stub.cpp index 42b6d246ba..74c835f6cb 100644 --- a/interfaces/inner_api/ability_manager/src/window_manager_service_handler_stub.cpp +++ b/interfaces/inner_api/ability_manager/src/window_manager_service_handler_stub.cpp @@ -18,7 +18,6 @@ #include "ability_manager_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { @@ -27,23 +26,9 @@ WindowManagerServiceHandlerStub::WindowManagerServiceHandlerStub() Init(); } -WindowManagerServiceHandlerStub::~WindowManagerServiceHandlerStub() -{ - requestFuncMap_.clear(); -} +WindowManagerServiceHandlerStub::~WindowManagerServiceHandlerStub() {} -void WindowManagerServiceHandlerStub::Init() -{ - requestFuncMap_[ON_NOTIFY_WINDOW_TRANSITION] = &WindowManagerServiceHandlerStub::NotifyWindowTransitionInner; - requestFuncMap_[ON_GET_FOCUS_ABILITY] = &WindowManagerServiceHandlerStub::GetFocusWindowInner; - requestFuncMap_[ON_COLD_STARTING_WINDOW] = &WindowManagerServiceHandlerStub::StartingWindowCold; - requestFuncMap_[ON_HOT_STARTING_WINDOW] = &WindowManagerServiceHandlerStub::StartingWindowHot; - requestFuncMap_[ON_CANCEL_STARTING_WINDOW] = &WindowManagerServiceHandlerStub::CancelStartingWindowInner; - requestFuncMap_[ON_NOTIFY_ANIMATION_ABILITY_DIED] = - &WindowManagerServiceHandlerStub::NotifyAnimationAbilityDiedInner; - requestFuncMap_[ON_MOVE_MISSINONS_TO_FOREGROUND] = &WindowManagerServiceHandlerStub::MoveMissionsToForegroundInner; - requestFuncMap_[ON_MOVE_MISSIONS_TO_BACKGROUND] = &WindowManagerServiceHandlerStub::MoveMissionsToBackgroundInner; -} +void WindowManagerServiceHandlerStub::Init() {} int WindowManagerServiceHandlerStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -53,13 +38,25 @@ int WindowManagerServiceHandlerStub::OnRemoteRequest( return ERR_AAFWK_PARCEL_FAIL; } - auto itFunc = requestFuncMap_.find(code); - if (itFunc != requestFuncMap_.end()) { - auto requestFunc = itFunc->second; - if (requestFunc != nullptr) { - return (this->*requestFunc)(data, reply); - } + switch (code) { + case ON_NOTIFY_WINDOW_TRANSITION: + return NotifyWindowTransitionInner(data, reply); + case ON_GET_FOCUS_ABILITY: + return GetFocusWindowInner(data, reply); + case ON_COLD_STARTING_WINDOW: + return StartingWindowCold(data, reply); + case ON_HOT_STARTING_WINDOW: + return StartingWindowHot(data, reply); + case ON_CANCEL_STARTING_WINDOW: + return CancelStartingWindowInner(data, reply); + case ON_NOTIFY_ANIMATION_ABILITY_DIED: + return NotifyAnimationAbilityDiedInner(data, reply); + case ON_MOVE_MISSINONS_TO_FOREGROUND: + return MoveMissionsToForegroundInner(data, reply); + case ON_MOVE_MISSIONS_TO_BACKGROUND: + return MoveMissionsToBackgroundInner(data, reply); } + TAG_LOGW(AAFwkTag::ABILITYMGR, "default case, it needs to be checked."); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/interfaces/inner_api/app_manager/BUILD.gn b/interfaces/inner_api/app_manager/BUILD.gn index 9f75523c6a..523bbdc736 100644 --- a/interfaces/inner_api/app_manager/BUILD.gn +++ b/interfaces/inner_api/app_manager/BUILD.gn @@ -79,7 +79,10 @@ ohos_shared_library("app_manager") { "src/appmgr/app_task_info.cpp", "src/appmgr/application_state_observer_proxy.cpp", "src/appmgr/application_state_observer_stub.cpp", + "src/appmgr/child_process_args.cpp", "src/appmgr/child_process_info.cpp", + "src/appmgr/child_process_options.cpp", + "src/appmgr/child_process_request.cpp", "src/appmgr/child_scheduler_proxy.cpp", "src/appmgr/child_scheduler_stub.cpp", "src/appmgr/configuration_observer_proxy.cpp", @@ -122,7 +125,6 @@ ohos_shared_library("app_manager") { deps = [ "${ability_runtime_path}/utils/global/freeze:freeze_util" ] external_deps = [ - "ability_base:configuration", "c_utils:utils", "faultloggerd:libdfx_dumpcatcher", "faultloggerd:libfaultloggerd", @@ -141,6 +143,7 @@ ohos_shared_library("app_manager") { "bundle_framework:appexecfwk_base", "image_framework:image_native", "relational_store:native_rdb", + "skia:skia_canvaskit", ] if (background_task_mgr_continuous_task_enable) { diff --git a/interfaces/inner_api/app_manager/include/appmgr/ability_controller_stub.h b/interfaces/inner_api/app_manager/include/appmgr/ability_controller_stub.h index e248b744b3..53803cf3d7 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/ability_controller_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/ability_controller_stub.h @@ -58,10 +58,6 @@ private: int32_t HandleAllowAbilityBackground(MessageParcel &data, MessageParcel &reply); - using AbilityControllerFunc = int32_t (AbilityControllerStub::*)(MessageParcel &data, - MessageParcel &reply); - std::map memberFuncMap_; - DISALLOW_COPY_AND_MOVE(AbilityControllerStub); }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/ability_debug_response_stub.h b/interfaces/inner_api/app_manager/include/appmgr/ability_debug_response_stub.h index fcc0f3947f..9753d7051b 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/ability_debug_response_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/ability_debug_response_stub.h @@ -36,9 +36,6 @@ private: int32_t HandleOnAbilitysDebugStoped(MessageParcel &data, MessageParcel &reply); int32_t HandleOnAbilitysAssertDebugChange(MessageParcel &data, MessageParcel &reply); - using AbilityDebugResponseFunc = int32_t (AbilityDebugResponseStub::*)(MessageParcel &data, MessageParcel &reply); - std::map responseFuncMap_; - DISALLOW_COPY_AND_MOVE(AbilityDebugResponseStub); }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/ability_foreground_state_observer_stub.h b/interfaces/inner_api/app_manager/include/appmgr/ability_foreground_state_observer_stub.h index d11c892e55..d75d850bb7 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/ability_foreground_state_observer_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/ability_foreground_state_observer_stub.h @@ -35,9 +35,6 @@ public: private: int32_t HandleOnAbilityStateChanged(MessageParcel &data, MessageParcel &reply); - using AbilityForegroundStateObserverFunc = int32_t (AbilityForegroundStateObserverStub::*)( - MessageParcel &data, MessageParcel &reply); - std::map memberFuncMap_; static std::mutex callbackMutex_; DISALLOW_COPY_AND_MOVE(AbilityForegroundStateObserverStub); diff --git a/interfaces/inner_api/app_manager/include/appmgr/ability_info_callback_stub.h b/interfaces/inner_api/app_manager/include/appmgr/ability_info_callback_stub.h index ff41b555b5..17169e861d 100755 --- a/interfaces/inner_api/app_manager/include/appmgr/ability_info_callback_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/ability_info_callback_stub.h @@ -43,10 +43,6 @@ public: private: int32_t HandleNotifyAbilityToken(MessageParcel &data, MessageParcel &reply); - using AbilityInfoCallbackFunc = int32_t (AbilityInfoCallbackStub::*)(MessageParcel &data, - MessageParcel &reply); - std::map memberFuncMap_; - DISALLOW_COPY_AND_MOVE(AbilityInfoCallbackStub); }; } // namespace AppExecFwk 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 701efbfee4..f741d4ebc8 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 @@ -147,6 +147,16 @@ public: */ virtual int KillApplication(const std::string &bundleName, const bool clearPageStack = true) = 0; + /** + * ForceKillApplication, call ForceKillApplication() through proxy object, force kill the application. + * + * @param bundleName, bundle name in Application record. + * @param userId, userId. + * @param appIndex, appIndex. + * @return ERR_OK, return back success, others fail. + */ + virtual int ForceKillApplication(const std::string &bundleName, const int userId = -1, const int appIndex = 0) = 0; + /** * KillApplicationByUid, call KillApplicationByUid() through proxy object, kill the application. * @@ -168,7 +178,7 @@ public: virtual void AbilityAttachTimeOut(const sptr &token) = 0; - virtual void PrepareTerminate(const sptr &token) = 0; + virtual void PrepareTerminate(const sptr &token, bool clearMissionFlag = false) = 0; virtual void GetRunningProcessInfoByToken( const sptr &token, OHOS::AppExecFwk::RunningProcessInfo &info) = 0; @@ -314,6 +324,24 @@ public: */ virtual void AttachedToStatusBar(const sptr &token) {} + /** + * Temporarily block the process cache feature. + * + * @param pids the pids of the processes that should be blocked. + */ + virtual void BlockProcessCacheByPids(const std::vector &pids) {} + + /** + * whether killed for upgrade web. + * + * @param bundleName the bundle name is killed for upgrade web. + * @return Returns true is killed for upgrade web, others return false. + */ + virtual bool IsKilledForUpgradeWeb(const std::string &bundleName) + { + return true; + } + enum class Message { LOAD_ABILITY = 0, TERMINATE_ABILITY, @@ -359,6 +387,9 @@ public: SET_KEEP_ALIVE_ENABLE_STATE, NOTIFY_APP_MGR_RECORD_EXIT_REASON, ATTACHED_TO_STATUS_BAR, + BLOCK_PROCESS_CACHE_BY_PIDS, + IS_KILLED_FOR_UPGRADE_WEB, + FORCE_KILL_APPLICATION, }; }; } // 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 0aae81ce59..f6e3aba4d3 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 @@ -140,6 +140,17 @@ public: */ virtual int32_t KillApplication(const std::string &bundleName, const bool clearPageStack = true) override; + /** + * ForceKillApplication, call ForceKillApplication() through proxy object, force kill the application. + * + * @param bundleName, bundle name in Application record. + * @param userId, userId. + * @param appIndex, appIndex. + * @return ERR_OK, return back success, others fail. + */ + virtual int ForceKillApplication(const std::string &bundleName, const int userId = -1, + const int appIndex = 0) override; + /** * KillApplication, call KillApplication() through proxy object, kill the application. * @@ -158,7 +169,7 @@ public: virtual void AbilityAttachTimeOut(const sptr &token) override; - virtual void PrepareTerminate(const sptr &token) override; + virtual void PrepareTerminate(const sptr &token, bool clearMissionFlag = false) override; void GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info) override; @@ -283,6 +294,21 @@ public: */ virtual void AttachedToStatusBar(const sptr &token) override; + /** + * Temporarily block the process cache feature. + * + * @param pids the pids of the processes that should be blocked. + */ + virtual void BlockProcessCacheByPids(const std::vector &pids) override; + + /** + * whether killed for upgrade web. + * + * @param bundleName the bundle name is killed for upgrade web. + * @return Returns true is killed for upgrade web, others return false. + */ + virtual bool IsKilledForUpgradeWeb(const std::string &bundleName) override; + private: bool WriteInterfaceToken(MessageParcel &data); int32_t SendTransactCmd(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); 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 7752a8773d..fb7b896c79 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 @@ -56,6 +56,7 @@ private: int32_t HandleAttachPidToParent(MessageParcel &data, MessageParcel &reply); int32_t HandleKillProcessWithAccount(MessageParcel &data, MessageParcel &reply); int32_t HandleKillApplication(MessageParcel &data, MessageParcel &reply); + int32_t HandleForceKillApplication(MessageParcel &data, MessageParcel &reply); int32_t HandleAbilityAttachTimeOut(MessageParcel &data, MessageParcel &reply); int32_t HandlePrepareTerminate(MessageParcel &data, MessageParcel &reply); int32_t HandleKillApplicationByUid(MessageParcel &data, MessageParcel &reply); @@ -84,10 +85,16 @@ private: int32_t HandleIsMemorySizeSufficent(MessageParcel &data, MessageParcel &reply); int32_t HandleSetKeepAliveEnableState(MessageParcel &data, MessageParcel &reply); int32_t HandleAttachedToStatusBar(MessageParcel &data, MessageParcel &reply); - - using AmsMgrFunc = int32_t (AmsMgrStub::*)(MessageParcel &data, MessageParcel &reply); - std::map memberFuncMap_; - + int32_t OnRemoteRequestInner(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerFirst(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerSecond(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerThird(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t HandleBlockProcessCacheByPids(MessageParcel &data, MessageParcel &reply); + int32_t HandleIsKilledForUpgradeWeb(MessageParcel &data, MessageParcel &reply); DISALLOW_COPY_AND_MOVE(AmsMgrStub); }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_debug_listener_stub.h b/interfaces/inner_api/app_manager/include/appmgr/app_debug_listener_stub.h index 561d99f0e4..3aab199f48 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_debug_listener_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_debug_listener_stub.h @@ -35,9 +35,6 @@ private: int32_t HandleOnAppDebugStarted(MessageParcel &data, MessageParcel &reply); int32_t HandleOnAppDebugStoped(MessageParcel &data, MessageParcel &reply); - using AppDebugListenerFunc = int32_t (AppDebugListenerStub::*)(MessageParcel &data, MessageParcel &reply); - std::map memberFuncMap_; - DISALLOW_COPY_AND_MOVE(AppDebugListenerStub); }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_foreground_state_observer_stub.h b/interfaces/inner_api/app_manager/include/appmgr/app_foreground_state_observer_stub.h index e734747c4f..cbde5f949c 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_foreground_state_observer_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_foreground_state_observer_stub.h @@ -34,10 +34,6 @@ public: private: int32_t HandleOnAppStateChanged(MessageParcel &data, MessageParcel &reply); - using AppForegroundStateObserverFunc = int32_t (AppForegroundStateObserverStub::*)( - MessageParcel &data, MessageParcel &reply); - std::map memberFuncMap_; - DISALLOW_COPY_AND_MOVE(AppForegroundStateObserverStub); }; diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_launch_data.h b/interfaces/inner_api/app_manager/include/appmgr/app_launch_data.h index 801af1606d..264466c88c 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_launch_data.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_launch_data.h @@ -182,6 +182,16 @@ public: return isMultiThread_; } + inline void SetErrorInfoEnhance(const bool errorInfoEnhance) + { + isErrorInfoEnhance_ = errorInfoEnhance; + } + + inline bool GetErrorInfoEnhance() const + { + return isErrorInfoEnhance_; + } + inline void SetJITEnabled(const bool jitEnabled) { jitEnabled_ = jitEnabled; @@ -249,6 +259,7 @@ private: bool jitEnabled_ = false; bool isNativeStart_ = false; bool isMultiThread_ = false; + bool isErrorInfoEnhance_ = false; std::string appRunningUniqueId_; }; } // namespace AppExecFwk 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 cee2046040..50b52a3075 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 @@ -162,6 +162,17 @@ public: */ virtual AppMgrResultCode KillApplication(const std::string &bundleName, const bool clearPageStack = true); + /** + * ForceKillApplication, call ForceKillApplication() through proxy object, force kill the application. + * + * @param bundleName, bundle name in Application record. + * @param userId, userId. + * @param appIndex, appIndex. + * @return ERR_OK, return back success, others fail. + */ + virtual AppMgrResultCode ForceKillApplication(const std::string &bundleName, const int userId = -1, + const int appIndex = 0); + /** * KillApplication, call KillApplication() through proxy object, kill the application. * @@ -292,8 +303,9 @@ public: * Prepare terminate. * * @param token Ability identify. + * @param clearMissionFlag Clear mission flag. */ - virtual void PrepareTerminate(const sptr &token); + virtual void PrepareTerminate(const sptr &token, bool clearMissionFlag = false); /** * Get running process information by ability token. @@ -516,6 +528,14 @@ public: */ int32_t NotifyAppFaultBySA(const AppFaultDataBySA &faultData); + /** + * Set Appfreeze Detect Filter + * + * @param pid the process pid. + * @return Returns true on success, others on failure. + */ + bool SetAppFreezeFilter(int32_t pid); + /** * Set AbilityForegroundingFlag of an app-record to true. * @@ -755,6 +775,26 @@ public: * @return Returns RESULT_OK on success, others on failure. */ virtual AppMgrResultCode AttachedToStatusBar(const sptr &token); + + int32_t NotifyProcessDependedOnWeb(); + + void KillProcessDependedOnWeb(); + + /** + * Temporarily block the process cache feature. + * + * @param pids the pids of the processes that should be blocked. + */ + virtual AppMgrResultCode BlockProcessCacheByPids(const std::vector &pids); + + /** + * whether killed for upgrade web. + * + * @param bundleName the bundle name is killed for upgrade web. + * @return Returns true is killed for upgrade web, others return false. + */ + bool IsKilledForUpgradeWeb(const std::string &bundleName); + private: void SetServiceManager(std::unique_ptr serviceMgr); /** 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 bb6e2616b4..3b68a92aad 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 @@ -26,6 +26,7 @@ #include "application_info.h" #include "bundle_info.h" #include "child_process_info.h" +#include "child_process_request.h" #include "fault_data.h" #include "iapp_state_callback.h" #include "iapplication_state_observer.h" @@ -431,6 +432,14 @@ public: */ virtual int32_t NotifyAppFaultBySA(const AppFaultDataBySA &faultData) = 0; + /** + * Set Appfreeze Detect Filter + * + * @param pid the process pid. + * @return Returns true on success, others on failure. + */ + virtual bool SetAppFreezeFilter(int32_t pid) = 0; + #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE /** * @brief Set whether the process is continuousTask. @@ -583,12 +592,11 @@ public: /** * Start child process, called by ChildProcessManager. * - * @param srcEntry Child process source file entrance path to be started. * @param childPid Created child process pid. + * @param request Child process start request params. * @return Returns ERR_OK on success, others on failure. */ - virtual int32_t StartChildProcess(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount, - bool isStartWithDebug) = 0; + virtual int32_t StartChildProcess(pid_t &childPid, const ChildProcessRequest &request) = 0; /** * Get child process record for self. @@ -719,6 +727,30 @@ public: { return 0; } + + /** + * Notify that the process depends on web by itself. + */ + virtual int32_t NotifyProcessDependedOnWeb() + { + return 0; + } + + /** + * Kill process depended on web by sa. + */ + virtual void KillProcessDependedOnWeb() + { + return; + } + + /** + * Restart resident process depended on web. + */ + virtual void RestartResidentProcessDependedOnWeb() + { + return; + } }; } // 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 0ba1e69925..011190daa9 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 @@ -106,6 +106,11 @@ enum class AppMgrInterfaceCode { GET_RUNNING_PROCESS_INFO_BY_PID = 80, IS_APP_RUNNING = 81, CHECK_CALLING_IS_USER_TEST_MODE = 82, + SET_APPFREEZE_FILTER = 83, + // ipc for process depended on arkweb + NOTIFY_PROCESS_DEPENDED_ON_WEB = 84, + KILL_PROCESS_DEPENDED_ON_WEB = 85, + RESTART_RESIDENT_PROCESS_DEPENDED_ON_WEB = 86, }; } // AppExecFwk } // OHOS 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 63851b235c..b449d4d203 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 @@ -358,6 +358,14 @@ public: */ virtual int32_t NotifyAppFaultBySA(const AppFaultDataBySA &faultData) override; + /** + * Set Appfreeze Detect Filter + * + * @param pid the process pid. + * @return Returns true on success, others on failure. + */ + virtual bool SetAppFreezeFilter(int32_t pid) override; + #ifdef ABILITY_COMMAND_FOR_TEST /** * Block app service. @@ -516,12 +524,11 @@ public: /** * Start child process, called by ChildProcessManager. * - * @param srcEntry Child process source file entrance path to be started. * @param childPid Created child process pid. + * @param request Child process start request params. * @return Returns ERR_OK on success, others on failure. */ - int32_t StartChildProcess(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount, - bool isStartWithDebug) override; + int32_t StartChildProcess(pid_t &childPid, const ChildProcessRequest &request) override; /** * Get child process record for self. @@ -629,6 +636,11 @@ public: */ int32_t CheckCallingIsUserTestMode(const pid_t pid, bool &isUserTest) override; + virtual int32_t NotifyProcessDependedOnWeb() override; + + virtual void KillProcessDependedOnWeb() override; + + virtual void RestartResidentProcessDependedOnWeb() 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 52c2e319a6..68e3ff0bbb 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 @@ -110,6 +110,7 @@ private: int32_t HandleStartNativeProcessForDebugger(MessageParcel &data, MessageParcel &reply); int32_t HandleNotifyFault(MessageParcel &data, MessageParcel &reply); int32_t HandleNotifyFaultBySA(MessageParcel &data, MessageParcel &reply); + int32_t HandleSetAppFreezeFilter(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); @@ -142,9 +143,24 @@ private: int32_t HandleStartNativeChildProcess(MessageParcel &data, MessageParcel &reply); int32_t HandleSaveBrowserChannel(MessageParcel &data, MessageParcel &reply); int32_t HandleCheckCallingIsUserTestMode(MessageParcel &data, MessageParcel &reply); - using AppMgrFunc = int32_t (AppMgrStub::*)(MessageParcel &data, MessageParcel &reply); - std::map memberFuncMap_; - + int32_t HandleNotifyProcessDependedOnWeb(MessageParcel &data, MessageParcel &reply); + int32_t HandleKillProcessDependedOnWeb(MessageParcel &data, MessageParcel &reply); + int32_t HandleRestartResidentProcessDependedOnWeb(MessageParcel &data, MessageParcel &reply); + int32_t OnRemoteRequestInner(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerFirst(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerSecond(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerThird(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerFourth(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerFifth(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerSixth(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerSeventh(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); DISALLOW_COPY_AND_MOVE(AppMgrStub); }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/app_running_status_stub.h b/interfaces/inner_api/app_manager/include/appmgr/app_running_status_stub.h index 4f430752f6..dd5d424787 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/app_running_status_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/app_running_status_stub.h @@ -32,9 +32,6 @@ public: private: ErrCode HandleAppRunningStatus(MessageParcel &data, MessageParcel &reply); - - using AppRunningStatusListenerFunc = int32_t (AppRunningStatusStub::*)(MessageParcel &data, MessageParcel &reply); - std::map requestFuncMap_; }; } // namespace AbilityRuntime } // namespace OHOS 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 90b81c9b60..5f0a8d8a07 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 @@ -67,10 +67,14 @@ private: int32_t HandleScheduleDumpIpcStat(MessageParcel &data, MessageParcel &reply); int32_t HandleScheduleDumpFfrt(MessageParcel &data, MessageParcel &reply); int32_t HandleScheduleCacheProcess(MessageParcel &data, MessageParcel &reply); - - using AppSchedulerFunc = int32_t (AppSchedulerHost::*)(MessageParcel &data, MessageParcel &reply); - std::map memberFuncMap_; - + int32_t OnRemoteRequestInner(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerFirst(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerSecond(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + int32_t OnRemoteRequestInnerThird(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); DISALLOW_COPY_AND_MOVE(AppSchedulerHost); }; } // namespace AppExecFwk 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 b80157a978..f325b25786 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 @@ -76,9 +76,6 @@ private: 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_; - DISALLOW_COPY_AND_MOVE(AppStateCallbackHost); }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/application_state_observer_stub.h b/interfaces/inner_api/app_manager/include/appmgr/application_state_observer_stub.h index 668545df9a..e5055eacaa 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/application_state_observer_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/application_state_observer_stub.h @@ -159,34 +159,6 @@ private: int32_t HandleOnAppCacheStateChanged(MessageParcel &data, MessageParcel &reply); - using ApplicationStateObserverFunc = int32_t (ApplicationStateObserverStub::*)(MessageParcel &data, - MessageParcel &reply); - const std::map memberFuncMap_ = { - { static_cast(Message::TRANSACT_ON_FOREGROUND_APPLICATION_CHANGED), - &ApplicationStateObserverStub::HandleOnForegroundApplicationChanged }, - { static_cast(Message::TRANSACT_ON_ABILITY_STATE_CHANGED), - &ApplicationStateObserverStub::HandleOnAbilityStateChanged }, - { static_cast(Message::TRANSACT_ON_EXTENSION_STATE_CHANGED), - &ApplicationStateObserverStub::HandleOnExtensionStateChanged }, - { static_cast(Message::TRANSACT_ON_PROCESS_CREATED), - &ApplicationStateObserverStub::HandleOnProcessCreated }, - { static_cast(Message::TRANSACT_ON_PROCESS_STATE_CHANGED), - &ApplicationStateObserverStub::HandleOnProcessStateChanged }, - { static_cast(Message::TRANSACT_ON_PROCESS_DIED), - &ApplicationStateObserverStub::HandleOnProcessDied }, - { static_cast(Message::TRANSACT_ON_APPLICATION_STATE_CHANGED), - &ApplicationStateObserverStub::HandleOnApplicationStateChanged }, - { static_cast(Message::TRANSACT_ON_APP_STATE_CHANGED), - &ApplicationStateObserverStub::HandleOnAppStateChanged }, - { static_cast(Message::TRANSACT_ON_PROCESS_REUSED), - &ApplicationStateObserverStub::HandleOnProcessReused }, - { static_cast(Message::TRANSACT_ON_APP_STARTED), &ApplicationStateObserverStub::HandleOnAppStarted }, - { static_cast(Message::TRANSACT_ON_APP_STOPPED), &ApplicationStateObserverStub::HandleOnAppStopped }, - { static_cast(Message::TRANSACT_ON_PAGE_SHOW), &ApplicationStateObserverStub::HandleOnPageShow }, - { static_cast(Message::TRANSACT_ON_PAGE_HIDE), &ApplicationStateObserverStub::HandleOnPageHide }, - { static_cast(Message::TRANSACT_ON_APP_CACHE_STATE_CHANGED), - &ApplicationStateObserverStub::HandleOnAppCacheStateChanged }, - }; static std::mutex callbackMutex_; DISALLOW_COPY_AND_MOVE(ApplicationStateObserverStub); diff --git a/interfaces/inner_api/app_manager/include/appmgr/child_process_args.h b/interfaces/inner_api/app_manager/include/appmgr/child_process_args.h new file mode 100644 index 0000000000..72c2bd729b --- /dev/null +++ b/interfaces/inner_api/app_manager/include/appmgr/child_process_args.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_CHILD_PROCESS_ARGS_H +#define OHOS_ABILITY_RUNTIME_CHILD_PROCESS_ARGS_H + +#include +#include + +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +constexpr int32_t CHILD_PROCESS_ARGS_FDS_MAX_COUNT = 16; +constexpr int32_t CHILD_PROCESS_ARGS_FD_KEY_MAX_LENGTH = 20; +struct ChildProcessArgs : public Parcelable { + std::string entryParams; + std::map fds; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static ChildProcessArgs *Unmarshalling(Parcel &parcel); + static bool CheckFdKeyLength(const std::string &key); + bool CheckFdsSize() const; + bool CheckFdsKeyLength() const; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_CHILD_PROCESS_ARGS_H 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 cb5352d12e..e5c708685f 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 @@ -23,17 +23,20 @@ namespace OHOS { namespace AppExecFwk { +constexpr int32_t CHILD_PROCESS_TYPE_NOT_CHILD = -1; constexpr int32_t CHILD_PROCESS_TYPE_JS = 0; constexpr int32_t CHILD_PROCESS_TYPE_NATIVE = 1; +constexpr int32_t CHILD_PROCESS_TYPE_ARK = 2; struct ChildProcessInfo : public Parcelable { - std::int32_t pid; - std::int32_t hostPid; - std::int32_t uid; - std::int32_t processType; + int32_t pid = 0; + int32_t hostPid = 0; + int32_t uid = -1; + int32_t childProcessType = CHILD_PROCESS_TYPE_JS; std::string bundleName; std::string processName; std::string srcEntry; + std::string entryParams; bool jitEnabled = false; bool isDebugApp = true; bool isStartWithDebug = false; diff --git a/interfaces/inner_api/app_manager/include/appmgr/child_process_options.h b/interfaces/inner_api/app_manager/include/appmgr/child_process_options.h new file mode 100644 index 0000000000..93ffc8c7e2 --- /dev/null +++ b/interfaces/inner_api/app_manager/include/appmgr/child_process_options.h @@ -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. + */ + +#ifndef OHOS_ABILITY_RUNTIME_CHILD_PROCESS_OPTIONS_H +#define OHOS_ABILITY_RUNTIME_CHILD_PROCESS_OPTIONS_H + +#include + +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +struct ChildProcessOptions : public Parcelable { + bool isolationMode = false; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static ChildProcessOptions *Unmarshalling(Parcel &parcel); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_CHILD_PROCESS_OPTIONS_H diff --git a/interfaces/inner_api/app_manager/include/appmgr/child_process_request.h b/interfaces/inner_api/app_manager/include/appmgr/child_process_request.h new file mode 100644 index 0000000000..378756946d --- /dev/null +++ b/interfaces/inner_api/app_manager/include/appmgr/child_process_request.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_CHILD_PROCESS_REQUEST_H +#define OHOS_ABILITY_RUNTIME_CHILD_PROCESS_REQUEST_H + +#include + +#include "child_process_args.h" +#include "child_process_info.h" +#include "child_process_options.h" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +struct ChildProcessRequest : public Parcelable { + std::string srcEntry; + int32_t childProcessType = CHILD_PROCESS_TYPE_JS; + int32_t childProcessCount = 0; + bool isStartWithDebug = false; + ChildProcessArgs args; + ChildProcessOptions options; + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static ChildProcessRequest *Unmarshalling(Parcel &parcel); +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // OHOS_ABILITY_RUNTIME_CHILD_PROCESS_REQUEST_H 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 a6ecf59dce..eebab13561 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 @@ -38,9 +38,6 @@ private: 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_; - DISALLOW_COPY_AND_MOVE(ChildSchedulerStub); }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/configuration_observer_stub.h b/interfaces/inner_api/app_manager/include/appmgr/configuration_observer_stub.h index 1224060dfe..9b08304abc 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/configuration_observer_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/configuration_observer_stub.h @@ -44,10 +44,6 @@ public: private: int32_t HandleOnConfigurationUpdated(MessageParcel &data, MessageParcel &reply); - using ConfigurationObserverFunc = int32_t (ConfigurationObserverStub::*)(MessageParcel &data, - MessageParcel &reply); - std::map memberFuncMap_; - DISALLOW_COPY_AND_MOVE(ConfigurationObserverStub); }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/fault_data.h b/interfaces/inner_api/app_manager/include/appmgr/fault_data.h index 4fc07219f0..c7703f7802 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/fault_data.h +++ b/interfaces/inner_api/app_manager/include/appmgr/fault_data.h @@ -64,6 +64,7 @@ struct FaultData : public Parcelable { bool notifyApp = false; bool forceExit = false; uint32_t state = 0; + int32_t eventId = -1; sptr token = nullptr; }; @@ -84,6 +85,7 @@ struct AppFaultDataBySA : public Parcelable { bool notifyApp = false; bool forceExit = false; uint32_t state = 0; + int32_t eventId = -1; sptr token = nullptr; }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/parcel_util.h b/interfaces/inner_api/app_manager/include/appmgr/parcel_util.h new file mode 100644 index 0000000000..d34e1aae9b --- /dev/null +++ b/interfaces/inner_api/app_manager/include/appmgr/parcel_util.h @@ -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. + */ + +#ifndef OHOS_ABILITY_RUNTIME_PARCEL_UTIL_H +#define OHOS_ABILITY_RUNTIME_PARCEL_UTIL_H + +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace AppExecFwk { +#define PARCEL_UTIL_WRITE_NORET(parcel, type, value) \ + do { \ + if (!(parcel).Write##type(value)) { \ + TAG_LOGE(AAFwkTag::APPMGR, "failed to write %{public}s", #value); \ + return; \ + } \ + } while (0) + +#define PARCEL_UTIL_WRITE_RET_INT(parcel, type, value) \ + do { \ + if (!(parcel).Write##type(value)) { \ + TAG_LOGE(AAFwkTag::APPMGR, "failed to write %{public}s", #value); \ + return IPC_PROXY_ERR; \ + } \ + } while (0) + +#define PARCEL_UTIL_SENDREQ_NORET(code, data, reply, option) \ + do { \ + int32_t ret = SendRequest(code, data, reply, option); \ + if (ret != NO_ERROR) { \ + TAG_LOGE(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); \ + } \ + } while (0) + +#define PARCEL_UTIL_SENDREQ_RET_INT(code, data, reply, option) \ + do { \ + int32_t ret = SendRequest(code, data, reply, option); \ + if (ret != NO_ERROR) { \ + TAG_LOGE(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); \ + return ret; \ + } \ + } while (0) +} // namespace AppExecFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_PARCEL_UTIL_H diff --git a/interfaces/inner_api/app_manager/include/appmgr/quick_fix_callback_stub.h b/interfaces/inner_api/app_manager/include/appmgr/quick_fix_callback_stub.h index e1a5e752b4..9dcf43da58 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/quick_fix_callback_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/quick_fix_callback_stub.h @@ -37,9 +37,6 @@ private: int32_t HandleOnUnloadPatchDoneInner(MessageParcel &data, MessageParcel &reply); int32_t HandleOnReloadPageDoneInner(MessageParcel &data, MessageParcel &reply); - using RequestFuncType = int32_t (QuickFixCallbackStub::*)(MessageParcel &data, MessageParcel &reply); - std::map requestFuncMap_; - DISALLOW_COPY_AND_MOVE(QuickFixCallbackStub); }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/render_scheduler_host.h b/interfaces/inner_api/app_manager/include/appmgr/render_scheduler_host.h index 8324820e8a..dab5275ee5 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/render_scheduler_host.h +++ b/interfaces/inner_api/app_manager/include/appmgr/render_scheduler_host.h @@ -40,9 +40,6 @@ public: private: int32_t HandleNotifyBrowserFd(MessageParcel &data, MessageParcel &reply); - using RenderSchedulerFunc = int32_t (RenderSchedulerHost::*)(MessageParcel &data, MessageParcel &reply); - std::map memberFuncMap_; - DISALLOW_COPY_AND_MOVE(RenderSchedulerHost); }; } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/include/appmgr/render_state_observer_stub.h b/interfaces/inner_api/app_manager/include/appmgr/render_state_observer_stub.h index 47551ce945..1416251d5c 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/render_state_observer_stub.h +++ b/interfaces/inner_api/app_manager/include/appmgr/render_state_observer_stub.h @@ -35,8 +35,6 @@ public: private: DISALLOW_COPY_AND_MOVE(RenderStateObserverStub); int32_t OnRenderStateChangedInner(MessageParcel &data, MessageParcel &reply); - using RenderStateObserverFunc = int32_t (RenderStateObserverStub::*)(MessageParcel &data, MessageParcel &reply); - std::map memberFuncMap_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/src/appmgr/ability_controller_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/ability_controller_proxy.cpp index b119199437..4d9e42b4f6 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/ability_controller_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ability_controller_proxy.cpp @@ -16,7 +16,6 @@ #include "ability_controller_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" diff --git a/interfaces/inner_api/app_manager/src/appmgr/ability_controller_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/ability_controller_stub.cpp index a432c0e234..4969aaa777 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/ability_controller_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ability_controller_stub.cpp @@ -16,26 +16,14 @@ #include "ability_controller_stub.h" #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" namespace OHOS { namespace AppExecFwk { -AbilityControllerStub::AbilityControllerStub() -{ - memberFuncMap_[static_cast( - IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_START)] = - &AbilityControllerStub::HandleAllowAbilityStart; - memberFuncMap_[static_cast( - IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_BACKGROUND)] = - &AbilityControllerStub::HandleAllowAbilityBackground; -} +AbilityControllerStub::AbilityControllerStub() {} -AbilityControllerStub::~AbilityControllerStub() -{ - memberFuncMap_.clear(); -} +AbilityControllerStub::~AbilityControllerStub() {} int AbilityControllerStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -49,13 +37,13 @@ int AbilityControllerStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + switch (code) { + case static_cast(IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_START): + return HandleAllowAbilityStart(data, reply); + case static_cast(IAbilityController::Message::TRANSACT_ON_ALLOW_ABILITY_BACKGROUND): + return HandleAllowAbilityBackground(data, reply); } + TAG_LOGI(AAFwkTag::APPMGR, "AbilityControllerStub::OnRemoteRequest finish"); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/interfaces/inner_api/app_manager/src/appmgr/ability_debug_response_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/ability_debug_response_proxy.cpp index b07ef640a2..2ea9594139 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/ability_debug_response_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ability_debug_response_proxy.cpp @@ -16,7 +16,6 @@ #include "ability_debug_response_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { @@ -40,20 +39,20 @@ bool AbilityDebugResponseProxy::WriteInterfaceToken(MessageParcel &data) void AbilityDebugResponseProxy::OnAbilitysDebugStarted(const std::vector> &tokens) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); SendRequest(IAbilityDebugResponse::Message::ON_ABILITYS_DEBUG_STARTED, tokens); } void AbilityDebugResponseProxy::OnAbilitysDebugStoped(const std::vector> &tokens) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); SendRequest(IAbilityDebugResponse::Message::ON_ABILITYS_DEBUG_STOPED, tokens); } void AbilityDebugResponseProxy::OnAbilitysAssertDebugChange( const std::vector> &tokens, bool isAssertDebug) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -95,7 +94,7 @@ void AbilityDebugResponseProxy::OnAbilitysAssertDebugChange( void AbilityDebugResponseProxy::SendRequest( const IAbilityDebugResponse::Message &message, const std::vector> &tokens) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); diff --git a/interfaces/inner_api/app_manager/src/appmgr/ability_debug_response_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/ability_debug_response_stub.cpp index 4711aa13de..201d15e614 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/ability_debug_response_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ability_debug_response_stub.cpp @@ -17,7 +17,6 @@ #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" @@ -27,18 +26,9 @@ namespace { constexpr int32_t CYCLE_LIMIT_MIN = 0; constexpr int32_t CYCLE_LIMIT_MAX = 1000; } -AbilityDebugResponseStub::AbilityDebugResponseStub() -{ - responseFuncMap_[static_cast(IAbilityDebugResponse::Message::ON_ABILITYS_DEBUG_STARTED)] = - &AbilityDebugResponseStub::HandleOnAbilitysDebugStarted; - responseFuncMap_[static_cast(IAbilityDebugResponse::Message::ON_ABILITYS_DEBUG_STOPED)] = - &AbilityDebugResponseStub::HandleOnAbilitysDebugStoped; -} +AbilityDebugResponseStub::AbilityDebugResponseStub() {} -AbilityDebugResponseStub::~AbilityDebugResponseStub() -{ - responseFuncMap_.clear(); -} +AbilityDebugResponseStub::~AbilityDebugResponseStub() {} int32_t AbilityDebugResponseStub::HandleOnAbilitysDebugStarted(MessageParcel &data, MessageParcel &reply) { @@ -115,13 +105,13 @@ int AbilityDebugResponseStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = responseFuncMap_.find(code); - if (itFunc != responseFuncMap_.end()) { - auto responseFunc = itFunc->second; - if (responseFunc != nullptr) { - return (this->*responseFunc)(data, reply); - } + switch (code) { + case static_cast(IAbilityDebugResponse::Message::ON_ABILITYS_DEBUG_STARTED): + return HandleOnAbilitysDebugStarted(data, reply); + case static_cast(IAbilityDebugResponse::Message::ON_ABILITYS_DEBUG_STOPED): + return HandleOnAbilitysDebugStoped(data, reply); } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } } // namespace AppExecFwk diff --git a/interfaces/inner_api/app_manager/src/appmgr/ability_foreground_state_observer_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/ability_foreground_state_observer_proxy.cpp index f66d521ae3..b0e097a836 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/ability_foreground_state_observer_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ability_foreground_state_observer_proxy.cpp @@ -16,7 +16,6 @@ #include "ability_foreground_state_observer_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { diff --git a/interfaces/inner_api/app_manager/src/appmgr/ability_foreground_state_observer_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/ability_foreground_state_observer_stub.cpp index f995119ec1..19c9502886 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/ability_foreground_state_observer_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ability_foreground_state_observer_stub.cpp @@ -17,27 +17,19 @@ #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" namespace OHOS { namespace AppExecFwk { -AbilityForegroundStateObserverStub::AbilityForegroundStateObserverStub() -{ - memberFuncMap_[static_cast(IAbilityForegroundStateObserver::Message::ON_ABILITY_STATE_CHANGED)] = - &AbilityForegroundStateObserverStub::HandleOnAbilityStateChanged; -} +AbilityForegroundStateObserverStub::AbilityForegroundStateObserverStub() {} -AbilityForegroundStateObserverStub::~AbilityForegroundStateObserverStub() -{ - memberFuncMap_.clear(); -} +AbilityForegroundStateObserverStub::~AbilityForegroundStateObserverStub() {} int32_t AbilityForegroundStateObserverStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::u16string descriptor = AbilityForegroundStateObserverStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { @@ -45,12 +37,8 @@ int32_t AbilityForegroundStateObserverStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + if (code == static_cast(IAbilityForegroundStateObserver::Message::ON_ABILITY_STATE_CHANGED)) { + return HandleOnAbilityStateChanged(data, reply); } return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/interfaces/inner_api/app_manager/src/appmgr/ability_info_callback_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/ability_info_callback_proxy.cpp index 58fd5d5fcd..b564116cf6 100755 --- a/interfaces/inner_api/app_manager/src/appmgr/ability_info_callback_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ability_info_callback_proxy.cpp @@ -16,7 +16,6 @@ #include "ability_info_callback_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { diff --git a/interfaces/inner_api/app_manager/src/appmgr/ability_info_callback_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/ability_info_callback_stub.cpp index 5feb809a59..a891e5f3ee 100755 --- a/interfaces/inner_api/app_manager/src/appmgr/ability_info_callback_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ability_info_callback_stub.cpp @@ -16,22 +16,14 @@ #include "ability_info_callback_stub.h" #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" namespace OHOS { namespace AppExecFwk { -AbilityInfoCallbackStub::AbilityInfoCallbackStub() -{ - memberFuncMap_[static_cast( - IAbilityInfoCallback::Notify_ABILITY_TOKEN)] = &AbilityInfoCallbackStub::HandleNotifyAbilityToken; -} +AbilityInfoCallbackStub::AbilityInfoCallbackStub() {} -AbilityInfoCallbackStub::~AbilityInfoCallbackStub() -{ - memberFuncMap_.clear(); -} +AbilityInfoCallbackStub::~AbilityInfoCallbackStub() {} int AbilityInfoCallbackStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -45,13 +37,10 @@ int AbilityInfoCallbackStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + if (code == static_cast(IAbilityInfoCallback::Notify_ABILITY_TOKEN)) { + return HandleNotifyAbilityToken(data, reply); } + TAG_LOGI(AAFwkTag::APPMGR, "AbilityInfoCallbackStub::OnReceived end"); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/interfaces/inner_api/app_manager/src/appmgr/ability_state_data.cpp b/interfaces/inner_api/app_manager/src/appmgr/ability_state_data.cpp index ebee5d4084..82de598e78 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/ability_state_data.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/ability_state_data.cpp @@ -16,7 +16,6 @@ #include "ability_state_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { 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 dc09428b71..119c0b891c 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 @@ -20,7 +20,6 @@ #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { @@ -404,6 +403,41 @@ int32_t AmsMgrProxy::KillApplication(const std::string &bundleName, const bool c return reply.ReadInt32(); } +int32_t AmsMgrProxy::ForceKillApplication(const std::string &bundleName, + const int userId, const int appIndex) +{ + TAG_LOGD(AAFwkTag::APPMGR, "start"); + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + if (!WriteInterfaceToken(data)) { + return ERR_INVALID_DATA; + } + + if (!data.WriteString(bundleName)) { + TAG_LOGE(AAFwkTag::APPMGR, "parcel bundleName failed."); + return ERR_FLATTEN_OBJECT; + } + + if (!data.WriteInt32(userId)) { + TAG_LOGE(AAFwkTag::APPMGR, "parcel userId failed"); + return ERR_FLATTEN_OBJECT; + } + + if (!data.WriteInt32(appIndex)) { + TAG_LOGE(AAFwkTag::APPMGR, "parcel appIndex failed"); + return ERR_FLATTEN_OBJECT; + } + + int32_t ret = + SendTransactCmd(static_cast(IAmsMgr::Message::FORCE_KILL_APPLICATION), data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d.", ret); + return ret; + } + return reply.ReadInt32(); +} + int32_t AmsMgrProxy::UpdateApplicationInfoInstalled(const std::string &bundleName, const int uid) { TAG_LOGD(AAFwkTag::APPMGR, "start."); @@ -501,7 +535,7 @@ void AmsMgrProxy::AbilityAttachTimeOut(const sptr &token) TAG_LOGD(AAFwkTag::APPMGR, "end"); } -void AmsMgrProxy::PrepareTerminate(const sptr &token) +void AmsMgrProxy::PrepareTerminate(const sptr &token, bool clearMissionFlag) { TAG_LOGD(AAFwkTag::APPMGR, "start"); MessageParcel data; @@ -514,6 +548,10 @@ void AmsMgrProxy::PrepareTerminate(const sptr &token) TAG_LOGE(AAFwkTag::APPMGR, "Failed to write token"); return; } + if (!data.WriteBool(clearMissionFlag)) { + TAG_LOGE(AAFwkTag::APPMGR, "Failed to write clearMissionFlag"); + return; + } int32_t ret = SendTransactCmd(static_cast(IAmsMgr::Message::PREPARE_TERMINATE_ABILITY), data, reply, option); @@ -764,7 +802,7 @@ int32_t AmsMgrProxy::GetBundleNameByPid(const int pid, std::string &bundleName, int32_t AmsMgrProxy::RegisterAppDebugListener(const sptr &listener) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -789,7 +827,7 @@ int32_t AmsMgrProxy::RegisterAppDebugListener(const sptr &lis int32_t AmsMgrProxy::UnregisterAppDebugListener(const sptr &listener) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -814,7 +852,7 @@ int32_t AmsMgrProxy::UnregisterAppDebugListener(const sptr &l int32_t AmsMgrProxy::AttachAppDebug(const std::string &bundleName) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -839,7 +877,7 @@ int32_t AmsMgrProxy::AttachAppDebug(const std::string &bundleName) int32_t AmsMgrProxy::DetachAppDebug(const std::string &bundleName) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -864,7 +902,7 @@ int32_t AmsMgrProxy::DetachAppDebug(const std::string &bundleName) void AmsMgrProxy::SetKeepAliveEnableState(const std::string &bundleName, bool enable) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -889,7 +927,7 @@ void AmsMgrProxy::SetKeepAliveEnableState(const std::string &bundleName, bool en int32_t AmsMgrProxy::SetAppWaitingDebug(const std::string &bundleName, bool isPersist) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -918,7 +956,7 @@ int32_t AmsMgrProxy::SetAppWaitingDebug(const std::string &bundleName, bool isPe int32_t AmsMgrProxy::CancelAppWaitingDebug() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -937,7 +975,7 @@ int32_t AmsMgrProxy::CancelAppWaitingDebug() int32_t AmsMgrProxy::GetWaitingDebugApp(std::vector &debugInfoList) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -974,7 +1012,7 @@ int32_t AmsMgrProxy::GetWaitingDebugApp(std::vector &debugInfoList) bool AmsMgrProxy::IsWaitingDebugApp(const std::string &bundleName) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -998,7 +1036,7 @@ bool AmsMgrProxy::IsWaitingDebugApp(const std::string &bundleName) void AmsMgrProxy::ClearNonPersistWaitingDebugFlag() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -1016,7 +1054,7 @@ void AmsMgrProxy::ClearNonPersistWaitingDebugFlag() int32_t AmsMgrProxy::RegisterAbilityDebugResponse(const sptr &response) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -1041,7 +1079,7 @@ int32_t AmsMgrProxy::RegisterAbilityDebugResponse(const sptr(IAmsMgr::Message::IS_MEMORY_SIZE_SUFFICIENT), data, reply, option); if (ret != NO_ERROR) { - HILOG_ERROR("Send request failed, error code is %{public}d.", ret); + TAG_LOGE(AAFwkTag::APPMGR, "Send request failed, error code is %{public}d.", ret); return true; } return reply.ReadBool(); @@ -1138,5 +1176,56 @@ void AmsMgrProxy::AttachedToStatusBar(const sptr &token) } TAG_LOGD(AAFwkTag::APPMGR, "end"); } + +void AmsMgrProxy::BlockProcessCacheByPids(const std::vector &pids) +{ + TAG_LOGD(AAFwkTag::APPMGR, "start"); + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); + return; + } + if (!data.WriteUint32(pids.size())) { + TAG_LOGE(AAFwkTag::APPMGR, "Write size failed."); + return; + } + for (const auto &pid: pids) { + if (!data.WriteInt32(pid)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write pid failed."); + return; + } + } + int32_t ret = + SendTransactCmd(static_cast(IAmsMgr::Message::BLOCK_PROCESS_CACHE_BY_PIDS), data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); + } + TAG_LOGD(AAFwkTag::APPMGR, "end"); +} + +bool AmsMgrProxy::IsKilledForUpgradeWeb(const std::string &bundleName) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); + return false; + } + if (!data.WriteString(bundleName)) { + TAG_LOGE(AAFwkTag::APPMGR, "parcel WriteString failed"); + return false; + } + + auto ret = SendTransactCmd(static_cast(IAmsMgr::Message::IS_KILLED_FOR_UPGRADE_WEB), data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGE(AAFwkTag::APPMGR, "Send request failed, error code is %{public}d.", ret); + return false; + } + return reply.ReadBool(); +} } // namespace AppExecFwk } // namespace OHOS 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 94c73dcac7..1a369d1d90 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 @@ -14,14 +14,13 @@ */ #include "ams_mgr_stub.h" - +#include "ability_manager_errors.h" #include "ability_info.h" #include "app_debug_listener_interface.h" #include "app_mgr_proxy.h" #include "app_scheduler_interface.h" #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "iapp_state_callback.h" #include "ipc_skeleton.h" @@ -35,97 +34,15 @@ namespace { constexpr int32_t MAX_APP_DEBUG_COUNT = 100; constexpr int32_t MAX_KILL_PROCESS_PID_COUNT = 100; } + AmsMgrStub::AmsMgrStub() { - memberFuncMap_[static_cast(IAmsMgr::Message::LOAD_ABILITY)] = &AmsMgrStub::HandleLoadAbility; - memberFuncMap_[static_cast(IAmsMgr::Message::TERMINATE_ABILITY)] = - &AmsMgrStub::HandleTerminateAbility; - memberFuncMap_[static_cast(IAmsMgr::Message::UPDATE_ABILITY_STATE)] = - &AmsMgrStub::HandleUpdateAbilityState; - memberFuncMap_[static_cast(IAmsMgr::Message::UPDATE_EXTENSION_STATE)] = - &AmsMgrStub::HandleUpdateExtensionState; - memberFuncMap_[static_cast(IAmsMgr::Message::REGISTER_APP_STATE_CALLBACK)] = - &AmsMgrStub::HandleRegisterAppStateCallback; - memberFuncMap_[static_cast(IAmsMgr::Message::ABILITY_BEHAVIOR_ANALYSIS)] = - &AmsMgrStub::HandleAbilityBehaviorAnalysis; - memberFuncMap_[static_cast(IAmsMgr::Message::KILL_PEOCESS_BY_ABILITY_TOKEN)] = - &AmsMgrStub::HandleKillProcessByAbilityToken; - memberFuncMap_[static_cast(IAmsMgr::Message::KILL_PROCESSES_BY_USERID)] = - &AmsMgrStub::HandleKillProcessesByUserId; - memberFuncMap_[static_cast(IAmsMgr::Message::KILL_PROCESS_WITH_ACCOUNT)] = - &AmsMgrStub::HandleKillProcessWithAccount; - memberFuncMap_[static_cast(IAmsMgr::Message::KILL_APPLICATION)] = &AmsMgrStub::HandleKillApplication; - memberFuncMap_[static_cast(IAmsMgr::Message::ABILITY_ATTACH_TIMEOUT)] = - &AmsMgrStub::HandleAbilityAttachTimeOut; - memberFuncMap_[static_cast(IAmsMgr::Message::PREPARE_TERMINATE_ABILITY)] = - &AmsMgrStub::HandlePrepareTerminate; - memberFuncMap_[static_cast(IAmsMgr::Message::KILL_APPLICATION_BYUID)] = - &AmsMgrStub::HandleKillApplicationByUid; - memberFuncMap_[static_cast(IAmsMgr::Message::KILL_APPLICATION_SELF)] = - &AmsMgrStub::HandleKillApplicationSelf; - memberFuncMap_[static_cast(IAmsMgr::Message::GET_RUNNING_PROCESS_INFO_BY_TOKEN)] = - &AmsMgrStub::HandleGetRunningProcessInfoByToken; - memberFuncMap_[static_cast(IAmsMgr::Message::SET_ABILITY_FOREGROUNDING_FLAG)] = - &AmsMgrStub::HandleSetAbilityForegroundingFlagToAppRecord; - memberFuncMap_[static_cast(IAmsMgr::Message::START_SPECIFIED_ABILITY)] = - &AmsMgrStub::HandleStartSpecifiedAbility; - memberFuncMap_[static_cast(IAmsMgr::Message::REGISTER_START_SPECIFIED_ABILITY_RESPONSE)] = - &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)] = - &AmsMgrStub::HandleSetCurrentUserId; - memberFuncMap_[static_cast(IAmsMgr::Message::Get_BUNDLE_NAME_BY_PID)] = - &AmsMgrStub::HandleGetBundleNameByPid; CreateMemberFuncMap(); } -AmsMgrStub::~AmsMgrStub() -{ - memberFuncMap_.clear(); -} +AmsMgrStub::~AmsMgrStub() {} -void AmsMgrStub::CreateMemberFuncMap() -{ - memberFuncMap_[static_cast(IAmsMgr::Message::REGISTER_APP_DEBUG_LISTENER)] = - &AmsMgrStub::HandleRegisterAppDebugListener; - memberFuncMap_[static_cast(IAmsMgr::Message::UNREGISTER_APP_DEBUG_LISTENER)] = - &AmsMgrStub::HandleUnregisterAppDebugListener; - memberFuncMap_[static_cast(IAmsMgr::Message::ATTACH_APP_DEBUG)] = - &AmsMgrStub::HandleAttachAppDebug; - memberFuncMap_[static_cast(IAmsMgr::Message::DETACH_APP_DEBUG)] = - &AmsMgrStub::HandleDetachAppDebug; - memberFuncMap_[static_cast(IAmsMgr::Message::SET_APP_WAITING_DEBUG)] = - &AmsMgrStub::HandleSetAppWaitingDebug; - memberFuncMap_[static_cast(IAmsMgr::Message::CANCEL_APP_WAITING_DEBUG)] = - &AmsMgrStub::HandleCancelAppWaitingDebug; - memberFuncMap_[static_cast(IAmsMgr::Message::GET_WAITING_DEBUG_APP)] = - &AmsMgrStub::HandleGetWaitingDebugApp; - memberFuncMap_[static_cast(IAmsMgr::Message::IS_WAITING_DEBUG_APP)] = - &AmsMgrStub::HandleIsWaitingDebugApp; - memberFuncMap_[static_cast(IAmsMgr::Message::CLEAR_NON_PERSIST_WAITING_DEBUG_FLAG)] = - &AmsMgrStub::HandleClearNonPersistWaitingDebugFlag; - memberFuncMap_[static_cast(IAmsMgr::Message::REGISTER_ABILITY_DEBUG_RESPONSE)] = - &AmsMgrStub::HandleRegisterAbilityDebugResponse; - memberFuncMap_[static_cast(IAmsMgr::Message::IS_ATTACH_DEBUG)] = - &AmsMgrStub::HandleIsAttachDebug; - memberFuncMap_[static_cast(IAmsMgr::Message::CLEAR_PROCESS_BY_TOKEN)] = - &AmsMgrStub::HandleClearProcessByToken; - memberFuncMap_[static_cast(IAmsMgr::Message::KILL_PROCESSES_BY_PIDS)] = - &AmsMgrStub::HandleKillProcessesByPids; - memberFuncMap_[static_cast(IAmsMgr::Message::ATTACH_PID_TO_PARENT)] = - &AmsMgrStub::HandleAttachPidToParent; - memberFuncMap_[static_cast(IAmsMgr::Message::IS_MEMORY_SIZE_SUFFICIENT)] = - &AmsMgrStub::HandleIsMemorySizeSufficent; - memberFuncMap_[static_cast(IAmsMgr::Message::SET_KEEP_ALIVE_ENABLE_STATE)] = - &AmsMgrStub::HandleSetKeepAliveEnableState; - memberFuncMap_[static_cast(IAmsMgr::Message::ATTACHED_TO_STATUS_BAR)] = - &AmsMgrStub::HandleAttachedToStatusBar; -} +void AmsMgrStub::CreateMemberFuncMap() {} int AmsMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -139,17 +56,146 @@ int AmsMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParce TAG_LOGE(AAFwkTag::APPMGR, "local descriptor is unequal to remote"); return ERR_INVALID_STATE; } + return OnRemoteRequestInner(code, data, reply, option); +} - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } +int32_t AmsMgrStub::OnRemoteRequestInner(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + int retCode = ERR_OK; + retCode = OnRemoteRequestInnerFirst(code, data, reply, option); + if (retCode != AAFwk::ERR_CODE_NOT_EXIST) { + return retCode; + } + retCode = OnRemoteRequestInnerSecond(code, data, reply, option); + if (retCode != AAFwk::ERR_CODE_NOT_EXIST) { + return retCode; + } + retCode = OnRemoteRequestInnerThird(code, data, reply, option); + if (retCode != AAFwk::ERR_CODE_NOT_EXIST) { + return retCode; } return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } +int32_t AmsMgrStub::OnRemoteRequestInnerFirst(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + case static_cast(IAmsMgr::Message::LOAD_ABILITY): + return HandleLoadAbility(data, reply); + case static_cast(IAmsMgr::Message::TERMINATE_ABILITY): + return HandleTerminateAbility(data, reply); + case static_cast(IAmsMgr::Message::UPDATE_ABILITY_STATE): + return HandleUpdateAbilityState(data, reply); + case static_cast(IAmsMgr::Message::UPDATE_EXTENSION_STATE): + return HandleUpdateExtensionState(data, reply); + case static_cast(IAmsMgr::Message::REGISTER_APP_STATE_CALLBACK): + return HandleRegisterAppStateCallback(data, reply); + case static_cast(IAmsMgr::Message::ABILITY_BEHAVIOR_ANALYSIS): + return HandleAbilityBehaviorAnalysis(data, reply); + case static_cast(IAmsMgr::Message::KILL_PEOCESS_BY_ABILITY_TOKEN): + return HandleKillProcessByAbilityToken(data, reply); + case static_cast(IAmsMgr::Message::KILL_PROCESSES_BY_USERID): + return HandleKillProcessesByUserId(data, reply); + case static_cast(IAmsMgr::Message::KILL_PROCESS_WITH_ACCOUNT): + return HandleKillProcessWithAccount(data, reply); + case static_cast(IAmsMgr::Message::KILL_APPLICATION): + return HandleKillApplication(data, reply); + case static_cast(IAmsMgr::Message::ABILITY_ATTACH_TIMEOUT): + return HandleAbilityAttachTimeOut(data, reply); + case static_cast(IAmsMgr::Message::PREPARE_TERMINATE_ABILITY): + return HandlePrepareTerminate(data, reply); + case static_cast(IAmsMgr::Message::KILL_APPLICATION_BYUID): + return HandleKillApplicationByUid(data, reply); + case static_cast(IAmsMgr::Message::KILL_APPLICATION_SELF): + return HandleKillApplicationSelf(data, reply); + case static_cast(IAmsMgr::Message::GET_RUNNING_PROCESS_INFO_BY_TOKEN): + return HandleGetRunningProcessInfoByToken(data, reply); + } + return AAFwk::ERR_CODE_NOT_EXIST; +} + +int32_t AmsMgrStub::OnRemoteRequestInnerSecond(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + case static_cast(IAmsMgr::Message::SET_ABILITY_FOREGROUNDING_FLAG): + return HandleSetAbilityForegroundingFlagToAppRecord(data, reply); + case static_cast(IAmsMgr::Message::START_SPECIFIED_ABILITY): + return HandleStartSpecifiedAbility(data, reply); + case static_cast(IAmsMgr::Message::REGISTER_START_SPECIFIED_ABILITY_RESPONSE): + return HandleRegisterStartSpecifiedAbilityResponse(data, reply); + case static_cast(IAmsMgr::Message::GET_APPLICATION_INFO_BY_PROCESS_ID): + return HandleGetApplicationInfoByProcessID(data, reply); + case static_cast(IAmsMgr::Message::NOTIFY_APP_MGR_RECORD_EXIT_REASON): + return HandleNotifyAppMgrRecordExitReason(data, reply); + case static_cast(IAmsMgr::Message::UPDATE_APPLICATION_INFO_INSTALLED): + return HandleUpdateApplicationInfoInstalled(data, reply); + case static_cast(IAmsMgr::Message::SET_CURRENT_USER_ID): + return HandleSetCurrentUserId(data, reply); + case static_cast(IAmsMgr::Message::Get_BUNDLE_NAME_BY_PID): + return HandleGetBundleNameByPid(data, reply); + case static_cast(IAmsMgr::Message::REGISTER_APP_DEBUG_LISTENER): + return HandleRegisterAppDebugListener(data, reply); + case static_cast(IAmsMgr::Message::UNREGISTER_APP_DEBUG_LISTENER): + return HandleUnregisterAppDebugListener(data, reply); + case static_cast(IAmsMgr::Message::ATTACH_APP_DEBUG): + return HandleAttachAppDebug(data, reply); + case static_cast(IAmsMgr::Message::DETACH_APP_DEBUG): + return HandleDetachAppDebug(data, reply); + case static_cast(IAmsMgr::Message::SET_APP_WAITING_DEBUG): + return HandleSetAppWaitingDebug(data, reply); + case static_cast(IAmsMgr::Message::CANCEL_APP_WAITING_DEBUG): + return HandleCancelAppWaitingDebug(data, reply); + case static_cast(IAmsMgr::Message::GET_WAITING_DEBUG_APP): + return HandleGetWaitingDebugApp(data, reply); + case static_cast(IAmsMgr::Message::IS_WAITING_DEBUG_APP): + return HandleIsWaitingDebugApp(data, reply); + } + return AAFwk::ERR_CODE_NOT_EXIST; +} + +int32_t AmsMgrStub::OnRemoteRequestInnerThird(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + case static_cast(IAmsMgr::Message::CLEAR_NON_PERSIST_WAITING_DEBUG_FLAG): + return HandleClearNonPersistWaitingDebugFlag(data, reply); + case static_cast(IAmsMgr::Message::REGISTER_ABILITY_DEBUG_RESPONSE): + return HandleRegisterAbilityDebugResponse(data, reply); + case static_cast(IAmsMgr::Message::IS_ATTACH_DEBUG): + return HandleIsAttachDebug(data, reply); + case static_cast(IAmsMgr::Message::CLEAR_PROCESS_BY_TOKEN): + return HandleClearProcessByToken(data, reply); + case static_cast(IAmsMgr::Message::KILL_PROCESSES_BY_PIDS): + return HandleKillProcessesByPids(data, reply); + case static_cast(IAmsMgr::Message::ATTACH_PID_TO_PARENT): + return HandleAttachPidToParent(data, reply); + case static_cast(IAmsMgr::Message::IS_MEMORY_SIZE_SUFFICIENT): + return HandleIsMemorySizeSufficent(data, reply); + case static_cast(IAmsMgr::Message::SET_KEEP_ALIVE_ENABLE_STATE): + return HandleSetKeepAliveEnableState(data, reply); + case static_cast(IAmsMgr::Message::ATTACHED_TO_STATUS_BAR): + return HandleAttachedToStatusBar(data, reply); + case static_cast(IAmsMgr::Message::UPDATE_CONFIGURATION): + return 0; + case static_cast(IAmsMgr::Message::GET_CONFIGURATION): + return 0; + case static_cast(IAmsMgr::Message::START_SPECIFIED_PROCESS): + return 0; + case static_cast(IAmsMgr::Message::REGISTER_ABILITY_MS_DELEGATE): + return 0; + case static_cast(IAmsMgr::Message::BLOCK_PROCESS_CACHE_BY_PIDS): + return HandleBlockProcessCacheByPids(data, reply); + case static_cast(IAmsMgr::Message::IS_KILLED_FOR_UPGRADE_WEB): + return HandleIsKilledForUpgradeWeb(data, reply); + case static_cast(IAmsMgr::Message::FORCE_KILL_APPLICATION): + return HandleForceKillApplication(data, reply); + } + return AAFwk::ERR_CODE_NOT_EXIST; +} + ErrCode AmsMgrStub::HandleLoadAbility(MessageParcel &data, MessageParcel &reply) { HITRACE_METER(HITRACE_TAG_APP); @@ -318,6 +364,21 @@ ErrCode AmsMgrStub::HandleKillApplication(MessageParcel &data, MessageParcel &re return NO_ERROR; } +ErrCode AmsMgrStub::HandleForceKillApplication(MessageParcel &data, MessageParcel &reply) +{ + HITRACE_METER(HITRACE_TAG_APP); + std::string bundleName = data.ReadString(); + int userId = data.ReadInt32(); + int appIndex = data.ReadInt32(); + + TAG_LOGI(AAFwkTag::APPMGR, "bundleName = %{public}s,userId=%{public}d,appIndex=%{public}d", + bundleName.c_str(), userId, appIndex); + + int32_t result = ForceKillApplication(bundleName, userId, appIndex); + reply.WriteInt32(result); + return NO_ERROR; +} + ErrCode AmsMgrStub::HandleKillApplicationByUid(MessageParcel &data, MessageParcel &reply) { HITRACE_METER(HITRACE_TAG_APP); @@ -351,7 +412,8 @@ int32_t AmsMgrStub::HandleAbilityAttachTimeOut(MessageParcel &data, MessageParce int32_t AmsMgrStub::HandlePrepareTerminate(MessageParcel &data, MessageParcel &reply) { sptr token = data.ReadRemoteObject(); - PrepareTerminate(token); + bool clearMissionFlag = data.ReadBool(); + PrepareTerminate(token, clearMissionFlag); return NO_ERROR; } @@ -473,7 +535,7 @@ int32_t AmsMgrStub::HandleGetBundleNameByPid(MessageParcel &data, MessageParcel int32_t AmsMgrStub::HandleRegisterAppDebugListener(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto appDebugLister = iface_cast(data.ReadRemoteObject()); if (appDebugLister == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "App debug lister is null."); @@ -490,7 +552,7 @@ int32_t AmsMgrStub::HandleRegisterAppDebugListener(MessageParcel &data, MessageP int32_t AmsMgrStub::HandleUnregisterAppDebugListener(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto appDebugLister = iface_cast(data.ReadRemoteObject()); if (appDebugLister == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "App debug lister is nullptr."); @@ -507,7 +569,7 @@ int32_t AmsMgrStub::HandleUnregisterAppDebugListener(MessageParcel &data, Messag int32_t AmsMgrStub::HandleAttachAppDebug(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto bundleName = data.ReadString(); if (bundleName.empty()) { TAG_LOGE(AAFwkTag::APPMGR, "Bundle name is empty."); @@ -524,7 +586,7 @@ int32_t AmsMgrStub::HandleAttachAppDebug(MessageParcel &data, MessageParcel &rep int32_t AmsMgrStub::HandleDetachAppDebug(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto bundleName = data.ReadString(); if (bundleName.empty()) { TAG_LOGE(AAFwkTag::APPMGR, "Bundle name is empty."); @@ -541,7 +603,7 @@ int32_t AmsMgrStub::HandleDetachAppDebug(MessageParcel &data, MessageParcel &rep int32_t AmsMgrStub::HandleSetAppWaitingDebug(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto bundleName = data.ReadString(); if (bundleName.empty()) { TAG_LOGE(AAFwkTag::APPMGR, "Bundle name is empty."); @@ -558,7 +620,7 @@ int32_t AmsMgrStub::HandleSetAppWaitingDebug(MessageParcel &data, MessageParcel int32_t AmsMgrStub::HandleCancelAppWaitingDebug(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto result = CancelAppWaitingDebug(); if (!reply.WriteInt32(result)) { TAG_LOGE(AAFwkTag::APPMGR, "Fail to write result."); @@ -569,7 +631,7 @@ int32_t AmsMgrStub::HandleCancelAppWaitingDebug(MessageParcel &data, MessageParc int32_t AmsMgrStub::HandleGetWaitingDebugApp(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::vector debugInfoList; auto result = GetWaitingDebugApp(debugInfoList); if (!reply.WriteInt32(result)) { @@ -597,7 +659,7 @@ int32_t AmsMgrStub::HandleGetWaitingDebugApp(MessageParcel &data, MessageParcel int32_t AmsMgrStub::HandleIsWaitingDebugApp(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto bundleName = data.ReadString(); if (bundleName.empty()) { TAG_LOGE(AAFwkTag::APPMGR, "Bundle name is empty."); @@ -614,7 +676,7 @@ int32_t AmsMgrStub::HandleIsWaitingDebugApp(MessageParcel &data, MessageParcel & int32_t AmsMgrStub::HandleSetKeepAliveEnableState(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto bundleName = data.ReadString(); auto enable = data.ReadBool(); SetKeepAliveEnableState(bundleName, enable); @@ -623,14 +685,14 @@ int32_t AmsMgrStub::HandleSetKeepAliveEnableState(MessageParcel &data, MessagePa int32_t AmsMgrStub::HandleClearNonPersistWaitingDebugFlag(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); ClearNonPersistWaitingDebugFlag(); return NO_ERROR; } int32_t AmsMgrStub::HandleRegisterAbilityDebugResponse(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto response = iface_cast(data.ReadRemoteObject()); if (response == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Response is nullptr."); @@ -647,7 +709,7 @@ int32_t AmsMgrStub::HandleRegisterAbilityDebugResponse(MessageParcel &data, Mess int32_t AmsMgrStub::HandleIsAttachDebug(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto bundleName = data.ReadString(); if (bundleName.empty()) { TAG_LOGE(AAFwkTag::APPMGR, "Bundle name is empty."); @@ -674,7 +736,7 @@ int32_t AmsMgrStub::HandleIsMemorySizeSufficent(MessageParcel &data, MessageParc { auto result = IsMemorySizeSufficent(); if (!reply.WriteBool(result)) { - HILOG_ERROR("Fail to write result."); + TAG_LOGE(AAFwkTag::APPMGR, "Fail to write result."); return ERR_INVALID_VALUE; } return NO_ERROR; @@ -687,5 +749,39 @@ ErrCode AmsMgrStub::HandleAttachedToStatusBar(MessageParcel &data, MessageParcel AttachedToStatusBar(token); return NO_ERROR; } + +ErrCode AmsMgrStub::HandleBlockProcessCacheByPids(MessageParcel &data, MessageParcel &reply) +{ + HITRACE_METER(HITRACE_TAG_APP); + auto size = data.ReadUint32(); + if (size == 0 || size > MAX_KILL_PROCESS_PID_COUNT) { + TAG_LOGE(AAFwkTag::APPMGR, "Invalid size."); + return ERR_INVALID_VALUE; + } + std::vector pids; + for (uint32_t i = 0; i < size; i++) { + pids.emplace_back(data.ReadInt32()); + } + + BlockProcessCacheByPids(pids); + return NO_ERROR; +} + +int32_t AmsMgrStub::HandleIsKilledForUpgradeWeb(MessageParcel &data, MessageParcel &reply) +{ + TAG_LOGD(AAFwkTag::APPMGR, "called"); + auto bundleName = data.ReadString(); + if (bundleName.empty()) { + TAG_LOGE(AAFwkTag::APPMGR, "Bundle name is empty."); + return ERR_INVALID_VALUE; + } + + auto result = IsKilledForUpgradeWeb(bundleName); + if (!reply.WriteBool(result)) { + TAG_LOGE(AAFwkTag::APPMGR, "Fail to write result."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_debug_info.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_debug_info.cpp index 7beffe1272..327338d54c 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_debug_info.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_debug_info.cpp @@ -16,7 +16,6 @@ #include "app_debug_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_debug_listener_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_debug_listener_proxy.cpp index 3dc7bfb8e4..fc271be274 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_debug_listener_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_debug_listener_proxy.cpp @@ -16,7 +16,6 @@ #include "app_debug_listener_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { @@ -40,13 +39,13 @@ bool AppDebugListenerProxy::WriteInterfaceToken(MessageParcel &data) void AppDebugListenerProxy::OnAppDebugStarted(const std::vector &debugInfos) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); SendRequest(IAppDebugListener::Message::ON_APP_DEBUG_STARTED, debugInfos); } void AppDebugListenerProxy::OnAppDebugStoped(const std::vector &debugInfos) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); SendRequest(IAppDebugListener::Message::ON_APP_DEBUG_STOPED, debugInfos); } diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_debug_listener_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_debug_listener_stub.cpp index e0188405f6..ae20e2535b 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_debug_listener_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_debug_listener_stub.cpp @@ -16,7 +16,6 @@ #include "app_debug_listener_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" @@ -26,18 +25,9 @@ namespace { constexpr int32_t CYCLE_LIMIT_MIN = 0; constexpr int32_t CYCLE_LIMIT_MAX = 1000; } -AppDebugListenerStub::AppDebugListenerStub() -{ - memberFuncMap_[static_cast(IAppDebugListener::Message::ON_APP_DEBUG_STARTED)] = - &AppDebugListenerStub::HandleOnAppDebugStarted; - memberFuncMap_[static_cast(IAppDebugListener::Message::ON_APP_DEBUG_STOPED)] = - &AppDebugListenerStub::HandleOnAppDebugStoped; -} +AppDebugListenerStub::AppDebugListenerStub() {} -AppDebugListenerStub::~AppDebugListenerStub() -{ - memberFuncMap_.clear(); -} +AppDebugListenerStub::~AppDebugListenerStub() {} int AppDebugListenerStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -50,13 +40,13 @@ int AppDebugListenerStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + switch (code) { + case static_cast(IAppDebugListener::Message::ON_APP_DEBUG_STARTED): + return HandleOnAppDebugStarted(data, reply); + case static_cast(IAppDebugListener::Message::ON_APP_DEBUG_STOPED): + return HandleOnAppDebugStoped(data, reply); } + TAG_LOGD(AAFwkTag::APPMGR, "AppDebugListenerStub::OnRemoteRequest end"); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_foreground_state_observer_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_foreground_state_observer_proxy.cpp index 5eb04bfa91..59d8eada73 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_foreground_state_observer_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_foreground_state_observer_proxy.cpp @@ -16,7 +16,6 @@ #include "app_foreground_state_observer_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_foreground_state_observer_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_foreground_state_observer_stub.cpp index e7beb687aa..b35443bb79 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_foreground_state_observer_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_foreground_state_observer_stub.cpp @@ -17,27 +17,19 @@ #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" namespace OHOS { namespace AppExecFwk { -AppForegroundStateObserverStub::AppForegroundStateObserverStub() -{ - memberFuncMap_[static_cast(IAppForegroundStateObserver::Message::ON_APP_STATE_CHANGED)] = - &AppForegroundStateObserverStub::HandleOnAppStateChanged; -} +AppForegroundStateObserverStub::AppForegroundStateObserverStub() {} -AppForegroundStateObserverStub::~AppForegroundStateObserverStub() -{ - memberFuncMap_.clear(); -} +AppForegroundStateObserverStub::~AppForegroundStateObserverStub() {} int32_t AppForegroundStateObserverStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::u16string descriptor = AppForegroundStateObserverStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { @@ -45,13 +37,10 @@ int32_t AppForegroundStateObserverStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + if (code == static_cast(IAppForegroundStateObserver::Message::ON_APP_STATE_CHANGED)) { + return HandleOnAppStateChanged(data, reply); } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } 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..f609ea7409 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 @@ -15,7 +15,6 @@ #include "app_jsheap_mem_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_launch_data.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_launch_data.cpp index 7f6c872d4b..b2f3bf8966 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_launch_data.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_launch_data.cpp @@ -16,7 +16,6 @@ #include "app_launch_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { @@ -102,6 +101,11 @@ bool AppLaunchData::Marshalling(Parcel &parcel) const return false; } + if (!parcel.WriteBool(isErrorInfoEnhance_)) { + TAG_LOGE(AAFwkTag::APPMGR, "Failed to write is error info enhance flag."); + return false; + } + return true; } @@ -147,6 +151,7 @@ bool AppLaunchData::ReadFromParcel(Parcel &parcel) isNativeStart_ = parcel.ReadBool(); appRunningUniqueId_ = parcel.ReadString(); isMultiThread_ = parcel.ReadBool(); + isErrorInfoEnhance_ = parcel.ReadBool(); return true; } 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 597fa9e294..0cea759327 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 @@ -25,7 +25,6 @@ #include "app_mgr_interface.h" #include "app_service_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "app_mem_info.h" @@ -300,6 +299,23 @@ AppMgrResultCode AppMgrClient::KillApplication(const std::string &bundleName, bo return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; } +AppMgrResultCode AppMgrClient::ForceKillApplication(const std::string &bundleName, + const int userId, const int appIndex) +{ + sptr service = iface_cast(mgrHolder_->GetRemoteObject()); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + int32_t result = amsService->ForceKillApplication(bundleName, userId, appIndex); + if (result == ERR_OK) { + return AppMgrResultCode::RESULT_OK; + } + return AppMgrResultCode::ERROR_SERVICE_NOT_READY; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + AppMgrResultCode AppMgrClient::KillApplicationByUid(const std::string &bundleName, const int uid) { sptr service = iface_cast(mgrHolder_->GetRemoteObject()); @@ -495,7 +511,7 @@ void AppMgrClient::AbilityAttachTimeOut(const sptr &token) amsService->AbilityAttachTimeOut(token); } -void AppMgrClient::PrepareTerminate(const sptr &token) +void AppMgrClient::PrepareTerminate(const sptr &token, bool clearMissionFlag) { sptr service = iface_cast(mgrHolder_->GetRemoteObject()); if (service == nullptr) { @@ -505,7 +521,7 @@ void AppMgrClient::PrepareTerminate(const sptr &token) if (amsService == nullptr) { return; } - amsService->PrepareTerminate(token); + amsService->PrepareTerminate(token, clearMissionFlag); } void AppMgrClient::GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info) @@ -854,6 +870,15 @@ int32_t AppMgrClient::NotifyAppFaultBySA(const AppFaultDataBySA &faultData) return service->NotifyAppFaultBySA(faultData); } +bool AppMgrClient::SetAppFreezeFilter(int32_t pid) +{ + sptr service = iface_cast(mgrHolder_->GetRemoteObject()); + if (service == nullptr) { + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; + } + return service->SetAppFreezeFilter(pid); +} + int32_t AppMgrClient::ChangeAppGcState(pid_t pid, int32_t state) { if (mgrHolder_ == nullptr) { @@ -1207,5 +1232,56 @@ AppMgrResultCode AppMgrClient::AttachedToStatusBar(const sptr &to TAG_LOGE(AAFwkTag::APPMGR, "Service is not connected."); return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; } + +int32_t AppMgrClient::NotifyProcessDependedOnWeb() +{ + sptr service = iface_cast(mgrHolder_->GetRemoteObject()); + if (service == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "Service is nullptr."); + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; + } + TAG_LOGD(AAFwkTag::APPMGR, "call"); + return service->NotifyProcessDependedOnWeb(); +} + +void AppMgrClient::KillProcessDependedOnWeb() +{ + sptr service = iface_cast(mgrHolder_->GetRemoteObject()); + if (service == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "Service is nullptr."); + return; + } + TAG_LOGD(AAFwkTag::APPMGR, "call"); + service->KillProcessDependedOnWeb(); +} + +AppMgrResultCode AppMgrClient::BlockProcessCacheByPids(const std::vector &pids) +{ + sptr service = iface_cast(mgrHolder_->GetRemoteObject()); + if (service != nullptr) { + sptr amsService = service->GetAmsMgr(); + if (amsService != nullptr) { + amsService->BlockProcessCacheByPids(pids); + return AppMgrResultCode::RESULT_OK; + } + } + return AppMgrResultCode::ERROR_SERVICE_NOT_CONNECTED; +} + +bool AppMgrClient::IsKilledForUpgradeWeb(const std::string &bundleName) +{ + sptr service = iface_cast(mgrHolder_->GetRemoteObject()); + if (service == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "Service is nullptr."); + return false; + } + sptr amsService = service->GetAmsMgr(); + if (amsService == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "amsService is nullptr."); + return false; + } + TAG_LOGD(AAFwkTag::APPMGR, "call"); + return amsService->IsKilledForUpgradeWeb(bundleName); +} } // 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 d485e4899a..6c1693444f 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 @@ -17,23 +17,13 @@ #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "ipc_types.h" #include "iremote_object.h" +#include "parcel_util.h" namespace OHOS { namespace AppExecFwk { -namespace { -#define PROXY_WRITE_PARCEL_AND_RETURN_IF_FAIL(messageParcel, type, value) \ - do { \ - if (!(messageParcel).Write##type(value)) { \ - TAG_LOGE(AAFwkTag::APPMGR, \ - "failed to write %{public}s", #value); \ - return IPC_PROXY_ERR; \ - } \ - } while (0) -} constexpr int32_t CYCLE_LIMIT = 1000; AppMgrProxy::AppMgrProxy(const sptr &impl) : IRemoteProxy(impl) {} @@ -55,14 +45,9 @@ void AppMgrProxy::AttachApplication(const sptr &obj) if (!WriteInterfaceToken(data)) { return; } - if (!data.WriteRemoteObject(obj.GetRefPtr())) { - TAG_LOGE(AAFwkTag::APPMGR, "Failed to write remote object"); - return; - } - int32_t ret = SendRequest(AppMgrInterfaceCode::APP_ATTACH_APPLICATION, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - } + PARCEL_UTIL_WRITE_NORET(data, RemoteObject, obj.GetRefPtr()); + + PARCEL_UTIL_SENDREQ_NORET(AppMgrInterfaceCode::APP_ATTACH_APPLICATION, data, reply, option); } int32_t AppMgrProxy::PreloadApplication(const std::string &bundleName, int32_t userId, @@ -72,21 +57,16 @@ int32_t AppMgrProxy::PreloadApplication(const std::string &bundleName, int32_t u MessageParcel data; MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); - if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "PreloadApplication Write interface token failed."); return IPC_PROXY_ERR; } - PROXY_WRITE_PARCEL_AND_RETURN_IF_FAIL(data, String16, Str8ToStr16(bundleName)); - PROXY_WRITE_PARCEL_AND_RETURN_IF_FAIL(data, Int32, userId); - PROXY_WRITE_PARCEL_AND_RETURN_IF_FAIL(data, Int32, static_cast(preloadMode)); - PROXY_WRITE_PARCEL_AND_RETURN_IF_FAIL(data, Int32, appIndex); + PARCEL_UTIL_WRITE_RET_INT(data, String16, Str8ToStr16(bundleName)); + PARCEL_UTIL_WRITE_RET_INT(data, Int32, userId); + PARCEL_UTIL_WRITE_RET_INT(data, Int32, static_cast(preloadMode)); + PARCEL_UTIL_WRITE_RET_INT(data, Int32, appIndex); - int32_t error = SendRequest(AppMgrInterfaceCode::PRELOAD_APPLICATION, data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "PreloadApplication Send request error: %{public}d.", error); - return error; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::PRELOAD_APPLICATION, data, reply, option); return reply.ReadInt32(); } @@ -98,11 +78,9 @@ void AppMgrProxy::ApplicationForegrounded(const int32_t recordId) if (!WriteInterfaceToken(data)) { return; } - data.WriteInt32(recordId); - int32_t ret = SendRequest(AppMgrInterfaceCode::APP_APPLICATION_FOREGROUNDED, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - } + PARCEL_UTIL_WRITE_NORET(data, Int32, recordId); + + PARCEL_UTIL_SENDREQ_NORET(AppMgrInterfaceCode::APP_APPLICATION_FOREGROUNDED, data, reply, option); } void AppMgrProxy::ApplicationBackgrounded(const int32_t recordId) @@ -113,11 +91,9 @@ void AppMgrProxy::ApplicationBackgrounded(const int32_t recordId) if (!WriteInterfaceToken(data)) { return; } - data.WriteInt32(recordId); - int32_t ret = SendRequest(AppMgrInterfaceCode::APP_APPLICATION_BACKGROUNDED, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - } + PARCEL_UTIL_WRITE_NORET(data, Int32, recordId); + + PARCEL_UTIL_SENDREQ_NORET(AppMgrInterfaceCode::APP_APPLICATION_BACKGROUNDED, data, reply, option); } void AppMgrProxy::ApplicationTerminated(const int32_t recordId) @@ -128,11 +104,9 @@ void AppMgrProxy::ApplicationTerminated(const int32_t recordId) if (!WriteInterfaceToken(data)) { return; } - data.WriteInt32(recordId); - int32_t ret = SendRequest(AppMgrInterfaceCode::APP_APPLICATION_TERMINATED, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - } + PARCEL_UTIL_WRITE_NORET(data, Int32, recordId); + + PARCEL_UTIL_SENDREQ_NORET(AppMgrInterfaceCode::APP_APPLICATION_TERMINATED, data, reply, option); } void AppMgrProxy::AbilityCleaned(const sptr &token) @@ -143,14 +117,9 @@ void AppMgrProxy::AbilityCleaned(const sptr &token) if (!WriteInterfaceToken(data)) { return; } - if (!data.WriteRemoteObject(token.GetRefPtr())) { - TAG_LOGE(AAFwkTag::APPMGR, "Failed to write token"); - return; - } - int32_t ret = SendRequest(AppMgrInterfaceCode::APP_ABILITY_CLEANED, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - } + PARCEL_UTIL_WRITE_NORET(data, RemoteObject, token.GetRefPtr()); + + PARCEL_UTIL_SENDREQ_NORET(AppMgrInterfaceCode::APP_ABILITY_CLEANED, data, reply, option); } sptr AppMgrProxy::GetAmsMgr() @@ -180,23 +149,11 @@ int32_t AppMgrProxy::ClearUpApplicationData(const std::string &bundleName, int32 if (!WriteInterfaceToken(data)) { return ERR_FLATTEN_OBJECT; } - if (!data.WriteString(bundleName)) { - TAG_LOGE(AAFwkTag::APPMGR, "parcel WriteString failed"); - return ERR_FLATTEN_OBJECT; - } - if (!data.WriteInt32(appCloneIndex)) { - TAG_LOGE(AAFwkTag::APPMGR, "appCloneIndex write failed."); - return ERR_INVALID_VALUE; - } - if (!data.WriteInt32(userId)) { - TAG_LOGE(AAFwkTag::APPMGR, "userId write failed."); - return ERR_INVALID_VALUE; - } - int32_t ret = SendRequest(AppMgrInterfaceCode::APP_CLEAR_UP_APPLICATION_DATA, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - return ret; - } + PARCEL_UTIL_WRITE_RET_INT(data, String, bundleName); + PARCEL_UTIL_WRITE_RET_INT(data, Int32, appCloneIndex); + PARCEL_UTIL_WRITE_RET_INT(data, Int32, userId); + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::APP_CLEAR_UP_APPLICATION_DATA, data, reply, option); return reply.ReadInt32(); } @@ -208,15 +165,9 @@ int32_t AppMgrProxy::ClearUpApplicationDataBySelf(int32_t userId) if (!WriteInterfaceToken(data)) { return ERR_FLATTEN_OBJECT; } - if (!data.WriteInt32(userId)) { - TAG_LOGE(AAFwkTag::APPMGR, "userId write failed."); - return ERR_INVALID_VALUE; - } - int32_t ret = SendRequest(AppMgrInterfaceCode::APP_CLEAR_UP_APPLICATION_DATA_BY_SELF, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - return ret; - } + PARCEL_UTIL_WRITE_RET_INT(data, Int32, userId); + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::APP_CLEAR_UP_APPLICATION_DATA_BY_SELF, data, reply, option); return reply.ReadInt32(); } @@ -250,15 +201,9 @@ int32_t AppMgrProxy::GetRunningMultiAppInfoByBundleName(const std::string &bundl 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; - } + PARCEL_UTIL_WRITE_RET_INT(data, String, bundleName); + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::GET_RUNNING_MULTIAPP_INFO_BY_BUNDLENAME, data, reply, option); std::unique_ptr infoReply(reply.ReadParcelable()); if (infoReply == nullptr) { TAG_LOGW(AAFwkTag::APPMGR, "reply ReadParcelable is nullptr"); @@ -278,10 +223,8 @@ int32_t AppMgrProxy::GetRunningProcessesByBundleType(const BundleType bundleType if (!WriteInterfaceToken(data)) { return ERR_FLATTEN_OBJECT; } - if (!data.WriteInt32(static_cast(bundleType))) { - TAG_LOGE(AAFwkTag::APPMGR, "Bundle type write failed."); - return ERR_FLATTEN_OBJECT; - } + PARCEL_UTIL_WRITE_RET_INT(data, Int32, static_cast(bundleType)); + if (!SendTransactCmd(AppMgrInterfaceCode::APP_GET_RUNNING_PROCESSES_BY_BUNDLE_TYPE, data, reply)) { return ERR_NULL_OBJECT; } @@ -322,16 +265,9 @@ int32_t AppMgrProxy::JudgeSandboxByPid(pid_t pid, bool &isSandbox) if (!WriteInterfaceToken(data)) { return ERR_FLATTEN_OBJECT; } - if (!data.WriteInt32(pid)) { - TAG_LOGE(AAFwkTag::APPMGR, "Pid write failed."); - return ERR_FLATTEN_OBJECT; - } - int32_t ret = SendRequest(AppMgrInterfaceCode::JUDGE_SANDBOX_BY_PID, - data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - return ret; - } + PARCEL_UTIL_WRITE_RET_INT(data, Int32, pid); + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::JUDGE_SANDBOX_BY_PID, data, reply, option); isSandbox = reply.ReadBool(); return reply.ReadInt32(); } @@ -345,7 +281,8 @@ int32_t AppMgrProxy::GetProcessRunningInfosByUserId(std::vector &procLevelMap) @@ -406,13 +340,10 @@ int32_t AppMgrProxy::NotifyProcMemoryLevel(const std::map &p return ERR_FLATTEN_OBJECT; } MemoryLevelInfo memoryLevelInfo(procLevelMap); - data.WriteParcelable(&memoryLevelInfo); - int32_t ret = SendRequest(AppMgrInterfaceCode::APP_NOTIFY_PROC_MEMORY_LEVEL, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - } - int result = reply.ReadInt32(); - return result; + PARCEL_UTIL_WRITE_RET_INT(data, Parcelable, &memoryLevelInfo); + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::APP_NOTIFY_PROC_MEMORY_LEVEL, data, reply, option); + return reply.ReadInt32(); } int32_t AppMgrProxy::DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo) @@ -423,7 +354,7 @@ int32_t AppMgrProxy::DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocI if (!WriteInterfaceToken(data)) { return ERR_FLATTEN_OBJECT; } - data.WriteInt32(pid); + PARCEL_UTIL_WRITE_RET_INT(data, Int32, pid); MessageOption option(MessageOption::TF_SYNC); int32_t ret = SendRequest(AppMgrInterfaceCode::DUMP_HEAP_MEMORY_PROCESS, data, reply, option); @@ -446,22 +377,14 @@ int32_t AppMgrProxy::DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info) TAG_LOGD(AAFwkTag::APPMGR, "AppMgrProxy::DumpJsHeapMemory."); MessageParcel data; MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); if (!WriteInterfaceToken(data)) { return ERR_FLATTEN_OBJECT; } + PARCEL_UTIL_WRITE_RET_INT(data, Parcelable, &info); - if (!data.WriteParcelable(&info)) { - TAG_LOGE(AAFwkTag::APPMGR, "info write failed"); - return ERR_FLATTEN_OBJECT; - } - MessageOption option(MessageOption::TF_SYNC); - int32_t ret = SendRequest(AppMgrInterfaceCode::DUMP_JSHEAP_MEMORY_PROCESS, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, - "AppMgrProxy SendRequest DUMP_JSHEAP_MEMORY_PROCESS is failed, error code: %{public}d", ret); - return ret; - } - return ret; + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::DUMP_JSHEAP_MEMORY_PROCESS, data, reply, option); + return reply.ReadInt32(); } bool AppMgrProxy::SendTransactCmd(AppMgrInterfaceCode code, MessageParcel &data, MessageParcel &reply) @@ -590,23 +513,15 @@ int AppMgrProxy::UnregisterApplicationStateObserver( if (!WriteInterfaceToken(data)) { return ERR_FLATTEN_OBJECT; } - if (!data.WriteRemoteObject(observer->AsObject())) { - TAG_LOGE(AAFwkTag::APPMGR, "observer write failed."); - return ERR_FLATTEN_OBJECT; - } + PARCEL_UTIL_WRITE_RET_INT(data, RemoteObject, observer->AsObject()); - auto error = SendRequest(AppMgrInterfaceCode::UNREGISTER_APPLICATION_STATE_OBSERVER, - data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request error: %{public}d", error); - return error; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::UNREGISTER_APPLICATION_STATE_OBSERVER, data, reply, option); return reply.ReadInt32(); } int32_t AppMgrProxy::RegisterAbilityForegroundStateObserver(const sptr &observer) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (observer == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Observer is null."); @@ -617,23 +532,17 @@ int32_t AppMgrProxy::RegisterAbilityForegroundStateObserver(const sptrAsObject())) { - TAG_LOGE(AAFwkTag::APPMGR, "Observer write failed."); - return ERR_FLATTEN_OBJECT; - } + PARCEL_UTIL_WRITE_RET_INT(data, RemoteObject, observer->AsObject()); MessageParcel reply; MessageOption option; - auto error = SendRequest(AppMgrInterfaceCode::REGISTER_ABILITY_FOREGROUND_STATE_OBSERVER, data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request error: %{public}d", error); - return error; - } + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::REGISTER_ABILITY_FOREGROUND_STATE_OBSERVER, data, reply, option); return reply.ReadInt32(); } int32_t AppMgrProxy::UnregisterAbilityForegroundStateObserver(const sptr &observer) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (observer == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Observer is null."); return ERR_INVALID_VALUE; @@ -643,17 +552,10 @@ int32_t AppMgrProxy::UnregisterAbilityForegroundStateObserver(const sptrAsObject())) { - TAG_LOGE(AAFwkTag::APPMGR, "Observer write failed."); - return ERR_FLATTEN_OBJECT; - } + PARCEL_UTIL_WRITE_RET_INT(data, RemoteObject, observer->AsObject()); MessageParcel reply; MessageOption option; - auto error = SendRequest(AppMgrInterfaceCode::UNREGISTER_ABILITY_FOREGROUND_STATE_OBSERVER, data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request error: %{public}d.", error); - return error; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::UNREGISTER_ABILITY_FOREGROUND_STATE_OBSERVER, data, reply, option); return reply.ReadInt32(); } @@ -665,12 +567,7 @@ int AppMgrProxy::GetForegroundApplications(std::vector &list) if (!WriteInterfaceToken(data)) { return ERR_FLATTEN_OBJECT; } - auto error = SendRequest(AppMgrInterfaceCode::GET_FOREGROUND_APPLICATIONS, - data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "GetForegroundApplications fail, error: %{public}d", error); - return error; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::GET_FOREGROUND_APPLICATIONS, data, reply, option); int32_t infoSize = reply.ReadInt32(); if (infoSize > CYCLE_LIMIT) { TAG_LOGE(AAFwkTag::APPMGR, "infoSize is too large"); @@ -697,27 +594,12 @@ int AppMgrProxy::StartUserTestProcess( if (!WriteInterfaceToken(data)) { return ERR_FLATTEN_OBJECT; } - if (!data.WriteParcelable(&want)) { - TAG_LOGE(AAFwkTag::APPMGR, "want write failed."); - return ERR_FLATTEN_OBJECT; - } - if (!data.WriteRemoteObject(observer)) { - TAG_LOGE(AAFwkTag::APPMGR, "observer write failed."); - return ERR_FLATTEN_OBJECT; - } - if (!data.WriteParcelable(&bundleInfo)) { - TAG_LOGE(AAFwkTag::APPMGR, "bundleInfo write failed."); - return ERR_FLATTEN_OBJECT; - } - if (!data.WriteInt32(userId)) { - TAG_LOGE(AAFwkTag::APPMGR, "userId write failed."); - return ERR_FLATTEN_OBJECT; - } - int32_t ret = SendRequest(AppMgrInterfaceCode::START_USER_TEST_PROCESS, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - return ret; - } + PARCEL_UTIL_WRITE_RET_INT(data, Parcelable, &want); + PARCEL_UTIL_WRITE_RET_INT(data, RemoteObject, observer); + PARCEL_UTIL_WRITE_RET_INT(data, Parcelable, &bundleInfo); + PARCEL_UTIL_WRITE_RET_INT(data, Int32, userId); + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::START_USER_TEST_PROCESS, data, reply, option); return reply.ReadInt32(); } @@ -730,23 +612,12 @@ int AppMgrProxy::FinishUserTest(const std::string &msg, const int64_t &resultCod if (!WriteInterfaceToken(data)) { return ERR_FLATTEN_OBJECT; } - if (!data.WriteString(msg)) { - TAG_LOGE(AAFwkTag::APPMGR, "msg write failed."); - return ERR_FLATTEN_OBJECT; - } - if (!data.WriteInt64(resultCode)) { - TAG_LOGE(AAFwkTag::APPMGR, "resultCode:WriteInt32 fail."); - return ERR_FLATTEN_OBJECT; - } - if (!data.WriteString(bundleName)) { - TAG_LOGE(AAFwkTag::APPMGR, "bundleName write failed."); - return ERR_FLATTEN_OBJECT; - } - int32_t ret = SendRequest(AppMgrInterfaceCode::FINISH_USER_TEST, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - return ret; - } + + PARCEL_UTIL_WRITE_RET_INT(data, String, msg); + PARCEL_UTIL_WRITE_RET_INT(data, Int64, resultCode); + PARCEL_UTIL_WRITE_RET_INT(data, String, bundleName); + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::FINISH_USER_TEST, data, reply, option); return reply.ReadInt32(); } @@ -827,19 +698,12 @@ int AppMgrProxy::PreStartNWebSpawnProcess() return ERR_FLATTEN_OBJECT; } - int32_t ret = SendRequest(AppMgrInterfaceCode::PRE_START_NWEBSPAWN_PROCESS, - data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "PreStartNWebSpawnProcess failed, result: %{public}d", ret); - return ret; - } - + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::PRE_START_NWEBSPAWN_PROCESS, data, reply, option); auto result = reply.ReadInt32(); if (result != 0) { - TAG_LOGW(AAFwkTag::APPMGR, "PreStartNWebSpawnProcess failed, result: %{public}d", ret); - return ret; + TAG_LOGW(AAFwkTag::APPMGR, "PreStartNWebSpawnProcess failed, result: %{public}d", result); } - return 0; + return result; } int AppMgrProxy::StartRenderProcess(const std::string &renderParam, @@ -888,9 +752,8 @@ int AppMgrProxy::StartRenderProcess(const std::string &renderParam, renderPid = reply.ReadInt32(); if (result != 0) { TAG_LOGW(AAFwkTag::APPMGR, "StartRenderProcess failed, result: %{public}d", result); - return result; } - return 0; + return result; } void AppMgrProxy::AttachRenderProcess(const sptr &renderScheduler) @@ -1263,13 +1126,8 @@ int32_t AppMgrProxy::NotifyUnLoadRepairPatch(const std::string &bundleName, cons MessageParcel reply; MessageOption option; - auto ret = SendRequest(AppMgrInterfaceCode::NOTIFY_UNLOAD_REPAIR_PATCH, - data, reply, option); - if (ret != 0) { - TAG_LOGW(AAFwkTag::APPMGR, "Notify unload patch, Send request failed with error code %{public}d.", ret); - return ret; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::NOTIFY_UNLOAD_REPAIR_PATCH, data, reply, option); return reply.ReadInt32(); } @@ -1313,13 +1171,8 @@ int32_t AppMgrProxy::StartNativeProcessForDebugger(const AAFwk::Want &want) MessageParcel reply; MessageOption option; - auto ret = SendRequest(AppMgrInterfaceCode::START_NATIVE_PROCESS_FOR_DEBUGGER, - data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - return ret; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::START_NATIVE_PROCESS_FOR_DEBUGGER, data, reply, option); return reply.ReadInt32(); } @@ -1339,11 +1192,7 @@ int32_t AppMgrProxy::GetBundleNameByPid(const int pid, std::string &bundleName, return ERR_INVALID_DATA; } - auto ret = SendRequest(AppMgrInterfaceCode::GET_BUNDLE_NAME_BY_PID, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "Send request failed with error code %{public}d.", ret); - return ret; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::GET_BUNDLE_NAME_BY_PID, data, reply, option); bundleName = reply.ReadString(); uid = reply.ReadInt32(); return ERR_NONE; @@ -1364,11 +1213,7 @@ int32_t AppMgrProxy::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFw 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; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::GET_RUNNING_PROCESS_INFO_BY_PID, data, reply, option); std::unique_ptr processInfo(reply.ReadParcelable()); if (processInfo == nullptr) { @@ -1396,13 +1241,8 @@ int32_t AppMgrProxy::NotifyAppFault(const FaultData &faultData) MessageParcel reply; MessageOption option; - auto ret = SendRequest(AppMgrInterfaceCode::NOTIFY_APP_FAULT, - data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request failed with error code %{public}d.", ret); - return ret; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::NOTIFY_APP_FAULT, data, reply, option); return reply.ReadInt32(); } @@ -1423,14 +1263,32 @@ int32_t AppMgrProxy::NotifyAppFaultBySA(const AppFaultDataBySA &faultData) MessageParcel reply; MessageOption option; - auto ret = SendRequest(AppMgrInterfaceCode::NOTIFY_APP_FAULT_BY_SA, + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::NOTIFY_APP_FAULT_BY_SA, data, reply, option); + return reply.ReadInt32(); +} + +bool AppMgrProxy::SetAppFreezeFilter(int32_t pid) +{ + TAG_LOGD(AAFwkTag::APPMGR, "called."); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); + return false; + } + if (!data.WriteInt32(pid)) { + TAG_LOGE(AAFwkTag::APPMGR, "write pid failed."); + return false; + } + auto ret = SendRequest(AppMgrInterfaceCode::SET_APPFREEZE_FILTER, data, reply, option); if (ret != NO_ERROR) { TAG_LOGE(AAFwkTag::APPMGR, "Send request failed with error code %{public}d.", ret); - return ret; + return false; } - - return reply.ReadInt32(); + return reply.ReadBool(); } int32_t AppMgrProxy::GetProcessMemoryByPid(const int32_t pid, int32_t &memorySize) @@ -1449,12 +1307,7 @@ int32_t AppMgrProxy::GetProcessMemoryByPid(const int32_t pid, int32_t &memorySiz return ERR_INVALID_DATA; } - auto ret = SendRequest(AppMgrInterfaceCode::GET_PROCESS_MEMORY_BY_PID, - data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request failed with error code %{public}d.", ret); - return ret; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::GET_PROCESS_MEMORY_BY_PID, data, reply, option); memorySize = reply.ReadInt32(); auto result = reply.ReadInt32(); return result; @@ -1494,8 +1347,7 @@ int32_t AppMgrProxy::GetRunningProcessInformation( TAG_LOGE(AAFwkTag::APPMGR, "GetParcelableInfos fail, error: %{public}d", error); return error; } - int result = reply.ReadInt32(); - return result; + return reply.ReadInt32(); } int32_t AppMgrProxy::ChangeAppGcState(pid_t pid, int32_t state) @@ -1516,11 +1368,8 @@ int32_t AppMgrProxy::ChangeAppGcState(pid_t pid, int32_t state) TAG_LOGE(AAFwkTag::APPMGR, "State write failed."); return ERR_FLATTEN_OBJECT; } - int32_t ret = SendRequest(AppMgrInterfaceCode::CHANGE_APP_GC_STATE, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); - return ret; - } + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::CHANGE_APP_GC_STATE, data, reply, option); return NO_ERROR; } @@ -1544,13 +1393,7 @@ int32_t AppMgrProxy::NotifyPageShow(const sptr &token, const Page return ERR_FLATTEN_OBJECT; } - auto error = SendRequest(AppMgrInterfaceCode::NOTIFY_PAGE_SHOW, - data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request error: %{public}d", error); - return error; - } - + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::NOTIFY_PAGE_SHOW, data, reply, option); return NO_ERROR; } @@ -1574,13 +1417,7 @@ int32_t AppMgrProxy::NotifyPageHide(const sptr &token, const Page return ERR_FLATTEN_OBJECT; } - auto error = SendRequest(AppMgrInterfaceCode::NOTIFY_PAGE_HIDE, - data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request error: %{public}d", error); - return error; - } - + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::NOTIFY_PAGE_HIDE, data, reply, option); return NO_ERROR; } @@ -1610,11 +1447,8 @@ int32_t AppMgrProxy::RegisterAppRunningStatusListener(const sptr MessageParcel reply; MessageOption option; - auto error = SendRequest(AppMgrInterfaceCode::REGISTER_APP_RUNNING_STATUS_LISTENER, data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request error: %{public}d", error); - return error; - } + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::REGISTER_APP_RUNNING_STATUS_LISTENER, data, reply, option); return reply.ReadInt32(); } @@ -1632,11 +1466,8 @@ int32_t AppMgrProxy::UnregisterAppRunningStatusListener(const sptr remote = Remote(); - if (remote == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "Remote is nullptr."); - return ERR_NULL_OBJECT; - } - auto error = remote->SendRequest( - static_cast(AppMgrInterfaceCode::REGISTER_APP_FOREGROUND_STATE_OBSERVER), data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request error: %{public}d.", error); - return error; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::REGISTER_APP_FOREGROUND_STATE_OBSERVER, data, reply, option); return reply.ReadInt32(); } @@ -1681,44 +1502,25 @@ int32_t AppMgrProxy::UnregisterAppForegroundStateObserver(const sptr remote = Remote(); - if (remote == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "Remote is nullptr."); - return ERR_NULL_OBJECT; - } - auto error = remote->SendRequest( - static_cast(AppMgrInterfaceCode::UNREGISTER_APP_FOREGROUND_STATE_OBSERVER), data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request error: %{public}d", error); - return error; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::UNREGISTER_APP_FOREGROUND_STATE_OBSERVER, data, reply, option); return reply.ReadInt32(); } int32_t AppMgrProxy::IsApplicationRunning(const std::string &bundleName, bool &isRunning) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); isRunning = false; MessageParcel data; + MessageParcel reply; + MessageOption option; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); return ERR_INVALID_DATA; } - if (!data.WriteString(bundleName)) { - TAG_LOGE(AAFwkTag::APPMGR, "Write bundle name failed."); - return ERR_INVALID_DATA; - } - - MessageParcel reply; - MessageOption option; - auto ret = SendRequest(AppMgrInterfaceCode::IS_APPLICATION_RUNNING, - data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request is failed, error code: %{public}d", ret); - return ret; - } + PARCEL_UTIL_WRITE_RET_INT(data, String, bundleName); + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::IS_APPLICATION_RUNNING, data, reply, option); isRunning = reply.ReadBool(); return reply.ReadInt32(); } @@ -1726,67 +1528,44 @@ int32_t AppMgrProxy::IsApplicationRunning(const std::string &bundleName, bool &i int32_t AppMgrProxy::IsAppRunning(const std::string &bundleName, int32_t appCloneIndex, bool &isRunning) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); return ERR_INVALID_DATA; } - if (!data.WriteString(bundleName)) { - TAG_LOGE(AAFwkTag::APPMGR, "Write bundle name failed."); - return ERR_INVALID_DATA; - } - if (!data.WriteInt32(appCloneIndex)) { - TAG_LOGE(AAFwkTag::APPMGR, "Write appCloneIndex failed."); - return ERR_INVALID_DATA; - } + PARCEL_UTIL_WRITE_RET_INT(data, String, bundleName); + PARCEL_UTIL_WRITE_RET_INT(data, Int32, appCloneIndex); MessageParcel reply; MessageOption option; - auto ret = SendRequest(AppMgrInterfaceCode::IS_APP_RUNNING, - data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request is failed, error code: %{public}d", ret); - return ret; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::IS_APP_RUNNING, data, reply, option); isRunning = reply.ReadBool(); return reply.ReadInt32(); } -int32_t AppMgrProxy::StartChildProcess(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount, - bool isStartWithDebug) +int32_t AppMgrProxy::StartChildProcess(pid_t &childPid, const ChildProcessRequest &request) { - TAG_LOGD(AAFwkTag::APPMGR, "called"); - if (srcEntry.empty()) { - TAG_LOGE(AAFwkTag::APPMGR, "Invalid params, srcEntry:%{private}s", srcEntry.c_str()); + TAG_LOGD(AAFwkTag::APPMGR, "StartChildProcess called."); + if (request.srcEntry.empty()) { + TAG_LOGE(AAFwkTag::APPMGR, "Invalid params, srcEntry:%{private}s", request.srcEntry.c_str()); return ERR_INVALID_VALUE; } MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "WriteInterfaceToken failed"); - return ERR_FLATTEN_OBJECT; + return IPC_PROXY_ERR; } - if (!data.WriteString(srcEntry)) { - TAG_LOGE(AAFwkTag::APPMGR, "Write param srcEntry failed."); - return ERR_FLATTEN_OBJECT; - } - if (!data.WriteInt32(childProcessCount)) { - TAG_LOGE(AAFwkTag::APPMGR, "Write param childProcessCount failed."); - return ERR_FLATTEN_OBJECT; - } - if (!data.WriteBool(isStartWithDebug)) { - TAG_LOGE(AAFwkTag::APPMGR, "Write param isStartWithDebug failed."); - return ERR_FLATTEN_OBJECT; + if (!data.WriteParcelable(&request)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write param request failed."); + return IPC_PROXY_ERR; } MessageParcel reply; MessageOption option; - int32_t ret = SendRequest(AppMgrInterfaceCode::START_CHILD_PROCESS, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "StartChildProcess SendRequest is failed, error code: %{public}d", ret); - return ret; - } + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::START_CHILD_PROCESS, data, reply, option); auto result = reply.ReadInt32(); if (result == ERR_OK) { childPid = reply.ReadInt32(); @@ -1798,17 +1577,14 @@ int32_t AppMgrProxy::GetChildProcessInfoForSelf(ChildProcessInfo &info) { TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; + MessageParcel reply; + MessageOption option; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "WriteInterfaceToken failed"); return ERR_FLATTEN_OBJECT; } - MessageParcel reply; - MessageOption option; - int32_t ret = SendRequest(AppMgrInterfaceCode::GET_CHILD_PROCCESS_INFO_FOR_SELF, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "GetChildProcessInfoForSelf SendRequest is failed, error code: %{public}d", ret); - return ret; - } + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::GET_CHILD_PROCCESS_INFO_FOR_SELF, data, reply, option); auto result = reply.ReadInt32(); if (result == ERR_OK) { std::unique_ptr infoReply(reply.ReadParcelable()); @@ -1825,41 +1601,34 @@ void AppMgrProxy::AttachChildProcess(const sptr &childScheduler) return; } MessageParcel data; + MessageParcel reply; + MessageOption option; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "WriteInterfaceToken failed"); return; } - if (!data.WriteRemoteObject(childScheduler.GetRefPtr())) { - TAG_LOGE(AAFwkTag::APPMGR, "Failed to write remote object"); - return; - } - MessageParcel reply; - MessageOption option; - int32_t ret = SendRequest(AppMgrInterfaceCode::ATTACH_CHILD_PROCESS, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "AttachChildProcess SendRequest is failed, error code: %{public}d", ret); - } + PARCEL_UTIL_WRITE_NORET(data, RemoteObject, childScheduler.GetRefPtr()); + + PARCEL_UTIL_SENDREQ_NORET(AppMgrInterfaceCode::ATTACH_CHILD_PROCESS, data, reply, option); } void AppMgrProxy::ExitChildProcessSafely() { TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; + MessageParcel reply; + MessageOption option; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "WriteInterfaceToken failed"); return; } - MessageParcel reply; - MessageOption option; - int32_t ret = SendRequest(AppMgrInterfaceCode::EXIT_CHILD_PROCESS_SAFELY, data, reply, option); - if (ret != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "ExitChildProcessSafely SendRequest is failed, error code: %{public}d", ret); - } + + PARCEL_UTIL_SENDREQ_NORET(AppMgrInterfaceCode::EXIT_CHILD_PROCESS_SAFELY, data, reply, option); } bool AppMgrProxy::IsFinalAppProcess() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -1880,7 +1649,7 @@ bool AppMgrProxy::IsFinalAppProcess() int32_t AppMgrProxy::RegisterRenderStateObserver(const sptr &observer) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -1894,17 +1663,13 @@ int32_t AppMgrProxy::RegisterRenderStateObserver(const sptr &observer) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -1918,45 +1683,31 @@ int32_t AppMgrProxy::UnregisterRenderStateObserver(const sptr return ERR_INVALID_DATA; } - if (!data.WriteInt32(pid)) { - TAG_LOGE(AAFwkTag::APPMGR, "Write pid failed."); - return ERR_FLATTEN_OBJECT; - } + PARCEL_UTIL_WRITE_RET_INT(data, Int32, pid); MessageParcel reply; MessageOption option; - auto error = SendRequest(AppMgrInterfaceCode::GET_ALL_UI_EXTENSION_ROOT_HOST_PID, data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request error: %{public}d.", error); - return error; - } + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::GET_ALL_UI_EXTENSION_ROOT_HOST_PID, data, reply, option); int32_t size = reply.ReadInt32(); if (size > CYCLE_LIMIT) { @@ -2045,19 +1778,12 @@ int32_t AppMgrProxy::GetAllUIExtensionProviderPid(pid_t hostPid, std::vector CYCLE_LIMIT) { @@ -2079,103 +1805,68 @@ int32_t AppMgrProxy::NotifyMemorySizeStateChanged(bool isMemorySizeSufficent) if (!WriteInterfaceToken(data)) { return ERR_INVALID_DATA; } - if (!data.WriteBool(isMemorySizeSufficent)) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "write isMemorySizeSufficent fail."); - return ERR_INVALID_DATA; - } + PARCEL_UTIL_WRITE_RET_INT(data, Bool, isMemorySizeSufficent); MessageParcel reply; MessageOption option; - auto error = SendRequest(AppMgrInterfaceCode::NOTIFY_MEMORY_SIZE_STATE_CHANGED, data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Send request error: %{public}d", error); - return error; - } + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::NOTIFY_MEMORY_SIZE_STATE_CHANGED, data, reply, option); return reply.ReadInt32(); } int32_t AppMgrProxy::SetSupportedProcessCacheSelf(bool isSupport) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); return ERR_INVALID_DATA; } - if (!data.WriteBool(isSupport)) { - TAG_LOGE(AAFwkTag::APPMGR, "isSupport write failed."); - return ERR_FLATTEN_OBJECT; - } + PARCEL_UTIL_WRITE_RET_INT(data, Bool, isSupport); MessageParcel reply; MessageOption option; - auto error = SendRequest(AppMgrInterfaceCode::SET_SUPPORTED_PROCESS_CACHE_SELF, data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::APPMGR, "Send request error: %{public}d", error); - return error; - } + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::SET_SUPPORTED_PROCESS_CACHE_SELF, data, reply, option); return reply.ReadInt32(); } void AppMgrProxy::SetAppAssertionPauseState(bool flag) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; + MessageParcel reply; + MessageOption option; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); return; } - if (!data.WriteBool(flag)) { - TAG_LOGE(AAFwkTag::APPMGR, "flag write failed."); - return; - } + PARCEL_UTIL_WRITE_NORET(data, Bool, flag); - 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; - } + PARCEL_UTIL_SENDREQ_NORET(AppMgrInterfaceCode::SET_APP_ASSERT_PAUSE_STATE_SELF, data, reply, option); } int32_t AppMgrProxy::StartNativeChildProcess(const std::string &libName, int32_t childProcessCount, const sptr &callback) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + 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; + MessageParcel reply; + MessageOption option; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); return IPC_PROXY_ERR; } + PARCEL_UTIL_WRITE_RET_INT(data, String, libName); + PARCEL_UTIL_WRITE_RET_INT(data, Int32, childProcessCount); + PARCEL_UTIL_WRITE_RET_INT(data, RemoteObject, callback); - 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; - } + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::START_NATIVE_CHILD_PROCESS, data, reply, option); return reply.ReadInt32(); } @@ -2187,10 +1878,7 @@ int32_t AppMgrProxy::CheckCallingIsUserTestMode(const pid_t pid, bool &isUserTes if (!WriteInterfaceToken(data)) { return ERR_FLATTEN_OBJECT; } - if (!data.WriteInt32(pid)) { - TAG_LOGE(AAFwkTag::APPMGR, "pid write failed."); - return ERR_INVALID_VALUE; - } + PARCEL_UTIL_WRITE_RET_INT(data, Int32, pid); int32_t ret = SendRequest(AppMgrInterfaceCode::CHECK_CALLING_IS_USER_TEST_MODE, data, reply, option); if (ret != NO_ERROR) { TAG_LOGW(AAFwkTag::APPMGR, "SendRequest is failed, error code: %{public}d", ret); @@ -2200,5 +1888,45 @@ int32_t AppMgrProxy::CheckCallingIsUserTestMode(const pid_t pid, bool &isUserTes isUserTest = reply.ReadBool(); return reply.ReadInt32(); } + +int32_t AppMgrProxy::NotifyProcessDependedOnWeb() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); + return IPC_PROXY_ERR; + } + + PARCEL_UTIL_SENDREQ_RET_INT(AppMgrInterfaceCode::NOTIFY_PROCESS_DEPENDED_ON_WEB, data, reply, option); + return reply.ReadInt32(); +} + +void AppMgrProxy::KillProcessDependedOnWeb() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); + return; + } + + PARCEL_UTIL_SENDREQ_NORET(AppMgrInterfaceCode::KILL_PROCESS_DEPENDED_ON_WEB, data, reply, option); +} + +void AppMgrProxy::RestartResidentProcessDependedOnWeb() +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); + return; + } + + PARCEL_UTIL_SENDREQ_NORET(AppMgrInterfaceCode::RESTART_RESIDENT_PROCESS_DEPENDED_ON_WEB, data, reply, option); +} } // 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 b6dedf7e42..e3d52ffcf6 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,14 +16,15 @@ #include "app_mgr_stub.h" #include "ability_info.h" +#include "ability_manager_errors.h" #include "app_jsheap_mem_info.h" #include "app_malloc_info.h" #include "app_mgr_proxy.h" #include "app_scheduler_interface.h" #include "appexecfwk_errors.h" #include "bundle_info.h" +#include "child_process_request.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "iapp_state_callback.h" #include "ipc_skeleton.h" @@ -36,181 +37,10 @@ namespace OHOS { namespace AppExecFwk { constexpr int32_t CYCLE_LIMIT = 1000; -AppMgrStub::AppMgrStub() -{ - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_ATTACH_APPLICATION)] = - &AppMgrStub::HandleAttachApplication; - memberFuncMap_[static_cast(AppMgrInterfaceCode::PRELOAD_APPLICATION)] = - &AppMgrStub::HandlePreloadApplication; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_APPLICATION_FOREGROUNDED)] = - &AppMgrStub::HandleApplicationForegrounded; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_APPLICATION_BACKGROUNDED)] = - &AppMgrStub::HandleApplicationBackgrounded; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_APPLICATION_TERMINATED)] = - &AppMgrStub::HandleApplicationTerminated; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_ABILITY_CLEANED)] = - &AppMgrStub::HandleAbilityCleaned; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_GET_MGR_INSTANCE)] = &AppMgrStub::HandleGetAmsMgr; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_CLEAR_UP_APPLICATION_DATA)] = - &AppMgrStub::HandleClearUpApplicationData; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_GET_ALL_RUNNING_PROCESSES)] = - &AppMgrStub::HandleGetAllRunningProcesses; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_NOTIFY_MEMORY_LEVEL)] = - &AppMgrStub::HandleNotifyMemoryLevel; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_NOTIFY_PROC_MEMORY_LEVEL)] = - &AppMgrStub::HandleNotifyProcMemoryLevel; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_GET_RUNNING_PROCESSES_BY_USER_ID)] = - &AppMgrStub::HandleGetProcessRunningInfosByUserId; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_ADD_ABILITY_STAGE_INFO_DONE)] = - &AppMgrStub::HandleAddAbilityStageDone; - memberFuncMap_[static_cast(AppMgrInterfaceCode::STARTUP_RESIDENT_PROCESS)] = - &AppMgrStub::HandleStartupResidentProcess; - memberFuncMap_[static_cast(AppMgrInterfaceCode::REGISTER_APPLICATION_STATE_OBSERVER)] = - &AppMgrStub::HandleRegisterApplicationStateObserver; - memberFuncMap_[static_cast(AppMgrInterfaceCode::UNREGISTER_APPLICATION_STATE_OBSERVER)] = - &AppMgrStub::HandleUnregisterApplicationStateObserver; - memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_FOREGROUND_APPLICATIONS)] = - &AppMgrStub::HandleGetForegroundApplications; - memberFuncMap_[static_cast(AppMgrInterfaceCode::START_USER_TEST_PROCESS)] = - &AppMgrStub::HandleStartUserTestProcess; - memberFuncMap_[static_cast(AppMgrInterfaceCode::FINISH_USER_TEST)] = - &AppMgrStub::HandleFinishUserTest; - memberFuncMap_[static_cast(AppMgrInterfaceCode::SCHEDULE_ACCEPT_WANT_DONE)] = - &AppMgrStub::HandleScheduleAcceptWantDone; - memberFuncMap_[static_cast(AppMgrInterfaceCode::SCHEDULE_NEW_PROCESS_REQUEST_DONE)] = - &AppMgrStub::HandleScheduleNewProcessRequestDone; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_GET_ABILITY_RECORDS_BY_PROCESS_ID)] = - &AppMgrStub::HandleGetAbilityRecordsByProcessID; - memberFuncMap_[static_cast(AppMgrInterfaceCode::PRE_START_NWEBSPAWN_PROCESS)] = - &AppMgrStub::HandlePreStartNWebSpawnProcess; - memberFuncMap_[static_cast(AppMgrInterfaceCode::START_RENDER_PROCESS)] = - &AppMgrStub::HandleStartRenderProcess; - memberFuncMap_[static_cast(AppMgrInterfaceCode::ATTACH_RENDER_PROCESS)] = - &AppMgrStub::HandleAttachRenderProcess; - memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_RENDER_PROCESS_TERMINATION_STATUS)] = - &AppMgrStub::HandleGetRenderProcessTerminationStatus; - memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_CONFIGURATION)] = - &AppMgrStub::HandleGetConfiguration; - memberFuncMap_[static_cast(AppMgrInterfaceCode::UPDATE_CONFIGURATION)] = - &AppMgrStub::HandleUpdateConfiguration; - memberFuncMap_[static_cast(AppMgrInterfaceCode::REGISTER_CONFIGURATION_OBSERVER)] = - &AppMgrStub::HandleRegisterConfigurationObserver; - memberFuncMap_[static_cast(AppMgrInterfaceCode::UNREGISTER_CONFIGURATION_OBSERVER)] = - &AppMgrStub::HandleUnregisterConfigurationObserver; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_GET_PROCESS_RUNNING_INFORMATION)] = - &AppMgrStub::HandleGetProcessRunningInformation; - memberFuncMap_[static_cast(AppMgrInterfaceCode::DUMP_HEAP_MEMORY_PROCESS)] = - &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; -#endif - memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_APP_RUNNING_STATE)] = - &AppMgrStub::HandleGetAppRunningStateByBundleName; - memberFuncMap_[static_cast(AppMgrInterfaceCode::NOTIFY_LOAD_REPAIR_PATCH)] = - &AppMgrStub::HandleNotifyLoadRepairPatch; - memberFuncMap_[static_cast(AppMgrInterfaceCode::NOTIFY_HOT_RELOAD_PAGE)] = - &AppMgrStub::HandleNotifyHotReloadPage; -#ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE - memberFuncMap_[static_cast(AppMgrInterfaceCode::SET_CONTINUOUSTASK_PROCESS)] = - &AppMgrStub::HandleSetContinuousTaskProcess; -#endif - memberFuncMap_[static_cast(AppMgrInterfaceCode::NOTIFY_UNLOAD_REPAIR_PATCH)] = - &AppMgrStub::HandleNotifyUnLoadRepairPatch; - memberFuncMap_[static_cast(AppMgrInterfaceCode::IS_SHARED_BUNDLE_RUNNING)] = - &AppMgrStub::HandleIsSharedBundleRunning; - memberFuncMap_[static_cast(AppMgrInterfaceCode::START_NATIVE_PROCESS_FOR_DEBUGGER)] = - &AppMgrStub::HandleStartNativeProcessForDebugger; - memberFuncMap_[static_cast(AppMgrInterfaceCode::NOTIFY_APP_FAULT)] = - &AppMgrStub::HandleNotifyFault; - memberFuncMap_[static_cast(AppMgrInterfaceCode::NOTIFY_APP_FAULT_BY_SA)] = - &AppMgrStub::HandleNotifyFaultBySA; - memberFuncMap_[static_cast(AppMgrInterfaceCode::JUDGE_SANDBOX_BY_PID)] = - &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)] = - &AppMgrStub::HandleGetProcessMemoryByPid; - memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_PIDS_BY_BUNDLENAME)] = - &AppMgrStub::HandleGetRunningProcessInformation; - memberFuncMap_[static_cast(AppMgrInterfaceCode::CHANGE_APP_GC_STATE)] = - &AppMgrStub::HandleChangeAppGcState; - memberFuncMap_[static_cast(AppMgrInterfaceCode::NOTIFY_PAGE_SHOW)] = - &AppMgrStub::HandleNotifyPageShow; - memberFuncMap_[static_cast(AppMgrInterfaceCode::NOTIFY_PAGE_HIDE)] = - &AppMgrStub::HandleNotifyPageHide; - memberFuncMap_[static_cast(AppMgrInterfaceCode::REGISTER_APP_RUNNING_STATUS_LISTENER)] = - &AppMgrStub::HandleRegisterAppRunningStatusListener; - memberFuncMap_[static_cast(AppMgrInterfaceCode::UNREGISTER_APP_RUNNING_STATUS_LISTENER)] = - &AppMgrStub::HandleUnregisterAppRunningStatusListener; - memberFuncMap_[static_cast(AppMgrInterfaceCode::REGISTER_APP_FOREGROUND_STATE_OBSERVER)] = - &AppMgrStub::HandleRegisterAppForegroundStateObserver; - memberFuncMap_[static_cast(AppMgrInterfaceCode::UNREGISTER_APP_FOREGROUND_STATE_OBSERVER)] = - &AppMgrStub::HandleUnregisterAppForegroundStateObserver; - memberFuncMap_[static_cast(AppMgrInterfaceCode::REGISTER_ABILITY_FOREGROUND_STATE_OBSERVER)] = - &AppMgrStub::HandleRegisterAbilityForegroundStateObserver; - memberFuncMap_[static_cast(AppMgrInterfaceCode::UNREGISTER_ABILITY_FOREGROUND_STATE_OBSERVER)] = - &AppMgrStub::HandleUnregisterAbilityForegroundStateObserver; - memberFuncMap_[static_cast(AppMgrInterfaceCode::IS_APPLICATION_RUNNING)] = - &AppMgrStub::HandleIsApplicationRunning; - memberFuncMap_[static_cast(AppMgrInterfaceCode::START_CHILD_PROCESS)] = - &AppMgrStub::HandleStartChildProcess; - memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_CHILD_PROCCESS_INFO_FOR_SELF)] = - &AppMgrStub::HandleGetChildProcessInfoForSelf; - memberFuncMap_[static_cast(AppMgrInterfaceCode::ATTACH_CHILD_PROCESS)] = - &AppMgrStub::HandleAttachChildProcess; - memberFuncMap_[static_cast(AppMgrInterfaceCode::EXIT_CHILD_PROCESS_SAFELY)] = - &AppMgrStub::HandleExitChildProcessSafely; - memberFuncMap_[static_cast(AppMgrInterfaceCode::IS_FINAL_APP_PROCESS)] = - &AppMgrStub::HandleIsFinalAppProcess; - memberFuncMap_[static_cast(AppMgrInterfaceCode::APP_CLEAR_UP_APPLICATION_DATA_BY_SELF)] = - &AppMgrStub::HandleClearUpApplicationDataBySelf; - memberFuncMap_[static_cast(AppMgrInterfaceCode::REGISTER_RENDER_STATUS_OBSERVER)] = - &AppMgrStub::HandleRegisterRenderStateObserver; - memberFuncMap_[static_cast(AppMgrInterfaceCode::UNREGISTER_RENDER_STATUS_OBSERVER)] = - &AppMgrStub::HandleUnregisterRenderStateObserver; - memberFuncMap_[static_cast(AppMgrInterfaceCode::UPDATE_RENDER_STATUS)] = - &AppMgrStub::HandleUpdateRenderState; - memberFuncMap_[static_cast(AppMgrInterfaceCode::SIGN_RESTART_APP_FLAG)] = - &AppMgrStub::HandleSignRestartAppFlag; - memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_APP_RUNNING_UNIQUE_ID_BY_PID)] = - &AppMgrStub::HandleGetAppRunningUniqueIdByPid; - memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_ALL_UI_EXTENSION_ROOT_HOST_PID)] = - &AppMgrStub::HandleGetAllUIExtensionRootHostPid; - memberFuncMap_[static_cast(AppMgrInterfaceCode::GET_ALL_UI_EXTENSION_PROVIDER_PID)] = - &AppMgrStub::HandleGetAllUIExtensionProviderPid; - memberFuncMap_[static_cast(AppMgrInterfaceCode::UPDATE_CONFIGURATION_BY_BUNDLE_NAME)] = - &AppMgrStub::HandleUpdateConfigurationByBundleName; - memberFuncMap_[static_cast(AppMgrInterfaceCode::NOTIFY_MEMORY_SIZE_STATE_CHANGED)] = - &AppMgrStub::HandleNotifyMemorySizeStateChanged; - memberFuncMap_[static_cast(AppMgrInterfaceCode::SET_SUPPORTED_PROCESS_CACHE_SELF)] = - &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; - memberFuncMap_[static_cast(AppMgrInterfaceCode::IS_APP_RUNNING)] = - &AppMgrStub::HandleIsAppRunning; - memberFuncMap_[static_cast(AppMgrInterfaceCode::CHECK_CALLING_IS_USER_TEST_MODE)] = - &AppMgrStub::HandleCheckCallingIsUserTestMode; -} -AppMgrStub::~AppMgrStub() -{ - memberFuncMap_.clear(); -} +AppMgrStub::AppMgrStub() {} + +AppMgrStub::~AppMgrStub() {} int AppMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -222,18 +52,293 @@ int AppMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParce TAG_LOGE(AAFwkTag::APPMGR, "local descriptor is not equal to remote"); return ERR_INVALID_STATE; } + return OnRemoteRequestInner(code, data, reply, option); +} - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } +int32_t AppMgrStub::OnRemoteRequestInner(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + int retCode = ERR_OK; + retCode = OnRemoteRequestInnerFirst(code, data, reply, option); + if (retCode != INVALID_FD) { + return retCode; + } + retCode = OnRemoteRequestInnerSecond(code, data, reply, option); + if (retCode != INVALID_FD) { + return retCode; + } + retCode = OnRemoteRequestInnerThird(code, data, reply, option); + if (retCode != INVALID_FD) { + return retCode; + } + retCode = OnRemoteRequestInnerFourth(code, data, reply, option); + if (retCode != INVALID_FD) { + return retCode; + } + retCode = OnRemoteRequestInnerFifth(code, data, reply, option); + if (retCode != INVALID_FD) { + return retCode; + } + retCode = OnRemoteRequestInnerSixth(code, data, reply, option); + if (retCode != INVALID_FD) { + return retCode; + } + retCode = OnRemoteRequestInnerSeventh(code, data, reply, option); + if (retCode != INVALID_FD) { + return retCode; } TAG_LOGD(AAFwkTag::APPMGR, "AppMgrStub::OnRemoteRequest end"); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } +int32_t AppMgrStub::OnRemoteRequestInnerFirst(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + case static_cast(AppMgrInterfaceCode::APP_ATTACH_APPLICATION): + return HandleAttachApplication(data, reply); + case static_cast(AppMgrInterfaceCode::PRELOAD_APPLICATION): + return HandlePreloadApplication(data, reply); + case static_cast(AppMgrInterfaceCode::APP_APPLICATION_FOREGROUNDED): + return HandleApplicationForegrounded(data, reply); + case static_cast(AppMgrInterfaceCode::APP_APPLICATION_BACKGROUNDED): + return HandleApplicationBackgrounded(data, reply); + case static_cast(AppMgrInterfaceCode::APP_APPLICATION_TERMINATED): + return HandleApplicationTerminated(data, reply); + case static_cast(AppMgrInterfaceCode::APP_ABILITY_CLEANED): + return HandleAbilityCleaned(data, reply); + case static_cast(AppMgrInterfaceCode::APP_GET_MGR_INSTANCE): + return HandleGetAmsMgr(data, reply); + case static_cast(AppMgrInterfaceCode::APP_CLEAR_UP_APPLICATION_DATA): + return HandleClearUpApplicationData(data, reply); + case static_cast(AppMgrInterfaceCode::APP_GET_ALL_RUNNING_PROCESSES): + return HandleGetAllRunningProcesses(data, reply); + case static_cast(AppMgrInterfaceCode::APP_NOTIFY_MEMORY_LEVEL): + return HandleNotifyMemoryLevel(data, reply); + case static_cast(AppMgrInterfaceCode::APP_NOTIFY_PROC_MEMORY_LEVEL): + return HandleNotifyProcMemoryLevel(data, reply); + case static_cast(AppMgrInterfaceCode::APP_GET_RUNNING_PROCESSES_BY_USER_ID): + return HandleGetProcessRunningInfosByUserId(data, reply); + case static_cast(AppMgrInterfaceCode::APP_ADD_ABILITY_STAGE_INFO_DONE): + return HandleAddAbilityStageDone(data, reply); + case static_cast(AppMgrInterfaceCode::STARTUP_RESIDENT_PROCESS): + return HandleStartupResidentProcess(data, reply); + case static_cast(AppMgrInterfaceCode::REGISTER_APPLICATION_STATE_OBSERVER): + return HandleRegisterApplicationStateObserver(data, reply); + case static_cast(AppMgrInterfaceCode::UNREGISTER_APPLICATION_STATE_OBSERVER): + return HandleUnregisterApplicationStateObserver(data, reply); + } + return INVALID_FD; +} + +int32_t AppMgrStub::OnRemoteRequestInnerSecond(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + case static_cast(AppMgrInterfaceCode::GET_FOREGROUND_APPLICATIONS): + return HandleGetForegroundApplications(data, reply); + case static_cast(AppMgrInterfaceCode::START_USER_TEST_PROCESS): + return HandleStartUserTestProcess(data, reply); + case static_cast(AppMgrInterfaceCode::FINISH_USER_TEST): + return HandleFinishUserTest(data, reply); + case static_cast(AppMgrInterfaceCode::SCHEDULE_ACCEPT_WANT_DONE): + return HandleScheduleAcceptWantDone(data, reply); + case static_cast(AppMgrInterfaceCode::SCHEDULE_NEW_PROCESS_REQUEST_DONE): + return HandleScheduleNewProcessRequestDone(data, reply); + case static_cast(AppMgrInterfaceCode::APP_GET_ABILITY_RECORDS_BY_PROCESS_ID): + return HandleGetAbilityRecordsByProcessID(data, reply); + case static_cast(AppMgrInterfaceCode::PRE_START_NWEBSPAWN_PROCESS): + return HandlePreStartNWebSpawnProcess(data, reply); + case static_cast(AppMgrInterfaceCode::START_RENDER_PROCESS): + return HandleStartRenderProcess(data, reply); + case static_cast(AppMgrInterfaceCode::ATTACH_RENDER_PROCESS): + return HandleAttachRenderProcess(data, reply); + case static_cast(AppMgrInterfaceCode::GET_RENDER_PROCESS_TERMINATION_STATUS): + return HandleGetRenderProcessTerminationStatus(data, reply); + case static_cast(AppMgrInterfaceCode::GET_CONFIGURATION): + return HandleGetConfiguration(data, reply); + case static_cast(AppMgrInterfaceCode::UPDATE_CONFIGURATION): + return HandleUpdateConfiguration(data, reply); + case static_cast(AppMgrInterfaceCode::REGISTER_CONFIGURATION_OBSERVER): + return HandleRegisterConfigurationObserver(data, reply); + case static_cast(AppMgrInterfaceCode::UNREGISTER_CONFIGURATION_OBSERVER): + return HandleUnregisterConfigurationObserver(data, reply); + case static_cast(AppMgrInterfaceCode::APP_GET_PROCESS_RUNNING_INFORMATION): + return HandleGetProcessRunningInformation(data, reply); + case static_cast(AppMgrInterfaceCode::DUMP_HEAP_MEMORY_PROCESS): + return HandleDumpHeapMemory(data, reply); + case static_cast(AppMgrInterfaceCode::DUMP_JSHEAP_MEMORY_PROCESS): + return HandleDumpJsHeapMemory(data, reply); + case static_cast(AppMgrInterfaceCode::GET_RUNNING_MULTIAPP_INFO_BY_BUNDLENAME): + return HandleGetRunningMultiAppInfoByBundleName(data, reply); + } + return INVALID_FD; +} + +int32_t AppMgrStub::OnRemoteRequestInnerThird(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + #ifdef ABILITY_COMMAND_FOR_TEST + case AppMgrInterfaceCode::BLOCK_APP_SERVICE: + return HandleBlockAppServiceDone(data, reply); + #endif + case static_cast(AppMgrInterfaceCode::GET_APP_RUNNING_STATE): + return HandleGetAppRunningStateByBundleName(data, reply); + case static_cast(AppMgrInterfaceCode::NOTIFY_LOAD_REPAIR_PATCH): + return HandleNotifyLoadRepairPatch(data, reply); + case static_cast(AppMgrInterfaceCode::NOTIFY_HOT_RELOAD_PAGE): + return HandleNotifyHotReloadPage(data, reply); + #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE + case static_cast(AppMgrInterfaceCode::SET_CONTINUOUSTASK_PROCESS): + return HandleSetContinuousTaskProcess(data, reply); + #endif + case static_cast(AppMgrInterfaceCode::NOTIFY_UNLOAD_REPAIR_PATCH): + return HandleNotifyUnLoadRepairPatch(data, reply); + case static_cast(AppMgrInterfaceCode::IS_SHARED_BUNDLE_RUNNING): + return HandleIsSharedBundleRunning(data, reply); + case static_cast(AppMgrInterfaceCode::START_NATIVE_PROCESS_FOR_DEBUGGER): + return HandleStartNativeProcessForDebugger(data, reply); + case static_cast(AppMgrInterfaceCode::NOTIFY_APP_FAULT): + return HandleNotifyFault(data, reply); + } + return INVALID_FD; +} + +int32_t AppMgrStub::OnRemoteRequestInnerFourth(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE + case static_cast(AppMgrInterfaceCode::SET_CONTINUOUSTASK_PROCESS): + return HandleSetContinuousTaskProcess(data, reply); + #endif + case static_cast(AppMgrInterfaceCode::NOTIFY_APP_FAULT_BY_SA): + return HandleNotifyFaultBySA(data, reply); + case static_cast(AppMgrInterfaceCode::JUDGE_SANDBOX_BY_PID): + return HandleJudgeSandboxByPid(data, reply); + case static_cast(AppMgrInterfaceCode::SET_APPFREEZE_FILTER): + return HandleSetAppFreezeFilter(data, reply); + case static_cast(AppMgrInterfaceCode::GET_BUNDLE_NAME_BY_PID): + return HandleGetBundleNameByPid(data, reply); + case static_cast(AppMgrInterfaceCode::GET_RUNNING_PROCESS_INFO_BY_PID): + return HandleGetRunningProcessInfoByPid(data, reply); + case static_cast(AppMgrInterfaceCode::APP_GET_ALL_RENDER_PROCESSES): + return HandleGetAllRenderProcesses(data, reply); + case static_cast(AppMgrInterfaceCode::GET_PROCESS_MEMORY_BY_PID): + return HandleGetProcessMemoryByPid(data, reply); + } + return INVALID_FD; +} + +int32_t AppMgrStub::OnRemoteRequestInnerFifth(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE + case static_cast(AppMgrInterfaceCode::SET_CONTINUOUSTASK_PROCESS): + return HandleSetContinuousTaskProcess(data, reply); + #endif + case static_cast(AppMgrInterfaceCode::GET_PIDS_BY_BUNDLENAME): + return HandleGetRunningProcessInformation(data, reply); + case static_cast(AppMgrInterfaceCode::CHANGE_APP_GC_STATE): + return HandleChangeAppGcState(data, reply); + case static_cast(AppMgrInterfaceCode::NOTIFY_PAGE_SHOW): + return HandleNotifyPageShow(data, reply); + case static_cast(AppMgrInterfaceCode::NOTIFY_PAGE_HIDE): + return HandleNotifyPageHide(data, reply); + case static_cast(AppMgrInterfaceCode::REGISTER_APP_RUNNING_STATUS_LISTENER): + return HandleRegisterAppRunningStatusListener(data, reply); + case static_cast(AppMgrInterfaceCode::UNREGISTER_APP_RUNNING_STATUS_LISTENER): + return HandleUnregisterAppRunningStatusListener(data, reply); + case static_cast(AppMgrInterfaceCode::REGISTER_APP_FOREGROUND_STATE_OBSERVER): + return HandleRegisterAppForegroundStateObserver(data, reply); + case static_cast(AppMgrInterfaceCode::UNREGISTER_APP_FOREGROUND_STATE_OBSERVER): + return HandleUnregisterAppForegroundStateObserver(data, reply); + case static_cast(AppMgrInterfaceCode::REGISTER_ABILITY_FOREGROUND_STATE_OBSERVER): + return HandleRegisterAbilityForegroundStateObserver(data, reply); + case static_cast(AppMgrInterfaceCode::UNREGISTER_ABILITY_FOREGROUND_STATE_OBSERVER): + return HandleUnregisterAbilityForegroundStateObserver(data, reply); + case static_cast(AppMgrInterfaceCode::IS_APPLICATION_RUNNING): + return HandleIsApplicationRunning(data, reply); + case static_cast(AppMgrInterfaceCode::START_CHILD_PROCESS): + return HandleStartChildProcess(data, reply); + } + return INVALID_FD; +} + +int32_t AppMgrStub::OnRemoteRequestInnerSixth(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE + case static_cast(AppMgrInterfaceCode::SET_CONTINUOUSTASK_PROCESS): + return HandleSetContinuousTaskProcess(data, reply); + #endif + case static_cast(AppMgrInterfaceCode::GET_CHILD_PROCCESS_INFO_FOR_SELF): + return HandleGetChildProcessInfoForSelf(data, reply); + case static_cast(AppMgrInterfaceCode::ATTACH_CHILD_PROCESS): + return HandleAttachChildProcess(data, reply); + case static_cast(AppMgrInterfaceCode::EXIT_CHILD_PROCESS_SAFELY): + return HandleExitChildProcessSafely(data, reply); + case static_cast(AppMgrInterfaceCode::IS_FINAL_APP_PROCESS): + return HandleIsFinalAppProcess(data, reply); + case static_cast(AppMgrInterfaceCode::APP_CLEAR_UP_APPLICATION_DATA_BY_SELF): + return HandleClearUpApplicationDataBySelf(data, reply); + case static_cast(AppMgrInterfaceCode::REGISTER_RENDER_STATUS_OBSERVER): + return HandleRegisterRenderStateObserver(data, reply); + case static_cast(AppMgrInterfaceCode::UNREGISTER_RENDER_STATUS_OBSERVER): + return HandleUnregisterRenderStateObserver(data, reply); + case static_cast(AppMgrInterfaceCode::UPDATE_RENDER_STATUS): + return HandleUpdateRenderState(data, reply); + case static_cast(AppMgrInterfaceCode::SIGN_RESTART_APP_FLAG): + return HandleSignRestartAppFlag(data, reply); + case static_cast(AppMgrInterfaceCode::GET_APP_RUNNING_UNIQUE_ID_BY_PID): + return HandleGetAppRunningUniqueIdByPid(data, reply); + case static_cast(AppMgrInterfaceCode::GET_ALL_UI_EXTENSION_ROOT_HOST_PID): + return HandleGetAllUIExtensionRootHostPid(data, reply); + case static_cast(AppMgrInterfaceCode::GET_ALL_UI_EXTENSION_PROVIDER_PID): + return HandleGetAllUIExtensionProviderPid(data, reply); + } + return INVALID_FD; +} + +int32_t AppMgrStub::OnRemoteRequestInnerSeventh(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE + case static_cast(AppMgrInterfaceCode::SET_CONTINUOUSTASK_PROCESS): + return HandleSetContinuousTaskProcess(data, reply); + #endif + case static_cast(AppMgrInterfaceCode::UPDATE_CONFIGURATION_BY_BUNDLE_NAME): + return HandleUpdateConfigurationByBundleName(data, reply); + case static_cast(AppMgrInterfaceCode::NOTIFY_MEMORY_SIZE_STATE_CHANGED): + return HandleNotifyMemorySizeStateChanged(data, reply); + case static_cast(AppMgrInterfaceCode::SET_SUPPORTED_PROCESS_CACHE_SELF): + return HandleSetSupportedProcessCacheSelf(data, reply); + case static_cast(AppMgrInterfaceCode::APP_GET_RUNNING_PROCESSES_BY_BUNDLE_TYPE): + return HandleGetRunningProcessesByBundleType(data, reply); + case static_cast(AppMgrInterfaceCode::SET_APP_ASSERT_PAUSE_STATE_SELF): + return HandleSetAppAssertionPauseState(data, reply); + case static_cast(AppMgrInterfaceCode::START_NATIVE_CHILD_PROCESS): + return HandleStartNativeChildProcess(data, reply); + case static_cast(AppMgrInterfaceCode::SAVE_BROWSER_CHANNEL): + return HandleSaveBrowserChannel(data, reply); + case static_cast(AppMgrInterfaceCode::IS_APP_RUNNING): + return HandleIsAppRunning(data, reply); + case static_cast(AppMgrInterfaceCode::CHECK_CALLING_IS_USER_TEST_MODE): + return HandleCheckCallingIsUserTestMode(data, reply); + case static_cast(AppMgrInterfaceCode::NOTIFY_PROCESS_DEPENDED_ON_WEB): + return HandleNotifyProcessDependedOnWeb(data, reply); + case static_cast(AppMgrInterfaceCode::KILL_PROCESS_DEPENDED_ON_WEB): + return HandleKillProcessDependedOnWeb(data, reply); + case static_cast(AppMgrInterfaceCode::RESTART_RESIDENT_PROCESS_DEPENDED_ON_WEB): + return HandleRestartResidentProcessDependedOnWeb(data, reply); + } + return INVALID_FD; +} + int32_t AppMgrStub::HandleAttachApplication(MessageParcel &data, MessageParcel &reply) { HITRACE_METER(HITRACE_TAG_APP); @@ -1010,6 +1115,17 @@ int32_t AppMgrStub::HandleNotifyFaultBySA(MessageParcel &data, MessageParcel &re return NO_ERROR; } +int32_t AppMgrStub::HandleSetAppFreezeFilter(MessageParcel &data, MessageParcel &reply) +{ + int32_t pid = data.ReadInt32(); + bool result = SetAppFreezeFilter(pid); + if (!reply.WriteBool(result)) { + TAG_LOGE(AAFwkTag::APPMGR, "reply write failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + int32_t AppMgrStub::HandleGetProcessMemoryByPid(MessageParcel &data, MessageParcel &reply) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); @@ -1156,7 +1272,7 @@ int32_t AppMgrStub::HandleUnregisterAppForegroundStateObserver(MessageParcel &da int32_t AppMgrStub::HandleIsApplicationRunning(MessageParcel &data, MessageParcel &reply) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::string bundleName = data.ReadString(); bool isRunning = false; int32_t result = IsApplicationRunning(bundleName, isRunning); @@ -1172,7 +1288,7 @@ int32_t AppMgrStub::HandleIsApplicationRunning(MessageParcel &data, MessageParce int32_t AppMgrStub::HandleIsAppRunning(MessageParcel &data, MessageParcel &reply) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::string bundleName = data.ReadString(); bool isRunning = false; int32_t appCloneIndex = data.ReadInt32(); @@ -1189,18 +1305,19 @@ int32_t AppMgrStub::HandleIsAppRunning(MessageParcel &data, MessageParcel &reply int32_t AppMgrStub::HandleStartChildProcess(MessageParcel &data, MessageParcel &reply) { TAG_LOGD(AAFwkTag::APPMGR, "called."); - std::string srcEntry = data.ReadString(); + std::unique_ptr request(data.ReadParcelable()); + if (!request) { + return IPC_STUB_ERR; + } int32_t childPid = 0; - int32_t childProcessCount = data.ReadInt32(); - int32_t isStartWithDebug = data.ReadBool(); - int32_t result = StartChildProcess(srcEntry, childPid, childProcessCount, isStartWithDebug); + int32_t result = StartChildProcess(childPid, *request); if (!reply.WriteInt32(result)) { TAG_LOGE(AAFwkTag::APPMGR, "Write result error."); - return ERR_INVALID_VALUE; + return IPC_STUB_ERR; } if (result == ERR_OK && !reply.WriteInt32(childPid)) { TAG_LOGE(AAFwkTag::APPMGR, "Write childPid error."); - return ERR_INVALID_VALUE; + return IPC_STUB_ERR; } return NO_ERROR; } @@ -1237,7 +1354,7 @@ int32_t AppMgrStub::HandleExitChildProcessSafely(MessageParcel &data, MessagePar int32_t AppMgrStub::HandleIsFinalAppProcess(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!reply.WriteBool(IsFinalAppProcess())) { TAG_LOGE(AAFwkTag::APPMGR, "Fail to write bool result."); return ERR_INVALID_VALUE; @@ -1247,7 +1364,7 @@ int32_t AppMgrStub::HandleIsFinalAppProcess(MessageParcel &data, MessageParcel & int32_t AppMgrStub::HandleRegisterRenderStateObserver(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto callback = iface_cast(data.ReadRemoteObject()); if (callback == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Callback is null."); @@ -1263,7 +1380,7 @@ int32_t AppMgrStub::HandleRegisterRenderStateObserver(MessageParcel &data, Messa int32_t AppMgrStub::HandleUnregisterRenderStateObserver(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto callback = iface_cast(data.ReadRemoteObject()); if (callback == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Callback is null."); @@ -1279,7 +1396,7 @@ int32_t AppMgrStub::HandleUnregisterRenderStateObserver(MessageParcel &data, Mes int32_t AppMgrStub::HandleUpdateRenderState(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); int32_t pid = data.ReadInt32(); int32_t state = data.ReadInt32(); int32_t result = UpdateRenderState(pid, state); @@ -1292,7 +1409,7 @@ int32_t AppMgrStub::HandleUpdateRenderState(MessageParcel &data, MessageParcel & int32_t AppMgrStub::HandleSignRestartAppFlag(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::string bundleName = data.ReadString(); auto ret = SignRestartAppFlag(bundleName); if (!reply.WriteInt32(ret)) { @@ -1304,7 +1421,7 @@ int32_t AppMgrStub::HandleSignRestartAppFlag(MessageParcel &data, MessageParcel int32_t AppMgrStub::HandleGetAppRunningUniqueIdByPid(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); int32_t pid = data.ReadInt32(); std::string appRunningUniqueId; int32_t result = GetAppRunningUniqueIdByPid(pid, appRunningUniqueId); @@ -1375,7 +1492,7 @@ int32_t AppMgrStub::HandleNotifyMemorySizeStateChanged(MessageParcel &data, Mess int32_t AppMgrStub::HandleSetSupportedProcessCacheSelf(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); bool isSupport = data.ReadBool(); auto ret = SetSupportedProcessCacheSelf(isSupport); if (!reply.WriteInt32(ret)) { @@ -1387,7 +1504,7 @@ int32_t AppMgrStub::HandleSetSupportedProcessCacheSelf(MessageParcel &data, Mess int32_t AppMgrStub::HandleSetAppAssertionPauseState(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); bool flag = data.ReadBool(); SetAppAssertionPauseState(flag); return NO_ERROR; @@ -1395,7 +1512,7 @@ int32_t AppMgrStub::HandleSetAppAssertionPauseState(MessageParcel &data, Message int32_t AppMgrStub::HandleStartNativeChildProcess(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::string libName = data.ReadString(); int32_t childCount = data.ReadInt32(); sptr callback = data.ReadRemoteObject(); @@ -1410,7 +1527,7 @@ int32_t AppMgrStub::HandleStartNativeChildProcess(MessageParcel &data, MessagePa int32_t AppMgrStub::HandleCheckCallingIsUserTestMode(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); pid_t pid = data.ReadInt32(); bool isUserTest = false; int32_t ret = CheckCallingIsUserTestMode(pid, isUserTest); @@ -1425,5 +1542,30 @@ int32_t AppMgrStub::HandleCheckCallingIsUserTestMode(MessageParcel &data, Messag return NO_ERROR; } +int32_t AppMgrStub::HandleNotifyProcessDependedOnWeb(MessageParcel &data, MessageParcel &reply) +{ + TAG_LOGD(AAFwkTag::APPMGR, "call"); + int32_t ret = NotifyProcessDependedOnWeb(); + if (!reply.WriteInt32(ret)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write ret error."); + return IPC_STUB_ERR; + } + + return NO_ERROR; +} + +int32_t AppMgrStub::HandleKillProcessDependedOnWeb(MessageParcel &data, MessageParcel &reply) +{ + TAG_LOGD(AAFwkTag::APPMGR, "call"); + KillProcessDependedOnWeb(); + return NO_ERROR; +} + +int32_t AppMgrStub::HandleRestartResidentProcessDependedOnWeb(MessageParcel &data, MessageParcel &reply) +{ + TAG_LOGD(AAFwkTag::APPMGR, "call"); + RestartResidentProcessDependedOnWeb(); + return NO_ERROR; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_process_data.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_process_data.cpp index b79c6e37de..0be519a67c 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_process_data.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_process_data.cpp @@ -16,7 +16,6 @@ #include "app_process_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "nlohmann/json.hpp" #include "string_ex.h" diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_resident_process_info.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_resident_process_info.cpp index 8dec8f5db7..38fbd8837f 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_resident_process_info.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_resident_process_info.cpp @@ -15,7 +15,6 @@ #include "app_resident_process_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_running_status_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_running_status_proxy.cpp index 296e4f763e..125e2cd854 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_running_status_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_running_status_proxy.cpp @@ -16,7 +16,6 @@ #include "app_running_status_listener_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_proxy.h" diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_running_status_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_running_status_stub.cpp index 348a2e61ba..c511b43183 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_running_status_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_running_status_stub.cpp @@ -16,22 +16,14 @@ #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" namespace OHOS { namespace AbilityRuntime { -AppRunningStatusStub::AppRunningStatusStub() -{ - requestFuncMap_[static_cast(AppRunningStatusListenerInterface::MessageCode::APP_RUNNING_STATUS)] = - &AppRunningStatusStub::HandleAppRunningStatus; -} +AppRunningStatusStub::AppRunningStatusStub() {} -AppRunningStatusStub::~AppRunningStatusStub() -{ - requestFuncMap_.clear(); -} +AppRunningStatusStub::~AppRunningStatusStub() {} int AppRunningStatusStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -44,13 +36,10 @@ int AppRunningStatusStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = requestFuncMap_.find(code); - if (itFunc != requestFuncMap_.end()) { - auto requestFunc = itFunc->second; - if (requestFunc != nullptr) { - return (this->*requestFunc)(data, reply); - } + if (code == static_cast(AppRunningStatusListenerInterface::MessageCode::APP_RUNNING_STATUS)) { + return HandleAppRunningStatus(data, reply); } + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } 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 a7919fd2c6..e1c3de701d 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 @@ -15,89 +15,25 @@ #include "app_scheduler_host.h" #include "ability_info.h" +#include "ability_manager_errors.h" #include "appexecfwk_errors.h" #include "hitrace_meter.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { namespace AppExecFwk { AppSchedulerHost::AppSchedulerHost() { - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_FOREGROUND_APPLICATION_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleForegroundApplication; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_BACKGROUND_APPLICATION_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleBackgroundApplication; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_TERMINATE_APPLICATION_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleTerminateApplication; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_LOWMEMORY_APPLICATION_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleLowMemory; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_SHRINK_MEMORY_APPLICATION_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleShrinkMemory; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_MEMORYLEVEL_APPLICATION_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleMemoryLevel; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_LAUNCH_ABILITY_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleLaunchAbility; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_CLEAN_ABILITY_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleCleanAbility; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_LAUNCH_APPLICATION_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleLaunchApplication; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_PROFILE_CHANGED_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleProfileChanged; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_CONFIGURATION_UPDATED)] = - &AppSchedulerHost::HandleScheduleConfigurationUpdated; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_PROCESS_SECURITY_EXIT_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleProcessSecurityExit; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_CLEAR_PAGE_STACK)] = - &AppSchedulerHost::HandleScheduleClearPageStack; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_ABILITY_STAGE_INFO)] = - &AppSchedulerHost::HandleScheduleAbilityStage; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_ACCEPT_WANT)] = - &AppSchedulerHost::HandleScheduleAcceptWant; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_NEW_PROCESS_REQUEST)] = - &AppSchedulerHost::HandleScheduleNewProcessRequest; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_NOTIFY_LOAD_REPAIR_PATCH)] = - &AppSchedulerHost::HandleNotifyLoadRepairPatch; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_NOTIFY_HOT_RELOAD_PAGE)] = - &AppSchedulerHost::HandleNotifyHotReloadPage; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_NOTIFY_UNLOAD_REPAIR_PATCH)] = - &AppSchedulerHost::HandleNotifyUnLoadRepairPatch; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_UPDATE_APPLICATION_INFO_INSTALLED)] = - &AppSchedulerHost::HandleScheduleUpdateApplicationInfoInstalled; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_HEAPMEMORY_APPLICATION_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleHeapMemory; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_NOTIFY_FAULT)] = - &AppSchedulerHost::HandleNotifyAppFault; InitMemberFuncMap(); } -void AppSchedulerHost::InitMemberFuncMap() -{ - memberFuncMap_[static_cast(IAppScheduler::Message::APP_GC_STATE_CHANGE)] = - &AppSchedulerHost::HandleScheduleChangeAppGcState; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_ATTACH_APP_DEBUG)] = - &AppSchedulerHost::HandleAttachAppDebug; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_DETACH_APP_DEBUG)] = - &AppSchedulerHost::HandleDetachAppDebug; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_JSHEAP_MEMORY_APPLICATION_TRANSACTION)] = - &AppSchedulerHost::HandleScheduleJsHeapMemory; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_DUMP_IPC_START)] = - &AppSchedulerHost::HandleScheduleDumpIpcStart; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_DUMP_IPC_STOP)] = - &AppSchedulerHost::HandleScheduleDumpIpcStop; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_DUMP_IPC_STAT)] = - &AppSchedulerHost::HandleScheduleDumpIpcStat; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_DUMP_FFRT)] = - &AppSchedulerHost::HandleScheduleDumpFfrt; - memberFuncMap_[static_cast(IAppScheduler::Message::SCHEDULE_CACHE_PROCESS)] = - &AppSchedulerHost::HandleScheduleCacheProcess; -} + +void AppSchedulerHost::InitMemberFuncMap() {} AppSchedulerHost::~AppSchedulerHost() { TAG_LOGI(AAFwkTag::APPMGR, "AppSchedulerHost destruction"); - memberFuncMap_.clear(); } int AppSchedulerHost::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -110,18 +46,115 @@ int AppSchedulerHost::OnRemoteRequest(uint32_t code, MessageParcel &data, Messag TAG_LOGE(AAFwkTag::APPMGR, "local descriptor is not equal to remote"); return ERR_INVALID_STATE; } + return OnRemoteRequestInner(code, data, reply, option); +} - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } +int32_t AppSchedulerHost::OnRemoteRequestInner(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + int retCode = ERR_OK; + retCode = OnRemoteRequestInnerFirst(code, data, reply, option); + if (retCode != INVALID_FD) { + return retCode; + } + retCode = OnRemoteRequestInnerSecond(code, data, reply, option); + if (retCode != INVALID_FD) { + return retCode; + } + retCode = OnRemoteRequestInnerThird(code, data, reply, option); + if (retCode != INVALID_FD) { + return retCode; } TAG_LOGD(AAFwkTag::APPMGR, "AppSchedulerHost::OnRemoteRequest end"); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } +int32_t AppSchedulerHost::OnRemoteRequestInnerFirst(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + case static_cast(IAppScheduler::Message::SCHEDULE_FOREGROUND_APPLICATION_TRANSACTION): + return HandleScheduleForegroundApplication(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_BACKGROUND_APPLICATION_TRANSACTION): + return HandleScheduleBackgroundApplication(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_TERMINATE_APPLICATION_TRANSACTION): + return HandleScheduleTerminateApplication(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_LOWMEMORY_APPLICATION_TRANSACTION): + return HandleScheduleLowMemory(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_SHRINK_MEMORY_APPLICATION_TRANSACTION): + return HandleScheduleShrinkMemory(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_MEMORYLEVEL_APPLICATION_TRANSACTION): + return HandleScheduleMemoryLevel(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_LAUNCH_ABILITY_TRANSACTION): + return HandleScheduleLaunchAbility(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_CLEAN_ABILITY_TRANSACTION): + return HandleScheduleCleanAbility(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_LAUNCH_APPLICATION_TRANSACTION): + return HandleScheduleLaunchApplication(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_PROFILE_CHANGED_TRANSACTION): + return HandleScheduleProfileChanged(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_CONFIGURATION_UPDATED): + return HandleScheduleConfigurationUpdated(data, reply); + } + return INVALID_FD; +} + +int32_t AppSchedulerHost::OnRemoteRequestInnerSecond(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + case static_cast(IAppScheduler::Message::SCHEDULE_PROCESS_SECURITY_EXIT_TRANSACTION): + return HandleScheduleProcessSecurityExit(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_CLEAR_PAGE_STACK): + return HandleScheduleClearPageStack(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_ABILITY_STAGE_INFO): + return HandleScheduleAbilityStage(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_ACCEPT_WANT): + return HandleScheduleAcceptWant(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_NEW_PROCESS_REQUEST): + return HandleScheduleNewProcessRequest(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_NOTIFY_LOAD_REPAIR_PATCH): + return HandleNotifyLoadRepairPatch(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_NOTIFY_HOT_RELOAD_PAGE): + return HandleNotifyHotReloadPage(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_NOTIFY_UNLOAD_REPAIR_PATCH): + return HandleNotifyUnLoadRepairPatch(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_UPDATE_APPLICATION_INFO_INSTALLED): + return HandleScheduleUpdateApplicationInfoInstalled(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_HEAPMEMORY_APPLICATION_TRANSACTION): + return HandleScheduleHeapMemory(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_NOTIFY_FAULT): + return HandleNotifyAppFault(data, reply); + } + return INVALID_FD; +} + +int32_t AppSchedulerHost::OnRemoteRequestInnerThird(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + switch (static_cast(code)) { + case static_cast(IAppScheduler::Message::APP_GC_STATE_CHANGE): + return HandleScheduleChangeAppGcState(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_ATTACH_APP_DEBUG): + return HandleAttachAppDebug(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_DETACH_APP_DEBUG): + return HandleDetachAppDebug(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_JSHEAP_MEMORY_APPLICATION_TRANSACTION): + return HandleScheduleJsHeapMemory(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_DUMP_IPC_START): + return HandleScheduleDumpIpcStart(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_DUMP_IPC_STOP): + return HandleScheduleDumpIpcStop(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_DUMP_IPC_STAT): + return HandleScheduleDumpIpcStat(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_DUMP_FFRT): + return HandleScheduleDumpFfrt(data, reply); + case static_cast(IAppScheduler::Message::SCHEDULE_CACHE_PROCESS): + return HandleScheduleCacheProcess(data, reply); + } + return INVALID_FD; +} + int32_t AppSchedulerHost::HandleScheduleForegroundApplication(MessageParcel &data, MessageParcel &reply) { HITRACE_METER(HITRACE_TAG_APP); 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 333d01d4ff..1bcd18b141 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 @@ -16,7 +16,6 @@ #include "app_scheduler_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "ipc_types.h" #include "iremote_object.h" @@ -588,7 +587,7 @@ int32_t AppSchedulerProxy::ScheduleChangeAppGcState(int32_t state) void AppSchedulerProxy::AttachAppDebug() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); @@ -606,7 +605,7 @@ void AppSchedulerProxy::AttachAppDebug() void AppSchedulerProxy::DetachAppDebug() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); 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 e71dbf28c5..618689e2ec 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 @@ -19,7 +19,6 @@ #include "configuration.h" #include "hitrace_meter.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" @@ -28,24 +27,9 @@ namespace OHOS { namespace AppExecFwk { constexpr int32_t CYCLE_LIMIT = 1000; -AppStateCallbackHost::AppStateCallbackHost() -{ - memberFuncMap_[static_cast(IAppStateCallback::Message::TRANSACT_ON_APP_STATE_CHANGED)] = - &AppStateCallbackHost::HandleOnAppStateChanged; - memberFuncMap_[static_cast(IAppStateCallback::Message::TRANSACT_ON_ABILITY_REQUEST_DONE)] = - &AppStateCallbackHost::HandleOnAbilityRequestDone; - memberFuncMap_[static_cast(IAppStateCallback::Message::TRANSACT_ON_NOTIFY_CONFIG_CHANGE)] = - &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() {} -AppStateCallbackHost::~AppStateCallbackHost() -{ - memberFuncMap_.clear(); -} +AppStateCallbackHost::~AppStateCallbackHost() {} int AppStateCallbackHost::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -59,13 +43,19 @@ int AppStateCallbackHost::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + switch (code) { + case static_cast(IAppStateCallback::Message::TRANSACT_ON_APP_STATE_CHANGED): + return HandleOnAppStateChanged(data, reply); + case static_cast(IAppStateCallback::Message::TRANSACT_ON_ABILITY_REQUEST_DONE): + return HandleOnAbilityRequestDone(data, reply); + case static_cast(IAppStateCallback::Message::TRANSACT_ON_NOTIFY_CONFIG_CHANGE): + return HandleNotifyConfigurationChange(data, reply); + case static_cast(IAppStateCallback::Message::TRANSACT_ON_NOTIFY_START_RESIDENT_PROCESS): + return HandleNotifyStartResidentProcess(data, reply); + case static_cast(IAppStateCallback::Message::TRANSACT_ON_APP_REMOTE_DIED): + return HandleOnAppRemoteDied(data, reply); } + TAG_LOGD(AAFwkTag::APPMGR, "AppStateCallbackHost::OnRemoteRequest end"); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } 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 1636c1c45e..d99a535018 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 @@ -19,7 +19,6 @@ #include "ipc_types.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_state_data.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_state_data.cpp index f20b6ac620..8c3d6da0a2 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_state_data.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_state_data.cpp @@ -16,7 +16,6 @@ #include "app_state_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ui_extension_utils.h" namespace OHOS { diff --git a/interfaces/inner_api/app_manager/src/appmgr/app_task_info.cpp b/interfaces/inner_api/app_manager/src/appmgr/app_task_info.cpp index 02b3c05d8c..161358bf9c 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/app_task_info.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/app_task_info.cpp @@ -16,7 +16,6 @@ #include "app_task_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/inner_api/app_manager/src/appmgr/application_state_observer_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/application_state_observer_proxy.cpp index f818b60c5a..e084f819cc 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/application_state_observer_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/application_state_observer_proxy.cpp @@ -16,7 +16,6 @@ #include "application_state_observer_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" diff --git a/interfaces/inner_api/app_manager/src/appmgr/application_state_observer_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/application_state_observer_stub.cpp index b3417d9acb..15dd1b61ef 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/application_state_observer_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/application_state_observer_stub.cpp @@ -16,7 +16,6 @@ #include "application_state_observer_stub.h" #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" @@ -33,12 +32,35 @@ int ApplicationStateObserverStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + switch (static_cast(code)) { + case Message::TRANSACT_ON_FOREGROUND_APPLICATION_CHANGED: + return HandleOnForegroundApplicationChanged(data, reply); + case Message::TRANSACT_ON_ABILITY_STATE_CHANGED: + return HandleOnAbilityStateChanged(data, reply); + case Message::TRANSACT_ON_EXTENSION_STATE_CHANGED: + return HandleOnExtensionStateChanged(data, reply); + case Message::TRANSACT_ON_PROCESS_CREATED: + return HandleOnProcessCreated(data, reply); + case Message::TRANSACT_ON_PROCESS_STATE_CHANGED: + return HandleOnProcessStateChanged(data, reply); + case Message::TRANSACT_ON_PROCESS_DIED: + return HandleOnProcessDied(data, reply); + case Message::TRANSACT_ON_APPLICATION_STATE_CHANGED: + return HandleOnApplicationStateChanged(data, reply); + case Message::TRANSACT_ON_APP_STATE_CHANGED: + return HandleOnAppStateChanged(data, reply); + case Message::TRANSACT_ON_PROCESS_REUSED: + return HandleOnProcessReused(data, reply); + case Message::TRANSACT_ON_APP_STARTED: + return HandleOnAppStarted(data, reply); + case Message::TRANSACT_ON_APP_STOPPED: + return HandleOnAppStopped(data, reply); + case Message::TRANSACT_ON_PAGE_SHOW: + return HandleOnPageShow(data, reply); + case Message::TRANSACT_ON_PAGE_HIDE: + return HandleOnPageHide(data, reply); + case Message::TRANSACT_ON_APP_CACHE_STATE_CHANGED: + return HandleOnAppCacheStateChanged(data, reply); } TAG_LOGW(AAFwkTag::APPMGR, "ApplicationStateObserverStub::OnRemoteRequest, default case, need check"); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); diff --git a/interfaces/inner_api/app_manager/src/appmgr/child_process_args.cpp b/interfaces/inner_api/app_manager/src/appmgr/child_process_args.cpp new file mode 100644 index 0000000000..d49e7fbd0b --- /dev/null +++ b/interfaces/inner_api/app_manager/src/appmgr/child_process_args.cpp @@ -0,0 +1,116 @@ +/* + * 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 "child_process_args.h" + +#include "hilog_tag_wrapper.h" +#include "message_parcel.h" +#include "parcel_macro_base.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +bool ChildProcessArgs::ReadFromParcel(Parcel &parcel) +{ + entryParams = Str16ToStr8(parcel.ReadString16()); + + int32_t fdsSize = parcel.ReadInt32(); + if (fdsSize > CHILD_PROCESS_ARGS_FDS_MAX_COUNT) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "fds count must <= %{public}d.", CHILD_PROCESS_ARGS_FDS_MAX_COUNT); + return false; + } + auto messageParcel = static_cast(&parcel); + if (messageParcel == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "static cast messageParcel failed"); + return false; + } + for (int32_t i = 0; i < fdsSize; i++) { + std::string key = Str16ToStr8(parcel.ReadString16()); + if (!CheckFdKeyLength(key)) { + return false; + } + int32_t fd = messageParcel->ReadFileDescriptor(); + fds.emplace(key, fd); + } + return true; +} + +ChildProcessArgs *ChildProcessArgs::Unmarshalling(Parcel &parcel) +{ + ChildProcessArgs *obj = new (std::nothrow) ChildProcessArgs(); + if (obj && !obj->ReadFromParcel(parcel)) { + TAG_LOGW(AAFwkTag::APPMGR, "read from parcel failed"); + delete obj; + obj = nullptr; + } + return obj; +} + +bool ChildProcessArgs::Marshalling(Parcel &parcel) const +{ + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(entryParams)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, fds.size()); + auto messageParcel = static_cast(&parcel); + if (messageParcel == nullptr) { + TAG_LOGW(AAFwkTag::APPMGR, "static cast messageParcel failed"); + return false; + } + if (!CheckFdsSize()) { + return false; + } + for (auto &item : fds) { + if (!CheckFdKeyLength(item.first)) { + return false; + } + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(item.first)); + if (!messageParcel->WriteFileDescriptor(item.second)) { + TAG_LOGE(AAFwkTag::APPMGR, "WriteFileDescriptor failed, fd:%{private}d", item.second); + return false; + } + } + return true; +} + +bool ChildProcessArgs::CheckFdsSize() const +{ + TAG_LOGD(AAFwkTag::APPMGR, "CheckFdsSize: %{public}zu", fds.size()); + if (fds.size() > CHILD_PROCESS_ARGS_FDS_MAX_COUNT) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "fds count must <= %{public}d.", CHILD_PROCESS_ARGS_FDS_MAX_COUNT); + return false; + } + return true; +} + +bool ChildProcessArgs::CheckFdsKeyLength() const +{ + for (auto iter = fds.begin(); iter != fds.end(); iter++) { + if (!CheckFdKeyLength(iter->first)) { + return false; + } + } + return true; +} + +bool ChildProcessArgs::CheckFdKeyLength(const std::string &key) +{ + if (key.length() > CHILD_PROCESS_ARGS_FD_KEY_MAX_LENGTH) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "fd key length must <= %{public}d, key:%{public}s", + CHILD_PROCESS_ARGS_FD_KEY_MAX_LENGTH, key.c_str()); + return false; + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS 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 9790eeba07..9d1e3962b1 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 @@ -16,7 +16,6 @@ #include "child_process_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "nlohmann/json.hpp" #include "parcel_macro_base.h" #include "string_ex.h" @@ -37,11 +36,12 @@ 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); + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, childProcessType); bundleName = Str16ToStr8(parcel.ReadString16()); processName = Str16ToStr8(parcel.ReadString16()); srcEntry = Str16ToStr8(parcel.ReadString16()); + entryParams = Str16ToStr8(parcel.ReadString16()); jitEnabled = parcel.ReadBool(); isDebugApp = parcel.ReadBool(); isStartWithDebug = parcel.ReadBool(); @@ -66,10 +66,11 @@ 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(Int32, parcel, static_cast(childProcessType)); 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)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(entryParams)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, jitEnabled); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isDebugApp); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isStartWithDebug); diff --git a/interfaces/inner_api/app_manager/src/appmgr/child_process_options.cpp b/interfaces/inner_api/app_manager/src/appmgr/child_process_options.cpp new file mode 100644 index 0000000000..ee1ac0d90a --- /dev/null +++ b/interfaces/inner_api/app_manager/src/appmgr/child_process_options.cpp @@ -0,0 +1,46 @@ +/* + * 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 "child_process_options.h" + +#include "hilog_tag_wrapper.h" +#include "parcel_macro_base.h" + +namespace OHOS { +namespace AppExecFwk { +bool ChildProcessOptions::ReadFromParcel(Parcel &parcel) +{ + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isolationMode); + return true; +} + +ChildProcessOptions *ChildProcessOptions::Unmarshalling(Parcel &parcel) +{ + ChildProcessOptions *obj = new (std::nothrow) ChildProcessOptions(); + if (obj && !obj->ReadFromParcel(parcel)) { + TAG_LOGW(AAFwkTag::APPMGR, "read from parcel failed"); + delete obj; + obj = nullptr; + } + return obj; +} + +bool ChildProcessOptions::Marshalling(Parcel &parcel) const +{ + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isolationMode); + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/inner_api/app_manager/src/appmgr/child_process_request.cpp b/interfaces/inner_api/app_manager/src/appmgr/child_process_request.cpp new file mode 100644 index 0000000000..06b53d10be --- /dev/null +++ b/interfaces/inner_api/app_manager/src/appmgr/child_process_request.cpp @@ -0,0 +1,73 @@ +/* + * 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 "child_process_request.h" + +#include "hilog_tag_wrapper.h" +#include "parcel_macro_base.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +bool ChildProcessRequest::ReadFromParcel(Parcel &parcel) +{ + std::u16string srcEntryTemp; + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, srcEntryTemp); + srcEntry = Str16ToStr8(srcEntryTemp); + + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, childProcessType); + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, childProcessCount); + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isStartWithDebug); + + std::unique_ptr argsRead(parcel.ReadParcelable()); + if (!argsRead) { + TAG_LOGE(AAFwkTag::APPMGR, "Read ChildProcessArgs failed."); + return false; + } + args = *argsRead; + + std::unique_ptr optionsRead(parcel.ReadParcelable()); + if (!optionsRead) { + TAG_LOGE(AAFwkTag::APPMGR, "Read ChildProcessOptions failed."); + return false; + } + options = *optionsRead; + + return true; +} + +ChildProcessRequest *ChildProcessRequest::Unmarshalling(Parcel &parcel) +{ + ChildProcessRequest *data = new (std::nothrow) ChildProcessRequest(); + if (data && !data->ReadFromParcel(parcel)) { + TAG_LOGW(AAFwkTag::APPMGR, "Read from parcel failed."); + delete data; + data = nullptr; + } + return data; +} + +bool ChildProcessRequest::Marshalling(Parcel &parcel) const +{ + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(srcEntry)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(childProcessType)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(childProcessCount)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isStartWithDebug); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Parcelable, parcel, &args); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Parcelable, parcel, &options); + return true; +} +} // namespace AppExecFwk +} // namespace OHOS 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 e14eaa5e71..bc0d2df7d9 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 @@ -16,7 +16,6 @@ #include "child_scheduler_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" 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 b434032513..b751b4c850 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 @@ -16,25 +16,13 @@ #include "child_scheduler_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { namespace AppExecFwk { -ChildSchedulerStub::ChildSchedulerStub() -{ - memberFuncMap_[static_cast(IChildScheduler::Message::SCHEDULE_LOAD_JS)] = - &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() {} -ChildSchedulerStub::~ChildSchedulerStub() -{ - memberFuncMap_.clear(); -} +ChildSchedulerStub::~ChildSchedulerStub() {} int32_t ChildSchedulerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -48,12 +36,13 @@ int32_t ChildSchedulerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + switch (code) { + case static_cast(IChildScheduler::Message::SCHEDULE_LOAD_JS): + return HandleScheduleLoadJs(data, reply); + case static_cast(IChildScheduler::Message::SCHEDULE_EXIT_PROCESS_SAFELY): + return HandleScheduleExitProcessSafely(data, reply); + case static_cast(IChildScheduler::Message::SCHEDULE_RUN_NATIVE_PROC): + return HandleScheduleRunNativeProc(data, reply); } TAG_LOGI(AAFwkTag::APPMGR, "ChildSchedulerStub::OnRemoteRequest end"); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); diff --git a/interfaces/inner_api/app_manager/src/appmgr/configuration_observer_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/configuration_observer_stub.cpp index 1b3c603d42..2bffb3fcff 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/configuration_observer_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/configuration_observer_stub.cpp @@ -17,24 +17,15 @@ #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "ipc_types.h" #include "iremote_object.h" namespace OHOS { namespace AppExecFwk { -ConfigurationObserverStub::ConfigurationObserverStub() -{ - memberFuncMap_[static_cast( - IConfigurationObserver::Message::TRANSACT_ON_CONFIGURATION_UPDATED)] = - &ConfigurationObserverStub::HandleOnConfigurationUpdated; -} +ConfigurationObserverStub::ConfigurationObserverStub() {} -ConfigurationObserverStub::~ConfigurationObserverStub() -{ - memberFuncMap_.clear(); -} +ConfigurationObserverStub::~ConfigurationObserverStub() {} int ConfigurationObserverStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -48,13 +39,10 @@ int ConfigurationObserverStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + if (code == static_cast(IConfigurationObserver::Message::TRANSACT_ON_CONFIGURATION_UPDATED)) { + return HandleOnConfigurationUpdated(data, reply); } + TAG_LOGI(AAFwkTag::APPMGR, "ConfigurationObserverStub::OnRemoteRequest end"); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/interfaces/inner_api/app_manager/src/appmgr/fault_data.cpp b/interfaces/inner_api/app_manager/src/appmgr/fault_data.cpp index 57be82fe66..49411bf657 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/fault_data.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/fault_data.cpp @@ -18,7 +18,6 @@ #include "nlohmann/json.hpp" #include "string_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { @@ -60,6 +59,7 @@ bool FaultData::ReadFromParcel(Parcel &parcel) notifyApp = parcel.ReadBool(); forceExit = parcel.ReadBool(); state = parcel.ReadUint32(); + eventId = parcel.ReadInt32(); if (parcel.ReadBool()) { token = (static_cast(&parcel))->ReadRemoteObject(); } @@ -123,6 +123,11 @@ bool FaultData::Marshalling(Parcel &parcel) const return false; } + if (!parcel.WriteInt32(eventId)) { + TAG_LOGE(AAFwkTag::APPMGR, "EventId [%{public}u] write int32 failed.", eventId); + return false; + } + if (token == nullptr) { if (!parcel.WriteBool(false)) { TAG_LOGE(AAFwkTag::APPMGR, "Token falge [false] write bool failed."); @@ -180,6 +185,7 @@ bool AppFaultDataBySA::ReadFromParcel(Parcel &parcel) notifyApp = parcel.ReadBool(); forceExit = parcel.ReadBool(); state = parcel.ReadUint32(); + eventId = parcel.ReadInt32(); if (parcel.ReadBool()) { token = (static_cast(&parcel))->ReadRemoteObject(); } @@ -248,6 +254,11 @@ bool AppFaultDataBySA::Marshalling(Parcel &parcel) const return false; } + if (!parcel.WriteInt32(eventId)) { + TAG_LOGE(AAFwkTag::APPMGR, "EventId [%{public}u] write int32 failed.", eventId); + return false; + } + if (token == nullptr) { if (!parcel.WriteBool(false)) { TAG_LOGE(AAFwkTag::APPMGR, "Token falge [false] write bool failed."); 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 index e97ec17658..0bfd0770ee 100644 --- 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 @@ -15,7 +15,6 @@ #include "native_child_notify_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { 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 index 63ad1fb4e2..87f5336068 100644 --- 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 @@ -15,7 +15,6 @@ #include "native_child_notify_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { diff --git a/interfaces/inner_api/app_manager/src/appmgr/page_state_data.cpp b/interfaces/inner_api/app_manager/src/appmgr/page_state_data.cpp index d50836472a..b1747af9dd 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/page_state_data.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/page_state_data.cpp @@ -16,7 +16,6 @@ #include "page_state_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parcel_macro_base.h" namespace OHOS { diff --git a/interfaces/inner_api/app_manager/src/appmgr/priority_object.cpp b/interfaces/inner_api/app_manager/src/appmgr/priority_object.cpp index 73eb2453fd..bad79717ee 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/priority_object.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/priority_object.cpp @@ -16,7 +16,6 @@ #include "priority_object.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace 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 3e1759f9ec..e194c40028 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/process_data.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/process_data.cpp @@ -16,7 +16,6 @@ #include "process_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parcel_macro_base.h" #include "string_ex.h" diff --git a/interfaces/inner_api/app_manager/src/appmgr/process_info.cpp b/interfaces/inner_api/app_manager/src/appmgr/process_info.cpp index dc4abd5e95..0c4fe8ed69 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/process_info.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/process_info.cpp @@ -16,7 +16,6 @@ #include "process_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "string_ex.h" namespace OHOS { diff --git a/interfaces/inner_api/app_manager/src/appmgr/profile.cpp b/interfaces/inner_api/app_manager/src/appmgr/profile.cpp index 8c0f8591fb..f0b37048cf 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/profile.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/profile.cpp @@ -18,7 +18,6 @@ #include "string_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/inner_api/app_manager/src/appmgr/quick_fix_callback_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/quick_fix_callback_proxy.cpp index 87c7389d57..ffaac1fb00 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/quick_fix_callback_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/quick_fix_callback_proxy.cpp @@ -16,7 +16,6 @@ #include "quick_fix_callback_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "message_parcel.h" #include "parcel_macro_base.h" diff --git a/interfaces/inner_api/app_manager/src/appmgr/quick_fix_callback_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/quick_fix_callback_stub.cpp index 2a12a289f5..e557f4802a 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/quick_fix_callback_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/quick_fix_callback_stub.cpp @@ -16,21 +16,12 @@ #include "quick_fix_callback_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { -QuickFixCallbackStub::QuickFixCallbackStub() -{ - requestFuncMap_[ON_NOTIFY_LOAD_PATCH] = &QuickFixCallbackStub::HandleOnLoadPatchDoneInner; - requestFuncMap_[ON_NOTIFY_UNLOAD_PATCH] = &QuickFixCallbackStub::HandleOnUnloadPatchDoneInner; - requestFuncMap_[ON_NOTIFY_RELOAD_PAGE] = &QuickFixCallbackStub::HandleOnReloadPageDoneInner; -} +QuickFixCallbackStub::QuickFixCallbackStub() {} -QuickFixCallbackStub::~QuickFixCallbackStub() -{ - requestFuncMap_.clear(); -} +QuickFixCallbackStub::~QuickFixCallbackStub() {} int QuickFixCallbackStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -40,12 +31,13 @@ int QuickFixCallbackStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = requestFuncMap_.find(code); - if (itFunc != requestFuncMap_.end()) { - auto requestFunc = itFunc->second; - if (requestFunc != nullptr) { - return (this->*requestFunc)(data, reply); - } + switch (code) { + case ON_NOTIFY_LOAD_PATCH: + return HandleOnLoadPatchDoneInner(data, reply); + case ON_NOTIFY_UNLOAD_PATCH: + return HandleOnUnloadPatchDoneInner(data, reply); + case ON_NOTIFY_RELOAD_PAGE: + return HandleOnReloadPageDoneInner(data, reply); } TAG_LOGW(AAFwkTag::APPMGR, "default case, need check value of code!"); diff --git a/interfaces/inner_api/app_manager/src/appmgr/render_process_info.cpp b/interfaces/inner_api/app_manager/src/appmgr/render_process_info.cpp index 326238eaa9..399fb6c9c7 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/render_process_info.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/render_process_info.cpp @@ -19,7 +19,6 @@ #include "string_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parcel_macro_base.h" namespace OHOS { 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 059e9b6b72..2d18dec41c 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 @@ -16,21 +16,13 @@ #include "render_scheduler_host.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { namespace AppExecFwk { -RenderSchedulerHost::RenderSchedulerHost() -{ - memberFuncMap_[static_cast(IRenderScheduler::Message::NOTIFY_BROWSER_FD)] = - &RenderSchedulerHost::HandleNotifyBrowserFd; -} +RenderSchedulerHost::RenderSchedulerHost() {} -RenderSchedulerHost::~RenderSchedulerHost() -{ - memberFuncMap_.clear(); -} +RenderSchedulerHost::~RenderSchedulerHost() {} int RenderSchedulerHost::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -44,13 +36,10 @@ int RenderSchedulerHost::OnRemoteRequest(uint32_t code, MessageParcel &data, return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + if (code == static_cast(IRenderScheduler::Message::NOTIFY_BROWSER_FD)) { + return HandleNotifyBrowserFd(data, reply); } + TAG_LOGI(AAFwkTag::APPMGR, "RenderSchedulerHost::OnRemoteRequest end"); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } 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 9f670bedfb..8f226d5945 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 @@ -16,7 +16,6 @@ #include "render_scheduler_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" diff --git a/interfaces/inner_api/app_manager/src/appmgr/render_state_data.cpp b/interfaces/inner_api/app_manager/src/appmgr/render_state_data.cpp index 838ae0dda1..8910cd0533 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/render_state_data.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/render_state_data.cpp @@ -16,7 +16,6 @@ #include "render_state_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parcel_macro_base.h" namespace OHOS { diff --git a/interfaces/inner_api/app_manager/src/appmgr/render_state_observer_proxy.cpp b/interfaces/inner_api/app_manager/src/appmgr/render_state_observer_proxy.cpp index 82afb071d5..9c478fa52d 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/render_state_observer_proxy.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/render_state_observer_proxy.cpp @@ -16,7 +16,6 @@ #include "render_state_observer_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { diff --git a/interfaces/inner_api/app_manager/src/appmgr/render_state_observer_stub.cpp b/interfaces/inner_api/app_manager/src/appmgr/render_state_observer_stub.cpp index ed64661c1d..8d28fa4007 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/render_state_observer_stub.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/render_state_observer_stub.cpp @@ -17,22 +17,14 @@ #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" namespace OHOS { namespace AppExecFwk { -RenderStateObserverStub::RenderStateObserverStub() -{ - memberFuncMap_[IRenderStateObserver::ON_RENDER_STATE_CHANGED] = - &RenderStateObserverStub::OnRenderStateChangedInner; -} +RenderStateObserverStub::RenderStateObserverStub() {} -RenderStateObserverStub::~RenderStateObserverStub() -{ - memberFuncMap_.clear(); -} +RenderStateObserverStub::~RenderStateObserverStub() {} int32_t RenderStateObserverStub::OnRenderStateChangedInner(MessageParcel &data, MessageParcel &reply) { @@ -56,12 +48,8 @@ int RenderStateObserverStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } + if (code == IRenderStateObserver::ON_RENDER_STATE_CHANGED) { + return OnRenderStateChangedInner(data, reply); } return IPCObjectStub::OnRemoteRequest(code, data, reply, option); 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 index 104963d4c1..5c4aa852bf 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/running_multi_info.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/running_multi_info.cpp @@ -19,7 +19,6 @@ #include "string_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parcel_macro_base.h" namespace OHOS { diff --git a/interfaces/inner_api/app_manager/src/appmgr/running_process_info.cpp b/interfaces/inner_api/app_manager/src/appmgr/running_process_info.cpp index cc362aac71..a4bce0c84f 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/running_process_info.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/running_process_info.cpp @@ -19,7 +19,6 @@ #include "string_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parcel_macro_base.h" namespace OHOS { 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 c54bc1faee..85dbe9e45e 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 @@ -16,7 +16,6 @@ #include "start_specified_ability_response_proxy.h" #include "ipc_types.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { 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 677aed718f..85cc59f5c6 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 @@ -16,7 +16,6 @@ #include "start_specified_ability_response_stub.h" #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" @@ -25,26 +24,34 @@ namespace AppExecFwk { using namespace std::placeholders; StartSpecifiedAbilityResponseStub::StartSpecifiedAbilityResponseStub() { - auto handleOnAcceptWantResponse = - std::bind(&StartSpecifiedAbilityResponseStub::HandleOnAcceptWantResponse, this, _1, _2); + auto handleOnAcceptWantResponse = [this](OHOS::MessageParcel &arg1, OHOS::MessageParcel &arg2) { + return HandleOnAcceptWantResponse(arg1, arg2); + }; + responseFuncMap_.emplace(static_cast( IStartSpecifiedAbilityResponse::Message::ON_ACCEPT_WANT_RESPONSE), std::move(handleOnAcceptWantResponse)); - auto handleOnTimeoutResponse = - std::bind(&StartSpecifiedAbilityResponseStub::HandleOnTimeoutResponse, this, _1, _2); + auto handleOnTimeoutResponse = [this](OHOS::MessageParcel &arg1, OHOS::MessageParcel &arg2) { + return HandleOnTimeoutResponse(arg1, arg2); + }; + responseFuncMap_.emplace(static_cast( IStartSpecifiedAbilityResponse::Message::ON_TIMEOUT_RESPONSE), std::move(handleOnTimeoutResponse)); - auto handleOnNewProcessRequestResponse = - std::bind(&StartSpecifiedAbilityResponseStub::HandleOnNewProcessRequestResponse, this, _1, _2); + auto handleOnNewProcessRequestResponse = [this](OHOS::MessageParcel &arg1, OHOS::MessageParcel &arg2) { + return HandleOnNewProcessRequestResponse(arg1, arg2); + }; + responseFuncMap_.emplace(static_cast( IStartSpecifiedAbilityResponse::Message::ON_NEW_PROCESS_REQUEST_RESPONSE), std::move(handleOnNewProcessRequestResponse)); - auto handleOnNewProcessRequestTimeoutResponse = - std::bind(&StartSpecifiedAbilityResponseStub::HandleOnNewProcessRequestTimeoutResponse, this, _1, _2); + auto handleOnNewProcessRequestTimeoutResponse = [this](OHOS::MessageParcel &arg1, OHOS::MessageParcel &arg2) { + return HandleOnNewProcessRequestTimeoutResponse(arg1, arg2); + }; + responseFuncMap_.emplace(static_cast( IStartSpecifiedAbilityResponse::Message::ON_NEW_PROCESS_REQUEST_TIMEOUT_RESPONSE), std::move(handleOnNewProcessRequestTimeoutResponse)); diff --git a/interfaces/inner_api/app_manager/src/appmgr/system_memory_attr.cpp b/interfaces/inner_api/app_manager/src/appmgr/system_memory_attr.cpp index aa5f2bb77a..c83cf5739f 100644 --- a/interfaces/inner_api/app_manager/src/appmgr/system_memory_attr.cpp +++ b/interfaces/inner_api/app_manager/src/appmgr/system_memory_attr.cpp @@ -15,7 +15,6 @@ #include "system_memory_attr.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { 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 84b1028214..203c928655 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 @@ -16,6 +16,8 @@ #ifndef OHOS_ABILITY_RUNTIME_AUTO_FILL_EXTENSION_CALLBACK_H #define OHOS_ABILITY_RUNTIME_AUTO_FILL_EXTENSION_CALLBACK_H +#include + #include "auto_fill_custom_config.h" #include "fill_request_callback_interface.h" #include "save_request_callback_interface.h" @@ -32,50 +34,53 @@ enum AutoFillWindowType { POPUP_WINDOW }; } +#ifdef SUPPORT_GRAPHICS class AutoFillExtensionCallback : public std::enable_shared_from_this { public: - AutoFillExtensionCallback() = default; + AutoFillExtensionCallback(); ~AutoFillExtensionCallback() = default; void OnResult(int32_t errCode, const AAFwk::Want &want); void OnRelease(int32_t errCode); void OnError(int32_t errCode, const std::string &name, const std::string &message); void OnReceive(const AAFwk::WantParams &wantParams); -#ifdef SUPPORT_GRAPHICS void onRemoteReady(const std::shared_ptr &modalUIExtensionProxy); -#endif // SUPPORT_GRAPHICS void onDestroy(); void SetFillRequestCallback(const std::shared_ptr &callback); void SetSaveRequestCallback(const std::shared_ptr &callback); void SetSessionId(int32_t sessionId); -#ifdef SUPPORT_GRAPHICS void SetInstanceId(int32_t instanceId); int32_t GetInstanceId(); -#endif // SUPPORT_GRAPHICS - void SetEventId(uint32_t eventId); void SetWindowType(const AutoFill::AutoFillWindowType &autoFillWindowType); + AutoFill::AutoFillWindowType GetWindowType() const; void SetExtensionType(bool isSmartAutoFill); void SetAutoFillType(const AbilityBase::AutoFillType &autoFillType); void SetViewData(const AbilityBase::ViewData &viewData); void SetAutoFillRequestConfig(const AutoFill::AutoFillCustomConfig &config); - AbilityBase::ViewData GetViewData(); + uint32_t GetCallbackId() const; void HandleTimeOut(); + void UpdateCustomPopupUIExtension(const AbilityBase::ViewData &viewData); + void CloseUIExtension(); private: - void SendAutoFillSucess(const AAFwk::Want &want); + void SendAutoFillSuccess(const AAFwk::Want &want); void SendAutoFillFailed(int32_t errCode, const AAFwk::Want &want = AAFwk::Want()); - void CloseModalUIExtension(); void HandleReloadInModal(const AAFwk::WantParams &wantParams); + int32_t ReloadInModal(const AAFwk::WantParams &wantParams); + void UpdateCustomPopupConfig(const AAFwk::WantParams &wantParams); + void SetModalUIExtensionProxy(const std::shared_ptr& proxy); + std::shared_ptr GetModalUIExtensionProxy(); + uint32_t GenerateCallbackId(); + Ace::UIContent* GetUIContent(); + std::mutex requestCallbackMutex_; std::shared_ptr fillCallback_; std::shared_ptr saveCallback_; - int32_t sessionId_; -#ifdef SUPPORT_GRAPHICS - int32_t instanceId_ = -1; -#endif // SUPPORT_GRAPHICS - uint32_t eventId_ = 0; + int32_t sessionId_ = -1; + std::atomic instanceId_ {-1}; + uint32_t callbackId_ = 0; AutoFill::AutoFillWindowType autoFillWindowType_ = AutoFill::AutoFillWindowType::MODAL_WINDOW; AbilityBase::ViewData viewData_; AutoFill::AutoFillCustomConfig autoFillCustomConfig_; @@ -85,7 +90,11 @@ private: AAFwk::Want want_; int32_t errCode_ = 0; AbilityBase::AutoFillType autoFillType_ = AbilityBase::AutoFillType::UNSPECIFIED; + std::mutex proxyMutex_; + std::shared_ptr modalUIExtensionProxy_; + std::mutex closeMutex_; }; +#endif // SUPPORT_GRAPHICS } // AbilityRuntime } // OHOS #endif // OHOS_ABILITY_RUNTIME_AUTO_FILL_EXTENSION_CALLBACK_H 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 e6eab20570..00bbc283d3 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 @@ -22,6 +22,7 @@ #include "auto_fill_event_handler.h" #include "auto_fill_extension_callback.h" #include "fill_request_callback_interface.h" +#include "nocopyable.h" #include "save_request_callback_interface.h" #include "task_handler_wrap.h" #ifdef SUPPORT_GRAPHICS @@ -51,79 +52,66 @@ struct AutoFillRequest { AutoFillCommand autoFillCommand = AutoFillCommand::NONE; AbilityBase::ViewData viewData; AutoFillCustomConfig config; + std::function doAfterAsyncModalBinding; }; -/** - * @struct ReloadInModalRequest - * ReloadInModalRequest is used to define the reload in modal request parameter structure. - */ -#ifdef SUPPORT_GRAPHICS -struct ReloadInModalRequest { - int32_t instanceId = -1; - bool isSmartAutoFill = false; - int32_t nodeId; - std::string customData; - AutoFillWindowType autoFillWindowType; - AbilityBase::AutoFillType autoFillType = AbilityBase::AutoFillType::UNSPECIFIED; - std::shared_ptr extensionCallback; +struct AutoFillResult { + bool isPopup = false; + uint32_t autoFillSessionId = 0; }; - } +#ifdef SUPPORT_GRAPHICS class AutoFillManager { public: - AutoFillManager() = default; - ~AutoFillManager(); - static AutoFillManager &GetInstance(); - int32_t RequestAutoFill( - Ace::UIContent *uiContent, - const AutoFill::AutoFillRequest &request, - const std::shared_ptr &fillCallback, bool &isPopup); + int32_t RequestAutoFill(Ace::UIContent *uiContent, const AutoFill::AutoFillRequest &request, + const std::shared_ptr &fillCallback, AutoFill::AutoFillResult &result); - int32_t RequestAutoSave( - Ace::UIContent *uiContent, - const AutoFill::AutoFillRequest &request, - const std::shared_ptr &saveCallback); - void UpdateCustomPopupUIExtension(Ace::UIContent *uiContent, const AbilityBase::ViewData &viewData); - int32_t UpdateCustomPopupConfig(int32_t instanceId, const Ace::CustomPopupUIExtensionConfig &popupConfig); - void SetAutoFillExtensionProxy(int32_t instanceId, - const std::shared_ptr &modalUIExtensionProxy); - void RemoveAutoFillExtensionProxy(int32_t instanceId); - int32_t ReloadInModal(const AutoFill::ReloadInModalRequest &request); + bool IsNeedToCreatePopupWindow(const AbilityBase::AutoFillType &autoFillType); + + int32_t RequestAutoSave(Ace::UIContent *uiContent, const AutoFill::AutoFillRequest &request, + const std::shared_ptr &saveCallback, AutoFill::AutoFillResult &result); + + void UpdateCustomPopupUIExtension(uint32_t autoFillSessionId, const AbilityBase::ViewData &viewData); + + void CloseUIExtension(uint32_t autoFillSessionId); void HandleTimeOut(uint32_t eventId); + void SetTimeOutEvent(uint32_t eventId); void RemoveEvent(uint32_t eventId); -private: - int32_t HandleRequestExecuteInner( - Ace::UIContent *uiContent, - const AutoFill::AutoFillRequest &request, + void BindModalUIExtensionCallback(const std::shared_ptr &extensionCallback, + Ace::ModalUIExtensionCallbacks &callback); + void RemoveAutoFillExtensionCallback(uint32_t callbackId); +private: + AutoFillManager(); + ~AutoFillManager(); + DISALLOW_COPY_AND_MOVE(AutoFillManager); + + int32_t HandleRequestExecuteInner(Ace::UIContent *uiContent, const AutoFill::AutoFillRequest &request, const std::shared_ptr &fillCallback, - const std::shared_ptr &saveCallback, bool &isPopup); + const std::shared_ptr &saveCallback, + AutoFill::AutoFillResult &result); + int32_t CreateAutoFillExtension(Ace::UIContent *uiContent, const AutoFill::AutoFillRequest &request, const Ace::ModalUIExtensionCallbacks &callback, const AutoFill::AutoFillWindowType &autoFillWindowType, bool isSmartAutoFill); - void BindModalUIExtensionCallback( - const std::shared_ptr &extensionCallback, Ace::ModalUIExtensionCallbacks &callback); - void SetTimeOutEvent(uint32_t eventId); bool ConvertAutoFillWindowType(const AutoFill::AutoFillRequest &request, bool &isSmartAutoFill, AutoFill::AutoFillWindowType &autoFillWindowType); + std::shared_ptr GetAutoFillExtensionCallback(uint32_t callbackId); bool IsPreviousRequestFinished(Ace::UIContent *uiContent); bool IsNeed2SaveRequest(const AbilityBase::ViewData &viewData, bool &isSmartAutoFill); std::mutex extensionCallbacksMutex_; - std::mutex modalProxyMapMutex_; - std::map> extensionCallbacks_; + std::map> extensionCallbacks_; - std::map> modalUIExtensionProxyMap_; - uint32_t eventId_ = 0; std::shared_ptr eventHandler_; -#endif // SUPPORT_GRAPHICS }; +#endif // SUPPORT_GRAPHICS } // AbilityRuntime } // OHOS #endif // OHOS_ABILITY_RUNTIME_AUTO_FILL_MANAGER_H \ No newline at end of file diff --git a/interfaces/inner_api/auto_fill_manager/include/fill_request_callback_interface.h b/interfaces/inner_api/auto_fill_manager/include/fill_request_callback_interface.h index 7c0efb5513..aa67ad931f 100644 --- a/interfaces/inner_api/auto_fill_manager/include/fill_request_callback_interface.h +++ b/interfaces/inner_api/auto_fill_manager/include/fill_request_callback_interface.h @@ -16,6 +16,7 @@ #ifndef OHOS_ABILITY_RUNTIME_AUTO_REQUEST_CALLBACK_INTERFACE_H #define OHOS_ABILITY_RUNTIME_AUTO_REQUEST_CALLBACK_INTERFACE_H +#include "auto_fill_custom_config.h" #include "view_data.h" namespace OHOS { @@ -26,6 +27,7 @@ public: virtual void OnFillRequestSuccess(const AbilityBase::ViewData &viewData) = 0; virtual void OnFillRequestFailed(int32_t errCode, const std::string& fillContent = "", bool isPopup = false) = 0; + virtual void onPopupConfigWillUpdate(AutoFill::AutoFillCustomConfig& config) {} }; } // AbilityRuntime } // OHOS diff --git a/interfaces/inner_api/auto_fill_manager/src/auto_fill_event_handler.cpp b/interfaces/inner_api/auto_fill_manager/src/auto_fill_event_handler.cpp index 22976993a5..a1b971378e 100644 --- a/interfaces/inner_api/auto_fill_manager/src/auto_fill_event_handler.cpp +++ b/interfaces/inner_api/auto_fill_manager/src/auto_fill_event_handler.cpp @@ -17,7 +17,6 @@ #include "auto_fill_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { @@ -27,7 +26,7 @@ AutoFillEventHandler::AutoFillEventHandler(const std::shared_ptrDestroyCustomPopupUIExtension(request.nodeId); + if (oldWindowType == AutoFill::AutoFillWindowType::POPUP_WINDOW) { + isReloadInModal_ = true; + uiContent->DestroyCustomPopupUIExtension(oldSessionId); } else { TAG_LOGW(AAFwkTag::AUTOFILLMGR, "Window type is not popup, the window can not be destroyed."); } } +int32_t AutoFillExtensionCallback::ReloadInModal(const AAFwk::WantParams &wantParams) +{ + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); + std::lock_guard lock(closeMutex_); + auto uiContent = GetUIContent(); + if (uiContent == nullptr) { + TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Content is nullptr."); + return AutoFill::AUTO_FILL_OBJECT_IS_NULL; + } + + AutoFillManager::GetInstance().SetTimeOutEvent(callbackId_); + AAFwk::Want want; + want.SetParam(WANT_PARAMS_AUTO_FILL_CMD_KEY, static_cast(AutoFill::AutoFillCommand::RELOAD_IN_MODAL)); + want.SetParam(WANT_PARAMS_CUSTOM_DATA_KEY, wantParams.GetStringParam(WANT_PARAMS_CUSTOM_DATA_KEY)); + isSmartAutoFill_ ? want.SetParam(WANT_PARAMS_EXTENSION_TYPE_KEY, std::string(WANT_PARAMS_SMART_EXTENSION_TYPE)) : + want.SetParam(WANT_PARAMS_EXTENSION_TYPE_KEY, std::string(WANT_PARAMS_EXTENSION_TYPE)); + want.SetParam(WANT_PARAMS_AUTO_FILL_TYPE_KEY, static_cast(autoFillType_)); + want.SetParam(WANT_PARAMS_VIEW_DATA_KEY, viewData_.ToJsonString()); + want.SetParam(WANT_PARAMS_AUTO_FILL_POPUP_WINDOW_KEY, false); + Ace::ModalUIExtensionCallbacks callback; + AutoFillManager::GetInstance().BindModalUIExtensionCallback(shared_from_this(), callback); + Ace::ModalUIExtensionConfig config; + config.isAsyncModalBinding = true; + int32_t sessionId = 0; + sessionId = uiContent->CreateModalUIExtension(want, callback, config); + if (sessionId == 0) { + TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Create ui extension is failed."); + AutoFillManager::GetInstance().RemoveEvent(callbackId_); + return AutoFill::AUTO_FILL_CREATE_MODULE_UI_EXTENSION_FAILED; + } + SetSessionId(sessionId); + SetWindowType(AutoFill::AutoFillWindowType::MODAL_WINDOW); + return AutoFill::AUTO_FILL_SUCCESS; +} + void AutoFillExtensionCallback::OnReceive(const AAFwk::WantParams &wantParams) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); int32_t cmdValue = wantParams.GetIntParam(WANT_PARAMS_AUTO_FILL_CMD_KEY, 0); if (cmdValue == static_cast(AutoFill::AutoFillCommand::RELOAD_IN_MODAL)) { HandleReloadInModal(wantParams); return; } else if (cmdValue == static_cast(AutoFill::AutoFillCommand::RESIZE)) { - Ace::CustomPopupUIExtensionConfig popupConfig; - if (wantParams.HasParam(WANT_PARAMS_UPDATE_POPUP_WIDTH) && - wantParams.HasParam(WANT_PARAMS_UPDATE_POPUP_HEIGHT)) { - Ace::PopupSize popupSize; - popupSize.width = wantParams.GetIntParam(WANT_PARAMS_UPDATE_POPUP_WIDTH, 0); - popupSize.height = wantParams.GetIntParam(WANT_PARAMS_UPDATE_POPUP_HEIGHT, 0); - popupConfig.targetSize = popupSize; - } - if (wantParams.HasParam(WANT_PARAMS_UPDATE_POPUP_PLACEMENT)) { - popupConfig.placement = - static_cast(wantParams.GetIntParam(WANT_PARAMS_UPDATE_POPUP_PLACEMENT, 0)); - } - Ace::CustomPopupUIExtensionConfig popupConfigToConvert; - AutoFillManagerUtil::ConvertToPopupUIExtensionConfig(autoFillCustomConfig_, popupConfigToConvert); - popupConfig.nodeId = sessionId_; - popupConfig.isFocusable = popupConfigToConvert.isFocusable; - popupConfig.isShowInSubWindow = popupConfigToConvert.isShowInSubWindow; - popupConfig.isEnableArrow = popupConfigToConvert.isEnableArrow; - auto updateResult = AutoFillManager::GetInstance().UpdateCustomPopupConfig(instanceId_, popupConfig); - if (updateResult != AutoFill::AUTO_FILL_SUCCESS) { - TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Update custom popup config failed."); - } + UpdateCustomPopupConfig(wantParams); } if (wantParams.GetIntParam(WANT_PARAMS_AUTO_FILL_EVENT_KEY, 0) == AutoFill::AUTO_FILL_CANCEL_TIME_OUT) { - AutoFillManager::GetInstance().RemoveEvent(eventId_); + AutoFillManager::GetInstance().RemoveEvent(callbackId_); } } +void AutoFillExtensionCallback::UpdateCustomPopupConfig(const AAFwk::WantParams &wantParams) +{ + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); + AutoFill::AutoFillCustomConfig autoFillCustomConfig = autoFillCustomConfig_; + if (wantParams.HasParam(WANT_PARAMS_UPDATE_POPUP_WIDTH) && + wantParams.HasParam(WANT_PARAMS_UPDATE_POPUP_HEIGHT)) { + AutoFill::PopupSize popupSize; + popupSize.width = wantParams.GetIntParam(WANT_PARAMS_UPDATE_POPUP_WIDTH, 0); + popupSize.height = wantParams.GetIntParam(WANT_PARAMS_UPDATE_POPUP_HEIGHT, 0); + autoFillCustomConfig.targetSize = popupSize; + } + if (wantParams.HasParam(WANT_PARAMS_UPDATE_POPUP_PLACEMENT)) { + autoFillCustomConfig.placement = + static_cast(wantParams.GetIntParam(WANT_PARAMS_UPDATE_POPUP_PLACEMENT, 0)); + } + { + std::lock_guard lock(requestCallbackMutex_); + if (fillCallback_ != nullptr) { + fillCallback_->onPopupConfigWillUpdate(autoFillCustomConfig); + } + } + Ace::CustomPopupUIExtensionConfig popupConfig; + AutoFillManagerUtil::ConvertToPopupUIExtensionConfig(autoFillCustomConfig, popupConfig); + auto uiContent = GetUIContent(); + if (uiContent == nullptr) { + TAG_LOGE(AAFwkTag::AUTOFILLMGR, "UIContent is nullptr."); + return; + } + uiContent->UpdateCustomPopupUIExtension(popupConfig); +} + void AutoFillExtensionCallback::onRemoteReady(const std::shared_ptr &modalUIExtensionProxy) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); if (modalUIExtensionProxy == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Proxy is nullptr."); return; } - AutoFillManager::GetInstance().SetAutoFillExtensionProxy(instanceId_, modalUIExtensionProxy); + SetModalUIExtensionProxy(modalUIExtensionProxy); } -#endif // SUPPORT_GRAPHICS + void AutoFillExtensionCallback::onDestroy() { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); if (isReloadInModal_) { isReloadInModal_ = false; return; @@ -172,7 +217,7 @@ void AutoFillExtensionCallback::onDestroy() if (isOnResult_ && autoFillWindowType_ == AutoFill::AutoFillWindowType::POPUP_WINDOW) { isOnResult_ = false; if (errCode_ == AutoFill::AUTO_FILL_SUCCESS) { - SendAutoFillSucess(want_); + SendAutoFillSuccess(want_); } else { auto resultCode = (errCode_ == AutoFill::AUTO_FILL_CANCEL) ? AutoFill::AUTO_FILL_CANCEL : AutoFill::AUTO_FILL_FAILED; @@ -180,19 +225,19 @@ void AutoFillExtensionCallback::onDestroy() } return; } + CloseUIExtension(); SendAutoFillFailed(AutoFill::AUTO_FILL_FAILED); -#ifdef SUPPORT_GRAPHICS - CloseModalUIExtension(); -#endif } void AutoFillExtensionCallback::SetFillRequestCallback(const std::shared_ptr &callback) { + std::lock_guard lock(requestCallbackMutex_); fillCallback_ = callback; } void AutoFillExtensionCallback::SetSaveRequestCallback(const std::shared_ptr &callback) { + std::lock_guard lock(requestCallbackMutex_); saveCallback_ = callback; } @@ -200,20 +245,20 @@ void AutoFillExtensionCallback::SetSessionId(int32_t sessionId) { sessionId_= sessionId; } -#ifdef SUPPORT_GRAPHICS + void AutoFillExtensionCallback::SetInstanceId(int32_t instanceId) { - instanceId_ = instanceId; + instanceId_.store(instanceId); } int32_t AutoFillExtensionCallback::GetInstanceId() { - return instanceId_; + return instanceId_.load(); } -#endif // SUPPORT_GRAPHICS -void AutoFillExtensionCallback::SetEventId(uint32_t eventId) + +Ace::UIContent* AutoFillExtensionCallback::GetUIContent() { - eventId_ = eventId; + return Ace::UIContent::GetUIContent(GetInstanceId()); } void AutoFillExtensionCallback::SetWindowType(const AutoFill::AutoFillWindowType &autoFillWindowType) @@ -221,6 +266,11 @@ void AutoFillExtensionCallback::SetWindowType(const AutoFill::AutoFillWindowType autoFillWindowType_ = autoFillWindowType; } +AutoFill::AutoFillWindowType AutoFillExtensionCallback::GetWindowType() const +{ + return autoFillWindowType_; +} + void AutoFillExtensionCallback::SetViewData(const AbilityBase::ViewData &viewData) { viewData_ = viewData; @@ -241,22 +291,54 @@ void AutoFillExtensionCallback::SetAutoFillType(const AbilityBase::AutoFillType autoFillType_ = autoFillType; } -AbilityBase::ViewData AutoFillExtensionCallback::GetViewData() -{ - return viewData_; -} - void AutoFillExtensionCallback::HandleTimeOut() { -#ifdef SUPPORT_GRAPHICS - CloseModalUIExtension(); -#endif + CloseUIExtension(); SendAutoFillFailed(AutoFill::AUTO_FILL_REQUEST_TIME_OUT); } -void AutoFillExtensionCallback::SendAutoFillSucess(const AAFwk::Want &want) +uint32_t AutoFillExtensionCallback::GenerateCallbackId() { - TAG_LOGI(AAFwkTag::AUTOFILLMGR, "Called."); + static std::atomic callbackId(0); + ++callbackId; + return callbackId.load(); +} + +uint32_t AutoFillExtensionCallback::GetCallbackId() const +{ + return callbackId_; +} + +void AutoFillExtensionCallback::SetModalUIExtensionProxy(const std::shared_ptr& proxy) +{ + std::lock_guard lock(proxyMutex_); + modalUIExtensionProxy_ = proxy; +} + +std::shared_ptr AutoFillExtensionCallback::GetModalUIExtensionProxy() +{ + std::lock_guard lock(proxyMutex_); + return modalUIExtensionProxy_; +} + +void AutoFillExtensionCallback::UpdateCustomPopupUIExtension(const AbilityBase::ViewData &viewData) +{ + auto modalUIExtensionProxy = GetModalUIExtensionProxy(); + if (modalUIExtensionProxy == nullptr) { + TAG_LOGE(AAFwkTag::AUTOFILLMGR, "UIExtensionProxy is nullptr."); + return; + } + AAFwk::WantParams wantParams; + wantParams.SetParam(WANT_PARAMS_AUTO_FILL_CMD_KEY, + AAFwk::Integer::Box(static_cast(AutoFill::AutoFillCommand::UPDATE))); + wantParams.SetParam(WANT_PARAMS_VIEW_DATA_KEY, AAFwk::String::Box(viewData.ToJsonString())); + modalUIExtensionProxy->SendData(wantParams); +} + +void AutoFillExtensionCallback::SendAutoFillSuccess(const AAFwk::Want &want) +{ + TAG_LOGI(AAFwkTag::AUTOFILLMGR, "called"); + std::lock_guard lock(requestCallbackMutex_); if (fillCallback_ != nullptr) { std::string dataStr = want.GetStringParam(WANT_PARAMS_VIEW_DATA_KEY); AbilityBase::ViewData viewData; @@ -269,11 +351,13 @@ void AutoFillExtensionCallback::SendAutoFillSucess(const AAFwk::Want &want) saveCallback_->OnSaveRequestSuccess(); saveCallback_ = nullptr; } + AutoFillManager::GetInstance().RemoveAutoFillExtensionCallback(callbackId_); } void AutoFillExtensionCallback::SendAutoFillFailed(int32_t errCode, const AAFwk::Want &want) { - TAG_LOGI(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGI(AAFwkTag::AUTOFILLMGR, "called"); + std::lock_guard lock(requestCallbackMutex_); if (fillCallback_ != nullptr) { std::string fillContent = want.GetStringParam(WANT_PARAMS_FILL_CONTENT); bool isPopup = (autoFillWindowType_ == AutoFill::AutoFillWindowType::POPUP_WINDOW); @@ -285,14 +369,20 @@ void AutoFillExtensionCallback::SendAutoFillFailed(int32_t errCode, const AAFwk: saveCallback_->OnSaveRequestFailed(); saveCallback_ = nullptr; } + AutoFillManager::GetInstance().RemoveAutoFillExtensionCallback(callbackId_); } -#ifdef SUPPORT_GRAPHICS -void AutoFillExtensionCallback::CloseModalUIExtension() + +void AutoFillExtensionCallback::CloseUIExtension() { - auto uiContent = Ace::UIContent::GetUIContent(instanceId_); - if (uiContent == nullptr) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "uiContent is nullptr."); - return; + Ace::UIContent* uiContent = nullptr; + { + std::lock_guard lock(closeMutex_); + uiContent = GetUIContent(); + if (uiContent == nullptr) { + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "uiContent is nullptr."); + return; + } + SetInstanceId(-1); } if (autoFillWindowType_ == AutoFill::AutoFillWindowType::POPUP_WINDOW) { @@ -300,8 +390,7 @@ void AutoFillExtensionCallback::CloseModalUIExtension() } else if (autoFillWindowType_ == AutoFill::AutoFillWindowType::MODAL_WINDOW) { uiContent->CloseModalUIExtension(sessionId_); } - AutoFillManager::GetInstance().RemoveAutoFillExtensionProxy(instanceId_); - instanceId_ = -1; + SetModalUIExtensionProxy(nullptr); } #endif // SUPPORT_GRAPHICS } // 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 3f46888869..0e698f61f6 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 @@ -19,20 +19,16 @@ #include "auto_fill_manager_util.h" #include "extension_ability_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" -#include "int_wrapper.h" #include "parameters.h" -#include "string_wrapper.h" namespace OHOS { namespace AbilityRuntime { namespace { +#ifdef SUPPORT_GRAPHICS const std::string WANT_PARAMS_EXTENSION_TYPE = "autoFill/password"; const std::string WANT_PARAMS_SMART_EXTENSION_TYPE = "autoFill/smart"; const std::string AUTO_FILL_START_POPUP_WINDOW = "persist.sys.abilityms.autofill.is_passwd_popup_window"; -#ifdef SUPPORT_GRAPHICS constexpr static char WANT_PARAMS_VIEW_DATA_KEY[] = "ohos.ability.params.viewData"; -constexpr static char WANT_PARAMS_CUSTOM_DATA_KEY[] = "ohos.ability.params.customData"; constexpr static char WANT_PARAMS_AUTO_FILL_CMD_KEY[] = "ohos.ability.params.autoFillCmd"; constexpr static char WANT_PARAMS_AUTO_FILL_POPUP_WINDOW_KEY[] = "ohos.ability.params.popupWindow"; constexpr static char WANT_PARAMS_EXTENSION_TYPE_KEY[] = "ability.want.params.uiExtensionType"; @@ -49,20 +45,21 @@ AutoFillManager &AutoFillManager::GetInstance() return instance; } -AutoFillManager::~AutoFillManager() +AutoFillManager::AutoFillManager() { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); - if (eventHandler_ != nullptr) { - eventHandler_.reset(); - } + auto runner = AppExecFwk::EventRunner::Create(AUTO_FILL_MANAGER_THREAD); + eventHandler_ = std::make_shared(runner); } -int32_t AutoFillManager::RequestAutoFill( - Ace::UIContent *uiContent, - const AutoFill::AutoFillRequest &request, - const std::shared_ptr &fillCallback, bool &isPopup) +AutoFillManager::~AutoFillManager() { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); +} + +int32_t AutoFillManager::RequestAutoFill(Ace::UIContent *uiContent, const AutoFill::AutoFillRequest &request, + const std::shared_ptr &fillCallback, AutoFill::AutoFillResult &result) +{ + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); if (uiContent == nullptr || fillCallback == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "UIContent or fillCallback is nullptr."); return AutoFill::AUTO_FILL_OBJECT_IS_NULL; @@ -72,28 +69,24 @@ int32_t AutoFillManager::RequestAutoFill( TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Auto fill type is invalid."); return AutoFill::AUTO_FILL_TYPE_INVALID; } - return HandleRequestExecuteInner(uiContent, request, fillCallback, nullptr, isPopup); + return HandleRequestExecuteInner(uiContent, request, fillCallback, nullptr, result); } -int32_t AutoFillManager::RequestAutoSave( - Ace::UIContent *uiContent, - const AutoFill::AutoFillRequest &request, - const std::shared_ptr &saveCallback) +int32_t AutoFillManager::RequestAutoSave(Ace::UIContent *uiContent, const AutoFill::AutoFillRequest &request, + const std::shared_ptr &saveCallback, AutoFill::AutoFillResult &result) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); if (uiContent == nullptr || saveCallback == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "UIContent or save callback is nullptr."); return AutoFill::AUTO_FILL_OBJECT_IS_NULL; } - bool isPopup = false; - return HandleRequestExecuteInner(uiContent, request, nullptr, saveCallback, isPopup); + return HandleRequestExecuteInner(uiContent, request, nullptr, saveCallback, result); } -int32_t AutoFillManager::HandleRequestExecuteInner( - Ace::UIContent *uiContent, - const AutoFill::AutoFillRequest &request, +int32_t AutoFillManager::HandleRequestExecuteInner(Ace::UIContent *uiContent, const AutoFill::AutoFillRequest &request, const std::shared_ptr &fillCallback, - const std::shared_ptr &saveCallback, bool &isPopup) + const std::shared_ptr &saveCallback, + AutoFill::AutoFillResult &result) { if (uiContent == nullptr || (fillCallback == nullptr && saveCallback == nullptr)) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "UIContent or fillCallback&saveCallback is nullptr."); @@ -103,10 +96,6 @@ int32_t AutoFillManager::HandleRequestExecuteInner( TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Previous request is not finished."); return AutoFill::AUTO_FILL_PREVIOUS_REQUEST_NOT_FINISHED; } - { - std::lock_guard lock(extensionCallbacksMutex_); - SetTimeOutEvent(++eventId_); - } auto extensionCallback = std::make_shared(); if (fillCallback != nullptr) { @@ -121,163 +110,79 @@ int32_t AutoFillManager::HandleRequestExecuteInner( AutoFill::AutoFillWindowType autoFillWindowType = AutoFill::AutoFillWindowType::MODAL_WINDOW; if (!ConvertAutoFillWindowType(request, isSmartAutoFill, autoFillWindowType)) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Convert auto fill type failed."); - RemoveEvent(eventId_); return AutoFill::AUTO_FILL_CREATE_MODULE_UI_EXTENSION_FAILED; } - isPopup = autoFillWindowType == AutoFill::AutoFillWindowType::POPUP_WINDOW ? true : false; + auto callbackId = extensionCallback->GetCallbackId(); + SetTimeOutEvent(callbackId); + result.isPopup = autoFillWindowType == AutoFill::AutoFillWindowType::POPUP_WINDOW ? true : false; auto sessionId = CreateAutoFillExtension(uiContent, request, callback, autoFillWindowType, isSmartAutoFill); if (sessionId == AUTO_FILL_UI_EXTENSION_SESSION_ID_INVALID) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Create ui extension is failed."); - RemoveEvent(eventId_); + RemoveEvent(callbackId); return AutoFill::AUTO_FILL_CREATE_MODULE_UI_EXTENSION_FAILED; } + result.autoFillSessionId = callbackId; extensionCallback->SetInstanceId(uiContent->GetInstanceId()); extensionCallback->SetSessionId(sessionId); - extensionCallback->SetEventId(eventId_); extensionCallback->SetViewData(request.viewData); extensionCallback->SetWindowType(autoFillWindowType); extensionCallback->SetExtensionType(isSmartAutoFill); extensionCallback->SetAutoFillType(request.autoFillType); extensionCallback->SetAutoFillRequestConfig(request.config); + TAG_LOGI(AAFwkTag::AUTOFILLMGR, "callbackId: %{public}u.", callbackId); std::lock_guard lock(extensionCallbacksMutex_); - extensionCallbacks_.emplace(eventId_, extensionCallback); + extensionCallbacks_.emplace(callbackId, extensionCallback); return AutoFill::AUTO_FILL_SUCCESS; } -void AutoFillManager::UpdateCustomPopupUIExtension(Ace::UIContent *uiContent, const AbilityBase::ViewData &viewData) +void AutoFillManager::UpdateCustomPopupUIExtension(uint32_t autoFillSessionId, const AbilityBase::ViewData &viewData) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); - if (uiContent == nullptr) { - TAG_LOGE(AAFwkTag::AUTOFILLMGR, "UIContent is nullptr."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); + auto extensionCallback = GetAutoFillExtensionCallback(autoFillSessionId); + if (extensionCallback == nullptr) { + TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Extension callback is nullptr."); return; } - - std::shared_ptr modalUIExtensionProxy; - { - std::lock_guard lock(modalProxyMapMutex_); - auto it = modalUIExtensionProxyMap_.find(uiContent->GetInstanceId()); - if (it == modalUIExtensionProxyMap_.end()) { - TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Content is not in map."); - return; - } - modalUIExtensionProxy = it->second; - } - - if (modalUIExtensionProxy != nullptr) { - AAFwk::WantParams wantParams; - wantParams.SetParam(WANT_PARAMS_AUTO_FILL_CMD_KEY, - AAFwk::Integer::Box(static_cast(AutoFill::AutoFillCommand::UPDATE))); - wantParams.SetParam(WANT_PARAMS_VIEW_DATA_KEY, AAFwk::String::Box(viewData.ToJsonString())); - modalUIExtensionProxy->SendData(wantParams); - } + extensionCallback->UpdateCustomPopupUIExtension(viewData); } -int32_t AutoFillManager::UpdateCustomPopupConfig(int32_t instanceId, - const Ace::CustomPopupUIExtensionConfig &popupConfig) +void AutoFillManager::CloseUIExtension(uint32_t autoFillSessionId) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); - auto uiContent = Ace::UIContent::GetUIContent(instanceId); - if (uiContent == nullptr) { - TAG_LOGE(AAFwkTag::AUTOFILLMGR, "UIContent is nullptr."); - return AutoFill::AUTO_FILL_OBJECT_IS_NULL; - } - uiContent->UpdateCustomPopupUIExtension(popupConfig); - return AutoFill::AUTO_FILL_SUCCESS; -} - -void AutoFillManager::SetAutoFillExtensionProxy(int32_t instanceId, - const std::shared_ptr &modalUIExtensionProxy) -{ - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); - if (modalUIExtensionProxy == nullptr) { - TAG_LOGE(AAFwkTag::AUTOFILLMGR, "proxy is nullptr."); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); + auto extensionCallback = GetAutoFillExtensionCallback(autoFillSessionId); + if (extensionCallback == nullptr) { + TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Extension callback is nullptr."); return; } - - std::lock_guard lock(modalProxyMapMutex_); - auto it = modalUIExtensionProxyMap_.find(instanceId); - if (it != modalUIExtensionProxyMap_.end()) { - modalUIExtensionProxyMap_.erase(it); - } - modalUIExtensionProxyMap_.emplace(instanceId, modalUIExtensionProxy); -} - -void AutoFillManager::RemoveAutoFillExtensionProxy(int32_t instanceId) -{ - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); - std::lock_guard lock(modalProxyMapMutex_); - auto it = modalUIExtensionProxyMap_.find(instanceId); - if (it != modalUIExtensionProxyMap_.end()) { - modalUIExtensionProxyMap_.erase(it); - } + extensionCallback->CloseUIExtension(); } void AutoFillManager::BindModalUIExtensionCallback( const std::shared_ptr &extensionCallback, Ace::ModalUIExtensionCallbacks &callback) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); - callback.onResult = std::bind( - &AutoFillExtensionCallback::OnResult, extensionCallback, std::placeholders::_1, std::placeholders::_2); - callback.onRelease = std::bind( - &AutoFillExtensionCallback::OnRelease, extensionCallback, std::placeholders::_1); - callback.onError = std::bind(&AutoFillExtensionCallback::OnError, - extensionCallback, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); - callback.onReceive = std::bind(&AutoFillExtensionCallback::OnReceive, extensionCallback, std::placeholders::_1); - callback.onRemoteReady = std::bind(&AutoFillExtensionCallback::onRemoteReady, - extensionCallback, std::placeholders::_1); - callback.onDestroy = std::bind(&AutoFillExtensionCallback::onDestroy, extensionCallback); -} + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); + callback.onResult = [extensionCallback](int32_t errCode, const AAFwk::Want& want) { + extensionCallback->OnResult(errCode, want); + }; -int32_t AutoFillManager::ReloadInModal(const AutoFill::ReloadInModalRequest &request) -{ - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); - auto uiContent = Ace::UIContent::GetUIContent(request.instanceId); - if (uiContent == nullptr) { - TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Content is nullptr."); - return AutoFill::AUTO_FILL_OBJECT_IS_NULL; - } + callback.onRelease = [extensionCallback](int arg1) { + extensionCallback->OnRelease(arg1); + }; - if (request.extensionCallback == nullptr) { - TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Extension callback is nullptr."); - return AutoFill::AUTO_FILL_OBJECT_IS_NULL; - } + callback.onError = [extensionCallback](int32_t errCode, const std::string& name, const std::string& message) { + extensionCallback->OnError(errCode, name, message); + }; - if (request.autoFillType == AbilityBase::AutoFillType::UNSPECIFIED) { - TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Auto fill type is invalid."); - return AutoFill::AUTO_FILL_TYPE_INVALID; - } + callback.onReceive = [extensionCallback](const AAFwk::WantParams &arg1) { + extensionCallback->OnReceive(arg1); + }; - { - std::lock_guard lock(extensionCallbacksMutex_); - SetTimeOutEvent(++eventId_); - } + callback.onRemoteReady = [extensionCallback](const std::shared_ptr &arg1) { + extensionCallback->onRemoteReady(arg1); + }; - AAFwk::Want want; - want.SetParam(WANT_PARAMS_AUTO_FILL_CMD_KEY, static_cast(AutoFill::AutoFillCommand::RELOAD_IN_MODAL)); - want.SetParam(WANT_PARAMS_CUSTOM_DATA_KEY, request.customData); - request.isSmartAutoFill ? want.SetParam(WANT_PARAMS_EXTENSION_TYPE_KEY, WANT_PARAMS_SMART_EXTENSION_TYPE) : - want.SetParam(WANT_PARAMS_EXTENSION_TYPE_KEY, WANT_PARAMS_EXTENSION_TYPE); - want.SetParam(WANT_PARAMS_AUTO_FILL_TYPE_KEY, static_cast(request.autoFillType)); - want.SetParam(WANT_PARAMS_VIEW_DATA_KEY, request.extensionCallback->GetViewData().ToJsonString()); - want.SetParam(WANT_PARAMS_AUTO_FILL_POPUP_WINDOW_KEY, false); - Ace::ModalUIExtensionCallbacks callback; - BindModalUIExtensionCallback(request.extensionCallback, callback); - Ace::ModalUIExtensionConfig config; - config.isAsyncModalBinding = true; - int32_t sessionId = AUTO_FILL_UI_EXTENSION_SESSION_ID_INVALID; - sessionId = uiContent->CreateModalUIExtension(want, callback, config); - if (sessionId == AUTO_FILL_UI_EXTENSION_SESSION_ID_INVALID) { - TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Create ui extension is failed."); - RemoveEvent(eventId_); - return AutoFill::AUTO_FILL_CREATE_MODULE_UI_EXTENSION_FAILED; - } - request.extensionCallback->SetSessionId(sessionId); - request.extensionCallback->SetEventId(eventId_); - request.extensionCallback->SetWindowType(AutoFill::AutoFillWindowType::MODAL_WINDOW); - std::lock_guard lock(extensionCallbacksMutex_); - extensionCallbacks_.emplace(eventId_, request.extensionCallback); - return AutoFill::AUTO_FILL_SUCCESS; + callback.onDestroy = [extensionCallback]() { extensionCallback->onDestroy(); }; } int32_t AutoFillManager::CreateAutoFillExtension(Ace::UIContent *uiContent, @@ -308,6 +213,7 @@ int32_t AutoFillManager::CreateAutoFillExtension(Ace::UIContent *uiContent, want.SetParam(WANT_PARAMS_AUTO_FILL_POPUP_WINDOW_KEY, false); Ace::ModalUIExtensionConfig config; config.isAsyncModalBinding = true; + config.doAfterAsyncModalBinding = std::move(request.doAfterAsyncModalBinding); sessionId = uiContent->CreateModalUIExtension(want, callback, config); } return sessionId; @@ -364,47 +270,66 @@ bool AutoFillManager::ConvertAutoFillWindowType(const AutoFill::AutoFillRequest void AutoFillManager::SetTimeOutEvent(uint32_t eventId) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Called."); - auto runner = AppExecFwk::EventRunner::Create(AUTO_FILL_MANAGER_THREAD); + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); if (eventHandler_ == nullptr) { - TAG_LOGD(AAFwkTag::AUTOFILLMGR, "Eventhandler is nullptr."); - eventHandler_ = std::make_shared(runner); + TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Eventhandler is nullptr."); + return; } eventHandler_->SendEvent(eventId, AUTO_FILL_REQUEST_TIME_OUT_VALUE); } void AutoFillManager::RemoveEvent(uint32_t eventId) { - TAG_LOGI(AAFwkTag::AUTOFILLMGR, "Called."); + TAG_LOGI(AAFwkTag::AUTOFILLMGR, "called"); if (eventHandler_ == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Eventhandler is nullptr."); return; } eventHandler_->RemoveEvent(eventId); - - std::lock_guard lock(extensionCallbacksMutex_); - auto ret = extensionCallbacks_.find(eventId); - if (ret != extensionCallbacks_.end()) { - extensionCallbacks_.erase(ret); - } } void AutoFillManager::HandleTimeOut(uint32_t eventId) { - TAG_LOGI(AAFwkTag::AUTOFILLMGR, "Called."); - std::lock_guard lock(extensionCallbacksMutex_); - auto ret = extensionCallbacks_.find(eventId); - if (ret == extensionCallbacks_.end()) { - TAG_LOGW(AAFwkTag::AUTOFILLMGR, "Event id is not find."); - return; - } - auto extensionCallback = ret->second.lock(); + TAG_LOGI(AAFwkTag::AUTOFILLMGR, "called"); + auto extensionCallback = GetAutoFillExtensionCallback(eventId); if (extensionCallback == nullptr) { TAG_LOGE(AAFwkTag::AUTOFILLMGR, "Extension callback is nullptr."); return; } extensionCallback->HandleTimeOut(); - extensionCallbacks_.erase(ret); +} + +bool AutoFillManager::IsNeedToCreatePopupWindow(const AbilityBase::AutoFillType &autoFillType) +{ + TAG_LOGD(AAFwkTag::AUTOFILLMGR, "called"); + if (autoFillType == AbilityBase::AutoFillType::PASSWORD || + autoFillType == AbilityBase::AutoFillType::USER_NAME || + autoFillType == AbilityBase::AutoFillType::NEW_PASSWORD) { + if (system::GetBoolParameter(AUTO_FILL_START_POPUP_WINDOW, false)) { + return true; + } else { + return false; + } + } + return true; +} + +std::shared_ptr AutoFillManager::GetAutoFillExtensionCallback(uint32_t callbackId) +{ + std::lock_guard lock(extensionCallbacksMutex_); + auto iter = extensionCallbacks_.find(callbackId); + if (iter == extensionCallbacks_.end()) { + TAG_LOGE(AAFwkTag::AUTOFILLMGR, "callback is not find. callbackId: %{public}u", callbackId); + return nullptr; + } + return iter->second; +} + +void AutoFillManager::RemoveAutoFillExtensionCallback(uint32_t callbackId) +{ + TAG_LOGI(AAFwkTag::AUTOFILLMGR, "callbackId: %{public}u", callbackId); + std::lock_guard lock(extensionCallbacksMutex_); + extensionCallbacks_.erase(callbackId); } bool AutoFillManager::IsPreviousRequestFinished(Ace::UIContent *uiContent) @@ -413,12 +338,13 @@ bool AutoFillManager::IsPreviousRequestFinished(Ace::UIContent *uiContent) return false; } std::lock_guard lock(extensionCallbacksMutex_); - for (auto& item: extensionCallbacks_) { - auto extensionCallback = item.second.lock(); + for (const auto& item: extensionCallbacks_) { + auto extensionCallback = item.second; if (extensionCallback == nullptr) { continue; } - if (extensionCallback->GetInstanceId() == uiContent->GetInstanceId()) { + if (extensionCallback->GetWindowType() == AutoFill::AutoFillWindowType::MODAL_WINDOW && + extensionCallback->GetInstanceId() == uiContent->GetInstanceId()) { return false; } } diff --git a/interfaces/inner_api/auto_fill_manager/src/auto_fill_manager_util.cpp b/interfaces/inner_api/auto_fill_manager/src/auto_fill_manager_util.cpp index 916c21ee60..a2df34cdb3 100644 --- a/interfaces/inner_api/auto_fill_manager/src/auto_fill_manager_util.cpp +++ b/interfaces/inner_api/auto_fill_manager/src/auto_fill_manager_util.cpp @@ -16,7 +16,6 @@ #include "auto_fill_manager_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/interfaces/inner_api/child_process_manager/include/child_process.h b/interfaces/inner_api/child_process_manager/include/child_process.h index 645468ebe4..432d7f8648 100644 --- a/interfaces/inner_api/child_process_manager/include/child_process.h +++ b/interfaces/inner_api/child_process_manager/include/child_process.h @@ -18,6 +18,7 @@ #include +#include "child_process_args.h" #include "child_process_start_info.h" #include "runtime.h" @@ -32,6 +33,7 @@ public: virtual bool Init(const std::shared_ptr &info); virtual void OnStart(); + virtual void OnStart(std::shared_ptr args); protected: std::shared_ptr processStartInfo_ = nullptr; 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 8e150048fe..b772208781 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 @@ -21,8 +21,10 @@ #include "app_mgr_interface.h" #include "bundle_info.h" +#include "child_process_args.h" #include "child_process_info.h" #include "child_process_manager_error_utils.h" +#include "child_process_options.h" #include "hap_module_info.h" #include "runtime.h" #include "iremote_object.h" @@ -31,46 +33,50 @@ namespace OHOS { namespace AbilityRuntime { class ChildProcessManager { public: - static ChildProcessManager &GetInstance() - { - static ChildProcessManager instance; - return instance; - } + static ChildProcessManager &GetInstance(); ~ChildProcessManager(); static void HandleSigChild(int32_t signo); bool IsChildProcess(); ChildProcessManagerErrorCode StartChildProcessBySelfFork(const std::string &srcEntry, pid_t &pid); ChildProcessManagerErrorCode StartChildProcessByAppSpawnFork(const std::string &srcEntry, pid_t &pid); + ChildProcessManagerErrorCode StartArkChildProcess(const std::string &srcEntry, pid_t &pid, int32_t childProcessType, + const AppExecFwk::ChildProcessArgs &args, const AppExecFwk::ChildProcessOptions &options); ChildProcessManagerErrorCode StartNativeChildProcessByAppSpawnFork( const std::string &libName, const sptr &callbackStub); bool GetBundleInfo(AppExecFwk::BundleInfo &bundleInfo); - bool GetHapModuleInfo(const AppExecFwk::BundleInfo &bundleInfo, AppExecFwk::HapModuleInfo &hapModuleInfo); + bool GetEntryHapModuleInfo(const AppExecFwk::BundleInfo &bundleInfo, AppExecFwk::HapModuleInfo &hapModuleInfo); + bool GetHapModuleInfo(const AppExecFwk::BundleInfo &bundleInfo, const std::string &moduleName, + 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); + std::unique_ptr &runtime, + std::shared_ptr args = nullptr); bool LoadNativeLib(const std::string &moduleName, 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); + void SetAppSpawnForkDebugOption(Runtime::DebugOption &debugOption, + std::shared_ptr processInfo); + std::string GetModuleNameFromSrcEntry(const std::string &srcEntry); private: ChildProcessManager(); - ChildProcessManagerErrorCode PreCheck(); + ChildProcessManagerErrorCode PreCheck(bool useNewErrorCode = false); ChildProcessManagerErrorCode PreCheckNativeProcess(); void RegisterSignal(); void HandleChildProcessBySelfFork(const std::string &srcEntry, const AppExecFwk::BundleInfo &bundleInfo); - bool hasChildProcessRecord(); + bool HasChildProcessRecord(); sptr GetAppMgr(); void MakeProcessName(const std::string &srcEntry); static bool signalRegistered_; bool isChildProcessBySelfFork_ = false; int32_t childProcessCount_ = 0; - + DISALLOW_COPY_AND_MOVE(ChildProcessManager); }; } // namespace AAFwk 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 93e28ccfdf..7c3daca832 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 @@ -35,6 +35,8 @@ enum class ChildProcessManagerErrorCode { ERR_MAX_NATIVE_CHILD_PROCESSES = 9, ERR_LIB_LOADING_FAILED = 10, ERR_CONNECTION_FAILED = 11, + ERR_UNSUPPORTED_START_MODE = 12, + ERR_MULTI_PROCESS_MODEL_DISABLED_NEW = 13, }; const std::map INTERNAL_ERR_CODE_MAP = { @@ -48,6 +50,9 @@ const std::map INTERNAL_ERR_CODE { ChildProcessManagerErrorCode::ERR_GET_BUNDLE_INFO_FAILED, AbilityErrorCode::ERROR_CODE_INNER }, { ChildProcessManagerErrorCode::ERR_GET_APP_MGR_FAILED, AbilityErrorCode::ERROR_CODE_INNER }, { ChildProcessManagerErrorCode::ERR_GET_APP_MGR_START_PROCESS_FAILED, AbilityErrorCode::ERROR_CODE_INNER }, + { ChildProcessManagerErrorCode::ERR_UNSUPPORTED_START_MODE, AbilityErrorCode::ERROR_CODE_INVALID_PARAM }, + { ChildProcessManagerErrorCode::ERR_MULTI_PROCESS_MODEL_DISABLED_NEW, + AbilityErrorCode::ERROR_CODE_CAPABILITY_NOT_SUPPORT }, }; class ChildProcessManagerErrorUtil { diff --git a/interfaces/inner_api/child_process_manager/include/js_child_process.h b/interfaces/inner_api/child_process_manager/include/js_child_process.h index 7239a01094..7e1032abe6 100644 --- a/interfaces/inner_api/child_process_manager/include/js_child_process.h +++ b/interfaces/inner_api/child_process_manager/include/js_child_process.h @@ -31,6 +31,7 @@ public: bool Init(const std::shared_ptr &info) override; void OnStart() override; + void OnStart(std::shared_ptr args) override; private: napi_value CallObjectMethod(const char *name, napi_value const *argv = nullptr, size_t argc = 0); diff --git a/interfaces/inner_api/connectionobs_manager/include/connection_observer_stub.h b/interfaces/inner_api/connectionobs_manager/include/connection_observer_stub.h index 05304d6dde..d183286dfe 100644 --- a/interfaces/inner_api/connectionobs_manager/include/connection_observer_stub.h +++ b/interfaces/inner_api/connectionobs_manager/include/connection_observer_stub.h @@ -42,9 +42,6 @@ private: int OnExtensionDisconnectedInner(MessageParcel &data, MessageParcel &reply); int OnDlpAbilityOpenedInner(MessageParcel &data, MessageParcel &reply); int OnDlpAbilityClosedInner(MessageParcel &data, MessageParcel &reply); - - using ConnectionObserverFunc = int (ConnectionObserverStub::*)(MessageParcel &data, MessageParcel &reply); - std::vector vecMemberFunc_; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/interfaces/inner_api/connectionobs_manager/src/connection_data.cpp b/interfaces/inner_api/connectionobs_manager/src/connection_data.cpp index cbc8d3364e..5f45bdda86 100644 --- a/interfaces/inner_api/connectionobs_manager/src/connection_data.cpp +++ b/interfaces/inner_api/connectionobs_manager/src/connection_data.cpp @@ -16,7 +16,6 @@ #include "connection_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "string_ex.h" namespace OHOS { diff --git a/interfaces/inner_api/connectionobs_manager/src/connection_observer_client.cpp b/interfaces/inner_api/connectionobs_manager/src/connection_observer_client.cpp index 110d191ca5..74bd40edaf 100644 --- a/interfaces/inner_api/connectionobs_manager/src/connection_observer_client.cpp +++ b/interfaces/inner_api/connectionobs_manager/src/connection_observer_client.cpp @@ -18,7 +18,6 @@ #include "connection_observer_client_impl.h" #include "connection_observer_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/interfaces/inner_api/connectionobs_manager/src/connection_observer_client_impl.cpp b/interfaces/inner_api/connectionobs_manager/src/connection_observer_client_impl.cpp index 861ca95c41..93c3dc4f5f 100644 --- a/interfaces/inner_api/connectionobs_manager/src/connection_observer_client_impl.cpp +++ b/interfaces/inner_api/connectionobs_manager/src/connection_observer_client_impl.cpp @@ -18,7 +18,6 @@ #include "connection_observer_errors.h" #include "connection_observer_stub_impl.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iservice_registry.h" #include "system_ability_definition.h" diff --git a/interfaces/inner_api/connectionobs_manager/src/connection_observer_proxy.cpp b/interfaces/inner_api/connectionobs_manager/src/connection_observer_proxy.cpp index c9e1207b7c..a68a8639a8 100644 --- a/interfaces/inner_api/connectionobs_manager/src/connection_observer_proxy.cpp +++ b/interfaces/inner_api/connectionobs_manager/src/connection_observer_proxy.cpp @@ -16,7 +16,6 @@ #include "connection_observer_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" diff --git a/interfaces/inner_api/connectionobs_manager/src/connection_observer_stub.cpp b/interfaces/inner_api/connectionobs_manager/src/connection_observer_stub.cpp index d4bc349895..62a4dcb850 100644 --- a/interfaces/inner_api/connectionobs_manager/src/connection_observer_stub.cpp +++ b/interfaces/inner_api/connectionobs_manager/src/connection_observer_stub.cpp @@ -16,20 +16,12 @@ #include "connection_observer_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" namespace OHOS { namespace AbilityRuntime { -ConnectionObserverStub::ConnectionObserverStub() -{ - vecMemberFunc_.resize(IConnectionObserver::CMD_MAX); - vecMemberFunc_[ON_EXTENSION_CONNECTED] = &ConnectionObserverStub::OnExtensionConnectedInner; - vecMemberFunc_[ON_EXTENSION_DISCONNECTED] = &ConnectionObserverStub::OnExtensionDisconnectedInner; - vecMemberFunc_[ON_DLP_ABILITY_OPENED] = &ConnectionObserverStub::OnDlpAbilityOpenedInner; - vecMemberFunc_[ON_DLP_ABILITY_CLOSED] = &ConnectionObserverStub::OnDlpAbilityClosedInner; -} +ConnectionObserverStub::ConnectionObserverStub() {} int ConnectionObserverStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -40,12 +32,18 @@ int ConnectionObserverStub::OnRemoteRequest( TAG_LOGI(AAFwkTag::CONNECTION, "ConnectionObserverStub Local descriptor is not equal to remote."); return ERR_INVALID_STATE; } - if (code < IConnectionObserver::CMD_MAX && code >= 0) { - auto memberFunc = vecMemberFunc_[code]; - return (this->*memberFunc)(data, reply); + switch (code) { + case ON_EXTENSION_CONNECTED: + return OnExtensionConnectedInner(data, reply); + case ON_EXTENSION_DISCONNECTED: + return OnExtensionDisconnectedInner(data, reply); + case ON_DLP_ABILITY_OPENED: + return OnDlpAbilityOpenedInner(data, reply); + case ON_DLP_ABILITY_CLOSED: + return OnDlpAbilityClosedInner(data, reply); + } } - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/interfaces/inner_api/connectionobs_manager/src/dlp_state_data.cpp b/interfaces/inner_api/connectionobs_manager/src/dlp_state_data.cpp index ba6e5054ac..3d8fd338e1 100644 --- a/interfaces/inner_api/connectionobs_manager/src/dlp_state_data.cpp +++ b/interfaces/inner_api/connectionobs_manager/src/dlp_state_data.cpp @@ -16,7 +16,6 @@ #include "dlp_state_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "string_ex.h" namespace OHOS { diff --git a/interfaces/inner_api/connectionobs_manager/src/service_proxy_adapter.cpp b/interfaces/inner_api/connectionobs_manager/src/service_proxy_adapter.cpp index f7f1a7cc6e..c89b9619e7 100644 --- a/interfaces/inner_api/connectionobs_manager/src/service_proxy_adapter.cpp +++ b/interfaces/inner_api/connectionobs_manager/src/service_proxy_adapter.cpp @@ -17,7 +17,6 @@ #include "connection_observer_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/interfaces/inner_api/dataobs_manager/include/dataobs_mgr_client.h b/interfaces/inner_api/dataobs_manager/include/dataobs_mgr_client.h index ac4b7280aa..d6789dee21 100644 --- a/interfaces/inner_api/dataobs_manager/include/dataobs_mgr_client.h +++ b/interfaces/inner_api/dataobs_manager/include/dataobs_mgr_client.h @@ -112,7 +112,7 @@ private: * * @return Returns SUCCESS on success, others on failure. */ - Status Connect(); + std::pair> GetObsMgr(); void ResetService(); void OnRemoteDied(); diff --git a/interfaces/inner_api/deps_wrapper/src/os_account_manager_wrapper.cpp b/interfaces/inner_api/deps_wrapper/src/os_account_manager_wrapper.cpp index 16e82409f2..c38dfe5d17 100644 --- a/interfaces/inner_api/deps_wrapper/src/os_account_manager_wrapper.cpp +++ b/interfaces/inner_api/deps_wrapper/src/os_account_manager_wrapper.cpp @@ -16,7 +16,6 @@ #include "os_account_manager_wrapper.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #ifdef OS_ACCOUNT_PART_ENABLED #include "os_account_manager.h" #endif // OS_ACCOUNT_PART_ENABLED diff --git a/interfaces/inner_api/deps_wrapper/src/sa_mgr_client.cpp b/interfaces/inner_api/deps_wrapper/src/sa_mgr_client.cpp index 4b92a912c6..961a8a996a 100644 --- a/interfaces/inner_api/deps_wrapper/src/sa_mgr_client.cpp +++ b/interfaces/inner_api/deps_wrapper/src/sa_mgr_client.cpp @@ -16,7 +16,6 @@ #include "sa_mgr_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" 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 1c621573e5..aaf07eb4fe 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 @@ -59,7 +59,6 @@ enum { 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/error_utils/src/ability_runtime_error_util.cpp b/interfaces/inner_api/error_utils/src/ability_runtime_error_util.cpp index 4c09f0a694..6e28350599 100644 --- a/interfaces/inner_api/error_utils/src/ability_runtime_error_util.cpp +++ b/interfaces/inner_api/error_utils/src/ability_runtime_error_util.cpp @@ -18,7 +18,6 @@ #include #include "errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi/native_api.h" #include "runtime.h" @@ -150,8 +149,6 @@ const std::map ERROR_MSG_MAP = { "Restart too frequently. Try again at least 10s later." }, { ERR_ABILITY_RUNTIME_EXTERNAL_NOT_SYSTEM_HSP, "The input bundleName and moduleName is not system HSP" }, - { ERR_ABILITY_RUNTIME_SET_SUPPORTED_PROCESS_CACHE_AGAIN, - "The supported process cache state cannot be set more than once" }, }; } diff --git a/interfaces/inner_api/extension_manager/src/extension_manager_client.cpp b/interfaces/inner_api/extension_manager/src/extension_manager_client.cpp index 992a8b037f..90f385b802 100755 --- a/interfaces/inner_api/extension_manager/src/extension_manager_client.cpp +++ b/interfaces/inner_api/extension_manager/src/extension_manager_client.cpp @@ -19,7 +19,6 @@ #include "extension_ability_info.h" #include "extension_manager_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "iservice_registry.h" #include "system_ability_definition.h" diff --git a/interfaces/inner_api/extension_manager/src/extension_manager_proxy.cpp b/interfaces/inner_api/extension_manager/src/extension_manager_proxy.cpp index 8cf41b31be..880fd680b6 100755 --- a/interfaces/inner_api/extension_manager/src/extension_manager_proxy.cpp +++ b/interfaces/inner_api/extension_manager/src/extension_manager_proxy.cpp @@ -18,7 +18,6 @@ #include "ability_manager_errors.h" #include "ability_manager_ipc_interface_code.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "message_parcel.h" #include "want.h" diff --git a/interfaces/inner_api/insight_intent/insight_intent_context/js_insight_intent_context.h b/interfaces/inner_api/insight_intent/insight_intent_context/js_insight_intent_context.h index 7fbcd0e40f..b573067883 100644 --- a/interfaces/inner_api/insight_intent/insight_intent_context/js_insight_intent_context.h +++ b/interfaces/inner_api/insight_intent/insight_intent_context/js_insight_intent_context.h @@ -69,7 +69,7 @@ napi_value CreateJsInsightIntentContext(napi_env env, const std::shared_ptr #include "runtime.h" +#include "cj_envsetup.h" using AppLibPathMap = std::map>; using AppLibPathVec = std::vector; @@ -33,6 +34,10 @@ class CJRuntime : public Runtime { public: static std::unique_ptr Create(const Options& options); static void SetAppLibPath(const AppLibPathMap& appLibPaths); + static bool IsCJAbility(const std::string& info); + static void SetAsanVersion(); + static void SetTsanVersion(); + static void SetHWAsanVersion(); ~CJRuntime() override = default; Language GetLanguage() const override @@ -61,7 +66,7 @@ public: void ForceFullGC() override {}; void ForceFullGC(uint32_t tid) override {}; void DumpHeapSnapshot(uint32_t tid, bool isFullGC) override {}; - void DumpCpuProfile(bool isPrivate) override {}; + void DumpCpuProfile() override {}; void AllowCrossThreadExecution() override {}; void GetHeapPrepare() override {}; void RegisterUncaughtExceptionHandler(const CJUncaughtExceptionInfo& uncaughtExceptionInfo); diff --git a/interfaces/inner_api/runtime/include/js_runtime.h b/interfaces/inner_api/runtime/include/js_runtime.h index ceabd8f2b4..eadf52b2b1 100644 --- a/interfaces/inner_api/runtime/include/js_runtime.h +++ b/interfaces/inner_api/runtime/include/js_runtime.h @@ -81,7 +81,7 @@ public: void PostSyncTask(const std::function& task, const std::string& name); void RemoveTask(const std::string& name); void DumpHeapSnapshot(bool isPrivate) override; - void DumpCpuProfile(bool isPrivate) override; + void DumpCpuProfile() override; void DestroyHeapProfiler() override; void ForceFullGC() override; void ForceFullGC(uint32_t tid) override; @@ -98,6 +98,7 @@ public: void PreloadSystemModule(const std::string& moduleName) override; void StartDebugMode(const DebugOption debugOption) override; + void DebuggerConnectionHandler(bool isDebugApp, bool isStartWithDebug); void StopDebugMode(); bool LoadRepairPatch(const std::string& hqfFile, const std::string& hapPath) override; bool UnLoadRepairPatch(const std::string& hqfFile) override; @@ -121,6 +122,7 @@ public: void FreeNativeReference(std::unique_ptr reference); void FreeNativeReference(std::shared_ptr&& reference); void StartProfiler(const DebugOption debugOption) override; + void DebuggerConnectionManager(bool isDebugApp, bool isStartWithDebug, const DebugOption dOption); void ReloadFormComponent(); // Reload ArkTS-Card component void DoCleanWorkAfterStageCleaned() override; diff --git a/interfaces/inner_api/runtime/include/js_runtime_utils.h b/interfaces/inner_api/runtime/include/js_runtime_utils.h index e586f1bff0..47ab469ad6 100644 --- a/interfaces/inner_api/runtime/include/js_runtime_utils.h +++ b/interfaces/inner_api/runtime/include/js_runtime_utils.h @@ -302,6 +302,8 @@ std::unique_ptr CreateAsyncTaskWithLastParam(napi_env env, napi_v std::unique_ptr CreateAsyncTaskWithLastParam(napi_env env, napi_value lastParam, std::nullptr_t, std::nullptr_t, napi_value* result); + +std::unique_ptr CreateEmptyAsyncTask(napi_env env, napi_value lastParam, napi_value* result); } // namespace AbilityRuntime } // namespace OHOS #endif // OHOS_ABILITY_RUNTIME_JS_RUNTIME_UTILS_H diff --git a/interfaces/inner_api/runtime/include/js_utils.h b/interfaces/inner_api/runtime/include/js_utils.h index 190b6abf24..b1bcd2d491 100644 --- a/interfaces/inner_api/runtime/include/js_utils.h +++ b/interfaces/inner_api/runtime/include/js_utils.h @@ -17,7 +17,6 @@ #define OHOS_ABILITY_RUNTIME_JS_UTILS_H #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/interfaces/inner_api/runtime/include/runtime.h b/interfaces/inner_api/runtime/include/runtime.h index 8d0f13be06..3ef3114825 100644 --- a/interfaces/inner_api/runtime/include/runtime.h +++ b/interfaces/inner_api/runtime/include/runtime.h @@ -55,6 +55,7 @@ public: bool isTestFramework = false; bool jitEnabled = false; bool isMultiThread = false; + bool isErrorInfoEnhance = false; int32_t uid = -1; // ArkTsCard start bool isUnique = false; @@ -85,7 +86,7 @@ public: virtual void StartDebugMode(const DebugOption debugOption) = 0; virtual void DumpHeapSnapshot(bool isPrivate) = 0; - virtual void DumpCpuProfile(bool isPrivate) = 0; + virtual void DumpCpuProfile() = 0; virtual void DestroyHeapProfiler() = 0; virtual void ForceFullGC() = 0; virtual void ForceFullGC(uint32_t tid) = 0; diff --git a/interfaces/inner_api/session_handler/BUILD.gn b/interfaces/inner_api/session_handler/BUILD.gn index 6a950db1f7..c40fe59d36 100644 --- a/interfaces/inner_api/session_handler/BUILD.gn +++ b/interfaces/inner_api/session_handler/BUILD.gn @@ -32,6 +32,15 @@ config("session_handler_config") { } ohos_shared_library("session_handler") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + cfi_vcall_icall_only = true + debug = false + } sources = [ "src/session_handler_proxy.cpp", "src/session_handler_stub.cpp", diff --git a/interfaces/inner_api/session_handler/include/session_handler_stub.h b/interfaces/inner_api/session_handler/include/session_handler_stub.h index c73a4a3487..0073e3035c 100644 --- a/interfaces/inner_api/session_handler/include/session_handler_stub.h +++ b/interfaces/inner_api/session_handler/include/session_handler_stub.h @@ -33,8 +33,6 @@ public: private: DISALLOW_COPY_AND_MOVE(SessionHandlerStub); virtual int32_t OnSessionMovedToFrontInner(MessageParcel &data, MessageParcel &reply); - using StubFunc = int (SessionHandlerStub::*)(MessageParcel &data, MessageParcel &reply); - std::vector vecMemberFunc_; }; } // namespace AAFwk } // namespace OHOS diff --git a/interfaces/inner_api/session_handler/src/session_handler_proxy.cpp b/interfaces/inner_api/session_handler/src/session_handler_proxy.cpp index 13d958b998..9857c305ae 100644 --- a/interfaces/inner_api/session_handler/src/session_handler_proxy.cpp +++ b/interfaces/inner_api/session_handler/src/session_handler_proxy.cpp @@ -15,7 +15,6 @@ #include "session_handler_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "message_parcel.h" namespace OHOS { diff --git a/interfaces/inner_api/session_handler/src/session_handler_stub.cpp b/interfaces/inner_api/session_handler/src/session_handler_stub.cpp index e4a677af00..2f6a1cf3a5 100644 --- a/interfaces/inner_api/session_handler/src/session_handler_stub.cpp +++ b/interfaces/inner_api/session_handler/src/session_handler_stub.cpp @@ -15,16 +15,11 @@ #include "session_handler_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "message_parcel.h" namespace OHOS { namespace AAFwk { -SessionHandlerStub::SessionHandlerStub() -{ - vecMemberFunc_.resize(ISessionHandler::CODE_MAX); - vecMemberFunc_[ON_SESSION_MOVED_TO_FRONT] = &SessionHandlerStub::OnSessionMovedToFrontInner; -} +SessionHandlerStub::SessionHandlerStub() {} int32_t SessionHandlerStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -37,8 +32,9 @@ int32_t SessionHandlerStub::OnRemoteRequest( } if (code < ISessionHandler::CODE_MAX) { - auto memberFunc = vecMemberFunc_[code]; - return (this->*memberFunc)(data, reply); + if (code == ON_SESSION_MOVED_TO_FRONT) { + return OnSessionMovedToFrontInner(data, reply); + } } return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/interfaces/inner_api/uri_permission/BUILD.gn b/interfaces/inner_api/uri_permission/BUILD.gn index c33934caf2..d262798e91 100644 --- a/interfaces/inner_api/uri_permission/BUILD.gn +++ b/interfaces/inner_api/uri_permission/BUILD.gn @@ -40,6 +40,7 @@ ohos_shared_library("uri_permission_mgr") { external_deps = [ "ability_base:zuri", + "access_token:libaccesstoken_sdk", "c_utils:utils", "hilog:libhilog", "ipc:ipc_core", 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 9ec01e60ce..babfaa6d1d 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 @@ -16,7 +16,7 @@ #ifndef OHOS_ABILITY_RUNTIME_URI_PERMISSION_MANAGER_INTERFACE_H #define OHOS_ABILITY_RUNTIME_URI_PERMISSION_MANAGER_INTERFACE_H #include -#include "base/security/access_token/interfaces/innerkits/accesstoken/include/access_token.h" +#include "access_token.h" #include "iremote_broker.h" #include "uri.h" diff --git a/interfaces/inner_api/uri_permission/src/uri_permission_load_callback.cpp b/interfaces/inner_api/uri_permission/src/uri_permission_load_callback.cpp index 55a3edd5f6..a67615cb88 100644 --- a/interfaces/inner_api/uri_permission/src/uri_permission_load_callback.cpp +++ b/interfaces/inner_api/uri_permission/src/uri_permission_load_callback.cpp @@ -14,7 +14,6 @@ */ #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "uri_permission_load_callback.h" #include "uri_permission_manager_client.h" #include "system_ability_definition.h" 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 0f402cfb6f..667702e692 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 @@ -17,7 +17,6 @@ #include "ability_manager_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "system_ability_definition.h" 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 0e4b548a63..52a94db145 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 @@ -17,7 +17,6 @@ #include "ability_manager_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parcel.h" namespace OHOS { 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 43787ac1f1..03a693e722 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 @@ -17,7 +17,6 @@ #include "ability_manager_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/interfaces/inner_api/wantagent/BUILD.gn b/interfaces/inner_api/wantagent/BUILD.gn index c1ccfcf73f..05f3013152 100644 --- a/interfaces/inner_api/wantagent/BUILD.gn +++ b/interfaces/inner_api/wantagent/BUILD.gn @@ -38,6 +38,7 @@ config("wantagent_innerkits_public_config") { "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_path}/interfaces/kits/native/appkit", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", ] } @@ -75,7 +76,6 @@ ohos_shared_library("wantagent_innerkits") { external_deps = [ "ability_base:session_info", "ability_base:want", - "bundle_framework:appexecfwk_core", "c_utils:utils", "hilog:libhilog", "hitrace:hitrace_meter", diff --git a/interfaces/inner_api/wantagent/src/pending_want.cpp b/interfaces/inner_api/wantagent/src/pending_want.cpp index 2ddae5cf3c..45257e0967 100644 --- a/interfaces/inner_api/wantagent/src/pending_want.cpp +++ b/interfaces/inner_api/wantagent/src/pending_want.cpp @@ -17,7 +17,6 @@ #include "ability_runtime_error_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "want_agent_client.h" #include "want_agent_log_wrapper.h" diff --git a/interfaces/inner_api/wantagent/src/want_agent_client.cpp b/interfaces/inner_api/wantagent/src/want_agent_client.cpp index 35eae4bb08..bce06fc2f4 100644 --- a/interfaces/inner_api/wantagent/src/want_agent_client.cpp +++ b/interfaces/inner_api/wantagent/src/want_agent_client.cpp @@ -20,7 +20,6 @@ #include "ability_manager_interface.h" #include "ability_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" diff --git a/interfaces/inner_api/wantagent/src/want_agent_helper.cpp b/interfaces/inner_api/wantagent/src/want_agent_helper.cpp index fa8da769b1..725bea34eb 100644 --- a/interfaces/inner_api/wantagent/src/want_agent_helper.cpp +++ b/interfaces/inner_api/wantagent/src/want_agent_helper.cpp @@ -17,7 +17,6 @@ #include "ability_runtime_error_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "want_params_wrapper.h" #include "pending_want.h" diff --git a/interfaces/kits/native/ability/ability_runtime/ability_context.h b/interfaces/kits/native/ability/ability_runtime/ability_context.h index 4a05e9daab..462c3b2118 100644 --- a/interfaces/kits/native/ability/ability_runtime/ability_context.h +++ b/interfaces/kits/native/ability/ability_runtime/ability_context.h @@ -16,13 +16,13 @@ #ifndef OHOS_ABILITY_RUNTIME_ABILITY_CONTEXT_H #define OHOS_ABILITY_RUNTIME_ABILITY_CONTEXT_H -#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/context.h" - #include "ability_connect_callback.h" #include "ability_info.h" #include "ability_lifecycle_observer_interface.h" #include "caller_callback.h" #include "configuration.h" +#include "context.h" +#include "free_install_observer_interface.h" #include "iability_callback.h" #include "js_ui_extension_callback.h" #include "mission_info.h" @@ -159,6 +159,8 @@ public: virtual ErrCode StartServiceExtensionAbility(const AAFwk::Want &want, int32_t accountId = -1) = 0; + virtual ErrCode StartUIServiceExtensionAbility(const AAFwk::Want &want, int32_t accountId = -1) = 0; + virtual ErrCode StopServiceExtensionAbility(const AAFwk::Want& want, int32_t accountId = -1) = 0; virtual ErrCode TerminateAbilityWithResult(const AAFwk::Want &want, int resultCode) = 0; @@ -169,9 +171,13 @@ public: virtual ErrCode RequestModalUIExtension(const AAFwk::Want& want) = 0; + virtual ErrCode OpenLink(const AAFwk::Want& want, int requestCode) = 0; + virtual ErrCode OpenAtomicService(AAFwk::Want& want, const AAFwk::StartOptions &options, int requestCode, RuntimeTask &&task) = 0; + virtual ErrCode AddFreeInstallObserver(const sptr &observer) = 0; + virtual ErrCode ChangeAbilityVisibility(bool isShow) { return 0; } /** @@ -388,6 +394,7 @@ public: virtual bool IsTerminating() = 0; virtual void SetTerminating(bool state) = 0; virtual void InsertResultCallbackTask(int requestCode, RuntimeTask&& task) = 0; + virtual void RemoveResultCallbackTask(int requestCode) = 0; using SelfType = AbilityContext; static const size_t CONTEXT_TYPE_ID; diff --git a/interfaces/kits/native/ability/ability_runtime/ability_context_impl.h b/interfaces/kits/native/ability/ability_runtime/ability_context_impl.h index 4046a9e512..bf81193294 100644 --- a/interfaces/kits/native/ability/ability_runtime/ability_context_impl.h +++ b/interfaces/kits/native/ability/ability_runtime/ability_context_impl.h @@ -76,6 +76,7 @@ public: const AAFwk::StartOptions &startOptions, int requestCode, RuntimeTask &&task) override; ErrCode StartAbilityForResult(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions, int requestCode, RuntimeTask &&task) override; + ErrCode StartUIServiceExtensionAbility(const AAFwk::Want &want, int32_t accountId = -1) override; ErrCode StartServiceExtensionAbility(const Want &want, int32_t accountId = -1) override; ErrCode StopServiceExtensionAbility(const Want& want, int32_t accountId = -1) override; ErrCode TerminateAbilityWithResult(const AAFwk::Want &want, int resultCode) override; @@ -186,7 +187,7 @@ public: bool IsTerminating() override { - return isTerminating_; + return isTerminating_.load(); } void SetWeakSessionToken(const wptr& sessionToken) override; @@ -195,7 +196,7 @@ public: void SetTerminating(bool state) override { - isTerminating_ = state; + isTerminating_.store(state); } ErrCode RequestDialogService(napi_env env, AAFwk::Want &want, RequestDialogResultTask &&task) override; @@ -221,6 +222,9 @@ public: ErrCode ChangeAbilityVisibility(bool isShow) override; + ErrCode OpenLink(const AAFwk::Want& want, int requestCode) override; + ErrCode AddFreeInstallObserver(const sptr &observer) override; + ErrCode OpenAtomicService(AAFwk::Want& want, const AAFwk::StartOptions &options, int requestCode, RuntimeTask &&task) override; @@ -230,6 +234,8 @@ public: void InsertResultCallbackTask(int requestCode, RuntimeTask&& task) override; + void RemoveResultCallbackTask(int requestCode) override; + void SetRestoreEnabled(bool enabled) override; bool GetRestoreEnabled() override; @@ -292,7 +298,7 @@ private: std::shared_ptr config_ = nullptr; std::shared_ptr localCallContainer_ = nullptr; std::weak_ptr abilityCallback_; - bool isTerminating_ = false; + std::atomic isTerminating_ = false; int32_t missionId_ = -1; int32_t abilityRecordId_ = 0; std::mutex sessionTokenMutex_; diff --git a/interfaces/kits/native/ability/ability_runtime/connection_manager.h b/interfaces/kits/native/ability/ability_runtime/connection_manager.h index c4b718543d..3cec15ac7e 100644 --- a/interfaces/kits/native/ability/ability_runtime/connection_manager.h +++ b/interfaces/kits/native/ability/ability_runtime/connection_manager.h @@ -36,6 +36,7 @@ struct ConnectionInfo { sptr abilityConnection; int32_t userid; + void* uiServiceExtProxy = nullptr; ConnectionInfo(const sptr &connectCaller, const AAFwk::Operation &connectReceiver, const sptr &abilityConnection, int32_t accountId = -1) : connectCaller(connectCaller), @@ -43,11 +44,19 @@ struct ConnectionInfo { { } + void SetUIServiceExtProxyPtr(void* proxyPtr) + { + uiServiceExtProxy = proxyPtr; + } + inline bool operator < (const ConnectionInfo &that) const { if (userid < that.userid) { return true; } + if (uiServiceExtProxy < that.uiServiceExtProxy) { + return true; + } if (connectCaller < that.connectCaller) { return true; } @@ -167,6 +176,7 @@ private: bool IsConnectCallerEqual(const sptr &connectCaller, const sptr &connectCallerOther); bool IsConnectReceiverEqual(AAFwk::Operation &connectReceiver, const AppExecFwk::ElementName &connectReceiverOther); + void* GetUIServiceExtProxyPtr(const AAFwk::Want& want); bool MatchConnection( const sptr& connectCaller, const AAFwk::Want& connectReceiver, int32_t accountId, const std::map>>::value_type& connection); diff --git a/interfaces/kits/native/ability/native/ability.h b/interfaces/kits/native/ability/native/ability.h index e4abd69812..9cdab9c946 100644 --- a/interfaces/kits/native/ability/native/ability.h +++ b/interfaces/kits/native/ability/native/ability.h @@ -26,18 +26,19 @@ #include "ability_lifecycle_executor.h" #include "ability_lifecycle_interface.h" #include "ability_transaction_callback_info.h" -#include "appexecfwk_errors.h" #include "configuration.h" #include "context.h" #include "continuation_handler.h" #include "continuation_state.h" #include "dummy_notification_request.h" +#include "fa_ability_context.h" +#include "free_install_observer_interface.h" #include "iability_callback.h" +#include "want_agent.h" +#include "appexecfwk_errors.h" #include "iremote_object.h" #include "pac_map.h" #include "want.h" -#include "want_agent.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/ability/ability_runtime/ability_context.h" #ifdef SUPPORT_SCREEN #include "ability_window.h" @@ -45,8 +46,8 @@ #include "form_constants.h" #include "form_provider_info.h" #include "form_state_info.h" -#include "foundation/multimodalinput/input/interfaces/native/innerkits/event/include/key_event.h" -#include "foundation/multimodalinput/input/interfaces/native/innerkits/event/include/pointer_event.h" +#include "key_event.h" +#include "pointer_event.h" #include "session_info.h" #include "window_option.h" #include "window_scene.h" @@ -177,6 +178,7 @@ public: using AbilityContext::StartAbility; ErrCode StartAbility(const Want &want, AbilityStartSetting abilityStartSetting); + ErrCode AddFreeInstallObserver(const sptr observer); /** * @brief A Page or Service ability uses this method to start a specific ability. The system locates the target * ability from installed abilities based on the value of the want parameter and then starts it. You can specify 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 d17d0afba0..c26ead4973 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 @@ -177,7 +177,8 @@ enum class AbilityErrorCode { // target bundle not exist. ERROR_CODE_TARGET_BUNDLE_NOT_EXIST = 16300005, - ERROR_CODE_SET_SUPPORTED_PROCESS_CACHE_AGAIN = 16300006, + // target free install task does not exist. + ERROR_CODE_FREE_INSTALL_TASK_NOT_EXIST = 16300007, ERROR_CODE_BUNDLE_NAME_INVALID = 18500001, }; diff --git a/interfaces/kits/native/ability/native/ability_impl.h b/interfaces/kits/native/ability/native/ability_impl.h index 5430a2497d..a4b4b11ccf 100644 --- a/interfaces/kits/native/ability/native/ability_impl.h +++ b/interfaces/kits/native/ability/native/ability_impl.h @@ -25,7 +25,7 @@ #include "ability_manager_client.h" #include "ability_manager_interface.h" #ifdef SUPPORT_GRAPHICS -#include "foundation/multimodalinput/input/interfaces/native/innerkits/event/include/i_input_event_consumer.h" +#include "i_input_event_consumer.h" #endif namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/kits/native/ability/native/ability_runtime/cj_ability_context_object.h b/interfaces/kits/native/ability/native/ability_runtime/cj_ability_context_object.h index a88ab07357..a6da542726 100644 --- a/interfaces/kits/native/ability/native/ability_runtime/cj_ability_context_object.h +++ b/interfaces/kits/native/ability/native/ability_runtime/cj_ability_context_object.h @@ -18,7 +18,6 @@ #include "cj_want_ffi.h" #include "cj_ability_context_broker.h" -#include "hilog_wrapper.h" extern "C" { diff --git a/interfaces/kits/native/ability/native/ability_runtime/cj_ui_ability.h b/interfaces/kits/native/ability/native/ability_runtime/cj_ui_ability.h index a39e9aca83..bd98194a58 100644 --- a/interfaces/kits/native/ability/native/ability_runtime/cj_ui_ability.h +++ b/interfaces/kits/native/ability/native/ability_runtime/cj_ui_ability.h @@ -227,12 +227,6 @@ public: */ bool OnPrepareTerminate() override; - /** - * @brief Get CJWindow Stage - * @return Returns the current CJWindowStage - */ - std::shared_ptr GetCJWindowStage(); - /** * @brief Get CJRuntime * @return Returns the current CJRuntime @@ -274,7 +268,7 @@ private: const std::shared_ptr &executeParam, InsightIntentExecutorInfo& executeInfo); - std::shared_ptr cjWindowStage_; + sptr cjWindowStage_; int32_t windowMode_ = 0; #endif #endif diff --git a/interfaces/kits/native/ability/native/ability_runtime/js_ability_context.h b/interfaces/kits/native/ability/native/ability_runtime/js_ability_context.h index 3dffb32d12..70982f8d5f 100644 --- a/interfaces/kits/native/ability/native/ability_runtime/js_ability_context.h +++ b/interfaces/kits/native/ability/native/ability_runtime/js_ability_context.h @@ -21,7 +21,7 @@ #include #include "ability_connect_callback.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/ability/ability_runtime/ability_context.h" +#include "ability_context.h" #include "js_free_install_observer.h" #include "js_runtime.h" #include "event_handler.h" @@ -32,6 +32,7 @@ namespace OHOS { namespace AbilityRuntime { struct NapiCallbackInfo; class JsEmbeddableUIAbilityContext; +class JSUIServiceExtAbilityConnection; class JsAbilityContext final { public: explicit JsAbilityContext(const std::shared_ptr& context) : context_(context) {} @@ -68,7 +69,9 @@ public: static napi_value OpenAtomicService(napi_env env, napi_callback_info info); static napi_value MoveAbilityToBackground(napi_env env, napi_callback_info info); static napi_value SetRestoreEnabled(napi_env env, napi_callback_info info); - + static napi_value StartUIServiceExtension(napi_env env, napi_callback_info info); + static napi_value ConnectUIServiceExtension(napi_env env, napi_callback_info info); + static napi_value DisconnectUIServiceExtension(napi_env env, napi_callback_info info); static void ConfigurationUpdated(napi_env env, std::shared_ptr &jsContext, const std::shared_ptr &config); @@ -92,6 +95,8 @@ private: const std::weak_ptr& abilityContext, const std::shared_ptr &callback); napi_value OnStartAbility(napi_env env, NapiCallbackInfo& info, bool isStartRecent = false); napi_value OnOpenLink(napi_env env, NapiCallbackInfo& info); + napi_value OnOpenLinkInner(napi_env env, const AAFwk::Want& want, + int requestCode, const std::string& startTime, const std::string& url); napi_value OnStartAbilityAsCaller(napi_env env, NapiCallbackInfo& info); napi_value OnStartRecentAbility(napi_env env, NapiCallbackInfo& info); napi_value OnStartAbilityWithAccount(napi_env env, NapiCallbackInfo& info); @@ -124,6 +129,15 @@ private: napi_value OnSetRestoreEnabled(napi_env env, NapiCallbackInfo& info); bool CreateOpenLinkTask(const napi_env &env, const napi_value &lastParam, AAFwk::Want &want, int &requestCode); + napi_value OnStartUIServiceExtension(napi_env env, NapiCallbackInfo& info); + void RemoveOpenLinkTask(int requestCode); + bool UnwrapConnectUIServiceExtensionParam(napi_env env, NapiCallbackInfo& info, AAFwk::Want& want); + bool CheckConnectAlreadyExist(napi_env env, AAFwk::Want& want, napi_value callback, napi_value& result); + napi_value OnConnectUIServiceExtension(napi_env env, NapiCallbackInfo& info); + static void DoConnectUIServiceExtension(napi_env env, + std::weak_ptr weakContext, sptr connection, + std::shared_ptr uasyncTaskShared, const AAFwk::Want& want); + napi_value OnDisconnectUIServiceExtension(napi_env env, NapiCallbackInfo& info); static bool UnWrapWant(napi_env env, napi_value argv, AAFwk::Want& want); static napi_value WrapWant(napi_env env, const AAFwk::Want& want); @@ -132,7 +146,7 @@ private: void InheritWindowMode(AAFwk::Want &want); static napi_value WrapRequestDialogResult(napi_env env, int32_t resultCode, const AAFwk::Want& want); void AddFreeInstallObserver(napi_env env, const AAFwk::Want &want, napi_value callback, napi_value* result, - bool isAbilityResult = false); + bool isAbilityResult = false, bool isOpenLink = false); bool CheckStartAbilityByCallParams(napi_env env, NapiCallbackInfo& info, AAFwk::Want &want, int32_t &userId, napi_value &lastParam); @@ -152,21 +166,26 @@ class JSAbilityConnection : public AbilityConnectCallback { public: explicit JSAbilityConnection(napi_env env); ~JSAbilityConnection(); + void ReleaseNativeReference(NativeReference* ref); void OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; - void HandleOnAbilityConnectDone( + virtual void HandleOnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode); - void HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode); + virtual void HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode); void SetJsConnectionObject(napi_value jsConnectionObject); + std::unique_ptr& GetJsConnectionObject() { return jsConnectionObject_; } void RemoveConnectionObject(); void CallJsFailed(int32_t errorCode); + napi_value CallObjectMethod(const char* name, napi_value const *argv, size_t argc); void SetConnectionId(int64_t id); + int64_t GetConnectionId() { return connectionId_; } +protected: + napi_env env_; + int64_t connectionId_ = -1; + std::unique_ptr jsConnectionObject_ = nullptr; private: napi_value ConvertElement(const AppExecFwk::ElementName &element); - napi_env env_; - std::unique_ptr jsConnectionObject_ = nullptr; - int64_t connectionId_ = -1; }; struct ConnectionKey { diff --git a/interfaces/kits/native/ability/native/ability_runtime/js_caller_complex.h b/interfaces/kits/native/ability/native/ability_runtime/js_caller_complex.h index 00770bd070..3ee04a43e1 100644 --- a/interfaces/kits/native/ability/native/ability_runtime/js_caller_complex.h +++ b/interfaces/kits/native/ability/native/ability_runtime/js_caller_complex.h @@ -19,8 +19,8 @@ #include #include +#include "ability_context.h" #include "iremote_object.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/ability/ability_runtime/ability_context.h" namespace OHOS { namespace AbilityRuntime { diff --git a/interfaces/kits/native/ability/native/ability_runtime/js_uiservice_ability_connection.h b/interfaces/kits/native/ability/native/ability_runtime/js_uiservice_ability_connection.h new file mode 100644 index 0000000000..0b49e513c0 --- /dev/null +++ b/interfaces/kits/native/ability/native/ability_runtime/js_uiservice_ability_connection.h @@ -0,0 +1,63 @@ +/* + * 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_JS_UISERVICE_ABILITY_CONNECTION_H +#define OHOS_ABILITY_RUNTIME_JS_UISERVICE_ABILITY_CONNECTION_H + +#include "js_ability_context.h" + +namespace OHOS { +namespace AbilityRuntime { + +namespace UIServiceConnection { +void RemoveUIServiceAbilityConnection(int64_t connectId); +int64_t InsertUIServiceAbilityConnection(sptr connection, const AAFwk::Want &want); +void FindUIServiceAbilityConnection(const int64_t& connectId, AAFwk::Want& want, + sptr& connection); +void FindUIServiceAbilityConnection(napi_env env, AAFwk::Want& want, napi_value callback, + sptr& connection); +} + +class UIAbilityServiceHostStubImpl; +class JSUIServiceExtAbilityConnection : public JSAbilityConnection { +public: + JSUIServiceExtAbilityConnection(napi_env env); + ~JSUIServiceExtAbilityConnection(); + virtual void HandleOnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + virtual void HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + sptr GetServiceHostStub() { return serviceHostStub_; } + void SetProxyObject(napi_value proxy); + napi_value GetProxyObject(); + void SetNapiAsyncTask(std::shared_ptr& task); + void AddDuplicatedPendingTask(std::unique_ptr& task); + void ResolveDuplicatedPendingTask(napi_env env, napi_value proxy); + void RejectDuplicatedPendingTask(napi_env env, napi_value error); + int32_t OnSendData(OHOS::AAFwk::WantParams &data); + void HandleOnSendData(const OHOS::AAFwk::WantParams &data); + void CallJsOnDisconnect(); + static bool IsJsCallbackObjectEquals(napi_env env, std::unique_ptr& callback, napi_value value); + +private: + sptr serviceHostStub_; + std::shared_ptr napiAsyncTask_; + std::unique_ptr serviceProxyObject_; + std::vector> duplicatedPendingTaskList_; +}; + +} +} +#endif + diff --git a/interfaces/kits/native/ability/native/ability_runtime/ui_ability_servicehost_stub_impl.h b/interfaces/kits/native/ability/native/ability_runtime/ui_ability_servicehost_stub_impl.h new file mode 100644 index 0000000000..7238bb7600 --- /dev/null +++ b/interfaces/kits/native/ability/native/ability_runtime/ui_ability_servicehost_stub_impl.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_UI_ABILITY_SERVICEHOST_STUB_IMPL_H +#define OHOS_ABILITY_RUNTIME_UI_ABILITY_SERVICEHOST_STUB_IMPL_H + +#include "js_ability_context.h" +#include "ui_service_host_stub.h" + +namespace OHOS { +namespace AbilityRuntime { + +class UIAbilityServiceHostStubImpl : public AAFwk::UIServiceHostStub { +public: + UIAbilityServiceHostStubImpl(wptr conn); + ~UIAbilityServiceHostStubImpl() = default; + virtual int32_t SendData(OHOS::AAFwk::WantParams &data) override; + +protected: + wptr conn_; +}; + +} +} +#endif diff --git a/interfaces/kits/native/ability/native/ability_window.h b/interfaces/kits/native/ability/native/ability_window.h index 9dcd6bb31e..15e0ba8375 100644 --- a/interfaces/kits/native/ability/native/ability_window.h +++ b/interfaces/kits/native/ability/native/ability_window.h @@ -18,12 +18,13 @@ #include +#include "ability_context.h" + #include "nocopyable.h" #include "session_info.h" -#include "window.h" #include "window_option.h" #include "window_scene.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/ability/ability_runtime/ability_context.h" +#include "window.h" #ifdef SUPPORT_SCREEN #include "pixel_map.h" diff --git a/interfaces/kits/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_stub.h b/interfaces/kits/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_stub.h index 8b656dab25..4b03edff6b 100644 --- a/interfaces/kits/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_stub.h +++ b/interfaces/kits/native/ability/native/continuation/distributed/reverse_continuation_scheduler_primary_stub.h @@ -43,10 +43,6 @@ private: int ContinuationBackInner(MessageParcel &data, MessageParcel &reply); static const std::string DESCRIPTOR; - -private: - using RequestFuncType = int (ReverseContinuationSchedulerPrimaryStub::*)(MessageParcel &data, MessageParcel &reply); - std::map requestFuncMap_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/kits/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica_stub.h b/interfaces/kits/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica_stub.h index bb2f50bcb0..8b3819cfb6 100644 --- a/interfaces/kits/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica_stub.h +++ b/interfaces/kits/native/ability/native/continuation/distributed/reverse_continuation_scheduler_replica_stub.h @@ -38,10 +38,6 @@ public: int32_t NotifyReverseResultInner(MessageParcel &data, MessageParcel &reply); private: - using ReverseContinuationSchedulerReplicaFunc = int32_t (ReverseContinuationSchedulerReplicaStub::*)( - MessageParcel &data, MessageParcel &reply); - std::map continuationFuncMap_; - DISALLOW_COPY_AND_MOVE(ReverseContinuationSchedulerReplicaStub); }; } // namespace AppExecFwk diff --git a/interfaces/kits/native/ability/native/continuation/kits/ability_continuation_interface.h b/interfaces/kits/native/ability/native/continuation/kits/ability_continuation_interface.h index dd36e54c56..4e7472203e 100644 --- a/interfaces/kits/native/ability/native/continuation/kits/ability_continuation_interface.h +++ b/interfaces/kits/native/ability/native/continuation/kits/ability_continuation_interface.h @@ -27,9 +27,9 @@ public: virtual bool OnStartContinuation() = 0; - virtual bool OnSaveData(WantParams &saveData) = 0; + virtual bool OnSaveData(AAFwk::WantParams &saveData) = 0; - virtual bool OnRestoreData(WantParams &restoreData) = 0; + virtual bool OnRestoreData(AAFwk::WantParams &restoreData) = 0; virtual void OnCompleteContinuation(int result) = 0; diff --git a/interfaces/kits/native/ability/native/continuation/remote_register_service/connect_callback_stub.h b/interfaces/kits/native/ability/native/continuation/remote_register_service/connect_callback_stub.h index e2affc27ae..49934edaea 100644 --- a/interfaces/kits/native/ability/native/continuation/remote_register_service/connect_callback_stub.h +++ b/interfaces/kits/native/ability/native/continuation/remote_register_service/connect_callback_stub.h @@ -40,8 +40,6 @@ public: private: int ConnectInner(MessageParcel &data, MessageParcel &reply); int DisconnectInner(MessageParcel &data, MessageParcel &reply); - using ConnectCallbackFunc = int (ConnectCallbackStub::*)(MessageParcel &data, MessageParcel &reply); - std::map memberFuncMap_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/kits/native/ability/native/continuation/remote_register_service/continuation_connector.h b/interfaces/kits/native/ability/native/continuation/remote_register_service/continuation_connector.h index d0e41e34f0..9daf5644ec 100644 --- a/interfaces/kits/native/ability/native/continuation/remote_register_service/continuation_connector.h +++ b/interfaces/kits/native/ability/native/continuation/remote_register_service/continuation_connector.h @@ -22,15 +22,15 @@ #include #include -#include "iremote_broker.h" -#include "element_name.h" -#include "refbase.h" -#include "context.h" -#include "extra_params.h" -#include "continuation_request.h" #include "ability_connect_callback_stub.h" +#include "continuation_request.h" #include "continuation/kits/continuation_device_callback_interface.h" #include "continuation/remote_register_service_interface.h" +#include "fa_context.h" +#include "element_name.h" +#include "extra_params.h" +#include "iremote_broker.h" +#include "refbase.h" namespace OHOS { namespace AppExecFwk { diff --git a/interfaces/kits/native/ability/native/continuation/remote_register_service/remote_register_service_stub.h b/interfaces/kits/native/ability/native/continuation/remote_register_service/remote_register_service_stub.h index 44aee57faf..3e502f1f34 100644 --- a/interfaces/kits/native/ability/native/continuation/remote_register_service/remote_register_service_stub.h +++ b/interfaces/kits/native/ability/native/continuation/remote_register_service/remote_register_service_stub.h @@ -36,9 +36,6 @@ private: int UnregisterInner(MessageParcel &data, MessageParcel &reply); int UpdateConnectStatusInner(MessageParcel &data, MessageParcel &reply); int ShowDeviceListInner(MessageParcel &data, MessageParcel &reply); - - using RequestRegisterFuncType = int (RemoteRegisterServiceStub::*)(MessageParcel &data, MessageParcel &reply); - std::map requestFuncMap_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/kits/native/ability/native/data_ability_helper_impl.h b/interfaces/kits/native/ability/native/data_ability_helper_impl.h index 9dd6e50327..183a8e890c 100644 --- a/interfaces/kits/native/ability/native/data_ability_helper_impl.h +++ b/interfaces/kits/native/ability/native/data_ability_helper_impl.h @@ -20,8 +20,8 @@ #include #include -#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/app/context.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/context.h" +#include "context.h" +#include "fa_context.h" #include "uri.h" using Uri = OHOS::Uri; diff --git a/services/abilitymgr/include/distributed_client.h b/interfaces/kits/native/ability/native/distributed_ability_runtime/distributed_client.h similarity index 98% rename from services/abilitymgr/include/distributed_client.h rename to interfaces/kits/native/ability/native/distributed_ability_runtime/distributed_client.h index 7cf41d5531..9f021d360e 100644 --- a/services/abilitymgr/include/distributed_client.h +++ b/interfaces/kits/native/ability/native/distributed_ability_runtime/distributed_client.h @@ -39,7 +39,8 @@ public: int32_t ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo, const sptr &callBack); int32_t StartContinuation(const OHOS::AAFwk::Want& want, int32_t missionId, int32_t callerUid, int32_t status, uint32_t accessToken); - int32_t NotifyCompleteContinuation(const std::u16string &devId, int32_t sessionId, bool isSuccess); + int32_t NotifyCompleteContinuation(const std::u16string &devId, int32_t sessionId, bool isSuccess, + const std::string &callerBundleName); int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const sptr& connect); int32_t DisconnectRemoteAbility(const sptr& connect, int32_t callerUid, uint32_t accessToken); int32_t StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag); diff --git a/services/abilitymgr/include/distributed_parcel_helper.h b/interfaces/kits/native/ability/native/distributed_ability_runtime/distributed_parcel_helper.h similarity index 99% rename from services/abilitymgr/include/distributed_parcel_helper.h rename to interfaces/kits/native/ability/native/distributed_ability_runtime/distributed_parcel_helper.h index e935e456ad..f50e7e31eb 100644 --- a/services/abilitymgr/include/distributed_parcel_helper.h +++ b/interfaces/kits/native/ability/native/distributed_ability_runtime/distributed_parcel_helper.h @@ -19,7 +19,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/interfaces/kits/native/ability/native/extension.h b/interfaces/kits/native/ability/native/extension.h index 259eab9926..d2ab9ecb48 100644 --- a/interfaces/kits/native/ability/native/extension.h +++ b/interfaces/kits/native/ability/native/extension.h @@ -22,7 +22,7 @@ #include "napi_remote_object.h" #include "iremote_object.h" #include "session_info.h" -#include "foundation/window/window_manager/interfaces/innerkits/wm/window.h" +#include "wm/window.h" #include "launch_param.h" #include "ui_extension_window_command.h" #include "want.h" diff --git a/interfaces/kits/native/ability/native/extension_base.inl b/interfaces/kits/native/ability/native/extension_base.inl index 440300077b..887e16e7e5 100644 --- a/interfaces/kits/native/ability/native/extension_base.inl +++ b/interfaces/kits/native/ability/native/extension_base.inl @@ -13,8 +13,8 @@ * limitations under the License. */ -#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/context.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/application_context.h" +#include "application_context.h" +#include "context.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" @@ -39,7 +39,6 @@ std::shared_ptr ExtensionBase::CreateAndInitContext(const std::shared_ptr< { TAG_LOGD(AAFwkTag::EXT, "begin init base"); std::shared_ptr context = std::make_shared(); - context->SetToken(token); auto appContext = Context::GetApplicationContext(); if (appContext == nullptr) { TAG_LOGE(AAFwkTag::EXT, "ServiceExtension::CreateAndInitContext appContext is nullptr"); @@ -48,6 +47,7 @@ std::shared_ptr ExtensionBase::CreateAndInitContext(const std::shared_ptr< context->SetApplicationInfo(appContext->GetApplicationInfo()); context->SetResourceManager(appContext->GetResourceManager()); context->SetParentContext(appContext); + context->SetToken(token); if (record == nullptr) { TAG_LOGE(AAFwkTag::EXT, "ServiceExtension::CreateAndInitContext record is nullptr"); return context; diff --git a/interfaces/kits/native/ability/native/extension_impl.h b/interfaces/kits/native/ability/native/extension_impl.h index 56d52ff761..e1cae8cf56 100644 --- a/interfaces/kits/native/ability/native/extension_impl.h +++ b/interfaces/kits/native/ability/native/extension_impl.h @@ -38,7 +38,7 @@ namespace AbilityRuntime { class ExtensionImpl : public std::enable_shared_from_this { public: ExtensionImpl() = default; - virtual ~ExtensionImpl() = default; + virtual ~ExtensionImpl(); /** * @brief Init the object. @@ -205,6 +205,8 @@ protected: private: inline bool UIExtensionAbilityExecuteInsightIntent(const Want &want); + void PrintTokenInfo() const; + int lifecycleState_ = AAFwk::ABILITY_STATE_INITIAL; sptr token_; std::shared_ptr extension_; diff --git a/interfaces/kits/native/ability/native/ability_context.h b/interfaces/kits/native/ability/native/fa_ability_context.h similarity index 98% rename from interfaces/kits/native/ability/native/ability_context.h rename to interfaces/kits/native/ability/native/fa_ability_context.h index f7aa1a264a..2e122c22ba 100644 --- a/interfaces/kits/native/ability/native/ability_context.h +++ b/interfaces/kits/native/ability/native/fa_ability_context.h @@ -61,6 +61,8 @@ public: */ ErrCode StartAbility(const Want &want, int requestCode, const AbilityStartSetting &abilityStartSetting) override; + ErrCode AddFreeInstallObserver(const sptr &observer); + /** * @brief Destroys the current ability. * diff --git a/interfaces/kits/native/ability/native/free_install_observer_proxy.h b/interfaces/kits/native/ability/native/free_install_observer_proxy.h index 122a23d27c..3475866f6c 100644 --- a/interfaces/kits/native/ability/native/free_install_observer_proxy.h +++ b/interfaces/kits/native/ability/native/free_install_observer_proxy.h @@ -36,6 +36,17 @@ public: */ virtual void OnInstallFinished(const std::string &bundleName, const std::string &abilityName, const std::string &startTime, const int &resultCode) override; + + /** + * OnInstallFinishedByUrl, return free install result. + * + * @param startTime Free install start request time. + * @param url Free install url. + * @param resultCode The result of this free install. + */ + virtual void OnInstallFinishedByUrl(const std::string &startTime, const std::string &url, + const int &resultCode) override; + private: bool WriteInterfaceToken(MessageParcel &data); static inline BrokerDelegator delegator_; diff --git a/interfaces/kits/native/ability/native/free_install_observer_stub.h b/interfaces/kits/native/ability/native/free_install_observer_stub.h index d1a4c6701a..b23c34bf1f 100644 --- a/interfaces/kits/native/ability/native/free_install_observer_stub.h +++ b/interfaces/kits/native/ability/native/free_install_observer_stub.h @@ -35,6 +35,7 @@ public: private: DISALLOW_COPY_AND_MOVE(FreeInstallObserverStub); int OnInstallFinishedInner(MessageParcel &data, MessageParcel &reply); + int OnInstallFinishedByUrlInner(MessageParcel &data, MessageParcel &reply); }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/interfaces/kits/native/ability/native/js_free_install_observer.h b/interfaces/kits/native/ability/native/js_free_install_observer.h index 38d6c87c90..7219209651 100644 --- a/interfaces/kits/native/ability/native/js_free_install_observer.h +++ b/interfaces/kits/native/ability/native/js_free_install_observer.h @@ -30,6 +30,7 @@ struct JsFreeInstallObserverObject { std::string bundleName; std::string abilityName; std::string startTime; + std::string url; napi_deferred deferred; napi_ref callback; bool isAbilityResult = false; @@ -51,6 +52,16 @@ public: void OnInstallFinished(const std::string &bundleName, const std::string &abilityName, const std::string &startTime, const int &resultCode) override; + /** + * OnInstallFinishedByUrl, return free install result. + * + * @param startTime Free install start request time. + * @param url Free install url. + * @param resultCode The result of this free install. + */ + void OnInstallFinishedByUrl(const std::string &startTime, const std::string &url, + const int &resultCode) override; + /** * OnInstallFinished, return free install result. * @@ -74,6 +85,17 @@ public: void AddJsObserverObject(const std::string &bundleName, const std::string &abilityName, const std::string &startTime, napi_value jsObserverObject, napi_value* result, bool isAbilityResult = false); + /** + * @brief Use for context to add an callback into the observer. + * + * @param startTime The startTime that want requested. + * @param url Free install url. + * @param jsObserverObject The js object instance. + * @param result the promise to return. + */ + void AddJsObserverObject(const std::string &startTime, const std::string &url, + napi_value jsObserverObject, napi_value* result, bool isAbilityResult = false); + private: void CallPromise(napi_deferred deferred, int32_t resultCode); void CallPromise(napi_deferred deferred, napi_value abilityResult); @@ -81,6 +103,10 @@ private: void CallCallback(napi_ref callback, napi_value abilityResult); void HandleOnInstallFinished(const std::string &bundleName, const std::string &abilityName, const std::string &startTime, const int &resultCode); + void HandleOnInstallFinishedByUrl(const std::string &startTime, const std::string &url, + const int &resultCode); + void AddJsObserverCommon(JsFreeInstallObserverObject &object, + napi_value jsObserverObject, napi_value* result, bool isAbilityResult); napi_env env_; std::vector jsObserverObjectList_; }; diff --git a/interfaces/kits/native/ability/native/new_ability_impl.h b/interfaces/kits/native/ability/native/new_ability_impl.h index 2d49ddfdfc..d445102f2a 100644 --- a/interfaces/kits/native/ability/native/new_ability_impl.h +++ b/interfaces/kits/native/ability/native/new_ability_impl.h @@ -65,6 +65,8 @@ public: * */ bool AbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState); + + bool AbilityTransactionForeground(const Want &want, const AAFwk::LifeCycleStateInfo &targetState); /** * @description: Provide operating system ShareData information to the observer diff --git a/interfaces/kits/native/ability/native/page_ability_impl.h b/interfaces/kits/native/ability/native/page_ability_impl.h index fd5bdd215e..f2f57fb98f 100644 --- a/interfaces/kits/native/ability/native/page_ability_impl.h +++ b/interfaces/kits/native/ability/native/page_ability_impl.h @@ -60,6 +60,8 @@ public: */ bool AbilityTransaction(const Want &want, const AAFwk::LifeCycleStateInfo &targetState); + void AbilityTransactionForeground(const Want &want, const AAFwk::LifeCycleStateInfo &targetState); + /** * @brief Execution the KeyDown callback of the ability * @param keyEvent Indicates the key-down event. diff --git a/interfaces/kits/native/ability/native/photo_editor_extension_ability/photo_editor_extension_context.h b/interfaces/kits/native/ability/native/photo_editor_extension_ability/photo_editor_extension_context.h index a419223802..ef680eb18c 100644 --- a/interfaces/kits/native/ability/native/photo_editor_extension_ability/photo_editor_extension_context.h +++ b/interfaces/kits/native/ability/native/photo_editor_extension_ability/photo_editor_extension_context.h @@ -28,16 +28,16 @@ enum class PhotoEditorErrorCode { ERROR_OK = 0, // param error - ERROR_CODE_PARAM_ERROR = 1500000001, + ERROR_CODE_PARAM_ERROR = 401, // internal error - ERROR_CODE_INTERNAL_ERROR = 1500000002, + ERROR_CODE_INTERNAL_ERROR = 29600001, // image input error - ERROR_CODE_IMAGE_INPUT_ERROR = 1500000003, + ERROR_CODE_IMAGE_INPUT_ERROR = 29600002, // image too big - ERROR_CODE_IMAGE_TOO_BIG_ERROR = 1500000004 + ERROR_CODE_IMAGE_TOO_BIG_ERROR = 29600003 }; class PhotoEditorExtensionContext : public UIExtensionContext { diff --git a/interfaces/kits/native/ability/native/ui_ability.h b/interfaces/kits/native/ability/native/ui_ability.h index 78c299eeac..11a2ffe903 100644 --- a/interfaces/kits/native/ability/native/ui_ability.h +++ b/interfaces/kits/native/ability/native/ui_ability.h @@ -25,10 +25,11 @@ #include "configuration.h" #include "context.h" #include "continuation_handler_stage.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/ability/ability_runtime/ability_context.h" +#include "fa_ability_context.h" #include "iability_callback.h" -#include "want.h" #include "resource_config_helper.h" +#include "want.h" + #ifdef SUPPORT_SCREEN #include "display_manager.h" #include "session_info.h" @@ -590,6 +591,7 @@ protected: }; void OnDisplayMove(Rosen::DisplayId from, Rosen::DisplayId to); + void UpdateConfiguration(Rosen::DisplayId to, float density, int32_t width, int32_t height); virtual void DoOnForeground(const AAFwk::Want &want); sptr GetWindowOption(const AAFwk::Want &want); virtual void ContinuationRestore(const AAFwk::Want &want); diff --git a/interfaces/kits/native/ability/native/ui_ability_impl.h b/interfaces/kits/native/ability/native/ui_ability_impl.h index c08d3577d4..d1c88d4403 100644 --- a/interfaces/kits/native/ability/native/ui_ability_impl.h +++ b/interfaces/kits/native/ability/native/ui_ability_impl.h @@ -95,6 +95,8 @@ public: */ bool AbilityTransaction(const AAFwk::Want &want, const AAFwk::LifeCycleStateInfo &targetState); + void HandleInitialState(bool &ret); + /** * @brief Send the result code and data to be returned by this Page ability to the caller. * When a Page ability is destroyed, the caller overrides the AbilitySlice#onAbilityResult(int, int, Want) diff --git a/interfaces/kits/native/ability/native/ui_extension_ability/js_embeddable_ui_ability_context.h b/interfaces/kits/native/ability/native/ui_extension_ability/js_embeddable_ui_ability_context.h index 8ddc914ad8..c06feb93a2 100644 --- a/interfaces/kits/native/ability/native/ui_extension_ability/js_embeddable_ui_ability_context.h +++ b/interfaces/kits/native/ability/native/ui_extension_ability/js_embeddable_ui_ability_context.h @@ -21,8 +21,8 @@ #include #include "ability_connect_callback.h" +#include "ability_context.h" #include "event_handler.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/ability/ability_runtime/ability_context.h" #include "js_ability_context.h" #include "js_free_install_observer.h" #include "js_runtime.h" @@ -37,6 +37,7 @@ public: ~JsEmbeddableUIAbilityContext() = default; static void Finalizer(napi_env env, void* data, void* hint); static napi_value StartAbility(napi_env env, napi_callback_info info); + static napi_value OpenLink(napi_env env, napi_callback_info info); static napi_value StartAbilityForResult(napi_env env, napi_callback_info info); static napi_value ConnectAbility(napi_env env, napi_callback_info info); static napi_value DisconnectAbility(napi_env env, napi_callback_info info); @@ -68,6 +69,7 @@ private: static void WrapJsUIExtensionContext(napi_env env, std::shared_ptr uiExtContext, napi_value &objValue, int32_t screenMode); napi_value OnStartAbility(napi_env env, NapiCallbackInfo& info); + napi_value OnOpenLink(napi_env env, NapiCallbackInfo& info); napi_value OnStartAbilityForResult(napi_env env, NapiCallbackInfo& info); napi_value OnConnectAbility(napi_env env, NapiCallbackInfo& info); napi_value OnDisconnectAbility(napi_env env, NapiCallbackInfo& info); 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 85b45fddce..cbcec6e4e2 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 @@ -26,6 +26,7 @@ namespace OHOS { namespace AbilityRuntime { struct NapiCallbackInfo; class JsEmbeddableUIAbilityContext; +class JSUIServiceUIExtConnection; class JsUIExtensionContext { public: @@ -43,6 +44,9 @@ public: static napi_value DisconnectAbility(napi_env env, napi_callback_info info); static napi_value ReportDrawnCompleted(napi_env env, napi_callback_info info); static napi_value OpenAtomicService(napi_env env, napi_callback_info info); + static napi_value StartUIServiceExtension(napi_env env, napi_callback_info info); + static napi_value ConnectUIServiceExtension(napi_env env, napi_callback_info info); + static napi_value DisconnectUIServiceExtension(napi_env env, napi_callback_info info); protected: virtual napi_value OnStartAbility(napi_env env, NapiCallbackInfo& info); @@ -54,6 +58,14 @@ 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); + virtual napi_value OnStartUIServiceExtension(napi_env env, NapiCallbackInfo& info); + bool UnwrapConnectUIServiceExtensionParam(napi_env env, NapiCallbackInfo& info, AAFwk::Want& want); + bool CheckConnectAlreadyExist(napi_env env, AAFwk::Want& want, napi_value callback, napi_value& result); + virtual napi_value OnConnectUIServiceExtension(napi_env env, NapiCallbackInfo& info); + static void DoConnectUIServiceExtension(napi_env env, + std::weak_ptr weakContext, sptr connection, + std::shared_ptr uasyncTaskShared, const AAFwk::Want& want); + virtual napi_value OnDisconnectUIServiceExtension(napi_env env, NapiCallbackInfo& info); void SetCallbackForTerminateWithResult(int32_t resultCode, AAFwk::Want& want, NapiAsyncTask::CompleteCallback& complete); @@ -68,28 +80,34 @@ private: napi_value OpenAtomicServiceInner(napi_env env, NapiCallbackInfo& info, AAFwk::Want &want, const AAFwk::StartOptions &options, size_t unwrapArgc); void AddFreeInstallObserver(napi_env env, const AAFwk::Want &want, napi_value callback, napi_value* result, - bool isAbilityResult = false); + bool isAbilityResult = false, bool isOpenLink = false); bool CreateOpenLinkTask(const napi_env &env, const napi_value &lastParam, AAFwk::Want &want, int &requestCode); + void RemoveOpenLinkTask(int requestCode); napi_value OnOpenLink(napi_env env, NapiCallbackInfo& info); + napi_value OnOpenLinkInner(napi_env env, const AAFwk::Want& want, + int requestCode, const std::string& startTime, const std::string& url); }; class JSUIExtensionConnection : public AbilityConnectCallback { public: explicit JSUIExtensionConnection(napi_env env); ~JSUIExtensionConnection(); + void ReleaseNativeReference(NativeReference* ref); void OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; - void HandleOnAbilityConnectDone( + virtual void HandleOnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode); - void HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode); + virtual void HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode); void SetJsConnectionObject(napi_value jsConnectionObject); + std::unique_ptr& GetJsConnectionObject() { return jsConnectionObject_; } void RemoveConnectionObject(); void CallJsFailed(int32_t errorCode); + napi_value CallObjectMethod(const char* name, napi_value const *argv, size_t argc); void SetConnectionId(int64_t id); int64_t GetConnectionId(); -private: +protected: napi_env env_ = nullptr; std::unique_ptr jsConnectionObject_ = nullptr; int64_t connectionId_ = -1; diff --git a/interfaces/kits/native/ability/native/ui_extension_ability/js_uiservice_uiext_connection.h b/interfaces/kits/native/ability/native/ui_extension_ability/js_uiservice_uiext_connection.h new file mode 100644 index 0000000000..810d51a7c2 --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_extension_ability/js_uiservice_uiext_connection.h @@ -0,0 +1,62 @@ +/* + * 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_UISERVICE_UIEXT_CONNECTION_H +#define OHOS_ABILITY_RUNTIME_UISERVICE_UIEXT_CONNECTION_H + +#include "js_ui_extension_context.h" + +#include "ui_service_host_stub.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace UIServiceConnection { +void AddUIServiceExtensionConnection(AAFwk::Want& want, sptr& connection); +void RemoveUIServiceExtensionConnection(const int64_t& connectId); +void FindUIServiceExtensionConnection(const int64_t& connectId, AAFwk::Want& want, + sptr& connection); +void FindUIServiceExtensionConnection(napi_env env, AAFwk::Want& want, napi_value callback, + sptr& connection); +} + +class UIExtensionServiceHostStubImpl; +class JSUIServiceUIExtConnection : public JSUIExtensionConnection { +public: + JSUIServiceUIExtConnection(napi_env env); + ~JSUIServiceUIExtConnection(); + virtual void HandleOnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + virtual void HandleOnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + sptr GetServiceHostStub() { return serviceHostStub_; } + void SetProxyObject(napi_value proxy); + napi_value GetProxyObject(); + void SetNapiAsyncTask(std::shared_ptr& task); + void AddDuplicatedPendingTask(std::unique_ptr& task); + void ResolveDuplicatedPendingTask(napi_env env, napi_value proxy); + void RejectDuplicatedPendingTask(napi_env env, napi_value error); + int32_t OnSendData(OHOS::AAFwk::WantParams &data); + void HandleOnSendData(const OHOS::AAFwk::WantParams &data); + void CallJsOnDisconnect(); + static bool IsJsCallbackObjectEquals(napi_env env, std::unique_ptr& callback, napi_value value); + +private: + sptr serviceHostStub_; + std::unique_ptr serviceProxyObject_; + std::shared_ptr napiAsyncTask_; + std::vector> duplicatedPendingTaskList_; +}; + +} +} +#endif diff --git a/interfaces/kits/native/ability/native/ui_extension_ability/ui_extension_context.h b/interfaces/kits/native/ability/native/ui_extension_ability/ui_extension_context.h index 9f112a5b8c..821dc4af9d 100755 --- a/interfaces/kits/native/ability/native/ui_extension_ability/ui_extension_context.h +++ b/interfaces/kits/native/ability/native/ui_extension_ability/ui_extension_context.h @@ -20,6 +20,7 @@ #include "ability_connect_callback.h" #include "extension_context.h" +#include "free_install_observer_interface.h" #include "start_options.h" #include "want.h" #ifdef SUPPORT_SCREEN @@ -54,6 +55,7 @@ public: virtual ErrCode StartAbility(const AAFwk::Want &want) const; virtual ErrCode StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const; virtual ErrCode StartAbility(const AAFwk::Want &want, int requestCode) const; + virtual ErrCode StartUIServiceExtension(const AAFwk::Want& want, int32_t accountId = -1) const; /** * @brief Destroys the current ui extension ability. * @@ -144,11 +146,17 @@ public: #endif // SUPPORT_SCREEN Ace::UIContent* GetUIContent(); + ErrCode OpenLink(const AAFwk::Want& want, int reuqestCode); + ErrCode OpenAtomicService(AAFwk::Want& want, const AAFwk::StartOptions &options, int requestCode, RuntimeTask &&task); + ErrCode AddFreeInstallObserver(const sptr &observer); + void InsertResultCallbackTask(int requestCode, RuntimeTask&& task); + void RemoveResultCallbackTask(int requestCode); + using SelfType = UIExtensionContext; static const size_t CONTEXT_TYPE_ID; #ifdef SUPPORT_SCREEN diff --git a/interfaces/kits/native/ability/native/ui_extension_ability/ui_extension_servicehost_stub_impl.h b/interfaces/kits/native/ability/native/ui_extension_ability/ui_extension_servicehost_stub_impl.h new file mode 100644 index 0000000000..a912158086 --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_extension_ability/ui_extension_servicehost_stub_impl.h @@ -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. + */ +#ifndef OHOS_ABILITY_RUNTIME_UI_EXTENSION_SERVICEHOST_STUB_IMPL_H +#define OHOS_ABILITY_RUNTIME_UI_EXTENSION_SERVICEHOST_STUB_IMPL_H + +#include "js_ui_extension_context.h" + +#include "ui_service_host_stub.h" + +namespace OHOS { +namespace AbilityRuntime { + +class UIExtensionServiceHostStubImpl : public AAFwk::UIServiceHostStub { +public: + UIExtensionServiceHostStubImpl(wptr conn); + ~UIExtensionServiceHostStubImpl() = default; + virtual int32_t SendData(OHOS::AAFwk::WantParams &data) override; + +protected: + wptr conn_; +}; + +} +} +#endif + diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/js_ui_service_host_proxy.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/js_ui_service_host_proxy.h new file mode 100644 index 0000000000..deafe69238 --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/js_ui_service_host_proxy.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_JSUI_SERVICE_HOST_PROXY_H +#define OHOS_ABILITY_RUNTIME_JSUI_SERVICE_HOST_PROXY_H + +#include + +#include "ui_service_host_proxy.h" +#include "js_runtime_utils.h" + +namespace OHOS { +namespace AAFwk { +using namespace AbilityRuntime; + +class JsUIServiceHostProxy { +public: + static napi_ref CreateJsUIServiceHostProxy(napi_env env, const sptr& impl); + static void Finalizer(napi_env env, void* data, void* hint); + + JsUIServiceHostProxy(const sptr& impl); + virtual ~JsUIServiceHostProxy(); + +private: + bool CheckCallerIsSystemApp(); + static napi_value SendData(napi_env env, napi_callback_info info); + napi_value OnSendData(napi_env env, NapiCallbackInfo& info); + +protected: + sptr proxy_; +}; + +} // namespace AbilityRuntime +} // namespace OHOS +#endif //OHOS_ABILITY_RUNTIME_JSUI_SERVICE_HOST_PROXY_H \ No newline at end of file diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/js_ui_service_proxy.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/js_ui_service_proxy.h new file mode 100644 index 0000000000..a9d91a1e78 --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/js_ui_service_proxy.h @@ -0,0 +1,51 @@ +/* + * 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_JSUI_SERVICE_PROXY_H +#define OHOS_ABILITY_RUNTIME_JSUI_SERVICE_PROXY_H + +#include + +#include "ui_service_proxy.h" +#include "js_runtime_utils.h" + +namespace OHOS { +namespace AAFwk { +using namespace AbilityRuntime; + +class JsUIServiceProxy { +public: + static napi_value CreateJsUIServiceProxy(napi_env env, const sptr& impl, + int64_t connectionId, const sptr& hostProxy); + static void Finalizer(napi_env env, void* data, void* hint); + + JsUIServiceProxy(const sptr& impl, const sptr& hostProxy); + virtual ~JsUIServiceProxy(); + + void SetConnectionId(int64_t id) { connectionId_ = id; } + int64_t GetConnectionId() { return connectionId_; } +private: + static napi_value SendData(napi_env env, napi_callback_info info); + napi_value OnSendData(napi_env env, NapiCallbackInfo& info); + +protected: + sptr proxy_ = nullptr; + int64_t connectionId_ = 0; + sptr hostProxy_ = nullptr; +}; + +} // namespace AAFwk +} // namespace OHOS +#endif //OHOS_ABILITY_RUNTIME_JSUI_SERVICE_PROXY_H \ No newline at end of file diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_extension_connection_constants.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_extension_connection_constants.h new file mode 100644 index 0000000000..9e0901efe7 --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_extension_connection_constants.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_UISERVICEEXTENSION_CONNECTION_CONSTANTS_H +#define OHOS_ABILITY_RUNTIME_UISERVICEEXTENSION_CONNECTION_CONSTANTS_H + +namespace OHOS { +namespace AbilityRuntime { +constexpr const char* UISERVICEHOSTPROXY_KEY = "ohos.ability.params.UIServiceHostProxy"; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_UISERVICEEXTENSION_CONNECTION_CONSTANTS_H diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_host_interface.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_host_interface.h new file mode 100644 index 0000000000..3f9706fe70 --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_host_interface.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_UI_SERVICE_HOST_INTERFACE_H +#define OHOS_ABILITY_RUNTIME_UI_SERVICE_HOST_INTERFACE_H + +#include + +#include "want.h" + +namespace OHOS { +namespace AAFwk { + +class IUIServiceHost : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.IUIServiceHost"); + + /** + * SendData, send the data from ui sevice host to other application + * + * @param data, the data which is sent + */ + virtual int32_t SendData(OHOS::AAFwk::WantParams &data) = 0; + + enum { + SEND_DATA = 1, + }; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_UI_SERVICE_HOST_INTERFACE_H diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_host_proxy.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_host_proxy.h new file mode 100644 index 0000000000..b7ab6f4ac8 --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_host_proxy.h @@ -0,0 +1,39 @@ +/* + * 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_UI_SERVICE_HOST_PROXY_H +#define OHOS_ABILITY_RUNTIME_UI_SERVICE_HOST_PROXY_H + +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_proxy.h" +#include "ui_service_host_interface.h" + +namespace OHOS { +namespace AAFwk { + +class UIServiceHostProxy : public IRemoteProxy { +public: + explicit UIServiceHostProxy(const sptr& impl); + virtual ~UIServiceHostProxy(); + + virtual int32_t SendData(OHOS::AAFwk::WantParams &data) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif //OHOS_ABILITY_RUNTIME_UI_SERVICE_HOST_PROXY_H \ No newline at end of file diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_host_stub.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_host_stub.h new file mode 100644 index 0000000000..7825c2c4dd --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_host_stub.h @@ -0,0 +1,45 @@ +/* + * 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_UI_SERVICE_HOST_STUB_H +#define OHOS_ABILITY_RUNTIME_UI_SERVICE_HOST_STUB_H + +#include + +#include +#include +#include "ipc_types.h" +#include "message_parcel.h" +#include "ui_service_host_interface.h" + +namespace OHOS { +namespace AAFwk { + +class UIServiceHostStub : public IRemoteStub { +public: + UIServiceHostStub(); + virtual ~UIServiceHostStub(); + + int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; + + int32_t OnSendData(MessageParcel& data, MessageParcel& reply); + +protected: + using RequestFuncType = int32_t (UIServiceHostStub::*)(MessageParcel& data, MessageParcel& reply); + std::map requestFuncMap_; +}; + +} // namespace AAFwk +} // namespace OHOS +#endif //OHOS_ABILITY_RUNTIME_UI_SERVICE_HOST_STUB_H \ No newline at end of file diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_interface.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_interface.h new file mode 100644 index 0000000000..9e52452caf --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_interface.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_UI_SERVICE_INTERFACE_H +#define OHOS_ABILITY_RUNTIME_UI_SERVICE_INTERFACE_H + +#include + +#include "want.h" + +namespace OHOS { +namespace AAFwk { + +class IUIService : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.aafwk.IUIService"); + + /** + * SendData, send the data from ui sevice host to other application + * + * @param data, the data which is sent + */ + virtual int32_t SendData(sptr hostProxy, OHOS::AAFwk::WantParams &data) = 0; + + enum { + SEND_DATA = 1, + }; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_UI_SERVICE_INTERFACE_H diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_proxy.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_proxy.h new file mode 100644 index 0000000000..11e073036f --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_proxy.h @@ -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. + */ + +#ifndef OHOS_ABILITY_RUNTIME_UI_SERVICE_PROXY_H +#define OHOS_ABILITY_RUNTIME_UI_SERVICE_PROXY_H + +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_proxy.h" +#include "ui_service_interface.h" + +namespace OHOS { +namespace AAFwk { +class UIServiceProxy : public IRemoteProxy { +public: + explicit UIServiceProxy(const sptr& impl); + virtual ~UIServiceProxy(); + + virtual int32_t SendData(sptr hostProxy, OHOS::AAFwk::WantParams &data) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif //OHOS_ABILITY_RUNTIME_UI_SERVICE_PROXY_H \ No newline at end of file diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_stub.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_stub.h new file mode 100644 index 0000000000..53127e5f81 --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/connection/ui_service_stub.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_UI_SERVICE_STUB_H +#define OHOS_ABILITY_RUNTIME_UI_SERVICE_STUB_H + +#include +#include +#include "ui_service_interface.h" + +namespace OHOS { +namespace AAFwk { + +class UIServiceStub : public IRemoteStub { +public: + UIServiceStub(); + virtual ~UIServiceStub(); + + int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; + + int32_t OnSendData(MessageParcel& data, MessageParcel& reply); + +protected: + using RequestFuncType = int32_t (UIServiceStub::*)(MessageParcel& data, MessageParcel& reply); + std::map requestFuncMap_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif //OHOS_ABILITY_RUNTIME_UI_SERVICE_STUB_H \ No newline at end of file diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/js_ui_service_extension.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/js_ui_service_extension.h new file mode 100644 index 0000000000..26b71febeb --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/js_ui_service_extension.h @@ -0,0 +1,258 @@ +/* + * 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_JS_UI_SERVICE_EXTENSION_H +#define OHOS_ABILITY_RUNTIME_JS_UI_SERVICE_EXTENSION_H + +#include "ui_service_extension.h" +#include "configuration.h" +#include "ability_info.h" +#include "ui_service_extension_context.h" +#ifdef SUPPORT_GRAPHICS +#include "display_manager.h" +#include "system_ability_status_change_stub.h" +#include "js_window_stage.h" +#include "window_option.h" +#endif +#include "ui_service_extension.h" +#include "ui_service_stub.h" + +class NativeReference; + +namespace OHOS { +namespace AbilityRuntime { +class UIServiceExtension; +class Runtime; +class UIServiceExtensionContext; +class JsUIServiceExtension; + +class UIServiceStubImpl : public AAFwk::UIServiceStub { +public: + UIServiceStubImpl(std::weak_ptr& ext); + ~UIServiceStubImpl(); + virtual int32_t SendData(sptr hostProxy, OHOS::AAFwk::WantParams &data) override; + +protected: + std::weak_ptr extension_; +}; + +/** + * @brief Basic service components. + */ +class JsUIServiceExtension : public UIServiceExtension { +public: + explicit JsUIServiceExtension(JsRuntime& jsRuntime); + virtual ~JsUIServiceExtension() override; + + /** + * @brief Create JsServiceExtension. + * + * @param runtime The runtime. + * @return The JsServiceExtension instance. + */ + static JsUIServiceExtension* Create(const std::unique_ptr& runtime); + + /** + * @brief Init the extension. + * + * @param record the extension record. + * @param application the application info. + * @param handler the extension handler. + * @param token the remote token. + */ + virtual void Init(const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) override; + + /** + * @brief Called when this extension is started. You must override this function if you want to perform some + * initialization operations during extension startup. + * + * This function can be called only once in the entire lifecycle of an extension. + * @param Want Indicates the {@link Want} structure containing startup information about the extension. + */ + virtual void OnStart(const AAFwk::Want &want) override; + + /** + * @brief Called when this extension is started. You must override this function if you want to perform some + * initialization operations during extension startup. + * + * This function can be called only once in the entire lifecycle of an extension. + * @param Want Indicates the {@link Want} structure containing startup information about the extension. + * @param sessionInfo Indicates the {@link SessionInfo} structure containing window session info. + */ + virtual void OnStart(const AAFwk::Want &want, sptr sessionInfo) override; + + /** + * @brief Called when this extension enters the STATE_STOP state. + * + * The extension in the STATE_STOP is being destroyed. + * You can override this function to implement your own processing logic. + */ + virtual void OnStop() override; + + /** + * @brief Called when this Service extension is connected for the first time. + * + * You can override this function to implement your own processing logic. + * + * @param want Indicates the {@link Want} structure containing connection information about the Service extension. + * @param callbackInfo Indicates the lifecycle transaction callback information + * @param isAsyncCallback Indicates whether it is an asynchronous lifecycle callback + * @return Returns a pointer to the sid of the connected Service extension. + */ + virtual sptr OnConnect(const AAFwk::Want &want, + AppExecFwk::AbilityTransactionCallbackInfo> *callbackInfo, bool &isAsyncCallback) override; + + /** + * @brief Called when all abilities connected to this Service extension are disconnected. + * + * You can override this function to implement your own processing logic. + * @param callbackInfo Indicates the lifecycle transaction callback information + * @param isAsyncCallback Indicates whether it is an asynchronous lifecycle callback + */ + virtual void OnDisconnect(const AAFwk::Want &want, AppExecFwk::AbilityTransactionCallbackInfo<> *callbackInfo, + bool &isAsyncCallback) override; + + /** + * @brief Called back when Service is started. + * This method can be called only by Service. You can use the StartAbility(ohos.aafwk.content.Want) method to start + * Service. Then the system calls back the current method to use the transferred want parameter to execute its own + * logic. + * + * @param want Indicates the want of Service to start. + * @param restart Indicates the startup mode. The value true indicates that Service is restarted after being + * destroyed, and the value false indicates a normal startup. + * @param startId Indicates the number of times the Service extension has been started. The startId is incremented + * by 1 every time the extension is started. For example, if the extension has been started for six times, the + * value of startId is 6. + */ + virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; + + /** + * @brief Called when the system configuration is updated. + * + * @param configuration Indicates the updated configuration information. + */ + void OnConfigurationUpdated(const AppExecFwk::Configuration& configuration) override; + + /** + * @brief Called when configuration changed, including system configuration and window configuration. + * + */ + void ConfigurationUpdated(); + + /** + * @brief Called when client send data to extension. + * + * @param hostProxy the proxy used to send data back to client + * @param data The data to send. + */ + int32_t OnSendData(sptr hostProxy, OHOS::AAFwk::WantParams &data); + +protected: + bool showOnLockScreen_ = false; + +private: + sptr CallOnConnect(const AAFwk::Want &want); + + napi_value CallOnDisconnect(const AAFwk::Want &want); + + napi_value CallObjectMethod(const char* name, napi_value const *argv = nullptr, size_t argc = 0); + + napi_value WrapWant(napi_env env, const AAFwk::Want &want); + + void HandleSendData(sptr hostProxy, const OHOS::AAFwk::WantParams &data); + + void SetupServiceStub(); + + sptr GetHostProxyFromWant(const AAFwk::Want &want); + + void BindContext(napi_env env, napi_value obj); + + void GetSrcPath(std::string& srcPath); + + void ListenWMS(); + + JsRuntime& jsRuntime_; + std::unique_ptr jsObj_; + std::shared_ptr aContext_ = nullptr; + std::shared_ptr shellContextRef_ = nullptr; + std::shared_ptr handler_ = nullptr; + sptr extensionStub_ = nullptr; + std::map, std::unique_ptr> hostProxyMap_; + +#ifdef SUPPORT_GRAPHICS + void OnSceneWillCreated(std::shared_ptr extensionWindowConfig); + void OnSceneDidCreated(sptr& window); +protected: + class JsUIServiceExtensionDisplayListener : public Rosen::DisplayManager::IDisplayListener { + public: + explicit JsUIServiceExtensionDisplayListener(const std::weak_ptr& jsUIServiceExtension) + { + jsUIServiceExtension_ = jsUIServiceExtension; + } + + void OnCreate(Rosen::DisplayId displayId) override + { + auto ptrJsUIServiceExtension = jsUIServiceExtension_.lock(); + if (ptrJsUIServiceExtension != nullptr) { + ptrJsUIServiceExtension->OnCreate(displayId); + } + } + + void OnDestroy(Rosen::DisplayId displayId) override + { + auto ptrJsUIServiceExtension = jsUIServiceExtension_.lock(); + if (ptrJsUIServiceExtension != nullptr) { + ptrJsUIServiceExtension->OnDestroy(displayId); + } + } + + void OnChange(Rosen::DisplayId displayId) override + { + auto ptrJsUIServiceExtension = jsUIServiceExtension_.lock(); + if (ptrJsUIServiceExtension != nullptr) { + ptrJsUIServiceExtension->OnChange(displayId); + } + } + + private: + std::weak_ptr jsUIServiceExtension_; + }; + + void OnCreate(Rosen::DisplayId displayId); + void OnDestroy(Rosen::DisplayId displayId); + void OnChange(Rosen::DisplayId displayId); + +private: + class SystemAbilityStatusChangeListener : public OHOS::SystemAbilityStatusChangeStub { + public: + SystemAbilityStatusChangeListener(sptr displayListener) + : tmpDisplayListener_(displayListener) {}; + 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 displayListener_ = nullptr; +#endif +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_JS_SERVICE_EXTENSION_H diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/js_ui_service_extension_context.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/js_ui_service_extension_context.h new file mode 100644 index 0000000000..965d5fe470 --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/js_ui_service_extension_context.h @@ -0,0 +1,32 @@ +/* + * 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_JS_UI_SERVICE_EXTENSION_CONTEXT_H +#define OHOS_ABILITY_RUNTIME_JS_UI_SERVICE_EXTENSION_CONTEXT_H + +#include + +#include "ability_connect_callback.h" +#include "ui_service_extension_context.h" +#include "event_handler.h" +#include "js_free_install_observer.h" +#include "native_engine/native_engine.h" + +namespace OHOS { +namespace AbilityRuntime { +napi_value CreateJsUIServiceExtensionContext(napi_env env, std::shared_ptr context); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_JS_UI_SERVICE_EXTENSION_CONTEXT_H \ No newline at end of file diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/ui_service_extension.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/ui_service_extension.h new file mode 100644 index 0000000000..599826501e --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/ui_service_extension.h @@ -0,0 +1,95 @@ +/* + * 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_UI_SERVICE_EXTENSION_H +#define OHOS_ABILITY_RUNTIME_UI_SERVICE_EXTENSION_H + +#include "extension_base.h" +#include "js_runtime.h" +#include "context/context.h" +#ifdef SUPPORT_GRAPHICS +#include "js_extension_window_config.h" +#include "js_window_utils.h" +#include "window_helper.h" +#include "window_scene.h" +#include "js_window_stage.h" +#include "session_info.h" +#endif + + +namespace OHOS { +namespace AbilityRuntime { +class UIServiceExtensionContext; +class Runtime; +using AbilityHandler = AppExecFwk::AbilityHandler; +using OHOSApplication = AppExecFwk::OHOSApplication; + +/** + * @brief Basic ui extension components. + */ +class UIServiceExtension : public ExtensionBase { +public: + UIServiceExtension() = default; + virtual ~UIServiceExtension() = default; + + /** + * @brief Create and init context. + * + * @param record the ui service extension record. + * @param application the application info. + * @param handler the ui service extension handler. + * @param token the remote token. + * @return The created context. + */ + virtual std::shared_ptr CreateAndInitContext( + const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) override; + + /** + * @brief Init the ui service extension. + * + * @param record the ui service extension record. + * @param application the application info. + * @param handler the ui service extension handler. + * @param token the remote token. + */ + virtual void Init(const std::shared_ptr &record, + const std::shared_ptr &application, + std::shared_ptr &handler, + const sptr &token) override; + + /** + * @brief Create ui service extension. + * + * @param runtime The runtime. + * @return The ui service extension instance. + */ + static UIServiceExtension* Create(const std::unique_ptr& runtime); + +#ifdef SUPPORT_GRAPHICS + /** + * @brief get the window option. + * @return Returns a window option object pointer. + */ + sptr GetWindowOption(const AAFwk::Want &want, + const std::shared_ptr< Rosen::ExtensionWindowConfig>& extensionWindowConfig, + const sptr& sessionInfo); +#endif +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_UI_SERVICE_EXTENSION_H diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/ui_service_extension_context.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/ui_service_extension_context.h new file mode 100644 index 0000000000..d9a31e8c3d --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/ui_service_extension_context.h @@ -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. + */ + +#ifndef OHOS_ABILITY_RUNTIME_UI_SERVICE_EXTENSION_CONTEXT_H +#define OHOS_ABILITY_RUNTIME_UI_SERVICE_EXTENSION_CONTEXT_H + +#include "extension_context.h" + +#include "ability_connect_callback.h" +#include "connection_manager.h" +#include "local_call_container.h" +#include "start_options.h" +#include "iability_callback.h" +#include "want.h" +#include "window.h" +#ifdef SUPPORT_SCREEN +#include "scene_board_judgement.h" +#include "ui_content.h" +#endif // SUPPORT_SCREEN + +namespace OHOS { +namespace AbilityRuntime { +/** + * @brief context supply for ui_service + * + */ +class UIServiceExtensionContext : public ExtensionContext { +public: + UIServiceExtensionContext() = default; + virtual ~UIServiceExtensionContext() = default; + + /** + * @brief Starts a new ability. + * An ability using the AbilityInfo.AbilityType.SERVICE or AbilityInfo.AbilityType.PAGE template uses this method + * to start a specific ability. The system locates the target ability from installed abilities based on the value + * of the want parameter and then starts it. You can specify the ability to start using the want parameter. + * + * @param want Indicates the Want containing information about the target ability to start. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode StartAbility(const AAFwk::Want &want, const AAFwk::StartOptions &startOptions) const; + + /** + * @brief Destroys the current ability. + * + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode TerminateSelf(); + + void SetWindow(sptr window); + + sptr GetWindow(); + + /** + * @brief Start a new ability using type; + * @return errCode ERR_OK on success, others on failure. + */ + ErrCode StartAbilityByType(const std::string &type, + AAFwk::WantParams &wantParam, const std::shared_ptr &uiExtensionCallbacks); + + /** + * @brief Get ui content object. + * + * @return UIContent object of ACE. + */ + Ace::UIContent *GetUIContent(); + static const size_t CONTEXT_TYPE_ID; + +protected: + bool IsContext(size_t contextTypeId) override + { + return contextTypeId == CONTEXT_TYPE_ID || ExtensionContext::IsContext(contextTypeId); + } + +private: + static int ILLEGAL_REQUEST_CODE; + sptr window_ = nullptr; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_UI_SERVICE_EXTENSION_CONTEXT_H diff --git a/interfaces/kits/native/ability/native/ui_service_extension_ability/ui_service_extension_module_loader.h b/interfaces/kits/native/ability/native/ui_service_extension_ability/ui_service_extension_module_loader.h new file mode 100644 index 0000000000..4d7b5ec255 --- /dev/null +++ b/interfaces/kits/native/ability/native/ui_service_extension_ability/ui_service_extension_module_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_UI_SERVICE_EXTENSION_MODULE_LOADER_H +#define OHOS_ABILITY_RUNTIME_UI_SERVICE_EXTENSION_MODULE_LOADER_H + +#include "extension_module_loader.h" + +namespace OHOS::AbilityRuntime { +class UIServiceExtensionModuleLoader : public ExtensionModuleLoader, public Singleton { + DECLARE_SINGLETON(UIServiceExtensionModuleLoader); + +public: + /** + * @brief Create Extension. + * + * @param runtime The runtime. + * @return The Extension instance. + */ + virtual Extension *Create(const std::unique_ptr& runtime) const override; + + virtual std::map GetParams() override; +}; +} +#endif // OHOS_ABILITY_RUNTIME_UI_SERVICE_EXTENSION_MODULE_LOADER_H 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 fe8029909e..c5082b7feb 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 @@ -79,10 +79,10 @@ public: int32_t flags, int32_t userId, AbilityInfo &abilityInfo, const sptr &callBack); void UpgradeAtomicService(const Want &want, int32_t userId); bool ImplicitQueryInfos(const Want &want, int32_t flags, int32_t userId, bool withDefault, - std::vector &abilityInfos, std::vector &extensionInfos); + std::vector &abilityInfos, std::vector &extensionInfos, + bool &findDefaultApp); bool CleanBundleDataFiles(const std::string &bundleName, int32_t userId, int32_t appCloneIndex); bool QueryDataGroupInfos(const std::string &bundleName, int32_t userId, std::vector &infos); - bool GetBundleGidsByUid(const std::string &bundleName, const int32_t &uid, std::vector &gids); bool RegisterBundleEventCallback(const sptr &bundleEventCallback); bool GetBundleInfos( const BundleFlag flag, std::vector &bundleInfos, int32_t userId = Constants::UNSPECIFIED_USERID); @@ -99,6 +99,7 @@ public: BundleInfo &bundleInfo, int32_t userId); ErrCode QueryCloneExtensionAbilityInfoWithAppIndex(const ElementName &element, int32_t flags, int32_t appCloneIndex, ExtensionAbilityInfo &extensionInfo, int32_t userId); + ErrCode GetCloneAppIndexes(const std::string &bundleName, std::vector &appIndexes, int32_t userId); private: sptr Connect(); diff --git a/interfaces/kits/native/appkit/ability_delegator/ability_delegator.h b/interfaces/kits/native/appkit/ability_delegator/ability_delegator.h index 1eab52f3c1..d891180b54 100644 --- a/interfaces/kits/native/appkit/ability_delegator/ability_delegator.h +++ b/interfaces/kits/native/appkit/ability_delegator/ability_delegator.h @@ -29,14 +29,13 @@ #endif #include "ability_delegator_infos.h" +#include "ability_lifecycle_executor.h" +#include "context.h" +#include "delegator_thread.h" #include "iability_monitor.h" #include "iability_stage_monitor.h" -#include "delegator_thread.h" #include "shell_cmd_result.h" #include "test_runner.h" - -#include "ability_lifecycle_executor.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/context.h" #include "want.h" namespace OHOS { 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 index 4cd03a8a37..aeb4194f0c 100644 --- a/interfaces/kits/native/appkit/ability_runtime/app/cj_ability_stage.h +++ b/interfaces/kits/native/appkit/ability_runtime/app/cj_ability_stage.h @@ -57,6 +57,8 @@ public: std::shared_ptr cjStage) : cjAbilityStageObject_(std::move(cjStage)) {} ~CJAbilityStage() override = default; + void Init(const std::shared_ptr &context, + const std::weak_ptr application) override; void OnCreate(const AAFwk::Want& want) const override; std::string OnAcceptWant(const AAFwk::Want& want) override; void OnConfigurationUpdated(const AppExecFwk::Configuration& configuration) override; diff --git a/interfaces/kits/native/appkit/ability_runtime/app/cj_ability_stage_context.h b/interfaces/kits/native/appkit/ability_runtime/app/cj_ability_stage_context.h index 7ddbbe1e5a..4b115858d9 100644 --- a/interfaces/kits/native/appkit/ability_runtime/app/cj_ability_stage_context.h +++ b/interfaces/kits/native/appkit/ability_runtime/app/cj_ability_stage_context.h @@ -19,7 +19,6 @@ #include #include "cj_common_ffi.h" -#include "hilog_wrapper.h" #include "ffi_remote_data.h" #include "hap_module_info.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 index dd512f1e07..44a7ff7005 100644 --- 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 @@ -46,6 +46,7 @@ struct CJAbilityStageFuncs { char* (*AbilityStageOnAcceptWant)(int64_t handle, OHOS::AAFwk::Want* want); void (*AbilityStageOnConfigurationUpdated)(int64_t id, CJConfiguration configuration); void (*AbilityStageOnMemoryLevel)(int64_t id, int32_t level); + void (*AbilityStageInit)(int64_t id, void* abilityStage); }; CJ_EXPORT void RegisterCJAbilityStageFuncs(void (*registerFunc)(CJAbilityStageFuncs* result)); @@ -60,6 +61,7 @@ public: explicit CJAbilityStageObject(int64_t id) : id_(id) {} ~CJAbilityStageObject(); + void Init(AbilityStageHandle abilityStage) const; void OnCreate() const; std::string OnAcceptWant(const AAFwk::Want& want) const; void OnConfigurationUpdated(const std::shared_ptr& configuration) const; diff --git a/interfaces/kits/native/appkit/ability_runtime/app/js_ability_stage_context.h b/interfaces/kits/native/appkit/ability_runtime/app/js_ability_stage_context.h index efb7d3c5a2..cc878f1b2c 100644 --- a/interfaces/kits/native/appkit/ability_runtime/app/js_ability_stage_context.h +++ b/interfaces/kits/native/appkit/ability_runtime/app/js_ability_stage_context.h @@ -39,8 +39,7 @@ private: std::weak_ptr context_; }; -napi_value CreateJsAbilityStageContext(napi_env env, - std::shared_ptr context, DetachCallback detach, NapiAttachCallback attach); +napi_value CreateJsAbilityStageContext(napi_env env, std::shared_ptr context); } // namespace AbilityRuntime } // namespace OHOS #endif // OHOS_ABILITY_RUNTIME_JS_ABILITY_STAGE_CONTEXT_H diff --git a/interfaces/kits/native/appkit/ability_runtime/context/ability_lifecycle_callback.h b/interfaces/kits/native/appkit/ability_runtime/context/ability_lifecycle_callback.h index 815034abc3..02417f1191 100644 --- a/interfaces/kits/native/appkit/ability_runtime/context/ability_lifecycle_callback.h +++ b/interfaces/kits/native/appkit/ability_runtime/context/ability_lifecycle_callback.h @@ -212,6 +212,14 @@ public: * @StageModelOnly */ virtual void OnAbilityContinue(const std::shared_ptr &ability) = 0; + + virtual void OnAbilityWillContinue(const std::shared_ptr &ability) {} + virtual void OnWindowStageWillRestore(const std::shared_ptr &ability, + const std::shared_ptr &windowStage) {} + virtual void OnWindowStageRestore(const std::shared_ptr &ability, + const std::shared_ptr &windowStage) {} + virtual void OnAbilityWillSaveState(const std::shared_ptr &ability) {} + virtual void OnAbilitySaveState(const std::shared_ptr &ability) {} }; class JsAbilityLifecycleCallback : public AbilityLifecycleCallback, @@ -241,6 +249,13 @@ public: void OnAbilityForeground(const std::shared_ptr &ability) override; void OnAbilityBackground(const std::shared_ptr &ability) override; void OnAbilityContinue(const std::shared_ptr &ability) override; + void OnAbilityWillContinue(const std::shared_ptr &ability) override; + void OnWindowStageWillRestore(const std::shared_ptr &ability, + const std::shared_ptr &windowStage) override; + void OnWindowStageRestore(const std::shared_ptr &ability, + const std::shared_ptr &windowStage) override; + void OnAbilityWillSaveState(const std::shared_ptr &ability) override; + void OnAbilitySaveState(const std::shared_ptr &ability) override; int32_t Register(napi_value jsCallback, bool isSync = false); bool UnRegister(int32_t callbackId, bool isSync = false); bool IsEmpty() const; diff --git a/interfaces/kits/native/appkit/ability_runtime/context/ability_stage_context.h b/interfaces/kits/native/appkit/ability_runtime/context/ability_stage_context.h new file mode 100755 index 0000000000..8943cb8ba7 --- /dev/null +++ b/interfaces/kits/native/appkit/ability_runtime/context/ability_stage_context.h @@ -0,0 +1,92 @@ +/* + * 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_ABILITY_STAGE_CONTEXT_H +#define OHOS_ABILITY_RUNTIME_ABILITY_STAGE_CONTEXT_H + +#include "context.h" +#include "context_impl.h" + +namespace OHOS { +namespace AbilityRuntime { +class AbilityStageContext : public Context { +public: + AbilityStageContext(); + virtual ~AbilityStageContext() = default; + + void SetParentContext(const std::shared_ptr &context); + + void InitHapModuleInfo(const std::shared_ptr &abilityInfo); + void InitHapModuleInfo(const AppExecFwk::HapModuleInfo &hapModuleInfo); + std::shared_ptr GetHapModuleInfo() const override; + + void SetConfiguration(const std::shared_ptr &config); + std::shared_ptr GetConfiguration() const override; + + void SetResourceManager(const std::shared_ptr &resourceManager); + std::shared_ptr GetResourceManager() const override; + + std::string GetBundleName() const override; + std::shared_ptr GetApplicationInfo() const override; + + std::shared_ptr CreateBundleContext(const std::string &bundleName) override; + std::shared_ptr CreateModuleContext(const std::string &moduleName) override; + std::shared_ptr CreateModuleContext(const std::string &bundleName, const std::string &moduleName) override; + std::shared_ptr CreateModuleResourceManager( + const std::string &bundleName, const std::string &moduleName) override; + int32_t CreateSystemHspModuleResourceManager(const std::string &bundleName, + const std::string &moduleName, std::shared_ptr &resourceManager) override; + + std::string GetBundleCodePath() const override; + std::string GetBundleCodeDir() override; + std::string GetCacheDir() override; + std::string GetTempDir() override; + std::string GetFilesDir() override; + std::string GetResourceDir() override; + std::string GetDatabaseDir() override; + std::string GetPreferencesDir() override; + std::string GetGroupDir(std::string groupId) override; + std::string GetDistributedFilesDir() override; + std::string GetCloudFileDir() override; + std::string GetBaseDir() const override; + int32_t GetSystemDatabaseDir(const std::string &groupId, bool checkExist, std::string &databaseDir) override; + int32_t GetSystemPreferencesDir(const std::string &groupId, bool checkExist, std::string &preferencesDir) override; + + bool IsUpdatingConfigurations() override; + bool PrintDrawnCompleted() override; + + sptr GetToken() override; + void SetToken(const sptr &token) override; + + void SwitchArea(int mode) override; + int GetArea() override; + + Global::Resource::DeviceType GetDeviceType() const override; + + using SelfType = AbilityStageContext; + static const size_t CONTEXT_TYPE_ID; + +protected: + bool IsContext(size_t contextTypeId) override + { + return contextTypeId == CONTEXT_TYPE_ID || Context::IsContext(contextTypeId); + } + +private: + std::shared_ptr contextImpl_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_ABILITY_STAGE_CONTEXT_H 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 1e2d2355e4..40c8641e14 100644 --- a/interfaces/kits/native/appkit/ability_runtime/context/application_context.h +++ b/interfaces/kits/native/appkit/ability_runtime/context/application_context.h @@ -54,6 +54,13 @@ public: void DispatchOnAbilityForeground(const std::shared_ptr &ability); void DispatchOnAbilityBackground(const std::shared_ptr &ability); void DispatchOnAbilityContinue(const std::shared_ptr &ability); + void DispatchOnAbilityWillContinue(const std::shared_ptr &ability); + void DispatchOnWindowStageWillRestore(const std::shared_ptr &ability, + const std::shared_ptr &windowStage); + void DispatchOnWindowStageRestore(const std::shared_ptr &ability, + const std::shared_ptr &windowStage); + void DispatchOnAbilityWillSaveState(const std::shared_ptr &ability); + void DispatchOnAbilitySaveState(const std::shared_ptr &ability); void DispatchConfigurationUpdated(const AppExecFwk::Configuration &config); void DispatchMemoryLevel(const int level); void NotifyApplicationForeground(); @@ -102,6 +109,8 @@ public: void SetColorMode(int32_t colorMode); void SetLanguage(const std::string &language); void SetFont(const std::string &font); + void SetMcc(const std::string &mcc); + void SetMnc(const std::string &mnc); void ClearUpApplicationData(); int GetArea() override; std::shared_ptr GetConfiguration() const override; @@ -130,6 +139,16 @@ public: void SetCurrentAppCloneIndex(int32_t appIndex); int32_t GetCurrentAppMode(); void SetCurrentAppMode(int32_t appIndex); + + using SelfType = ApplicationContext; + static const size_t CONTEXT_TYPE_ID; + +protected: + bool IsContext(size_t contextTypeId) override + { + return contextTypeId == CONTEXT_TYPE_ID || Context::IsContext(contextTypeId); + } + private: std::shared_ptr contextImpl_; static std::vector> callbacks_; 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 71c8043dd5..b6473549f3 100644 --- a/interfaces/kits/native/appkit/ability_runtime/context/context_impl.h +++ b/interfaces/kits/native/appkit/ability_runtime/context/context_impl.h @@ -170,6 +170,10 @@ public: */ void SetFont(std::string font); + void SetMcc(std::string mcc); + + void SetMnc(std::string mnc); + /** * @brief clear the application data by app self */ @@ -364,6 +368,8 @@ public: int32_t SetSupportedProcessCacheSelf(bool isSupport); + void PrintTokenInfo() const; + static const int EL_DEFAULT = 1; protected: @@ -427,6 +433,13 @@ private: const AppExecFwk::BundleInfo &bundleInfo, bool currentBundle, const std::string& moduleName); std::shared_ptr InitResourceManagerInner( const AppExecFwk::BundleInfo &bundleInfo, bool currentBundle, const std::string& moduleName); + void GetOverlayPath(std::shared_ptr &resourceManager, + const std::string &bundleName, const std::string &moduleName, std::string &loadPath, bool currentBundle); + void AddPatchResource(std::shared_ptr &resourceManager, + const std::string &loadPath, const std::string &hqfPath, bool isDebug); + void SubscribeToOverlayEvents(std::shared_ptr &resourceManager, + const std::string &name, const std::string &hapModuleName, std::string &loadPath, + std::vector overlayModuleInfos); void UpdateResConfig(std::shared_ptr &resourceManager); int32_t GetBundleInfo(const std::string &bundleName, AppExecFwk::BundleInfo &bundleInfo, bool ¤tBundle); void GetBundleInfo(const std::string &bundleName, AppExecFwk::BundleInfo &bundleInfo, const int &accountId); 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 777d32a5f9..c9a11bd463 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 @@ -133,6 +133,7 @@ private: napi_value OnSwitchArea(napi_env env, NapiCallbackInfo& info); napi_value OnGetArea(napi_env env, NapiCallbackInfo& info); napi_value OnCreateModuleContext(napi_env env, NapiCallbackInfo& info); + napi_value CreateJsModuleContext(napi_env env, const std::shared_ptr& moduleContext); napi_value OnCreateSystemHspModuleResourceManager(napi_env env, NapiCallbackInfo& info); napi_value OnGetApplicationContext(napi_env env, NapiCallbackInfo& info); bool CheckCallerIsSystemApp(); diff --git a/interfaces/kits/native/appkit/ability_runtime/service_extension_context.h b/interfaces/kits/native/appkit/ability_runtime/service_extension_context.h index e50ebbdc46..db0e3828fd 100644 --- a/interfaces/kits/native/appkit/ability_runtime/service_extension_context.h +++ b/interfaces/kits/native/appkit/ability_runtime/service_extension_context.h @@ -20,6 +20,7 @@ #include "ability_connect_callback.h" #include "connection_manager.h" +#include "free_install_observer_interface.h" #include "local_call_container.h" #include "start_options.h" #include "want.h" @@ -74,6 +75,8 @@ public: ErrCode StartAbilityByCall(const AAFwk::Want& want, const std::shared_ptr &callback, int32_t accountId = DEFAULT_INVAL_VALUE); + ErrCode AddFreeInstallObserver(const sptr &observer); + /** * caller release by callback object * @@ -122,6 +125,8 @@ public: ErrCode StartServiceExtensionAbility(const AAFwk::Want &want, int32_t accountId = -1) const; + ErrCode StartUIServiceExtensionAbility(const AAFwk::Want &want, int32_t accountId = -1) const; + ErrCode StopServiceExtensionAbility(const AAFwk::Want& want, int32_t accountId = -1) const; /** @@ -158,6 +163,9 @@ public: ErrCode RequestModalUIExtension(const Want &want); + ErrCode PreStartMission(const std::string& bundleName, const std::string& moduleName, + const std::string& abilityName, const std::string& startTime); + using SelfType = ServiceExtensionContext; static const size_t CONTEXT_TYPE_ID; diff --git a/interfaces/kits/native/appkit/app/child_main_thread.h b/interfaces/kits/native/appkit/app/child_main_thread.h index 5b77395a95..89bdaffb55 100644 --- a/interfaces/kits/native/appkit/app/child_main_thread.h +++ b/interfaces/kits/native/appkit/app/child_main_thread.h @@ -34,17 +34,20 @@ namespace OHOS { namespace AppExecFwk { class ChildMainThread : public ChildSchedulerStub { DECLARE_DELAYED_IPCSINGLETON(ChildMainThread); - + public: - static void Start(const ChildProcessInfo &processInfo); + static void Start(const std::map &fds); + void SetFds(const std::map &fds); bool ScheduleLoadJs() override; bool ScheduleExitProcessSafely() override; bool ScheduleRunNativeProc(const sptr &mainProcessCb) override; private: + static int32_t GetChildProcessInfo(ChildProcessInfo &info); bool Init(const std::shared_ptr &runner, const ChildProcessInfo &processInfo); bool Attach(); void HandleLoadJs(); + void HandleLoadArkTs(); void InitNativeLib(const BundleInfo &bundleInfo); void HandleExitProcessSafely(); void ExitProcessSafely(); @@ -60,6 +63,7 @@ private: std::shared_ptr processInfo_ = nullptr; std::unique_ptr runtime_ = nullptr; std::string nativeLibModuleName_; + std::shared_ptr processArgs_ = nullptr; DISALLOW_COPY_AND_MOVE(ChildMainThread); }; diff --git a/interfaces/kits/native/appkit/app/context_container.h b/interfaces/kits/native/appkit/app/context_container.h index 76e6ca8540..7348d91b61 100644 --- a/interfaces/kits/native/appkit/app/context_container.h +++ b/interfaces/kits/native/appkit/app/context_container.h @@ -231,6 +231,9 @@ public: */ void InitResourceManager(BundleInfo &bundleInfo, std::shared_ptr &deal); + void LoadResources(BundleInfo &bundleInfo, std::shared_ptr &resourceManager, + std::unique_ptr &resConfig, std::shared_ptr &deal); + /** * @brief Get the string of this Context based on the specified resource ID. * diff --git a/interfaces/kits/native/appkit/app/context_deal.h b/interfaces/kits/native/appkit/app/context_deal.h index 73cb8ca70e..569721bd9e 100644 --- a/interfaces/kits/native/appkit/app/context_deal.h +++ b/interfaces/kits/native/appkit/app/context_deal.h @@ -16,7 +16,7 @@ #ifndef OHOS_ABILITY_RUNTIME_CONTEXT_DEAL_H #define OHOS_ABILITY_RUNTIME_CONTEXT_DEAL_H -#include "context.h" +#include "fa_context.h" #include "lifecycle_state_info.h" namespace OHOS { diff --git a/interfaces/kits/native/appkit/app/dump_runtime_helper.h b/interfaces/kits/native/appkit/app/dump_runtime_helper.h new file mode 100644 index 0000000000..89f36960e4 --- /dev/null +++ b/interfaces/kits/native/appkit/app/dump_runtime_helper.h @@ -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. + */ + +#ifndef OHOS_ABILITY_RUNTIME_DUMP_RUNTIME_HELPER_H +#define OHOS_ABILITY_RUNTIME_DUMP_RUNTIME_HELPER_H + +#include "ohos_application.h" + +namespace OHOS { +namespace AppExecFwk { +class DumpRuntimeHelper : public std::enable_shared_from_this { +public: + explicit DumpRuntimeHelper(const std::shared_ptr &application); + ~DumpRuntimeHelper() = default; + void SetAppFreezeFilterCallback(); +private: + std::shared_ptr application_ = nullptr; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // OHOS_ABILITY_RUNTIME_DUMP_RUNTIME_HELPER_H diff --git a/interfaces/kits/native/appkit/app/context.h b/interfaces/kits/native/appkit/app/fa_context.h similarity index 100% rename from interfaces/kits/native/appkit/app/context.h rename to interfaces/kits/native/appkit/app/fa_context.h index 3a2b3a5f31..58408acea0 100644 --- a/interfaces/kits/native/appkit/app/context.h +++ b/interfaces/kits/native/appkit/app/fa_context.h @@ -18,13 +18,13 @@ #include -#include "bundle_mgr_interface.h" -#include "ability_manager_interface.h" #include "ability_info.h" -#include "process_info.h" -#include "resource_manager.h" +#include "ability_manager_interface.h" +#include "bundle_mgr_interface.h" #include "dummy_hap_module_info.h" #include "hap_module_info.h" +#include "process_info.h" +#include "resource_manager.h" #include "task/task_priority.h" namespace OHOS { diff --git a/interfaces/kits/native/appkit/app/main_thread.h b/interfaces/kits/native/appkit/app/main_thread.h index 47f5846a61..82c7c1fee7 100644 --- a/interfaces/kits/native/appkit/app/main_thread.h +++ b/interfaces/kits/native/appkit/app/main_thread.h @@ -19,28 +19,30 @@ #include #include #include + +#include "ability_record_mgr.h" +#include "app_jsheap_mem_info.h" +#include "app_malloc_info.h" +#include "app_mgr_interface.h" +#include "app_scheduler_host.h" +#include "application_impl.h" +#include "assert_fault_task_thread.h" +#include "common_event_subscriber.h" #include "event_handler.h" #include "extension_config_mgr.h" #include "idle_time.h" #include "inner_event.h" -#include "app_scheduler_host.h" -#include "app_mgr_interface.h" -#include "ability_record_mgr.h" -#include "application_impl.h" -#include "assert_fault_task_thread.h" -#include "common_event_subscriber.h" -#include "resource_manager.h" -#include "foundation/ability/ability_runtime/interfaces/inner_api/runtime/include/runtime.h" #include "ipc_singleton.h" -#ifdef CJ_FRONTEND -#include "cj_environment.h" -#endif #include "js_runtime.h" #include "native_engine/native_engine.h" #include "overlay_event_subscriber.h" +#include "resource_manager.h" +#include "runtime.h" #include "watchdog.h" -#include "app_malloc_info.h" -#include "app_jsheap_mem_info.h" + +#ifdef CJ_FRONTEND +#include "cj_envsetup.h" +#endif #define ABILITY_LIBRARY_LOADER class Runtime; @@ -251,6 +253,8 @@ public: */ static void Start(); + static void StartChild(const std::map &fds); + /** * * @brief Preload extensions in appspawn. @@ -613,6 +617,14 @@ private: bool IsBgWorkingThread(const AbilityInfo &info); + /** + * @brief parse app configuration params + * + * @param configuration input configuration + * @config the config of application + */ + void ParseAppConfigurationParams(const std::string configuration, Configuration &config); + class MainHandler : public EventHandler { public: MainHandler(const std::shared_ptr &runner, const sptr &thread); @@ -658,7 +670,8 @@ private: * */ void LoadAbilityLibrary(const std::vector &libraryPaths); - + void LoadAceAbilityLibrary(); + void CalcNativeLiabraryEntries(const BundleInfo &bundleInfo, std::string &nativeLibraryPath); void LoadNativeLiabrary(const BundleInfo &bundleInfo, std::string &nativeLibraryPath); @@ -690,7 +703,15 @@ private: bool CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData); bool InitResourceManager(std::shared_ptr &resourceManager, const AppExecFwk::HapModuleInfo &entryHapModuleInfo, const std::string &bundleName, - bool multiProjects, const Configuration &config); + const Configuration &config, const ApplicationInfo &appInfo); + void OnStartAbility(const std::string& bundleName, + std::shared_ptr &resourceManager, + const AppExecFwk::HapModuleInfo &entryHapModuleInfo, const bool isDebugApp); + std::vector GetOverlayPaths(const std::string &bundleName, + const std::vector &overlayModuleInfos); + void SubscribeOverlayChange(const std::string &bundleName, const std::string &loadPath, + std::shared_ptr &resourceManager, + const AppExecFwk::HapModuleInfo &entryHapModuleInfo); void HandleInitAssertFaultTask(bool isDebugModule, bool isDebugApp); void HandleCancelAssertFaultTask(); @@ -699,14 +720,6 @@ private: void GetNativeLibPath(const BundleInfo &bundleInfo, const HspList &hspList, AppLibPathMap &appLibPaths); void SetAppDebug(uint32_t modeFlag, bool isDebug); - /** - * @brief Whether MainThread is started by ChildProcessManager. - * - * @param info The child process info to be set from appMgr. - * @return true if started by ChildProcessManager, false otherwise. - */ - static bool IsStartChild(ChildProcessInfo &info); - std::vector fileEntries_; std::vector nativeFileEntries_; std::vector handleAbilityLib_; // the handler of ACE Library. diff --git a/interfaces/kits/native/appkit/app/ohos_application.h b/interfaces/kits/native/appkit/app/ohos_application.h index f8a664ce28..ca9e9a3ca2 100644 --- a/interfaces/kits/native/appkit/app/ohos_application.h +++ b/interfaces/kits/native/appkit/app/ohos_application.h @@ -22,9 +22,9 @@ #include #include "ability_lifecycle_callbacks.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/context.h" #include "ability_stage.h" #include "app_context.h" +#include "context.h" #include "element_callback.h" namespace OHOS { diff --git a/interfaces/kits/native/appkit/app_startup/startup_topologysort.h b/interfaces/kits/native/appkit/app_startup/startup_topologysort.h index 4b6b8c02bb..eb1cf5c41e 100644 --- a/interfaces/kits/native/appkit/app_startup/startup_topologysort.h +++ b/interfaces/kits/native/appkit/app_startup/startup_topologysort.h @@ -21,7 +21,6 @@ #include #include -#include "hilog_wrapper.h" #include "startup_task.h" #include "startup_sort_result.h" #include "startup_utils.h" diff --git a/js_environment/frameworks/js_environment/src/js_environment.cpp b/js_environment/frameworks/js_environment/src/js_environment.cpp index 6c4f1a90cf..900ea3f0ed 100644 --- a/js_environment/frameworks/js_environment/src/js_environment.cpp +++ b/js_environment/frameworks/js_environment/src/js_environment.cpp @@ -17,7 +17,6 @@ #include "ffrt.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_environment_impl.h" #include "native_engine/impl/ark/ark_native_engine.h" #include "uncaught_exception_callback.h" @@ -182,7 +181,7 @@ bool JsEnvironment::LoadScript(const std::string& path, std::vector* bu } bool JsEnvironment::StartDebugger( - std::string& option, uint32_t socketFd, bool isDebugApp, const DebuggerPostTask &debuggerPostTask) + std::string& option, uint32_t socketFd, bool isDebugApp) { TAG_LOGD(AAFwkTag::JSENV, "call."); if (vm_ == nullptr) { @@ -194,18 +193,7 @@ bool JsEnvironment::StartDebugger( TAG_LOGE(AAFwkTag::JSENV, "Abnormal parsing of tid results."); return false; } - if (isDebugApp) { - debugMode_ = panda::JSNApi::StartDebuggerForSocketPair(identifierId, socketFd); - } else { - if (debuggerPostTask == nullptr) { - TAG_LOGE(AAFwkTag::JSENV, "debuggerPostTask is nullptr."); - return false; - } - auto startDebuggerForSocketPairTask = [identifierId, socketFd, this]() { - debugMode_ = panda::JSNApi::StartDebuggerForSocketPair(identifierId, socketFd); - }; - debuggerPostTask(startDebuggerForSocketPairTask); - } + debugMode_ = panda::JSNApi::StartDebuggerForSocketPair(identifierId, socketFd); return debugMode_; } diff --git a/js_environment/frameworks/js_environment/src/source_map.cpp b/js_environment/frameworks/js_environment/src/source_map.cpp index ad09f8fda2..8091090dc1 100644 --- a/js_environment/frameworks/js_environment/src/source_map.cpp +++ b/js_environment/frameworks/js_environment/src/source_map.cpp @@ -24,7 +24,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace JsEnv { @@ -490,7 +489,7 @@ ErrorPos SourceMap::GetErrorPos(const std::string& rawStack) if (findLineEnd == std::string::npos) { return std::make_pair(0, 0); } - int32_t lineEnd = findLineEnd - 1; + int32_t lineEnd = (int32_t)findLineEnd - 1; if (lineEnd < 1 || rawStack[lineEnd - 1] == '?') { return std::make_pair(0, 0); } diff --git a/js_environment/frameworks/js_environment/src/uncaught_exception_callback.cpp b/js_environment/frameworks/js_environment/src/uncaught_exception_callback.cpp index 0a1f4efd5a..c6da39184f 100644 --- a/js_environment/frameworks/js_environment/src/uncaught_exception_callback.cpp +++ b/js_environment/frameworks/js_environment/src/uncaught_exception_callback.cpp @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "native_engine/native_engine.h" #ifdef SUPPORT_GRAPHICS #include "ui_content.h" diff --git a/js_environment/interfaces/inner_api/js_environment.h b/js_environment/interfaces/inner_api/js_environment.h index d5b8eb9a9c..b71140e4f9 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, uint32_t socketFd, bool isDebugApp, const DebuggerPostTask &debuggerPostTask); + std::string& option, uint32_t socketFd, bool isDebugApp); void StopDebugger(); 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 9e2611e4a8..3e2d27512b 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 @@ -21,7 +21,6 @@ #include #include "ecmascript/napi/include/jsnapi.h" -#include "hilog_wrapper.h" #include "ohos_js_env_logger.h" #include "ohos_js_environment_impl.h" @@ -235,7 +234,7 @@ HWTEST_F(JsEnvironmentTest, StartDebugger_0100, TestSize.Level0) std::string option = "ark:1234@Debugger"; uint32_t socketFd = 10; bool isDebugApp = true; - bool result = jsEnv->StartDebugger(option, socketFd, isDebugApp, jsEnv->GetDebuggerPostTask()); + bool result = jsEnv->StartDebugger(option, socketFd, isDebugApp); ASSERT_EQ(result, false); } @@ -256,7 +255,7 @@ HWTEST_F(JsEnvironmentTest, StartDebugger_0200, TestSize.Level0) std::string option = "ark:1234@Debugger"; uint32_t socketFd = 10; bool isDebugApp = true; - bool result = jsEnv->StartDebugger(option, socketFd, isDebugApp, jsEnv->GetDebuggerPostTask()); + bool result = jsEnv->StartDebugger(option, socketFd, isDebugApp); ASSERT_EQ(result, false); } diff --git a/services/abilitymgr/BUILD.gn b/services/abilitymgr/BUILD.gn index 34dfdda01c..c406730d89 100644 --- a/services/abilitymgr/BUILD.gn +++ b/services/abilitymgr/BUILD.gn @@ -20,6 +20,7 @@ group("abilityms_target") { deps = [ ":abilityms", ":ams_service_config", + ":mission_list", ] } @@ -32,6 +33,7 @@ config("abilityms_config") { "include/", "include/rdb/", "include/screen_lock/", + "include/dialog_session/", "${ability_runtime_innerkits_path}/ability_manager/include", "${ability_runtime_services_path}/appdfr/include", "${ability_runtime_innerkits_path}/app_manager/include", @@ -104,9 +106,12 @@ ohos_shared_library("abilityms") { ":abilityms_config", ":abilityms_exception_config", ] - include_dirs = [ "${ability_runtime_services_path}/appdfr/include" ] + include_dirs = [ + "${ability_runtime_services_path}/appdfr/include", + "${ability_runtime_path}/interfaces/kits/native/ability/native/ui_service_extension_ability/connection", + ] deps = [ - "${ability_runtime_innerkits_path}/ability_manager:ability_manager_base", + "${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", @@ -116,6 +121,214 @@ ohos_shared_library("abilityms") { "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_innerkits_path}/session_handler:session_handler", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${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:res_sched_util", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:extractortool", + "ability_base:session_info", + "ability_base:view_data", + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:libappexecfwk_common", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "graphic_2d:color_manager", + "hicollie:libhicollie", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "icu:shared_icuuc", + "init:libbeget_proxy", + "init:libbegetutil", + "ipc:ipc_core", + "json:nlohmann_json_static", + "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", + "samgr:samgr_proxy", + "window_manager:libmodal_system_ui_extension_client", + "window_manager:libwsutils", + "window_manager:scene_session", + "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" ] + } + + if (resource_schedule_service_enable) { + external_deps += [ "resource_schedule_service:ressched_client" ] + } + + if (os_dlp_part_enabled) { + cflags_cc += [ "-DWITH_DLP" ] + external_deps += [ "dlp_permission_service:libdlp_permission_sdk" ] + } + + defines = [] + + if (ability_runtime_graphics) { + defines += [ "SUPPORT_GRAPHICS" ] + external_deps += [ + "ability_base:session_info", + "i18n:intl_util", + "icu:shared_icuuc", + "image_framework:image_native", + "input:libmmi-client", + "resource_management:global_resmgr", + "screenlock_mgr:screenlock_client", + "window_manager:libdm", + "window_manager:libmodal_system_ui_extension_client", + "window_manager:libwm", + "window_manager:libwsutils", + "window_manager:scene_session", + "window_manager:sms", + ] + } + + if (include_app_domain_verify) { + external_deps += [ + "app_domain_verify:app_domain_verify_common", + "app_domain_verify:app_domain_verify_mgr_client", + ] + defines += [ "APP_DOMAIN_VERIFY_ENABLED" ] + } + + if (ability_runtime_power) { + defines += [ "SUPPORT_POWER" ] + external_deps += [ "power_manager:powermgr_client" ] + } + + version_script = "libabilityms.map" + subsystem_name = "ability" + innerapi_tags = [ "platformsdk_indirect" ] + part_name = "ability_runtime" +} + +ohos_prebuilt_etc("ams_service_config.json") { + source = "resource/ams_service_config.json" + subsystem_name = "ability" + part_name = "ability_runtime" +} + +ohos_prebuilt_etc("uiextension_picker_config.json") { + source = "resource/uiextension_picker_config.json" + subsystem_name = "ability" + part_name = "ability_runtime" +} + +ohos_prebuilt_etc("deeplink_reserve_config.json") { + source = "resource/deeplink_reserve_config.json" + subsystem_name = "ability" + part_name = "ability_runtime" +} + +ohos_prebuilt_etc("ams_extension_config.json") { + source = "resource/ams_extension_config.json" + subsystem_name = "ability" + part_name = "ability_runtime" +} + +ohos_prebuilt_etc("default_recovery_config.json") { + source = "resource/default_recovery_config.json" + subsystem_name = "ability" + part_name = "ability_runtime" +} + +ohos_prebuilt_etc("start_ability_without_caller_token.json") { + source = "resource/start_ability_without_caller_token.json" + subsystem_name = "ability" + part_name = "ability_runtime" +} + +ohos_shared_library("mission_list") { + 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 = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/ability_manager/include/status_bar_delegate", + "${ability_runtime_innerkits_path}/connectionobs_manager/include", + "${ability_runtime_innerkits_path}/deps_wrapper/include", + "${ability_runtime_innerkits_path}/session_handler/include", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_services_path}/common/include", + "${ability_runtime_services_path}/appdfr/include", + "${ability_runtime_utils_path}/global/constant", + "${ability_runtime_utils_path}/server/constant", + ] + + defines = [] + + if (ability_command_for_test) { + defines += [ "ABILITY_COMMAND_FOR_TEST" ] + } + + if (ability_runtime_graphics) { + defines += [ + "SUPPORT_GRAPHICS", + "SUPPORT_SCREEN", + ] + } + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + sources = [ + "src/mission.cpp", + "src/mission_data_storage.cpp", + "src/mission_info_mgr.cpp", + "src/mission_list.cpp", + "src/mission_list_manager.cpp", + "src/task_data_persistence_mgr.cpp", + ] + + deps = [ + ":abilityms", + "${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", + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${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", @@ -162,87 +375,39 @@ ohos_shared_library("abilityms") { "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr:samgr_proxy", - "window_manager:session_manager_lite", ] - public_external_deps = [ "background_task_mgr:bgtaskmgr_innerkits" ] if (background_task_mgr_continuous_task_enable) { external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] } - if (resource_schedule_service_enable) { - external_deps += [ "resource_schedule_service:ressched_client" ] - } - if (os_dlp_part_enabled) { - cflags_cc += [ "-DWITH_DLP" ] + defines += [ "WITH_DLP" ] external_deps += [ "dlp_permission_service:libdlp_permission_sdk" ] } - defines = [] - if (ability_runtime_graphics) { - defines += [ "SUPPORT_GRAPHICS" ] external_deps += [ "ability_base:session_info", "i18n:intl_util", "image_framework:image_native", - "screenlock_mgr:screenlock_client", + "resource_management:global_resmgr", "window_manager:libdm", - "window_manager:libmodal_system_ui_extension_client", "window_manager:libwm", - "window_manager:libwsutils", - "window_manager:scene_session", - "window_manager:sms", ] } - if (ability_runtime_power) { - defines += [ "SUPPORT_POWER" ] - external_deps += [ "power_manager:powermgr_client" ] - } - - version_script = "libabilityms.map" subsystem_name = "ability" innerapi_tags = [ "platformsdk_indirect" ] part_name = "ability_runtime" } -ohos_prebuilt_etc("ams_service_config.json") { - source = "resource/ams_service_config.json" - subsystem_name = "ability" - part_name = "ability_runtime" -} - -ohos_prebuilt_etc("uiextension_picker_config.json") { - source = "resource/uiextension_picker_config.json" - subsystem_name = "ability" - part_name = "ability_runtime" -} - -ohos_prebuilt_etc("deeplink_reserve_config.json") { - source = "resource/deeplink_reserve_config.json" - subsystem_name = "ability" - part_name = "ability_runtime" -} - -ohos_prebuilt_etc("ams_extension_config.json") { - source = "resource/ams_extension_config.json" - subsystem_name = "ability" - part_name = "ability_runtime" -} - -ohos_prebuilt_etc("default_recovery_config.json") { - source = "resource/default_recovery_config.json" - subsystem_name = "ability" - part_name = "ability_runtime" -} - group("ams_service_config") { deps = [ ":ams_service_config.json", ":deeplink_reserve_config.json", ":default_recovery_config.json", + ":start_ability_without_caller_token.json", ":uiextension_picker_config.json", ] } diff --git a/services/abilitymgr/abilitymgr.gni b/services/abilitymgr/abilitymgr.gni index be41b7ec36..fead53582d 100644 --- a/services/abilitymgr/abilitymgr.gni +++ b/services/abilitymgr/abilitymgr.gni @@ -35,14 +35,21 @@ abilityms_files = [ "src/data_ability_caller_recipient.cpp", "src/data_ability_manager.cpp", "src/data_ability_record.cpp", - "src/dialog_session_record.cpp", + "src/dialog_session/dialog_session_manager.cpp", "src/lifecycle_deal.cpp", + "src/ability_running_info.cpp", "src/ecological_rule/ability_ecological_rule_mgr_service_param.cpp", "src/ecological_rule/ability_ecological_rule_mgr_service.cpp", "src/extension_config.cpp", + "src/extension_running_info.cpp", + "src/caller_info.cpp", + "src/sender_info.cpp", "src/sub_managers_helper.cpp", + "src/wants_info.cpp", + "src/want_sender_info.cpp", "src/pending_want_record.cpp", "src/want_receiver_proxy.cpp", + "src/want_sender_proxy.cpp", "src/want_sender_stub.cpp", "src/pending_want_key.cpp", "src/pending_want_manager.cpp", @@ -72,27 +79,23 @@ abilityms_files = [ "src/start_ability_utils.cpp", # new ability manager service here - "src/task_data_persistence_mgr.cpp", "src/extension_record_manager.cpp", "src/extension_record.cpp", "src/extension_record_factory.cpp", "src/ui_extension_record.cpp", "src/ui_extension_record_factory.cpp", "src/screen_lock/unlock_screen_manager.cpp", + "src/start_options.cpp", + "src/user_callback_proxy.cpp", "src/call_container.cpp", "src/call_record.cpp", "src/inner_mission_info.cpp", - "src/mission.cpp", - "src/mission_data_storage.cpp", - "src/mission_info_mgr.cpp", "src/mission_listener_controller.cpp", "src/mission_listener_proxy.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/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/deeplink_reserve/deeplink_reserve_config.cpp", @@ -114,7 +117,6 @@ abilityms_files = [ "src/atomic_service_status_callback.cpp", "src/free_install_manager.cpp", "src/free_install_observer_manager.cpp", - "src/distributed_client.cpp", "src/background_task_observer.cpp", "src/resident_process_manager.cpp", @@ -126,12 +128,18 @@ abilityms_files = [ "src/ability_auto_startup_data_manager.cpp", "src/ability_auto_startup_service.cpp", + "src/auto_startup_info.cpp", "src/insight_intent_execute_manager.cpp", + "src/insight_intent_execute_result.cpp", "src/ability_manager_event_subscriber.cpp", #utils "src/utils/window_options_utils.cpp", + "src/utils/state_utils.cpp", + "src/utils/extension_permissions_util.cpp", + "src/utils/app_mgr_util.cpp", + "src/utils/dump_utils.cpp", ] if (ability_runtime_graphics) { @@ -143,3 +151,7 @@ if (ability_runtime_graphics) { "src/screen_lock/unlock_screen_callback.cpp", ] } + +if (include_app_domain_verify) { + abilityms_files += [ "src/ag_convert_callback_impl.cpp" ] +} diff --git a/services/abilitymgr/etc/appfwk.para b/services/abilitymgr/etc/appfwk.para index 7e0fca3c58..744752292a 100644 --- a/services/abilitymgr/etc/appfwk.para +++ b/services/abilitymgr/etc/appfwk.para @@ -34,6 +34,6 @@ persist.sys.abilityms.start_options_with_process_option = false persist.sys.abilityms.move_ui_ability_to_background_api_enable = true persist.sys.abilityms.prevent_startability = true const.abilityms.launch_embeded_ui_ability = false -persist.sys.abilityms.limit_maximum_extensions_of_per_process = 10 -persist.sys.abilityms.limit_maximum_extensions_of_per_device = 100 -persist.sys.abilityms.cache_extension = 3;5;17 \ No newline at end of file +const.sys.abilityms.limit_maximum_extensions_of_per_process = 10 +const.sys.abilityms.limit_maximum_extensions_of_per_device = 100 +const.sys.abilityms.cache_extension = 260 \ No newline at end of file diff --git a/services/abilitymgr/etc/appfwk.para.dac b/services/abilitymgr/etc/appfwk.para.dac index 9ca134de7f..2d31be0f30 100644 --- a/services/abilitymgr/etc/appfwk.para.dac +++ b/services/abilitymgr/etc/appfwk.para.dac @@ -34,6 +34,6 @@ persist.sys.abilityms.start_options_with_process_option = foundation:foundation: persist.sys.abilityms.move_ui_ability_to_background_api_enable = foundation:foundation:0755 persist.sys.abilityms.prevent_startability = foundation:foundation:0755 const.abilityms.launch_embeded_ui_ability = foundation:foundation:0755 -persist.sys.abilityms.limit_maximum_extensions_of_per_process = foundation:foundation:0755 -persist.sys.abilityms.limit_maximum_extensions_of_per_device = foundation:foundation:0755 -persist.sys.abilityms.cache_extension = foundation:foundation:0755 \ No newline at end of file +const.sys.abilityms.limit_maximum_extensions_of_per_process = foundation:foundation:0755 +const.sys.abilityms.limit_maximum_extensions_of_per_device = foundation:foundation:0755 +const.sys.abilityms.cache_extension = foundation:foundation:0755 \ No newline at end of file diff --git a/services/abilitymgr/include/ability_auto_startup_service.h b/services/abilitymgr/include/ability_auto_startup_service.h index c1503fe5b7..9340c8f345 100644 --- a/services/abilitymgr/include/ability_auto_startup_service.h +++ b/services/abilitymgr/include/ability_auto_startup_service.h @@ -22,6 +22,7 @@ #include "auto_startup_info.h" #include "bundle_mgr_client.h" +#include "bundle_mgr_helper.h" #include "iremote_object.h" #include "singleton.h" @@ -139,7 +140,8 @@ private: void CleanResource(const wptr &remote); std::string GetSelfApplicationBundleName(); bool CheckSelfApplication(const std::string &bundleName); - bool GetBundleInfo(const std::string &bundleName, AppExecFwk::BundleInfo &bundleInfo, int32_t uid, int32_t &userId); + bool GetBundleInfo(const std::string &bundleName, AppExecFwk::BundleInfo &bundleInfo, int32_t uid, + int32_t &userId, int32_t appIndex); bool GetAbilityData(const AutoStartupInfo &info, bool &isVisible, std::string &abilityTypeName, std::string &accessTokenId, int32_t &userId); std::string GetAbilityTypeName(AppExecFwk::AbilityInfo abilityInfo); diff --git a/services/abilitymgr/include/ability_bundle_event_callback.h b/services/abilitymgr/include/ability_bundle_event_callback.h index f8d8d99bf7..c10ac63c94 100644 --- a/services/abilitymgr/include/ability_bundle_event_callback.h +++ b/services/abilitymgr/include/ability_bundle_event_callback.h @@ -21,7 +21,6 @@ #include "common_event_support.h" #include "task_handler_wrap.h" #include "ability_event_util.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { @@ -49,6 +48,7 @@ private: void HandleUpdatedModuleInfo(const std::string &bundleName, int32_t uid); void HandleAppUpgradeCompleted(const std::string &bundleName, int32_t uid); void HandleRemoveUriPermission(uint32_t tokenId); + void HandleRestartResidentProcessDependedOnWeb(); DISALLOW_COPY_AND_MOVE(AbilityBundleEventCallback); AbilityEventUtil abilityEventHelper_; diff --git a/services/abilitymgr/include/ability_cache_manager.h b/services/abilitymgr/include/ability_cache_manager.h index df8aadfe34..1c2538288a 100644 --- a/services/abilitymgr/include/ability_cache_manager.h +++ b/services/abilitymgr/include/ability_cache_manager.h @@ -19,10 +19,10 @@ #include #include #include -#include -#include #include +#include "ability_config.h" +#include "ability_info.h" #include "ability_record.h" namespace OHOS { namespace AAFwk { @@ -33,6 +33,7 @@ namespace AAFwk { class AbilityCacheManager { public: using AbilityInfo = OHOS::AppExecFwk::AbilityInfo; + using AbilityType = OHOS::AppExecFwk::AbilityType; /** * Get ability cache manager. * @return AbilityCacheManager @@ -72,6 +73,43 @@ public: * @return AbilityRecord if one is matched, otherwise nullptr. */ std::shared_ptr FindRecordByToken(const sptr &token); + + /** + * Get all the abilities of current ability cache manager. + * @return AbilityRecord list. + */ + std::list> GetAbilityList(); + + /** + * Get a single ability by sessionId from ability cache manager. + * @param assertSessionId the ability assertSessionId to be searched in cache manager. + * @return AbilityRecord if one is matched, otherwise nullptr. + */ + std::shared_ptr FindRecordBySessionId(const std::string &assertSessionId); + + /** + * Get a single ability by serviceKey from ability cache manager. + * @param serviceKey the ability serviceKey to be searched in cache manager. + * @return AbilityRecord if one is matched, otherwise nullptr. + */ + std::shared_ptr FindRecordByServiceKey(const std::string &serviceKey); + + /** + * Remove the launcher death recipient from ability cache manager. + */ + void RemoveLauncherDeathRecipient(); + + /** + * Sign the restart flag by bundleName of ability from ability cache manager. + * @param bundleName the ability bundleName to be searched in cache manager. + */ + void SignRestartAppFlag(const std::string &bundleName); + + /** + * Delete the invalid ability by bundleName from ability cache manager. + * @param bundleName the ability bundleName to be searched in cache manager. + */ + void DeleteInvalidServiceRecord(const std::string &bundleName); private: AbilityCacheManager(); ~AbilityCacheManager(); diff --git a/services/abilitymgr/include/ability_config.h b/services/abilitymgr/include/ability_config.h index 65f393f128..ad41abbb48 100644 --- a/services/abilitymgr/include/ability_config.h +++ b/services/abilitymgr/include/ability_config.h @@ -38,6 +38,7 @@ constexpr const char* SCENEBOARD_ABILITY_NAME = "com.ohos.sceneboard.MainAbility constexpr const char* GRANT_ABILITY_BUNDLE_NAME = "com.ohos.permissionmanager"; constexpr const char* GRANT_ABILITY_ABILITY_NAME = "com.ohos.permissionmanager.GrantAbility"; constexpr const char* PARAMS_STREAM = "ability.params.stream"; +constexpr const char* CALLUI_ABILITY_NAME = "com.ohos.callui.ServiceAbility"; constexpr const char* MISSION_NAME_MARK_HEAD = "#"; constexpr const char* MISSION_NAME_SEPARATOR = ":"; } // namespace AbilityConfig diff --git a/services/abilitymgr/include/ability_connect_manager.h b/services/abilitymgr/include/ability_connect_manager.h index b35f19dc6f..9d008d315c 100644 --- a/services/abilitymgr/include/ability_connect_manager.h +++ b/services/abilitymgr/include/ability_connect_manager.h @@ -44,6 +44,7 @@ namespace AAFwk { using OHOS::AppExecFwk::AbilityType; using UIExtensionAbilityConnectInfo = AbilityRuntime::UIExtensionAbilityConnectInfo; using UIExtensionAbilityConnectManager = AbilityRuntime::ExtensionRecordManager; +using UIExtensionSessionInfo = AbilityRuntime::UIExtensionSessionInfo; /** * @class AbilityConnectManager * AbilityConnectManager provides a facility for managing service ability connection. @@ -301,6 +302,16 @@ public: std::shared_ptr GetUIExtensionRootHostInfo(const sptr token); + /** + * @brief Get ui extension session info + * + * @param token The ability token. + * @param uiExtensionSessionInfo The ui extension session info. + * @param userId The user id. + * @return int32_t Returns ERR_OK on success, others on failure. + */ + int32_t GetUIExtensionSessionInfo(const sptr token, UIExtensionSessionInfo &uiExtensionSessionInfo); + void CloseAssertDialog(const std::string &assertSessionId); void SignRestartAppFlag(const std::string &bundleName); @@ -342,11 +353,10 @@ private: * DisconnectAbilityLocked, disconnect session with callback. * * @param connect, Callback used to notify caller the result of connecting or disconnecting. - * @param force, Indicates forcing to disconnect and clear. For example, it is called when the source - * dies and the connection has not completed yet. + * @param callerDied, bool Indicates if it is caused by the caller's death. * @return Returns ERR_OK on success, others on failure. */ - int DisconnectAbilityLocked(const sptr &connect, bool force); + int DisconnectAbilityLocked(const sptr &connect, bool callerDied); /** * LoadAbility. @@ -362,6 +372,20 @@ private: */ void ConnectAbility(const std::shared_ptr &abilityRecord); + /** + * ConnectAbility.Schedule connect ability + * + * @param abilityRecord, the ptr of the ability to connect. + */ + void ConnectUIServiceExtAbility(const std::shared_ptr &abilityRecord, const Want &want); + + /** + * ConnectAbility.Schedule Resume Connect ability + * + * @param abilityRecord, the ptr of the ability to connect. + */ + void ResumeConnectAbility(const std::shared_ptr &abilityRecord); + /** * CommandAbility. Schedule command ability * @@ -558,12 +582,12 @@ private: private: void TerminateRecord(std::shared_ptr abilityRecord); - int DisconnectRecordNormal(ConnectListType &list, std::shared_ptr connectRecord) const; + int DisconnectRecordNormal(ConnectListType &list, std::shared_ptr connectRecord, + bool callerDied) const; void DisconnectRecordForce(ConnectListType &list, std::shared_ptr connectRecord); std::shared_ptr GetExtensionByIdFromServiceMap(int32_t abilityRecordId); int TerminateAbilityInner(const sptr &token); bool IsLauncher(std::shared_ptr serviceExtension) const; - bool IsSampleManagement(std::shared_ptr serviceExtension) const; void KillProcessesByUserId() const; void SetLastExitReason(const AbilityRequest &abilityRequest, std::shared_ptr &targetService); inline bool IsUIExtensionAbility(const std::shared_ptr &abilityRecord); @@ -591,19 +615,20 @@ private: void KeepAbilityAlive(const std::shared_ptr &abilityRecord, int32_t currentUserId); void ProcessEliminateAbilityRecord(std::shared_ptr eliminateRecord); + std::string GetServiceKey(const std::shared_ptr &service); private: const std::string TASK_ON_CALLBACK_DIED = "OnCallbackDiedTask"; const std::string TASK_ON_ABILITY_DIED = "OnAbilityDiedTask"; - std::mutex serialMutex_; + ffrt::mutex serialMutex_; std::mutex connectMapMutex_; ConnectMapType connectMap_; - std::mutex serviceMapMutex_; + ffrt::mutex serviceMapMutex_; ServiceMapType serviceMap_; - ServiceMapType terminatingExtensionMap_; + std::list> terminatingExtensionList_; std::mutex recipientMapMutex_; RecipientMapType recipientMap_; diff --git a/services/abilitymgr/include/ability_manager_proxy.h b/services/abilitymgr/include/ability_manager_proxy.h index 2cd94095fc..c561cee2ff 100644 --- a/services/abilitymgr/include/ability_manager_proxy.h +++ b/services/abilitymgr/include/ability_manager_proxy.h @@ -18,7 +18,6 @@ #include "ability_manager_interface.h" #include "auto_startup_info.h" -#include "hilog_wrapper.h" #include "iremote_proxy.h" #include "mission_info.h" @@ -145,8 +144,7 @@ public: const sptr &callerToken, sptr asCallerSourceToken, int32_t userId = DEFAULT_INVAL_VALUE, - int requestCode = DEFAULT_INVAL_VALUE, - bool isSendDialogResult = false) override; + int requestCode = DEFAULT_INVAL_VALUE) override; /** * Starts a new ability using the original caller information. @@ -579,15 +577,27 @@ public: */ virtual int UninstallApp(const std::string &bundleName, int32_t uid) override; + /** + * Uninstall app + * + * @param bundleName bundle name of uninstalling app. + * @param uid uid of bundle. + * @param appIndex the app index of app clone. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t UninstallApp(const std::string &bundleName, int32_t uid, int32_t appIndex) override; + /** * Upgrade app, record exit reason and kill application * * @param bundleName bundle name of upgrading app. * @param uid uid of bundle. * @param exitMsg the exit reason message. + * @param appIndex the app index of app clone. * @return Returns ERR_OK on success, others on failure. */ - virtual int32_t UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg) override; + virtual int32_t UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg, + int32_t appIndex = 0) override; virtual sptr GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) override; @@ -708,7 +718,8 @@ public: virtual int SetMissionIcon(const sptr &token, const std::shared_ptr &icon) override; - virtual int RegisterWindowManagerServiceHandler(const sptr& handler) override; + virtual int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled) override; virtual void CompleteFirstFrameDrawing(const sptr &abilityToken) override; @@ -717,9 +728,9 @@ public: virtual int PrepareTerminateAbility( const sptr &token, sptr &callback) override; - virtual int GetDialogSessionInfo(const std::string dialogSessionId, sptr &info) override; + virtual int GetDialogSessionInfo(const std::string &dialogSessionId, sptr &info) override; - virtual int SendDialogResult(const Want &want, const std::string dialogSessionId, bool isAllow) override; + virtual int SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllow) override; virtual int RegisterAbilityFirstFrameStateObserver(const sptr &observer, const std::string &targetBundleName) override; @@ -874,7 +885,8 @@ public: * @param observer the observer of ability free install start. * @return Returns ERR_OK on success, others on failure. */ - virtual int AddFreeInstallObserver(const sptr &observer) override; + virtual int AddFreeInstallObserver(const sptr &callerToken, + const sptr &observer) override; /** * Called when client complete dump. @@ -1165,6 +1177,17 @@ public: int32_t GetUIExtensionRootHostInfo(const sptr token, UIExtensionHostInfo &hostInfo, int32_t userId = DEFAULT_INVAL_VALUE) override; + /** + * @brief Get ui extension session info + * + * @param token The ability token. + * @param uiExtensionSessionInfo The ui extension session info. + * @param userId The user id. + * @return int32_t Returns ERR_OK on success, others on failure. + */ + int32_t GetUIExtensionSessionInfo(const sptr token, UIExtensionSessionInfo &uiExtensionSessionInfo, + int32_t userId = DEFAULT_INVAL_VALUE) override; + /** * @brief Restart app self. * @param want The ability type must be UIAbility. @@ -1255,6 +1278,30 @@ public: */ virtual void NotifyFrozenProcessByRSS(const std::vector &pidList, int32_t uid) override; + /** + * Open atomic service window prior to finishing free install. + * + * @param bundleName, the bundle name of the atomic service. + * @param moduleName, the module name of the atomic service. + * @param abilityName, the ability name of the atomic service. + * @param startTime, the starting time of the free install task. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t PreStartMission(const std::string& bundleName, const std::string& moduleName, + const std::string& abilityName, const std::string& startTime) override; + + /** + * Open link of ability and atomic service. + * + * @param want Ability want. + * @param callerToken Caller ability token. + * @param userId User ID. + * @param requestCode Ability request code. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t OpenLink(const Want& want, sptr callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = DEFAULT_INVAL_VALUE) 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 b5fb6e0399..e702ab45c8 100644 --- a/services/abilitymgr/include/ability_manager_service.h +++ b/services/abilitymgr/include/ability_manager_service.h @@ -16,6 +16,7 @@ #ifndef OHOS_ABILITY_RUNTIME_ABILITY_MANAGER_SERVICE_H #define OHOS_ABILITY_RUNTIME_ABILITY_MANAGER_SERVICE_H +#include #include #include #include @@ -30,6 +31,7 @@ #include "ability_connect_manager.h" #include "ability_debug_deal.h" #include "ability_event_handler.h" +#include "ability_info.h" #include "ability_manager_event_subscriber.h" #include "ability_manager_stub.h" #include "ams_configuration_parameter.h" @@ -47,11 +49,10 @@ #include "deeplink_reserve/deeplink_reserve_config.h" #include "event_report.h" #include "free_install_manager.h" -#include "hilog_wrapper.h" #include "iacquire_share_data_callback_interface.h" #include "interceptor/ability_interceptor_executer.h" #include "iremote_object.h" -#include "mission_list_manager.h" +#include "mission_list_manager_interface.h" #include "parameter.h" #include "pending_want_manager.h" #include "permission_verification.h" @@ -64,7 +65,6 @@ #include "uri.h" #include "user_controller.h" #ifdef SUPPORT_GRAPHICS -#include "dialog_session_record.h" #include "implicit_start_processor.h" #include "system_dialog_scheduler.h" #endif @@ -83,6 +83,7 @@ enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; constexpr int32_t BASE_USER_RANGE = 200000; constexpr int32_t U0_USER_ID = 0; constexpr int32_t INVALID_USER_ID = -1; +constexpr const char* KEY_SESSION_ID = "com.ohohs.param.sessionId"; using OHOS::AppExecFwk::IAbilityController; class PendingWantManager; struct StartAbilityInfo; @@ -99,6 +100,8 @@ class AbilityManagerService : public SystemAbility, DECLARE_DELAYED_SINGLETON(AbilityManagerService) DECLEAR_SYSTEM_ABILITY(AbilityManagerService) public: + static std::shared_ptr GetPubInstance(); + void OnStart() override; void OnStop() override; @@ -251,8 +254,7 @@ public: const sptr &callerToken, sptr asCallerSourceToken, int32_t userId = DEFAULT_INVAL_VALUE, - int requestCode = DEFAULT_INVAL_VALUE, - bool isSendDialogResult = false) override; + int requestCode = DEFAULT_INVAL_VALUE) override; /** * Starts a new ability using the original caller information. @@ -341,6 +343,18 @@ public: int32_t userId, int requestCode) override; + /** + * Open link of ability and atomic service. + * + * @param want Ability want. + * @param callerToken Caller ability token. + * @param userId User ID. + * @param requestCode Ability request code. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t OpenLink(const Want& want, sptr callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = DEFAULT_INVAL_VALUE) override; + /** * Pop-up launch of full-screen atomic service. * @@ -791,15 +805,27 @@ public: */ virtual int UninstallApp(const std::string &bundleName, int32_t uid) override; + /** + * Uninstall app + * + * @param bundleName bundle name of uninstalling app. + * @param uid uid of bundle. + * @param appIndex the app index of app clone. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t UninstallApp(const std::string &bundleName, int32_t uid, int32_t appIndex) override; + /** * Upgrade app, record exit reason and kill application * * @param bundleName bundle name of upgrading app. * @param uid uid of bundle. * @param exitMsg the exit reason message. + * @param appIndex the app index of app clone. * @return Returns ERR_OK on success, others on failure. */ - virtual int32_t UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg) override; + virtual int32_t UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg, + int32_t appIndex = 0) override; virtual sptr GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr &callerToken) override; @@ -933,7 +959,6 @@ public: int requestCode, int32_t userId = DEFAULT_INVAL_VALUE, bool isStartAsCaller = false, - bool isSendDialogResult = false, uint32_t specifyTokenId = 0, bool isForegroundToRestartApp = false, bool isImplicit = false); @@ -944,7 +969,6 @@ public: int requestCode, int32_t userId = DEFAULT_INVAL_VALUE, bool isStartAsCaller = false, - bool isSendDialogResult = false, uint32_t specifyTokenId = 0, bool isForegroundToRestartApp = false, bool isImplicit = false); @@ -971,7 +995,8 @@ public: int requestCode = DEFAULT_INVAL_VALUE, bool isStartAsCaller = false, uint32_t callerTokenId = 0, - bool isImplicit = false); + bool isImplicit = false, + bool isCallByShortcut = false); int StartAbilityForOptionInner( const Want &want, @@ -981,7 +1006,8 @@ public: int requestCode = DEFAULT_INVAL_VALUE, bool isStartAsCaller = false, uint32_t specifyTokenId = 0, - bool isImplicit = false); + bool isImplicit = false, + bool isCallByShortcut = false); int ImplicitStartAbility( const Want &want, @@ -1017,7 +1043,6 @@ public: sptr asCallerSourceToken, int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = DEFAULT_INVAL_VALUE, - bool isSendDialogResult = false, bool isImplicit = false); int ImplicitStartAbilityAsCaller( @@ -1025,8 +1050,7 @@ public: const sptr &callerToken, sptr asCallerSourceToken, int32_t userId = DEFAULT_INVAL_VALUE, - int requestCode = DEFAULT_INVAL_VALUE, - bool isSendDialogResult = false); + int requestCode = DEFAULT_INVAL_VALUE); void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag, int32_t requestId = 0); void OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want, int32_t requestId = 0); @@ -1096,7 +1120,8 @@ public: virtual int SetMissionIcon(const sptr &token, const std::shared_ptr &icon) override; - virtual int RegisterWindowManagerServiceHandler(const sptr& handler) override; + virtual int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled) override; virtual void CompleteFirstFrameDrawing(const sptr &abilityToken) override; @@ -1111,15 +1136,12 @@ public: void HandleUnfocused(const sptr &focusChangeInfo); - virtual int GetDialogSessionInfo(const std::string dialogSessionId, + virtual int GetDialogSessionInfo(const std::string &dialogSessionId, sptr &dialogSessionInfo) override; - bool GenerateDialogSessionRecord(AbilityRequest &abilityRequest, int32_t userId, - std::string &dialogSessionId, std::vector &dialogAppInfos, bool isSelector); + virtual int SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllowed) override; - int CreateModalDialog(const Want &replaceWant, sptr callerToken, std::string dialogSessionId); - - virtual int SendDialogResult(const Want &want, const std::string dialogSessionId, bool isAllowed) override; + int CreateCloneSelectorDialog(AbilityRequest &request, int32_t userId, const std::string &replaceWantString = ""); virtual int RegisterAbilityFirstFrameStateObserver(const sptr &observer, const std::string &bundleName) override; @@ -1127,6 +1149,8 @@ public: virtual int UnregisterAbilityFirstFrameStateObserver( const sptr &observer) override; + bool GetAnimationFlag(); + #endif void ClearUserData(int32_t userId); @@ -1281,7 +1305,8 @@ public: * @param observer the observer of ability free install start. * @return Returns ERR_OK on success, others on failure. */ - virtual int AddFreeInstallObserver(const sptr &observer) override; + virtual int AddFreeInstallObserver(const sptr &callerToken, + const sptr &observer) override; /** * Check the uid is background task uid. @@ -1610,6 +1635,17 @@ public: int32_t GetUIExtensionRootHostInfo(const sptr token, UIExtensionHostInfo &hostInfo, int32_t userId = DEFAULT_INVAL_VALUE) override; + /** + * @brief Get ui extension session info + * + * @param token The ability token. + * @param uiExtensionSessionInfo The ui extension session info. + * @param userId The user id. + * @return int32_t Returns ERR_OK on success, others on failure. + */ + int32_t GetUIExtensionSessionInfo(const sptr token, UIExtensionSessionInfo &uiExtensionSessionInfo, + int32_t userId = DEFAULT_INVAL_VALUE) override; + /** * Set the enable status for starting and stopping resident processes. * The caller application can only set the resident status of the configured process. @@ -1672,7 +1708,9 @@ public: virtual int32_t TransferAbilityResultForExtension(const sptr &callerToken, int32_t resultCode, const Want &want) override; - std::shared_ptr GetMissionListManagerByUserId(int32_t userId); + std::shared_ptr GetMissionListManagerByUserId(int32_t userId); + std::shared_ptr GetMissionListWrap(); + /** * Notify ability manager service frozen process. * @@ -1681,6 +1719,25 @@ public: */ virtual void NotifyFrozenProcessByRSS(const std::vector &pidList, int32_t uid) override; + void HandleRestartResidentProcessDependedOnWeb(); + + /** + * Open atomic service window prior to finishing free install. + * + * @param bundleName, the bundle name of the atomic service. + * @param moduleName, the module name of the atomic service. + * @param abilityName, the ability name of the atomic service. + * @param startTime, the starting time of the free install task. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t PreStartMission(const std::string& bundleName, const std::string& moduleName, + const std::string& abilityName, const std::string& startTime) override; + + int32_t StartUIAbilityByPreInstall(const FreeInstallInfo &taskInfo); + + void NotifySCBToHandleAtomicServiceException(const std::string& sessionId, int errCode, + const std::string& reason); + // MSG 0 - 20 represents timeout message static constexpr uint32_t LOAD_TIMEOUT_MSG = 0; static constexpr uint32_t ACTIVE_TIMEOUT_MSG = 1; @@ -1704,31 +1761,6 @@ public: static constexpr uint32_t MAX_WAIT_SYSTEM_UI_NUM = 600; static constexpr uint32_t MAX_WAIT_SETTINGS_DATA_NUM = 300; - enum DumpKey { - KEY_DUMP_ALL = 0, - KEY_DUMP_STACK_LIST, - KEY_DUMP_STACK, - KEY_DUMP_MISSION, - KEY_DUMP_TOP_ABILITY, - KEY_DUMP_WAIT_QUEUE, - KEY_DUMP_SERVICE, - KEY_DUMP_DATA, - KEY_DUMP_FOCUS_ABILITY, - KEY_DUMP_WINDOW_MODE, - KEY_DUMP_MISSION_LIST, - KEY_DUMP_MISSION_INFOS, - }; - - enum DumpsysKey { - KEY_DUMPSYS_ALL = 0, - KEY_DUMPSYS_MISSION_LIST, - KEY_DUMPSYS_ABILITY, - KEY_DUMPSYS_SERVICE, - KEY_DUMPSYS_PENDING, - KEY_DUMPSYS_PROCESS, - KEY_DUMPSYS_DATA, - }; - enum { ABILITY_MOVE_TO_FOREGROUND_CODE = 0, ABILITY_MOVE_TO_BACKGROUND_CODE, @@ -1791,6 +1823,12 @@ private: int StartRemoteAbility(const Want &want, int requestCode, int32_t validUserId, const sptr &callerToken); + int StartUIAbilityBySCBDefault(sptr sessionInfo, bool &isColdStart); + int StartUIAbilityByPreInstallInner(sptr sessionInfo, + uint32_t specifyTokenId, bool &isColdStart); + int32_t PreStartInner(const FreeInstallInfo& taskInfo); + void RemovePreStartSession(const std::string& sessionId); + int ConnectLocalAbility( const Want &want, const int32_t userId, @@ -1891,8 +1929,8 @@ private: std::shared_ptr GetConnectManagerByToken(const sptr &token); std::shared_ptr GetCurrentPendingWantManager(); std::shared_ptr GetPendingWantManagerByUserId(int32_t userId); - std::unordered_map> GetMissionListManagers(); - std::shared_ptr GetCurrentMissionListManager(); + std::unordered_map> GetMissionListManagers(); + std::shared_ptr GetCurrentMissionListManager(); std::unordered_map> GetUIAbilityManagers(); std::shared_ptr GetCurrentUIAbilityManager(); std::shared_ptr GetUIAbilityManagerByUserId(int32_t userId); @@ -1926,6 +1964,8 @@ private: int CheckStaticCfgPermission(const AppExecFwk::AbilityRequest &abilityRequest, bool isStartAsCaller, uint32_t callerTokenId, bool isData = false, bool isSaCall = false, bool isImplicit = false); + int CheckPermissionForUIService(const Want &want, const AbilityRequest &abilityRequest); + bool GetValidDataAbilityUri(const std::string &abilityInfoUri, std::string &adjustUri); int GenerateExtensionAbilityRequest(const Want &want, AbilityRequest &request, @@ -1947,7 +1987,7 @@ private: void ReportAbilitAssociatedStartInfoToRSS(const AppExecFwk::AbilityInfo &abilityInfo, int64_t type, const sptr &callerToken); - void ReportEventToRSS(const AppExecFwk::AbilityInfo &abilityInfo); + void ReportEventToRSS(const AppExecFwk::AbilityInfo &abilityInfo, sptr callerToken); void ReportAppRecoverResult(const int32_t appId, const AppExecFwk::ApplicationInfo &appInfo, const std::string& abilityName, const std::string& result); @@ -2006,7 +2046,8 @@ private: * @param abilityRequest, abilityRequest. * @return Returns whether the caller is allowed to start Ability. */ - int CheckCallAbilityPermission(const AbilityRequest &abilityRequest, uint32_t specifyTokenId = 0); + int CheckCallAbilityPermission(const AbilityRequest &abilityRequest, uint32_t specifyTokenId = 0, + bool isCallByShortcut = false); /** * Check if Caller is allowed to start Ability(Stage) by call. @@ -2130,7 +2171,7 @@ private: bool CheckSenderWantInfo(int32_t callerUid, const WantSenderInfo &wantSenderInfo); - int32_t UninstallAppInner(const std::string &bundleName, const int32_t uid, const bool isUpgrade, + int32_t UninstallAppInner(const std::string &bundleName, const int32_t uid, int32_t appIndex, const bool isUpgrade, const std::string &exitMsg); int32_t GetMissionIdByAbilityTokenInner(const sptr &token); @@ -2145,12 +2186,39 @@ private: std::shared_ptr ConnectInitAbilityDebugDeal(); int StartUIAbilityForOptionWrap(const Want &want, const StartOptions &options, sptr callerToken, - int32_t userId, int requestCode, uint32_t callerTokenId = 0, bool isImplicit = false); + int32_t userId, int requestCode, uint32_t callerTokenId = 0, bool isImplicit = false, + bool isCallByShortcut = false); int32_t SetBackgroundCall(const AppExecFwk::RunningProcessInfo &processInfo, const AbilityRequest &abilityRequest, bool &isBackgroundCall) const; void GetRunningMultiAppIndex(const std::string &bundleName, int32_t uid, int32_t &appIndex); + ErrCode ConvertToExplicitWant(Want& want); + + int CheckUIExtensionUsage(AppExecFwk::UIExtensionUsage uiExtensionUsage, + AppExecFwk::ExtensionAbilityType extensionType); + + int CheckExtensionCallPermission(const Want& want, const AbilityRequest& abilityRequest); + + int CheckServiceCallPermission(const AbilityRequest& abilityRequest, + const AppExecFwk::AbilityInfo& abilityInfo); + + int CheckBrokerCallPermission(const AbilityRequest& abilityRequest, + const AppExecFwk::AbilityInfo& abilityInfo); + + int CheckAbilityCallPermission(const AbilityRequest& abilityRequest, + const AppExecFwk::AbilityInfo& abilityInfo, uint32_t specifyTokenId); + + int CheckCallPermission(const Want& want, const AppExecFwk::AbilityInfo& abilityInfo, + const AbilityRequest& abilityRequest, bool isForegroundToRestartApp, + bool isSendDialogResult, uint32_t specifyTokenId, + const std::string& callerBundleName); + + int StartAbilityByConnectManager(const Want& want, const AbilityRequest& abilityRequest, + const AppExecFwk::AbilityInfo& abilityInfo, int validUserId, sptr callerToken); + + int PreStartFreeInstall(const Want &want, sptr callerToken, + uint32_t specifyTokenId, bool isStartAsCaller, Want &localWant); constexpr static int REPOLL_TIME_MICRO_SECONDS = 1000000; constexpr static int WAITING_BOOT_ANIMATION_TIMER = 5; @@ -2161,9 +2229,6 @@ private: sptr iBundleManager_; std::shared_ptr bundleMgrHelper_; sptr appMgr_ { nullptr }; - const static std::map dumpMap; - const static std::map dumpsysMap; - const static std::map windowModeMap; std::shared_ptr freeInstallManager_; @@ -2175,8 +2240,10 @@ private: ffrt::mutex globalLock_; ffrt::mutex bgtaskObserverMutex_; ffrt::mutex abilityTokenLock_; + ffrt::mutex preStartSessionMapLock_; std::multimap timeoutMap_; + std::map> preStartSessionMap_; static sptr instance_; int32_t uniqueId_ = 0; @@ -2236,6 +2303,8 @@ private: void ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo &callerAbilityInfo, const AppExecFwk::AbilityInfo &abilityInfo); + + void SetAbilityRequestSessionInfo(AbilityRequest &abilityRequest, AppExecFwk::ExtensionAbilityType extensionType); #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE std::shared_ptr bgtaskObserver_; #endif @@ -2250,7 +2319,7 @@ private: void InitPrepareTerminateConfig(); std::shared_ptr implicitStartProcessor_; sptr wmsHandler_; - std::shared_ptr dialogSessionRecord_; + bool isAnimationEnabled_ = true; //only use on mission list #endif std::shared_ptr interceptorExecuter_; std::shared_ptr afterCheckExecuter_; diff --git a/services/abilitymgr/include/ability_manager_stub.h b/services/abilitymgr/include/ability_manager_stub.h index b2e56e3768..26c262ba31 100644 --- a/services/abilitymgr/include/ability_manager_stub.h +++ b/services/abilitymgr/include/ability_manager_stub.h @@ -22,7 +22,6 @@ #include #include "dlp_connection_info.h" -#include "hilog_wrapper.h" #include "iconnection_observer.h" namespace OHOS { @@ -93,7 +92,8 @@ private: int StartAbilityAsCallerForOptionInner(MessageParcel &data, MessageParcel &reply); int StartExtensionAbilityInner(MessageParcel &data, MessageParcel &reply); int StartUIExtensionAbilityInner(MessageParcel &data, MessageParcel &reply); - int StartUIExtensionAbilityNonModalInner(MessageParcel &data, MessageParcel &reply); + int StartUIExtensionAbilityEmbeddedInner(MessageParcel &data, MessageParcel &reply); + int StartUIExtensionConstrainedEmbeddedInner(MessageParcel &data, MessageParcel &reply); int StartUIAbilityBySCBInner(MessageParcel &data, MessageParcel &reply); int StopExtensionAbilityInner(MessageParcel& data, MessageParcel& reply); int StartAbilityAddCallerInner(MessageParcel &data, MessageParcel &reply); @@ -287,6 +287,7 @@ private: int32_t GetForegroundUIAbilitiesInner(MessageParcel &data, MessageParcel &reply); int32_t GetUIExtensionRootHostInfoInner(MessageParcel &data, MessageParcel &reply); + int32_t GetUIExtensionSessionInfoInner(MessageParcel &data, MessageParcel &reply); int32_t RestartAppInner(MessageParcel &data, MessageParcel &reply); int32_t RequestAssertFaultDialogInner(MessageParcel &data, MessageParcel &reply); int32_t NotifyDebugAssertResultInner(MessageParcel &data, MessageParcel &reply); @@ -294,6 +295,7 @@ private: int32_t GetAbilityStateByPersistentIdInner(MessageParcel &data, MessageParcel &reply); int32_t TransferAbilityResultForExtensionInner(MessageParcel &data, MessageParcel &reply); int32_t NotifyFrozenProcessByRSSInner(MessageParcel &data, MessageParcel &reply); + int32_t PreStartMissionInner(MessageParcel &data, MessageParcel &reply); int OnRemoteRequestInnerFirst(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); int OnRemoteRequestInnerSecond(uint32_t code, MessageParcel &data, @@ -338,6 +340,7 @@ private: MessageParcel &reply, MessageOption &option); int HandleOnRemoteRequestInnerSecond(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t OpenLinkInner(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 602bcba928..bc446fcac5 100644 --- a/services/abilitymgr/include/ability_record.h +++ b/services/abilitymgr/include/ability_record.h @@ -21,6 +21,7 @@ #include #include #include +#include #include "cpp/mutex.h" #include "cpp/condition_variable.h" @@ -249,13 +250,16 @@ struct AbilityRequest { sptr sessionInfo; uint32_t specifyTokenId = 0; - bool IsContinuation() const + std::pair IsContinuation() const { auto flags = want.GetFlags(); if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) { - return true; + return {true, LaunchReason::LAUNCHREASON_CONTINUATION}; } - return false; + if ((flags & Want::FLAG_ABILITY_PREPARE_CONTINUATION) == Want::FLAG_ABILITY_PREPARE_CONTINUATION) { + return {true, LaunchReason::LAUNCHREASON_PREPARE_CONTINUATION}; + } + return {false, LaunchReason::LAUNCHREASON_UNKNOWN}; } bool IsAcquireShareData() const @@ -621,12 +625,24 @@ public: */ void ConnectAbility(); + /** + * connect the ability. + * + */ + void ConnectUIServiceExtAbility(const Want &want); + /** * disconnect the ability. * */ void DisconnectAbility(); + /** + * disconnect the ability with want + * + */ + void DisconnectUIServiceExtAbility(const Want &want); + /** * Command the ability. * @@ -739,6 +755,11 @@ public: */ std::list> GetConnectingRecordList(); + /** + * get the count of In Progress record. + * + */ + uint32_t GetInProgressRecordCount(); /** * remove the connect record from list. * @@ -1148,9 +1169,6 @@ private: std::list> callerList_ = {}; bool isUninstall_ = false; - const static std::map stateToStrMap; - const static std::map convertStateMap; - const static std::map appStateToStrMap_; bool isLauncherRoot_ = false; diff --git a/services/abilitymgr/include/ability_service_util.h b/services/abilitymgr/include/ability_service_util.h deleted file mode 100644 index 9e946a4e50..0000000000 --- a/services/abilitymgr/include/ability_service_util.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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_ABILITY_SERVICE_UTIL_H -#define OHOS_ABILITY_RUNTIME_ABILITY_SERVICE_UTIL_H - -#include "ability_manager_service.h" -#include "bundle_mgr_helper.h" -#include "hilog_tag_wrapper.h" - -namespace OHOS { -namespace AAFwk { -namespace AbilityUtil { -constexpr const char* MARKET_BUNDLE_NAME = "com.huawei.hmsapp.appgallery"; -constexpr const char* MARKET_CROWD_TEST_BUNDLE_PARAM = "crowd_test_bundle_name"; - -[[maybe_unused]] static int StartAppgallery(const std::string &bundleName, const int requestCode, const int32_t userId, - const std::string &action) -{ - std::string appGalleryBundleName; - auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper(); - if (bundleMgrHelper == nullptr || !bundleMgrHelper->QueryAppGalleryBundleName(appGalleryBundleName)) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Get bundle manager helper failed or QueryAppGalleryBundleName failed."); - appGalleryBundleName = MARKET_BUNDLE_NAME; - } - - TAG_LOGD(AAFwkTag::ABILITYMGR, "appGalleryBundleName:%{public}s", appGalleryBundleName.c_str()); - - Want want; - want.SetElementName(appGalleryBundleName, ""); - want.SetAction(action); - want.SetParam(MARKET_CROWD_TEST_BUNDLE_PARAM, bundleName); - return DelayedSingleton::GetInstance()->StartAbility(want, requestCode, userId); -} -} // namespace AbilityUtil -} // namespace AAFwk -} // namespace OHOS -#endif \ No newline at end of file diff --git a/services/abilitymgr/include/ability_util.h b/services/abilitymgr/include/ability_util.h index 5097d4770f..316d125233 100644 --- a/services/abilitymgr/include/ability_util.h +++ b/services/abilitymgr/include/ability_util.h @@ -20,8 +20,8 @@ #include #include "ability_config.h" +#include "ability_manager_client.h" #include "ability_manager_errors.h" -#include "ability_window_configuration.h" #include "app_jump_control_rule.h" #include "bundle_mgr_helper.h" #include "hilog_tag_wrapper.h" @@ -44,6 +44,8 @@ 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"; +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"; @@ -315,11 +317,33 @@ static constexpr int64_t MICROSECONDS = 1000000; // MICROSECONDS mean 10^6 mi windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY)) { want.SetParam(Want::PARAM_RESV_WINDOW_MODE, windowMode); TAG_LOGI(AAFwkTag::ABILITYMGR, "set parameter windownMode for inner application split-screen mode"); + } else if (windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FULLSCREEN) { + want.SetParam(Want::PARAM_RESV_WINDOW_MODE, windowMode); + TAG_LOGI(AAFwkTag::ABILITYMGR, "set parameter windownMode for full screen mode"); } else { RemoveWindowModeKey(want); } } +[[maybe_unused]] static int StartAppgallery(const std::string &bundleName, const int requestCode, const int32_t userId, + const std::string &action) +{ + std::string appGalleryBundleName; + auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper(); + if (bundleMgrHelper == nullptr || !bundleMgrHelper->QueryAppGalleryBundleName(appGalleryBundleName)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Get bundle manager helper failed or QueryAppGalleryBundleName failed."); + appGalleryBundleName = MARKET_BUNDLE_NAME; + } + + TAG_LOGD(AAFwkTag::ABILITYMGR, "appGalleryBundleName:%{public}s", appGalleryBundleName.c_str()); + + Want want; + want.SetElementName(appGalleryBundleName, ""); + want.SetAction(action); + want.SetParam(MARKET_CROWD_TEST_BUNDLE_PARAM, bundleName); + return AbilityManagerClient::GetInstance()->StartAbility(want, requestCode, userId); +} + inline ErrCode EdmErrorType(bool isEdm) { if (isEdm) { diff --git a/services/abilitymgr/include/ag_convert_callback_impl.h b/services/abilitymgr/include/ag_convert_callback_impl.h new file mode 100644 index 0000000000..1dc002aa18 --- /dev/null +++ b/services/abilitymgr/include/ag_convert_callback_impl.h @@ -0,0 +1,48 @@ +/* + * 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_AG_CONVERT_CALLBACK_IMPL_H +#define OHOS_ABILITY_RUNTIME_AG_CONVERT_CALLBACK_IMPL_H + +#include "convert_callback_stub.h" + +#include + +#include "ffrt.h" + +namespace OHOS { +namespace AAFwk { +using ConvertCallbackTask = std::function; + +/** + * @class ConvertCallbackImpl the implementation of the IConvertCallback +*/ +class ConvertCallbackImpl : public OHOS::AppDomainVerify::ConvertCallbackStub { +public: + explicit ConvertCallbackImpl(ConvertCallbackTask&& task) : task_(task) {} + virtual ~ConvertCallbackImpl() = default; + + void OnConvert(int resultCode, AAFwk::Want& want) override; + + void Cancel(); + +private: + ffrt::mutex taskMutex_; + ConvertCallbackTask task_; +}; +} // namespace AAFwk +} // namespace OHOS + +#endif // OHOS_ABILITY_RUNTIME_AG_CONVERT_CALLBACK_IMPL_H diff --git a/services/abilitymgr/include/app_exit_reason_data_manager.h b/services/abilitymgr/include/app_exit_reason_data_manager.h index d0fb0c43a6..79c3dafa9b 100644 --- a/services/abilitymgr/include/app_exit_reason_data_manager.h +++ b/services/abilitymgr/include/app_exit_reason_data_manager.h @@ -39,7 +39,9 @@ public: int32_t GetAppExitReason(const std::string &bundleName, uint32_t accessTokenId, const std::string &abilityName, bool &isSetReason, AAFwk::ExitReason &exitReason); - int32_t DeleteAppExitReason(const std::string &bundleName, int32_t uid); + int32_t DeleteAppExitReason(const std::string &bundleName, int32_t uid, int32_t appIndex); + + int32_t DeleteAppExitReason(const std::string &bundleName, uint32_t accessTokenId); int32_t AddAbilityRecoverInfo(uint32_t accessTokenId, const std::string &moduleName, const std::string &abilityName, const int &sessionId); diff --git a/services/abilitymgr/include/app_exit_reason_helper.h b/services/abilitymgr/include/app_exit_reason_helper.h index 6cb25d8f16..91c87ef0fa 100644 --- a/services/abilitymgr/include/app_exit_reason_helper.h +++ b/services/abilitymgr/include/app_exit_reason_helper.h @@ -31,20 +31,18 @@ public: ~AppExitReasonHelper() = default; int32_t RecordAppExitReason(const ExitReason &exitReason); + int32_t RecordAppExitReason(const std::string &bundleName, int32_t uid, int32_t appIndex, + const ExitReason &exitReason); int32_t RecordProcessExtensionExitReason( const int32_t pid, const std::string &bundleName, const ExitReason &exitReason); int32_t RecordProcessExitReason(const int32_t pid, const ExitReason &exitReason); - int32_t RecordProcessExitReason(const std::string &bundleName, int32_t uid, const ExitReason &exitReason); private: int32_t RecordProcessExitReason(const int32_t pid, const std::string bundleName, const int32_t uid, const uint32_t accessTokenId, const ExitReason &exitReason); - void GetActiveAbilityListByU0(const std::string bundleName, std::vector &abilityLists, + void GetActiveAbilityList(int32_t uid, std::vector &abilityLists, const int32_t pid); + void GetActiveAbilityListFromUIAbilityManager(int32_t uid, std::vector &abilityLists, const int32_t pid); - void GetActiveAbilityListByUser(const std::string bundleName, std::vector &abilityLists, - const int32_t targetUserId, const int32_t pid); - void GetActiveAbilityListFromUIAabilityManager(const std::string bundleName, - std::vector &abilityLists, const int32_t targetUserId, const int32_t pid); bool IsExitReasonValid(const ExitReason &exitReason); std::shared_ptr subManagersHelper_; diff --git a/services/abilitymgr/include/app_gallery_enable_util.h b/services/abilitymgr/include/app_gallery_enable_util.h index 94200dd65f..9cc5352aef 100644 --- a/services/abilitymgr/include/app_gallery_enable_util.h +++ b/services/abilitymgr/include/app_gallery_enable_util.h @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parameters.h" namespace OHOS { diff --git a/services/abilitymgr/include/app_scheduler.h b/services/abilitymgr/include/app_scheduler.h index 0503b782e2..141532b8ed 100644 --- a/services/abilitymgr/include/app_scheduler.h +++ b/services/abilitymgr/include/app_scheduler.h @@ -21,6 +21,7 @@ #include "ability_debug_response_interface.h" #include "ability_info.h" +#include "ability_manager_client.h" #include "app_debug_listener_interface.h" #include "application_info.h" #include "appmgr/app_mgr_client.h" @@ -232,6 +233,17 @@ public: */ int KillApplication(const std::string &bundleName, const bool clearPageStack = true); + /** + * ForceKillApplication, force kill the application. + * + * @param bundleName, bundle name in Application record. + * @param userId, userId. + * @param appIndex, appIndex. + * @return ERR_OK, return back success, others fail. + */ + int ForceKillApplication(const std::string &bundleName, const int userId = -1, + const int appIndex = 0); + /** * kill the application by uid * @@ -252,7 +264,7 @@ public: void AttachTimeOut(const sptr &token); - void PrepareTerminate(const sptr &token); + void PrepareTerminate(const sptr &token, bool clearMissionFlag = false); void GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info); @@ -433,6 +445,10 @@ public: */ void AttachedToStatusBar(const sptr &token); + void BlockProcessCacheByPids(const std::vector& pids); + + bool IsKilledForUpgradeWeb(const std::string &bundleName); + protected: /** * OnAbilityRequestDone, app manager service call this interface after ability request done. diff --git a/services/abilitymgr/include/application_util.h b/services/abilitymgr/include/application_util.h index b3befb45b6..2f7a6831ef 100644 --- a/services/abilitymgr/include/application_util.h +++ b/services/abilitymgr/include/application_util.h @@ -19,7 +19,6 @@ #include "common_event_manager.h" #include "common_event_support.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parameters.h" #include "want.h" diff --git a/services/abilitymgr/include/atomic_service_status_callback.h b/services/abilitymgr/include/atomic_service_status_callback.h index 960f7b2aff..3480cb0d0b 100644 --- a/services/abilitymgr/include/atomic_service_status_callback.h +++ b/services/abilitymgr/include/atomic_service_status_callback.h @@ -31,7 +31,7 @@ class FreeInstallManager; */ class AtomicServiceStatusCallback : public AtomicServiceStatusCallbackStub { public: - AtomicServiceStatusCallback(const std::weak_ptr &server, bool isAsync); + AtomicServiceStatusCallback(const std::weak_ptr &server, bool isAsync, int32_t recordId); virtual ~AtomicServiceStatusCallback() = default; /** @@ -52,16 +52,10 @@ public: */ void OnRemoteInstallFinished(int resultCode, const Want &want, int32_t userId) override; - /** - * OnRemoveTimeoutTask, BMS has connected AG. - * - * @param want, installed ability - */ - void OnRemoveTimeoutTask(const Want &want) override; - private: std::weak_ptr server_; bool isAsync_; + int32_t recordId_ = -1; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/connection_record.h b/services/abilitymgr/include/connection_record.h index 28f8eae51c..a1e75192d6 100644 --- a/services/abilitymgr/include/connection_record.h +++ b/services/abilitymgr/include/connection_record.h @@ -140,6 +140,8 @@ public: sptr GetTargetToken() const; sptr GetConnection() const; + void SetConnectWant(const Want &want); + Want GetConnectWant(); private: static int64_t connectRecordId; int recordId_ = 0; // record id @@ -154,6 +156,8 @@ private: uint32_t callerTokenId_ = 0; // caller pid std::string callerName_; // caller bundleName or processName + Want connectWant_; + DISALLOW_COPY_AND_MOVE(ConnectionRecord); }; } // namespace AAFwk diff --git a/services/abilitymgr/include/dialog_session/dialog_session_manager.h b/services/abilitymgr/include/dialog_session/dialog_session_manager.h new file mode 100644 index 0000000000..ba8f1c4d4f --- /dev/null +++ b/services/abilitymgr/include/dialog_session/dialog_session_manager.h @@ -0,0 +1,105 @@ +/* + * 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_DIALOG_SESSION_MANAGEER_H +#define OHOS_ABILITY_RUNTIME_DIALOG_SESSION_MANAGEER_H +#include +#include +#include +#include "ability_record.h" +#include "cpp/mutex.h" +#include "dialog_session_info.h" +#include "json_serializer.h" +#include "nocopyable.h" +#include "parcel.h" +#include "refbase.h" +#include "system_dialog_scheduler.h" +#include "want.h" + +namespace OHOS { +namespace AAFwk { +struct DialogCallerInfo { + int32_t userId = -1; + int requestCode = -1; + sptr callerToken; + Want targetWant; + bool isSelector = false; +}; + +enum class SelectorType { + IMPLICIT_START_SELECTOR = 0, + APP_CLONR_SELECTOR = 1 +}; + +class DialogSessionManager { +public: + static DialogSessionManager &GetInstance(); + ~DialogSessionManager() = default; + + sptr GetDialogSessionInfo(const std::string &dialogSessionId) const; + + std::shared_ptr GetDialogCallerInfo(const std::string &dialogSessionId) const; + + int SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllowed); + + int CreateJumpModalDialog(AbilityRequest &abilityRequest, int32_t userId, const Want &replaceWant); + + int CreateImplicitSelectorModalDialog(AbilityRequest &abilityRequest, const Want &want, int32_t userId, + std::vector &dialogAppInfos); + + int CreateCloneSelectorModalDialog(AbilityRequest &abilityRequest, const Want &want, int32_t userId, + std::vector &dialogAppInfos, const std::string &replaceWant); + + int HandleErmsResult(AbilityRequest &abilityRequest, int32_t userId, const Want &replaceWant); + + bool IsCreateCloneSelectorDialog(const std::string &bundleName, int32_t userId); + +private: + DialogSessionManager() = default; + std::string GenerateDialogSessionId(); + + void SetDialogSessionInfo(const std::string &dialogSessionId, sptr &dilogSessionInfo, + std::shared_ptr &dialogCallerInfo); + + void ClearDialogContext(const std::string &dialogSessionId); + + void ClearAllDialogContexts(); + + std::string GenerateDialogSessionRecordCommon(AbilityRequest &abilityRequest, int32_t userId, + const AAFwk::WantParams ¶meters, std::vector &dialogAppInfos, bool isSelector); + + void GenerateCallerAbilityInfo(AbilityRequest &abilityRequest, DialogAbilityInfo &callerAbilityInfo); + + void GenerateSelectorTargetAbilityInfos(std::vector &dialogAppInfos, + std::vector &targetAbilityInfos); + + void GenerateJumpTargetAbilityInfos(AbilityRequest &abilityRequest, + std::vector &targetAbilityInfos); + + void GenerateDialogCallerInfo(AbilityRequest &abilityRequest, int32_t userId, + std::shared_ptr dialogCallerInfo, bool isSelector); + + int CreateModalDialogCommon(const Want &replaceWant, sptr callerToken, + const std::string &dialogSessionId); + + mutable ffrt::mutex dialogSessionRecordLock_; + std::unordered_map> dialogSessionInfoMap_; + std::unordered_map> dialogCallerInfoMap_; + + DISALLOW_COPY_AND_MOVE(DialogSessionManager); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_DIALOG_SESSION_MANAGEER_H diff --git a/services/abilitymgr/include/dialog_session_record.h b/services/abilitymgr/include/dialog_session_record.h deleted file mode 100644 index 1db719fb53..0000000000 --- a/services/abilitymgr/include/dialog_session_record.h +++ /dev/null @@ -1,65 +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_DIALOG_SESSION_RECORD_H -#define OHOS_ABILITY_RUNTIME_DIALOG_SESSION_RECORD_H -#include -#include -#include -#include "ability_record.h" -#include "cpp/mutex.h" -#include "dialog_session_info.h" -#include "json_serializer.h" -#include "parcel.h" -#include "refbase.h" -#include "system_dialog_scheduler.h" -#include "want.h" - -namespace OHOS { -namespace AAFwk { -struct DialogCallerInfo { - int32_t userId = -1; - int requestCode = -1; - sptr callerToken; - Want targetWant; - bool isSelector = false; -}; - -class DialogSessionRecord { -public: - std::string GenerateDialogSessionId(); - - void SetDialogSessionInfo(const std::string dialogSessionId, sptr &dilogSessionInfo, - std::shared_ptr &dialogCallerInfo); - - sptr GetDialogSessionInfo(const std::string dialogSessionId) const; - - std::shared_ptr GetDialogCallerInfo(const std::string dialogSessionId) const; - - void ClearDialogContext(const std::string dialogSessionId); - - void ClearAllDialogContexts(); - - bool GenerateDialogSessionRecord(AbilityRequest &abilityRequest, int32_t userId, - std::string &dialogSessionId, std::vector &dialogAppInfos, bool isSelector); - -private: - mutable ffrt::mutex dialogSessionRecordLock_; - std::unordered_map> dialogSessionInfoMap_; - std::unordered_map> dialogCallerInfoMap_; -}; -} // namespace AAFwk -} // namespace OHOS -#endif // OHOS_ABILITY_RUNTIME_DIALOG_SESSION_RECORD_H diff --git a/services/abilitymgr/include/dlp_utils.h b/services/abilitymgr/include/dlp_utils.h index cfe58adec3..8b447d0680 100644 --- a/services/abilitymgr/include/dlp_utils.h +++ b/services/abilitymgr/include/dlp_utils.h @@ -23,7 +23,6 @@ #endif // WITH_DLP #include "global_constant.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "in_process_call_wrapper.h" #include "iremote_object.h" #include "permission_verification.h" 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 ea12333645..6214fe5836 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 @@ -28,7 +28,7 @@ namespace EcologicalRuleMgrService { using Want = OHOS::AAFwk::Want; struct AbilityExperienceRule : public Parcelable { - bool isAllow = true; + int32_t resultCode = 10; std::string sceneCode = ""; sptr replaceWant = nullptr; @@ -75,6 +75,8 @@ struct AbilityCallerInfo : public Parcelable { std::string callerAppProvisionType; std::string targetAppProvisionType; AppExecFwk::ExtensionAbilityType callerExtensionAbilityType = AppExecFwk::ExtensionAbilityType::UNSPECIFIED; + AppExecFwk::AbilityType targetAbilityType = AppExecFwk::AbilityType::UNKNOWN; + AppExecFwk::ExtensionAbilityType targetExtensionAbilityType = AppExecFwk::ExtensionAbilityType::UNSPECIFIED; bool ReadFromParcel(Parcel &parcel); diff --git a/services/abilitymgr/include/extension_record.h b/services/abilitymgr/include/extension_record.h index 5bb7e67527..591bbed947 100644 --- a/services/abilitymgr/include/extension_record.h +++ b/services/abilitymgr/include/extension_record.h @@ -54,6 +54,7 @@ public: int32_t extensionRecordId_ = INVALID_EXTENSION_RECORD_ID; uint32_t processMode_ = 0; bool isHostSpecified_ = false; + pid_t hostPid_ = 0; private: sptr rootCallerToken_ = nullptr; sptr preLoadUIExtStateObserver_; diff --git a/services/abilitymgr/include/extension_record_manager.h b/services/abilitymgr/include/extension_record_manager.h index ff7879cee3..621d6fdf74 100644 --- a/services/abilitymgr/include/extension_record_manager.h +++ b/services/abilitymgr/include/extension_record_manager.h @@ -25,6 +25,7 @@ #include "ability_record.h" #include "extension_record.h" #include "ui_extension_host_info.h" +#include "ui_extension_session_info.h" namespace OHOS { namespace AbilityRuntime { @@ -89,14 +90,14 @@ public: int32_t CreateExtensionRecord(const AAFwk::AbilityRequest &abilityRequest, const std::string &hostBundleName, std::shared_ptr &extensionRecord, int32_t &extensionRecordId); - + bool IsPreloadExtensionRecord(const AAFwk::AbilityRequest &abilityRequest, const std::string &hostBundleName, std::shared_ptr &extensionRecord, bool &isLoaded); int32_t AddPreloadUIExtensionRecord(const std::shared_ptr abilityRecord); void RemoveAllPreloadUIExtensionRecord(PreLoadUIExtensionMapKey &preLoadUIExtensionInfo); - + bool RemovePreloadUIExtensionRecord( const std::tuple extensionRecordMapKey); @@ -111,6 +112,8 @@ public: std::shared_ptr GetUIExtensionRootHostInfo(const sptr token); + int32_t GetUIExtensionSessionInfo(const sptr token, UIExtensionSessionInfo &uiExtensionSessionInfo); + void LoadTimeout(int32_t extensionRecordId); void ForegroundTimeout(int32_t extensionRecordId); void BackgroundTimeout(int32_t extensionRecordId); diff --git a/services/abilitymgr/include/free_install_manager.h b/services/abilitymgr/include/free_install_manager.h index 15285b8de1..8a2bcb1987 100644 --- a/services/abilitymgr/include/free_install_manager.h +++ b/services/abilitymgr/include/free_install_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 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 @@ -21,6 +21,7 @@ #include #include +#include #include "ability_info.h" #include "free_install_observer_manager.h" @@ -39,6 +40,13 @@ struct FreeInstallInfo { std::string identity; sptr callerToken = nullptr; sptr dmsCallback = nullptr; + bool isPreStartMissionCalled = false; + bool isStartUIAbilityBySCBCalled = false; + uint32_t specifyTokenId = 0; + bool isOpenAtomicServiceShortUrl = false; + std::shared_ptr originalWant = nullptr; + bool isFreeInstallFinished = false; + int resultCode = 0; }; /** @@ -57,7 +65,7 @@ public: * @param want, installed ability. * @param userId, user`s id. */ - void OnInstallFinished(int resultCode, const Want &want, int32_t userId, bool isAsync = false); + void OnInstallFinished(int32_t recordId, int resultCode, const Want &want, int32_t userId, bool isAsync = false); /** * OnRemoteInstallFinished, DMS has finished. @@ -66,7 +74,7 @@ public: * @param want, installed ability. * @param userId, user`s id. */ - void OnRemoteInstallFinished(int resultCode, const Want &want, int32_t userId); + void OnRemoteInstallFinished(int32_t recordId, int resultCode, const Want &want, int32_t userId); /** * Start to free install. @@ -76,10 +84,12 @@ public: * @param requestCode, ability request code. * @param callerToken, caller ability token. * @param isAsync, the request is async. + * @param isOpenAtomicServiceShortUrl, the flag of open atomic service short url. * @return Returns ERR_OK on success, others on failure. */ int StartFreeInstall(const Want &want, int32_t userId, int requestCode, const sptr &callerToken, - bool isAsync = false); + bool isAsync = false, uint32_t specifyTokenId = 0, bool isOpenAtomicServiceShortUrl = false, + std::shared_ptr originalWant = nullptr); /** * Start to remote free install. @@ -122,13 +132,62 @@ public: * @param observer, the observer of the ability to free install. * @return Returns ERR_OK on success, others on failure. */ - int AddFreeInstallObserver(const sptr &observer); + int AddFreeInstallObserver(const sptr &callerToken, + const sptr &observer); /** - * Remove the timeout task when bms connect FA center. - * @param want, the want of the ability to free install. - */ - void OnRemoveTimeoutTask(const Want &want); + * Get free install task info. + * + * @param bundleName, the bundle name of the task. + * @param abilityName, the ability name of the task. + * @param startTime, the start time of the task. + * @param taskInfo, the found task info + * @return Returns true on success, false on failure. + */ + bool GetFreeInstallTaskInfo(const std::string& bundleName, const std::string& abilityName, + const std::string& startTime, FreeInstallInfo& taskInfo); + + /** + * Get free install task info. + * + * @param sessionId, the sessionId of the task. + * @param taskInfo, the found task info + * @return Returns true on success, false on failure. + */ + bool GetFreeInstallTaskInfo(const std::string& sessionId, FreeInstallInfo& taskInfo); + + /** + * Set the isStartUIAbilityBySCBCalled flag of the given free install task. + * + * @param bundleName, the bundle name of the task. + * @param abilityName, the abilitu name of the task. + * @param startTime, the start time of the task. + * @param scbCallStatus, the status of whether StartUIAbilityBySCB is called. + */ + void SetSCBCallStatus(const std::string& bundleName, const std::string& abilityName, + const std::string& startTime, bool scbCallStatus); + + /** + * Set the isPreStartMissionCalled flag of the given free install task. + * + * @param bundleName, the bundle name of the task. + * @param abilityName, the abilitu name of the task. + * @param startTime, the start time of the task. + * @param preStartMissionCallStatus, the status of whether PreStartMission is called. + */ + void SetPreStartMissionCallStatus(const std::string& bundleName, const std::string& abilityName, + const std::string& startTime, bool preStartMissionCallStatus); + + /** + * Set the sessionId of the given free install task. + * + * @param bundleName, the bundle name of the task. + * @param abilityName, the abilitu name of the task. + * @param startTime, the start time of the task. + * @param sessionId, the sessionId of the free install task. + */ + void SetFreeInstallTaskSessionId(const std::string& bundleName, const std::string& abilityName, + const std::string& startTime, const std::string& sessionId); private: std::weak_ptr server_; @@ -138,6 +197,9 @@ private: ffrt::mutex distributedFreeInstallLock_; ffrt::mutex freeInstallListLock_; ffrt::mutex freeInstallObserverLock_; + + int SetAppRunningState(Want &want); + /** * Start remote free install. * @@ -151,23 +213,34 @@ private: int NotifyDmsCallback(const Want &want, int resultCode); bool IsTopAbility(const sptr &callerToken); - void NotifyFreeInstallResult(const Want &want, int resultCode, bool isAsync = false); + void NotifyFreeInstallResult(int32_t recordId, const Want &want, int resultCode, bool isAsync = false); FreeInstallInfo BuildFreeInstallInfo(const Want &want, int32_t userId, int requestCode, - const sptr &callerToken, bool isAsync); + const sptr &callerToken, bool isAsync, uint32_t specifyTokenId = 0, + bool isOpenAtomicServiceShortUrl = false, std::shared_ptr originalWant = nullptr); std::time_t GetTimeStamp(); void RemoveFreeInstallInfo(const std::string &bundleName, const std::string &abilityName, const std::string &startTime); - + void PostUpgradeAtomicServiceTask(int resultCode, const Want &want, int32_t userId); - void PostTimeoutTask(const Want &want); - void HandleTimeoutTask(const std::string &bundleName, const std::string &abilityName, const std::string &startTime); void RemoveTimeoutTask(const std::string &bundleName, const std::string &abilityName, const std::string &startTime); void StartAbilityByFreeInstall(FreeInstallInfo &info, std::string &bundleName, std::string &abilityName, std::string &startTime); + void StartAbilityByPreInstall(int32_t recordId, FreeInstallInfo &info, std::string &bundleName, + std::string &abilityName, std::string &startTime); int32_t UpdateElementName(Want &want, int32_t userId) const; + void HandleFreeInstallResult(int32_t recordId, FreeInstallInfo &freeInstallInfo, int resultCode, bool isAsync); + void HandleOnFreeInstallSuccess(int32_t recordId, FreeInstallInfo &freeInstallInfo, bool isAsync); + void HandleOnFreeInstallFail(int32_t recordId, FreeInstallInfo &freeInstallInfo, int resultCode, bool isAsync); + void NotifySCBToHandleException(const FreeInstallInfo &info, int resultCode); + void StartAbilityByConvertedWant(FreeInstallInfo &info, const std::string &startTime); + void StartAbilityByOriginalWant(FreeInstallInfo &info, const std::string &startTime); + bool VerifyStartFreeInstallPermission(const sptr &callerToken); + int32_t GetRecordIdByToken(const sptr &callerToken); + void NotifyInsightIntentFreeInstallResult(const Want &want, int resultCode); + void NotifyInsightIntentExecuteDone(const Want &want, int resultCode); }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/free_install_observer_manager.h b/services/abilitymgr/include/free_install_observer_manager.h index 132f68abec..84116ea635 100644 --- a/services/abilitymgr/include/free_install_observer_manager.h +++ b/services/abilitymgr/include/free_install_observer_manager.h @@ -18,7 +18,7 @@ #include #include -#include +#include #include "cpp/mutex.h" #include "free_install_observer_interface.h" @@ -30,24 +30,28 @@ using namespace OHOS::AbilityRuntime; class FreeInstallObserverManager : public std::enable_shared_from_this { DECLARE_DELAYED_SINGLETON(FreeInstallObserverManager) public: - int32_t AddObserver(const sptr &observer); + int32_t AddObserver(int32_t recordId, const sptr &observer); int32_t RemoveObserver(const sptr &observer); - void OnInstallFinished(const std::string &bundleName, const std::string &abilityName, + void OnInstallFinished(int32_t recordId, const std::string &bundleName, const std::string &abilityName, const std::string &startTime, const int &resultCode); + void OnInstallFinishedByUrl(int32_t recordId, const std::string &startTime, const std::string &url, + const int &resultCode); + private: - bool ObserverExistLocked(const sptr &observer); - void OnObserverDied(const wptr &remote); - void HandleOnInstallFinished(const std::string &bundleName, const std::string &abilityName, + void HandleOnInstallFinished(int32_t recordId, const std::string &bundleName, const std::string &abilityName, const std::string &startTime, const int &resultCode); + void HandleOnInstallFinishedByUrl(int32_t recordId, const std::string &startTime, const std::string &url, + const int &resultCode); + ffrt::mutex observerLock_; sptr deathRecipient_; - std::vector> observerList_; + std::unordered_map> observerMap_; }; class FreeInstallObserverRecipient : public IRemoteObject::DeathRecipient { diff --git a/services/abilitymgr/include/implicit_start_processor.h b/services/abilitymgr/include/implicit_start_processor.h index b61ecf71b7..697cdf804d 100644 --- a/services/abilitymgr/include/implicit_start_processor.h +++ b/services/abilitymgr/include/implicit_start_processor.h @@ -58,20 +58,25 @@ public: static bool IsImplicitStartAction(const Want &want); - int ImplicitStartAbility(AbilityRequest &request, int32_t userId, int32_t windowMode = 0); + int ImplicitStartAbility(AbilityRequest &request, int32_t userId, int32_t windowMode = 0, + const std::string &replaceWantString = "", bool isAppCloneSelector = false); void ResetCallingIdentityAsCaller(int32_t tokenId); - int NotifyCreateModalDialog(AbilityRequest &abilityRequest, const Want &want, int32_t userId, - std::vector &dialogAppInfos); - void SetUriReservedFlag(const bool flag); void SetUriReservedBundle(const std::string bundleName); private: int GenerateAbilityRequestByAction(int32_t userId, AbilityRequest &request, - std::vector &dialogAppInfos, bool isMoreHapList); + std::vector &dialogAppInfos, bool isMoreHapList, bool &findDefaultApp); + + int GenerateAbilityRequestByAppIndexes(int32_t userId, AbilityRequest &request, + std::vector &dialogAppInfos); + + int FindExtensionInfo(const Want &want, int32_t flags, int32_t userId, int32_t appIndex, + AppExecFwk::AbilityInfo &abilityInfo); + std::string MatchTypeAndUri(const AAFwk::Want &want); std::shared_ptr GetBundleManagerHelper(); std::vector SplitStr(const std::string& str, char delimiter); @@ -98,13 +103,13 @@ private: bool IsExistDefaultApp(int32_t userId, const std::string &typeName); - bool IsCallFromAncoShellOrBroker(const sptr &token); - void SetTargetLinkInfo(const std::vector &skillUri, Want &want); void OnlyKeepReserveApp(std::vector &abilityInfos, std::vector &extensionInfos); + bool IsActionImplicitStart(const Want &want, bool findDeafultApp); + private: const static std::vector blackList; const static std::unordered_set extensionWhiteList; diff --git a/services/abilitymgr/include/interceptor/ecological_rule_interceptor.h b/services/abilitymgr/include/interceptor/ecological_rule_interceptor.h index 9f9bd8aecf..a1b0c4b9c0 100644 --- a/services/abilitymgr/include/interceptor/ecological_rule_interceptor.h +++ b/services/abilitymgr/include/interceptor/ecological_rule_interceptor.h @@ -40,9 +40,13 @@ public: }; private: + void GetEcologicalTargetInfo(const Want &want, const std::shared_ptr &abilityInfo, + ErmsCallerInfo &callerInfo); void GetEcologicalCallerInfo(const Want &want, ErmsCallerInfo &callerInfo, int32_t userId, const sptr &callerToken = nullptr); - void InitErmsCallerInfo(Want &want, ErmsCallerInfo &callerInfo) const; + void InitErmsCallerInfo(const Want &want, const std::shared_ptr &abilityInfo, + ErmsCallerInfo &callerInfo, int32_t userId, const sptr &callerToken = nullptr); + static int32_t GetAppTypeByBundleType(int32_t bundleType); }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/mission_list.h b/services/abilitymgr/include/mission_list.h index 4b06464289..f38731267b 100644 --- a/services/abilitymgr/include/mission_list.h +++ b/services/abilitymgr/include/mission_list.h @@ -223,8 +223,7 @@ public: int32_t GetMissionCountByUid(int32_t targetUid) const; void FindEarliestMission(std::shared_ptr& targetMission) const; int32_t GetMissionCount() const; - void GetActiveAbilityList(const std::string &bundleName, std::vector &abilityList, - int32_t pid = NO_PID); + void GetActiveAbilityList(int32_t uid, std::vector &abilityList, int32_t pid = NO_PID); void SignRestartAppFlag(const std::string &bundleName); diff --git a/services/abilitymgr/include/mission_list_manager.h b/services/abilitymgr/include/mission_list_manager.h index 4b493995be..5580a41d69 100644 --- a/services/abilitymgr/include/mission_list_manager.h +++ b/services/abilitymgr/include/mission_list_manager.h @@ -24,6 +24,7 @@ #include "ability_running_info.h" #include "mission_list.h" +#include "mission_list_manager_interface.h" #include "mission_listener_controller.h" #include "mission_info.h" #include "mission_snapshot.h" @@ -34,16 +35,17 @@ namespace OHOS { namespace AAFwk { -class MissionListManager : public std::enable_shared_from_this { +class MissionListManager : public MissionListManagerInterface, + public std::enable_shared_from_this { public: explicit MissionListManager(int userId); - ~MissionListManager(); + virtual ~MissionListManager(); /** * init ability mission manager. * */ - void Init(); + void Init() override; /** * StartAbility with request. @@ -51,7 +53,7 @@ public: * @param abilityRequest, the request of the service ability to start. * @return Returns ERR_OK on success, others on failure. */ - int StartAbility(AbilityRequest &abilityRequest); + int StartAbility(AbilityRequest &abilityRequest) override; /** * MinimizeAbility, minimize the special ability. @@ -60,24 +62,24 @@ public: * @param fromUser mark the minimize operation source. * @return Returns ERR_OK on success, others on failure. */ - int MinimizeAbility(const sptr &token, bool fromUser); + int MinimizeAbility(const sptr &token, bool fromUser) override; - int RegisterMissionListener(const sptr &listener); + int RegisterMissionListener(const sptr &listener) override; - int UnRegisterMissionListener(const sptr &listener); + int UnRegisterMissionListener(const sptr &listener) override; - int GetMissionInfos(int32_t numMax, std::vector &missionInfos); + int GetMissionInfos(int32_t numMax, std::vector &missionInfos) override; - int GetMissionInfo(int32_t missionId, MissionInfo &missionInfo); + int GetMissionInfo(int32_t missionId, MissionInfo &missionInfo) override; - int MoveMissionToFront(int32_t missionId, std::shared_ptr startOptions = nullptr); + int MoveMissionToFront(int32_t missionId, std::shared_ptr startOptions = nullptr) override; int MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher, bool isRecent, - std::shared_ptr callerAbility, std::shared_ptr startOptions = nullptr); + std::shared_ptr callerAbility, std::shared_ptr startOptions = nullptr) override; - void NotifyMissionFocused(const int32_t missionId); + void NotifyMissionFocused(int32_t missionId) override; - void NotifyMissionUnfocused(const int32_t missionId); + void NotifyMissionUnfocused(int32_t missionId) override; /** * OnAbilityRequestDone, app manager service call this interface after ability request done. @@ -85,9 +87,9 @@ public: * @param token,ability's token. * @param state,the state of ability lift cycle. */ - void OnAbilityRequestDone(const sptr &token, const int32_t state); + void OnAbilityRequestDone(const sptr &token, int32_t state) override; - void OnAppStateChanged(const AppInfo &info); + void OnAppStateChanged(const AppInfo &info) override; /** * attach ability thread ipc object. @@ -96,7 +98,8 @@ public: * @param token, the token of ability. * @return Returns ERR_OK on success, others on failure. */ - int AttachAbilityThread(const sptr &scheduler, const sptr &token); + int AttachAbilityThread(const sptr &scheduler, + const sptr &token) override; /** * start waiting ability. @@ -109,7 +112,7 @@ public: * @param token the search token * @return std::shared_ptr the AbilityRecord of the token */ - std::shared_ptr GetAbilityRecordByToken(const sptr &token) const; + std::shared_ptr GetAbilityRecordByToken(const sptr &token) override; /** * @brief Get the Mission By Id object @@ -125,7 +128,7 @@ public: * @param abilityRecord the ability to move * @return int error code */ - int MoveAbilityToBackground(const std::shared_ptr &abilityRecord); + int MoveAbilityToBackground(const std::shared_ptr &abilityRecord) override; /** * @brief Terminate ability with the given abilityRecord @@ -137,7 +140,7 @@ public: * @return int error code */ int TerminateAbility(const std::shared_ptr &abilityRecord, - int resultCode, const Want *resultWant, bool flag); + int resultCode, const Want *resultWant, bool flag) override; /** * @brief remove the mission list from the mission list manager @@ -154,7 +157,7 @@ public: * @param saveData the saved data * @return execute error code */ - int AbilityTransactionDone(const sptr &token, int state, const PacMap &saveData); + int AbilityTransactionDone(const sptr &token, int state, const PacMap &saveData) override; /** * @brief search the ability from terminating list @@ -162,7 +165,7 @@ public: * @param token the ability token * @return the ability need to terminate */ - std::shared_ptr GetAbilityFromTerminateList(const sptr &token); + std::shared_ptr GetAbilityFromTerminateList(const sptr &token) override; /** * @brief clear the mission with the given id @@ -170,14 +173,14 @@ public: * @param missionId the mission need to delete * @return int error code */ - int ClearMission(int missionId); + int ClearMission(int missionId) override; /** * @brief clear all the missions * * @return int error code */ - int ClearAllMissions(); + int ClearAllMissions() override; void ClearAllMissionsLocked(std::list> &missionList, std::list> &foregroundAbilities, bool searchActive); @@ -188,7 +191,7 @@ public: * @param missionId the id of the mission * @return int error code */ - int SetMissionLockedState(int missionId, bool lockedState); + int SetMissionLockedState(int missionId, bool lockedState) override; /** * @brief schedule to background @@ -204,21 +207,21 @@ public: * @param abilityRecordId the id of ability record * @param isHalf is half */ - void OnTimeOut(uint32_t msgId, int64_t abilityRecordId, bool isHalf = false); + void OnTimeOut(uint32_t msgId, int64_t abilityRecordId, bool isHalf = false) override; /** * @brief handle when ability died * * @param abilityRecord the died ability */ - void OnAbilityDied(std::shared_ptr abilityRecord, int32_t currentUserId); + void OnAbilityDied(std::shared_ptr abilityRecord, int32_t currentUserId) override; /** * @brief handle when call connection died * * @param callRecord the died call connection */ - void OnCallConnectDied(const std::shared_ptr &callRecord); + void OnCallConnectDied(const std::shared_ptr &callRecord) override; /** * Get mission id by target ability token. @@ -226,7 +229,7 @@ public: * @param token target ability token. * @return the missionId of target mission. */ - int32_t GetMissionIdByAbilityToken(const sptr &token); + int32_t GetMissionIdByAbilityToken(const sptr &token) override; /** * Get ability token by target mission id. @@ -234,21 +237,22 @@ public: * @param missionId target missionId. * @return the ability token of target mission. */ - sptr GetAbilityTokenByMissionId(int32_t missionId); + sptr GetAbilityTokenByMissionId(int32_t missionId) override; + std::shared_ptr GetAbilityRecordByMissionId(int32_t missionId) override; /** * @brief dump all abilities * * @param info dump result. */ - void Dump(std::vector& info); + void Dump(std::vector& info) override; /** * @brief dump mission list * * @param info dump result. */ - void DumpMissionList(std::vector &info, bool isClient, const std::string &args = ""); + void DumpMissionList(std::vector &info, bool isClient, const std::string &args = "") override; /** * @brief dump mission list by id with params @@ -256,32 +260,32 @@ public: * @param info dump result. * @param params dump params. */ - void DumpMissionListByRecordId( - std::vector& info, bool isClient, int32_t abilityRecordId, const std::vector& params); + void DumpMissionListByRecordId(std::vector& info, bool isClient, int32_t abilityRecordId, + const std::vector& params) override; /** * @brief dump mission by id * * @param info dump result. */ - void DumpMission(int missionId, std::vector &info); + void DumpMission(int missionId, std::vector &info) override; /** * @brief dump mission infos * * @param info dump result. */ - void DumpMissionInfos(std::vector &info); + void DumpMissionInfos(std::vector &info) override; - void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag); + void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag) override; - void OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want); + void OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want) override; /** * resolve the call ipc of ability for scheduling oncall. * * @param abilityRequest, target ability request. */ - int ResolveLocked(const AbilityRequest &abilityRequest); + int ResolveLocked(const AbilityRequest &abilityRequest) override; /** * release the connection of this call. @@ -289,12 +293,12 @@ public: * @param connect, caller callback ipc. * @param element, target ability name. */ - int ReleaseCallLocked(const sptr &connect, const AppExecFwk::ElementName &element); + int ReleaseCallLocked(const sptr &connect, const AppExecFwk::ElementName &element) override; /** * @brief register snapshotHandler * @param handler the snapshotHandler */ - void RegisterSnapshotHandler(const sptr& handler); + void RegisterSnapshotHandler(const sptr& handler) override; /** * @brief Get the Mission Snapshot object @@ -305,8 +309,8 @@ public: * @return Returns true on success, false on failure. */ bool GetMissionSnapshot(int32_t missionId, const sptr& abilityToken, - MissionSnapshot& missionSnapshot, bool isLowResolution); - void GetAbilityRunningInfos(std::vector &info, bool isPerm); + MissionSnapshot& missionSnapshot, bool isLowResolution) override; + void GetAbilityRunningInfos(std::vector &info, bool isPerm) override; /** * Called to update mission snapshot. @@ -314,7 +318,7 @@ public: * @param pixelMap The snapshot. */ #ifdef SUPPORT_SCREEN - void UpdateSnapShot(const sptr &token, const std::shared_ptr &pixelMap); + void UpdateSnapShot(const sptr &token, const std::shared_ptr &pixelMap) override; #endif // SUPPORT_SCREEN /** @@ -324,7 +328,7 @@ public: */ int32_t GetAbilityNumber(const AppExecFwk::ElementName &element) const; - void EnableRecoverAbility(int32_t missionId); + void EnableRecoverAbility(int32_t missionId) override; #ifdef ABILITY_COMMAND_FOR_TEST /** @@ -333,32 +337,35 @@ public: * @param abilityRecordId The Ability Record Id. * @return Returns ERR_OK on success, others on failure. */ - int BlockAbility(int abilityRecordId); + int BlockAbility(int abilityRecordId) override; #endif - void UninstallApp(const std::string &bundleName, int32_t uid); + void UninstallApp(const std::string &bundleName, int32_t uid) override; - bool IsStarted(); - void PauseManager(); - void ResumeManager(); + bool IsStarted() override; + void PauseManager() override; + void ResumeManager() override; void SetMissionANRStateByTokens(const std::vector> &tokens); - int32_t IsValidMissionIds(const std::vector &missionIds, std::vector &results); + int32_t IsValidMissionIds(const std::vector &missionIds, + std::vector &results) override; - int DoAbilityForeground(std::shared_ptr &abilityRecord, uint32_t flag); + int DoAbilityForeground(std::shared_ptr &abilityRecord, uint32_t flag) override; - void GetActiveAbilityList(const std::string &bundleName, std::vector &abilityList, - int32_t pid = NO_PID); + void GetActiveAbilityList(int32_t uid, std::vector &abilityList, int32_t pid = NO_PID) override; - void CallRequestDone(const std::shared_ptr &abilityRecord, const sptr &callStub); + void CallRequestDone(const std::shared_ptr &abilityRecord, + const sptr &callStub) override; - int SetMissionContinueState(const sptr &token, const int32_t missionId, - const AAFwk::ContinueState &state); + int SetMissionContinueState(const sptr &token, int32_t missionId, + const AAFwk::ContinueState &state) override; - bool IsAbilityStarted(AbilityRequest &abilityRequest, std::shared_ptr &targetRecord); + bool IsAbilityStarted(AbilityRequest &abilityRequest, std::shared_ptr &targetRecord) override; - void SignRestartAppFlag(const std::string &bundleName); + void SignRestartAppFlag(const std::string &bundleName) override; + + void SetAnimationFlag(bool IsAnimationEnabled); #ifdef SUPPORT_SCREEN public: /** @@ -368,7 +375,7 @@ public: * @param label target label. * @return Return 0 if success. */ - int SetMissionLabel(const sptr &abilityToken, const std::string &label); + int SetMissionLabel(const sptr &abilityToken, const std::string &label) override; /** * Set mission icon of this ability. @@ -377,9 +384,9 @@ public: * @param icon target label. * @return Return 0 if success. */ - int SetMissionIcon(const sptr &token, const std::shared_ptr &icon); + int SetMissionIcon(const sptr &token, const std::shared_ptr &icon) override; - void CompleteFirstFrameDrawing(const sptr &abilityToken) const; + void CompleteFirstFrameDrawing(const sptr &abilityToken) override; void PostMissionLabelUpdateTask(int missionId) const; diff --git a/services/abilitymgr/include/mission_list_manager_interface.h b/services/abilitymgr/include/mission_list_manager_interface.h new file mode 100644 index 0000000000..c313f11189 --- /dev/null +++ b/services/abilitymgr/include/mission_list_manager_interface.h @@ -0,0 +1,143 @@ +/* + * 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_MISSION_LIST_MANAGER_INTERFACE_H +#define OHOS_ABILITY_RUNTIME_MISSION_LIST_MANAGER_INTERFACE_H + +#include +#include +#include + +#include "ability_running_info.h" +#include "mission_list.h" +#include "mission_listener_controller.h" +#include "mission_info.h" +#include "mission_snapshot.h" +#include "snapshot.h" +#include "start_options.h" +#include "want.h" +#include "iability_info_callback.h" + +namespace OHOS { +namespace AAFwk { +class MissionListManagerInterface { +public: + virtual ~MissionListManagerInterface() = default; + + virtual void Init() = 0; + virtual int StartAbility(AbilityRequest &abilityRequest) = 0; + virtual int MinimizeAbility(const sptr &token, bool fromUser) = 0; + virtual int RegisterMissionListener(const sptr &listener) = 0; + virtual int UnRegisterMissionListener(const sptr &listener) = 0; + virtual int GetMissionInfos(int32_t numMax, std::vector &missionInfos) = 0; + virtual int GetMissionInfo(int32_t missionId, MissionInfo &missionInfo) = 0; + virtual int MoveMissionToFront(int32_t missionId, std::shared_ptr startOptions = nullptr) = 0; + virtual int MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher, bool isRecent, + std::shared_ptr callerAbility, std::shared_ptr startOptions = nullptr) = 0; + virtual void NotifyMissionFocused(int32_t missionId) = 0; + virtual void NotifyMissionUnfocused(int32_t missionId) = 0; + virtual void OnAbilityRequestDone(const sptr &token, int32_t state) = 0; + virtual void OnAppStateChanged(const AppInfo &info) = 0; + virtual int AttachAbilityThread(const sptr &scheduler, + const sptr &token) = 0; + virtual std::shared_ptr GetAbilityRecordByToken(const sptr &token) = 0; + virtual std::shared_ptr GetAbilityRecordByMissionId(int missionId) = 0; + virtual int MoveAbilityToBackground(const std::shared_ptr &abilityRecord) = 0; + virtual int TerminateAbility(const std::shared_ptr &abilityRecord, + int resultCode, const Want *resultWant, bool flag) = 0; + virtual int AbilityTransactionDone(const sptr &token, int state, const PacMap &saveData) = 0; + virtual std::shared_ptr GetAbilityFromTerminateList(const sptr &token) = 0; + virtual int ClearMission(int missionId) = 0; + virtual int ClearAllMissions() = 0; + + virtual int SetMissionLockedState(int missionId, bool lockedState) = 0; + virtual void OnTimeOut(uint32_t msgId, int64_t abilityRecordId, bool isHalf = false) = 0; + virtual void OnAbilityDied(std::shared_ptr abilityRecord, int32_t currentUserId) = 0; + virtual void OnCallConnectDied(const std::shared_ptr &callRecord) = 0; + virtual int32_t GetMissionIdByAbilityToken(const sptr &token) = 0; + virtual sptr GetAbilityTokenByMissionId(int32_t missionId) = 0; + + virtual void Dump(std::vector &info) = 0; + + virtual void DumpMissionList(std::vector &info, bool isClient, const std::string &args = ""); + + virtual void DumpMissionListByRecordId(std::vector &info, bool isClient, int32_t abilityRecordId, + const std::vector ¶ms) = 0; + virtual void DumpMission(int missionId, std::vector &info) = 0; + virtual void DumpMissionInfos(std::vector &info) = 0; + virtual void OnAcceptWantResponse(const AAFwk::Want &want, const std::string &flag) = 0; + virtual void OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want) = 0; + virtual int ResolveLocked(const AbilityRequest &abilityRequest) = 0; + + virtual int ReleaseCallLocked(const sptr &connect, + const AppExecFwk::ElementName &element) = 0; + virtual void RegisterSnapshotHandler(const sptr &handler) = 0; + virtual bool GetMissionSnapshot(int32_t missionId, const sptr &abilityToken, + MissionSnapshot &missionSnapshot, bool isLowResolution) = 0; + virtual void GetAbilityRunningInfos(std::vector &info, bool isPerm) = 0; + +#ifdef SUPPORT_SCREEN + virtual void UpdateSnapShot(const sptr &token, + const std::shared_ptr &pixelMap) = 0; +#endif // SUPPORT_SCREEN + + virtual void EnableRecoverAbility(int32_t missionId) = 0; + +#ifdef ABILITY_COMMAND_FOR_TEST + virtual int BlockAbility(int abilityRecordId) = 0; +#endif + + virtual void UninstallApp(const std::string &bundleName, int32_t uid) = 0; + + virtual bool IsStarted() = 0; + virtual void PauseManager() = 0; + virtual void ResumeManager() = 0; + virtual int32_t IsValidMissionIds(const std::vector &missionIds, + std::vector &results) = 0; + virtual int DoAbilityForeground(std::shared_ptr &abilityRecord, uint32_t flag); + virtual void GetActiveAbilityList(int32_t uid, std::vector &abilityList, int32_t pid = NO_PID) = 0; + virtual void CallRequestDone(const std::shared_ptr &abilityRecord, + const sptr &callStub) = 0; + virtual int SetMissionContinueState(const sptr &token, int32_t missionId, + const AAFwk::ContinueState &state) = 0; + + virtual bool IsAbilityStarted(AbilityRequest &abilityRequest, std::shared_ptr &targetRecord) = 0; + virtual void SignRestartAppFlag(const std::string &bundleName) = 0; +#ifdef SUPPORT_SCREEN +public: + virtual int SetMissionLabel(const sptr &abilityToken, const std::string &label) = 0; + virtual int SetMissionIcon(const sptr &token, const std::shared_ptr &icon) = 0; + virtual void CompleteFirstFrameDrawing(const sptr &abilityToken) = 0; +#endif +}; + +class MissionListWrap { +public: + virtual ~MissionListWrap() = default; + virtual std::shared_ptr CreateMissionListManager(int32_t userId) = 0; + virtual void RemoveUserDir(int32_t userId) = 0; + virtual void InitMissionInfoMgr(int32_t userId) = 0; + virtual void SetMissionAbilityState(int32_t missionId, AbilityState state) = 0; + virtual int32_t GetInnerMissionInfoById(int32_t missionId, InnerMissionInfo &innerMissionInfo) = 0; +#ifdef SUPPORT_SCREEN + virtual std::shared_ptr GetSnapshot(int32_t missionId) = 0; +#endif +}; +} // namespace AAFwk +} // namespace OHOS + +extern "C" __attribute__((visibility("default"))) OHOS::AAFwk::MissionListWrap* CreateMissionListWrap(); + +#endif // OHOS_ABILITY_RUNTIME_MISSION_LIST_MANAGER_INTERFACE_H diff --git a/services/abilitymgr/include/pending_want_manager.h b/services/abilitymgr/include/pending_want_manager.h index 26328b5c65..d9cb53343e 100644 --- a/services/abilitymgr/include/pending_want_manager.h +++ b/services/abilitymgr/include/pending_want_manager.h @@ -173,6 +173,8 @@ private: static int32_t PendingRecordIdCreate(); void ClearPendingWantRecordTask(const std::string &bundleName, int32_t uid); + bool CheckCallerPermission(); + private: std::map, sptr> wantRecords_; ffrt::mutex mutex_; 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 2420f0e2a0..e5e41f4f56 100644 --- a/services/abilitymgr/include/scene_board/ui_ability_lifecycle_manager.h +++ b/services/abilitymgr/include/scene_board/ui_ability_lifecycle_manager.h @@ -28,9 +28,6 @@ #include "isession_handler_interface.h" namespace OHOS { -namespace AbilityRuntime { -class IStatusBarDelegate; -} namespace AAFwk { class SessionInfo; class StatusBarDelegateManager; @@ -153,6 +150,9 @@ public: int NotifySCBToStartUIAbility(const AbilityRequest &abilityRequest); + int NotifySCBToPreStartUIAbility(const AbilityRequest &abilityRequest, + sptr &sessionInfo); + /** * @brief handle time out event * @@ -253,8 +253,7 @@ public: */ int32_t GetSessionIdByAbilityToken(const sptr &token); - void GetActiveAbilityList(const std::string &bundleName, std::vector &abilityList, - int32_t pid = NO_PID); + void GetActiveAbilityList(int32_t uid, std::vector &abilityList, int32_t pid = NO_PID); bool PrepareTerminateAbility(const std::shared_ptr &abilityRecord); void SetSessionHandler(const sptr &handler); @@ -357,6 +356,9 @@ public: int32_t GetAbilityStateByPersistentId(int32_t persistentId, bool &state); + void NotifySCBToHandleAtomicServiceException(sptr sessionInfo, int32_t errorCode, + const std::string& errorReason); + private: int32_t GetPersistentIdByAbilityRequest(const AbilityRequest &abilityRequest, bool &reuse) const; int32_t GetReusedSpecifiedPersistentId(const AbilityRequest &abilityRequest, bool &reuse) const; @@ -379,7 +381,7 @@ private: AbilityState state = AbilityState::INITIAL); void HandleForegroundTimeout(const std::shared_ptr &ability); void NotifySCBToHandleException(const std::shared_ptr &ability, int32_t errorCode, - std::string errorReason); + const std::string& errorReason); void MoveToBackground(const std::shared_ptr &abilityRecord); void CompleteBackground(const std::shared_ptr &abilityRecord); void PrintTimeOutLog(std::shared_ptr ability, uint32_t msgId, bool isHalf = false); diff --git a/services/abilitymgr/include/start_ability_utils.h b/services/abilitymgr/include/start_ability_utils.h index b29e341d30..0ad2487d01 100644 --- a/services/abilitymgr/include/start_ability_utils.h +++ b/services/abilitymgr/include/start_ability_utils.h @@ -53,12 +53,17 @@ struct StartAbilityUtils { static bool GetCallerAbilityInfo(const sptr &callerToken, AppExecFwk::AbilityInfo &abilityInfo); static int32_t CheckAppProvisionMode(const Want& want, int32_t userId); + static std::vector GetCloneAppIndexes(const std::string &bundleName, int32_t userId); + + static bool IsCallFromAncoShellOrBroker(const sptr &callerToken); 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; + static thread_local int32_t ermsResultCode; + static thread_local bool isWantWithAppCloneIndex; }; struct StartAbilityInfoWrap { diff --git a/services/abilitymgr/include/sub_managers_helper.h b/services/abilitymgr/include/sub_managers_helper.h index c8b5e022cd..369182b34b 100644 --- a/services/abilitymgr/include/sub_managers_helper.h +++ b/services/abilitymgr/include/sub_managers_helper.h @@ -24,7 +24,7 @@ #include "ability_event_handler.h" #include "cpp/mutex.h" #include "data_ability_manager.h" -#include "mission_list_manager.h" +#include "mission_list_manager_interface.h" #include "nocopyable.h" #include "pending_want_manager.h" #include "scene_board/ui_ability_lifecycle_manager.h" @@ -32,10 +32,11 @@ namespace OHOS { namespace AAFwk { +using CreateMissionListMgrFunc = MissionListWrap*(*)(); class SubManagersHelper { public: SubManagersHelper(std::shared_ptr taskHandler, std::shared_ptr eventHandler); - virtual ~SubManagersHelper() = default; + virtual ~SubManagersHelper(); void InitSubManagers(int userId, bool switchUser); void InitMissionListManager(int userId, bool switchUser); @@ -59,10 +60,10 @@ public: std::shared_ptr GetCurrentPendingWantManager(); std::shared_ptr GetPendingWantManagerByUserId(int32_t userId); - std::unordered_map> GetMissionListManagers(); - std::shared_ptr GetCurrentMissionListManager(); - std::shared_ptr GetMissionListManagerByUserId(int32_t userId); - std::shared_ptr GetMissionListManagerByUid(int32_t uid); + std::unordered_map> GetMissionListManagers(); + std::shared_ptr GetCurrentMissionListManager(); + std::shared_ptr GetMissionListManagerByUserId(int32_t userId); + std::shared_ptr GetMissionListManagerByUid(int32_t uid); std::unordered_map> GetUIAbilityManagers(); std::shared_ptr GetCurrentUIAbilityManager(); @@ -75,6 +76,8 @@ public: bool VerificationAllToken(const sptr &token); bool VerificationAllTokenForConnectManagers(const sptr &token); + std::shared_ptr GetMissionListWrap(); + std::shared_ptr CreateMissionListMgr(int32_t userId); private: DISALLOW_COPY_AND_MOVE(SubManagersHelper); @@ -88,10 +91,14 @@ private: std::shared_ptr currentDataAbilityManager_; std::unordered_map> pendingWantManagers_; std::shared_ptr currentPendingWantManager_; - std::unordered_map> missionListManagers_; - std::shared_ptr currentMissionListManager_; + std::unordered_map> missionListManagers_; + std::shared_ptr currentMissionListManager_; std::unordered_map> uiAbilityManagers_; std::shared_ptr currentUIAbilityManager_; + + std::mutex missionListWrapMutex_; + void* missionLibHandle_ = nullptr; + std::shared_ptr missionListWrap_; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/system_dialog_scheduler.h b/services/abilitymgr/include/system_dialog_scheduler.h index 39254c47ca..06d3662509 100644 --- a/services/abilitymgr/include/system_dialog_scheduler.h +++ b/services/abilitymgr/include/system_dialog_scheduler.h @@ -17,6 +17,7 @@ #include +#include "application_info.h" #include "bundle_mgr_interface.h" #include "singleton.h" @@ -59,6 +60,8 @@ struct DialogAppInfo { std::string abilityName = {}; std::string moduleName = {}; bool visible = true; + int32_t appIndex = 0; + AppExecFwk::MultiAppModeData multiAppMode; }; /** * @class SystemDialogScheduler diff --git a/services/abilitymgr/include/utils/app_mgr_util.h b/services/abilitymgr/include/utils/app_mgr_util.h new file mode 100644 index 0000000000..43b42bbad8 --- /dev/null +++ b/services/abilitymgr/include/utils/app_mgr_util.h @@ -0,0 +1,32 @@ +/* + * 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_APP_MGR_UTIL_H +#define OHOS_ABILITY_RUNTIME_APP_MGR_UTIL_H + +#include "app_mgr_interface.h" + +namespace OHOS { +namespace AAFwk { +class AppMgrUtil final { +public: + static sptr GetAppMgr(); + +private: + static sptr appMgr_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_APP_MGR_UTIL_H diff --git a/services/abilitymgr/include/utils/dump_utils.h b/services/abilitymgr/include/utils/dump_utils.h new file mode 100644 index 0000000000..73a265e26a --- /dev/null +++ b/services/abilitymgr/include/utils/dump_utils.h @@ -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. + */ + +#ifndef OHOS_ABILITY_RUNTIME_DUMP_UTILS_H +#define OHOS_ABILITY_RUNTIME_DUMP_UTILS_H + +#include + +namespace OHOS { +namespace AAFwk { +class DumpUtils final { +public: + enum DumpKey { + KEY_DUMP_ALL = 0, + KEY_DUMP_STACK_LIST, + KEY_DUMP_STACK, + KEY_DUMP_MISSION, + KEY_DUMP_TOP_ABILITY, + KEY_DUMP_WAIT_QUEUE, + KEY_DUMP_SERVICE, + KEY_DUMP_DATA, + KEY_DUMP_FOCUS_ABILITY, + KEY_DUMP_WINDOW_MODE, + KEY_DUMP_MISSION_LIST, + KEY_DUMP_MISSION_INFOS, + }; + + enum DumpsysKey { + KEY_DUMP_SYS_ALL = 0, + KEY_DUMP_SYS_MISSION_LIST, + KEY_DUMP_SYS_ABILITY, + KEY_DUMP_SYS_SERVICE, + KEY_DUMP_SYS_PENDING, + KEY_DUMP_SYS_PROCESS, + KEY_DUMP_SYS_DATA, + }; + + static std::pair DumpMapOne(std::string argString); + static std::pair DumpMapTwo(std::string argString); + static std::pair DumpMap(std::string argString); + static std::pair DumpsysMap(std::string argString); +}; +} // namespace AAFwk +} // namespace OHOS +#endif //OHOS_ABILITY_RUNTIME_DUMP_UTILS_H diff --git a/services/abilitymgr/include/utils/extension_permissions_util.h b/services/abilitymgr/include/utils/extension_permissions_util.h new file mode 100644 index 0000000000..750814642b --- /dev/null +++ b/services/abilitymgr/include/utils/extension_permissions_util.h @@ -0,0 +1,31 @@ +/* + * 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_EXTENSION_PERMISSIONS_UTIL_H +#define OHOS_EXTENSION_PERMISSIONS_UTIL_H + +#include "extension_ability_info.h" + +namespace OHOS { +namespace AAFwk { +class ExtensionPermissionsUtil final { +public: + static bool CheckSAPermission(const AppExecFwk::ExtensionAbilityType &extensionType); + static bool CheckSAPermissionMore(const AppExecFwk::ExtensionAbilityType &extensionType); +}; + +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_EXTENSION_PERMISSIONS_UTIL_H \ No newline at end of file diff --git a/services/abilitymgr/include/utils/state_utils.h b/services/abilitymgr/include/utils/state_utils.h new file mode 100644 index 0000000000..423022c070 --- /dev/null +++ b/services/abilitymgr/include/utils/state_utils.h @@ -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. + */ + +#ifndef OHOS_ABILITY_RUNTIME_STATE_UTILS_H +#define OHOS_ABILITY_RUNTIME_STATE_UTILS_H + +#include + +#include "ability_state.h" +#include "app_scheduler.h" + +namespace OHOS { +namespace AAFwk { +class StateUtils final { +public: + static std::string StateToStrMap(const AbilityState &state); + static std::string AppStateToStrMap(const AppState &state); + static int ConvertStateMap(const AbilityLifeCycleState &state); +}; +} // namespace AAFwk +} // namespace OHOS +#endif //OHOS_ABILITY_RUNTIME_STATE_UTILS_H diff --git a/services/abilitymgr/include/utils/window_options_utils.h b/services/abilitymgr/include/utils/window_options_utils.h index 60151a4da5..26363d61f5 100644 --- a/services/abilitymgr/include/utils/window_options_utils.h +++ b/services/abilitymgr/include/utils/window_options_utils.h @@ -16,6 +16,7 @@ #ifndef OHOS_ABILITY_RUNTIME_WINDOW_OPTIONS_UTILS_H #define OHOS_ABILITY_RUNTIME_WINDOW_OPTIONS_UTILS_H +#include "ability_info.h" #include "iremote_object.h" #include "start_options.h" #include "want.h" @@ -26,6 +27,7 @@ class WindowOptionsUtils final { public: static void SetWindowPositionAndSize(Want& want, const sptr& callerToken, const StartOptions& startOptions); + static std::pair WindowModeMap(int32_t windowMode); }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/want_receiver_stub.h b/services/abilitymgr/include/want_receiver_stub.h index 3fe98628d0..8f27e0b4ac 100644 --- a/services/abilitymgr/include/want_receiver_stub.h +++ b/services/abilitymgr/include/want_receiver_stub.h @@ -35,8 +35,6 @@ public: private: int SendInner(MessageParcel &data, MessageParcel &reply); int PerformReceiveInner(MessageParcel &data, MessageParcel &reply); - using RequestFuncType = int (WantReceiverStub::*)(MessageParcel &data, MessageParcel &reply); - std::map requestFuncMap_; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/want_sender_stub.h b/services/abilitymgr/include/want_sender_stub.h index 0109723c9f..be789a76ff 100644 --- a/services/abilitymgr/include/want_sender_stub.h +++ b/services/abilitymgr/include/want_sender_stub.h @@ -34,8 +34,6 @@ public: private: int SendInner(MessageParcel &data, MessageParcel &reply); - using RequestFuncType = int (WantSenderStub::*)(MessageParcel &data, MessageParcel &reply); - std::map requestFuncMap_; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/libabilityms.map b/services/abilitymgr/libabilityms.map index 1398359572..3522bef1f4 100644 --- a/services/abilitymgr/libabilityms.map +++ b/services/abilitymgr/libabilityms.map @@ -19,6 +19,7 @@ *AbilityConnectionStub*; *AbilityConnectManager*; *AbilityEventHandler*; + *AbilityFirstFrameStateObserverManager*; *AbilityInterceptorExecuter*; *AbilityManagerService*; *AbilityManagerStub*; @@ -27,6 +28,7 @@ *AbilitySchedulerProxy*; *AbilitySchedulerStub*; *AmsConfigurationParameter*; + *AppExitReasonDataManager*; *ApplicationAnrListener*; *AppScheduler*; *AtomicServiceStatusCallback*; diff --git a/services/abilitymgr/resource/start_ability_without_caller_token.json b/services/abilitymgr/resource/start_ability_without_caller_token.json new file mode 100644 index 0000000000..bfb604a54c --- /dev/null +++ b/services/abilitymgr/resource/start_ability_without_caller_token.json @@ -0,0 +1,8 @@ +{ + "startAbilityWithoutCallerToken": [ + { + "bundleName": "com.ohos.contacts", + "abilityName": "com.ohos.contacts.MainAbility" + } + ] +} \ No newline at end of file diff --git a/services/abilitymgr/resource/uiextension_picker_config.json b/services/abilitymgr/resource/uiextension_picker_config.json index 2b8b187f5e..f51de049c0 100644 --- a/services/abilitymgr/resource/uiextension_picker_config.json +++ b/services/abilitymgr/resource/uiextension_picker_config.json @@ -27,6 +27,10 @@ { "type": "audioPicker", "typePicker": "sysPicker/audioPicker" + }, + { + "type": "mediaControl", + "typePicker": "sysPicker/mediaControl" } ] } \ No newline at end of file diff --git a/services/abilitymgr/src/ability_auto_startup_client.cpp b/services/abilitymgr/src/ability_auto_startup_client.cpp index 1cbffb3404..3464930ecb 100644 --- a/services/abilitymgr/src/ability_auto_startup_client.cpp +++ b/services/abilitymgr/src/ability_auto_startup_client.cpp @@ -16,7 +16,6 @@ #include "ability_auto_startup_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "system_ability_definition.h" @@ -94,7 +93,7 @@ ErrCode AbilityAutoStartupClient::Connect() ErrCode AbilityAutoStartupClient::SetApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->SetApplicationAutoStartupByEDM(info, flag); @@ -102,7 +101,7 @@ ErrCode AbilityAutoStartupClient::SetApplicationAutoStartupByEDM(const AutoStart ErrCode AbilityAutoStartupClient::CancelApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->CancelApplicationAutoStartupByEDM(info, flag); @@ -110,7 +109,7 @@ ErrCode AbilityAutoStartupClient::CancelApplicationAutoStartupByEDM(const AutoSt ErrCode AbilityAutoStartupClient::QueryAllAutoStartupApplications(std::vector &infoList) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->QueryAllAutoStartupApplications(infoList); diff --git a/services/abilitymgr/src/ability_auto_startup_data_manager.cpp b/services/abilitymgr/src/ability_auto_startup_data_manager.cpp index eee4fe5136..efb7043c38 100644 --- a/services/abilitymgr/src/ability_auto_startup_data_manager.cpp +++ b/services/abilitymgr/src/ability_auto_startup_data_manager.cpp @@ -21,7 +21,6 @@ #include "accesstoken_kit.h" #include "errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "nlohmann/json.hpp" #include "types.h" #include "os_account_manager_wrapper.h" @@ -299,7 +298,7 @@ AutoStartupStatus AbilityAutoStartupDataManager::QueryAutoStartupData(const Auto int32_t AbilityAutoStartupDataManager::QueryAllAutoStartupApplications(std::vector &infoList, int32_t userId) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); { std::lock_guard lock(kvStorePtrMutex_); if (!CheckKvStore()) { @@ -332,7 +331,7 @@ int32_t AbilityAutoStartupDataManager::QueryAllAutoStartupApplications(std::vect int32_t AbilityAutoStartupDataManager::GetCurrentAppAutoStartupData( const std::string &bundleName, std::vector &infoList, const std::string &accessTokenId) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); { std::lock_guard lock(kvStorePtrMutex_); if (!CheckKvStore()) { diff --git a/services/abilitymgr/src/ability_auto_startup_service.cpp b/services/abilitymgr/src/ability_auto_startup_service.cpp index dac29da4c4..3e4429f350 100644 --- a/services/abilitymgr/src/ability_auto_startup_service.cpp +++ b/services/abilitymgr/src/ability_auto_startup_service.cpp @@ -25,8 +25,9 @@ #include "auto_startup_callback_proxy.h" #include "auto_startup_info.h" #include "auto_startup_interface.h" +#include "ability_util.h" +#include "global_constant.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "in_process_call_wrapper.h" #include "ipc_skeleton.h" #include "parameters.h" @@ -46,7 +47,7 @@ AbilityAutoStartupService::~AbilityAutoStartupService() {} int32_t AbilityAutoStartupService::RegisterAutoStartupSystemCallback(const sptr &callback) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); int32_t code = CheckPermissionForSystem(); if (code != ERR_OK) { return code; @@ -76,7 +77,7 @@ int32_t AbilityAutoStartupService::RegisterAutoStartupSystemCallback(const sptr< int32_t AbilityAutoStartupService::UnregisterAutoStartupSystemCallback(const sptr &callback) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); int32_t code = CheckPermissionForSystem(); if (code != ERR_OK) { return code; @@ -230,7 +231,7 @@ int32_t AbilityAutoStartupService::InnerCancelApplicationAutoStartup(const AutoS int32_t AbilityAutoStartupService::QueryAllAutoStartupApplications(std::vector &infoList, int32_t userId) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); int32_t code = CheckPermissionForEDM(); code = code == ERR_OK ? code : CheckPermissionForSystem(); if (code != ERR_OK) { @@ -245,7 +246,7 @@ int32_t AbilityAutoStartupService::QueryAllAutoStartupApplications(std::vector &infoList, int32_t userId) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); if (!system::GetBoolParameter(PRODUCT_APPBOOT_SETTING_ENABLED, false)) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "Product configuration item is disable."); return ERR_NOT_SUPPORTED_PRODUCT_TYPE; @@ -257,15 +258,16 @@ int32_t AbilityAutoStartupService::QueryAllAutoStartupApplicationsWithoutPermiss int32_t AbilityAutoStartupService::DeleteAutoStartupData(const std::string &bundleName, const int32_t uid) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); return DelayedSingleton::GetInstance()->DeleteAutoStartupData(bundleName, uid); } int32_t AbilityAutoStartupService::CheckAutoStartupData(const std::string &bundleName, int32_t uid) { int32_t userId; + int32_t appIndex = 0; AppExecFwk::BundleInfo bundleInfo; - if (!GetBundleInfo(bundleName, bundleInfo, uid, userId)) { + if (!GetBundleInfo(bundleName, bundleInfo, uid, userId, appIndex)) { return INNER_ERR; } auto tokenId = bundleInfo.applicationInfo.accessTokenId; @@ -333,7 +335,7 @@ void AbilityAutoStartupService::ExecuteCallbacks(bool isCallOn, const AutoStartu void AbilityAutoStartupService::SetDeathRecipient( const sptr &callback, const sptr &deathRecipient) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); if (callback == nullptr || deathRecipient == nullptr) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "The callerToken or the deathRecipient is empty."); return; @@ -350,7 +352,7 @@ void AbilityAutoStartupService::SetDeathRecipient( void AbilityAutoStartupService::CleanResource(const wptr &remote) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); auto object = remote.promote(); if (object == nullptr) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "Remote object is nullptr."); @@ -396,7 +398,7 @@ AbilityAutoStartupService::ClientDeathRecipient::ClientDeathRecipient( void AbilityAutoStartupService::ClientDeathRecipient::OnRemoteDied(const wptr &remote) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); auto abilityAutoStartupService = weakPtr_.lock(); if (abilityAutoStartupService == nullptr) { TAG_LOGE(AAFwkTag::AUTO_STARTUP, "abilityAutoStartupService is nullptr."); @@ -429,15 +431,10 @@ bool AbilityAutoStartupService::CheckSelfApplication(const std::string &bundleNa return GetSelfApplicationBundleName() == bundleName ? true : false; } -bool AbilityAutoStartupService::GetBundleInfo( - const std::string &bundleName, AppExecFwk::BundleInfo &bundleInfo, int32_t uid, int32_t &userId) +bool AbilityAutoStartupService::GetBundleInfo(const std::string &bundleName, + AppExecFwk::BundleInfo &bundleInfo, int32_t uid, int32_t &userId, int32_t appIndex) { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); - auto bundleMgrClient = GetBundleMgrClient(); - if (bundleMgrClient == nullptr) { - TAG_LOGE(AAFwkTag::AUTO_STARTUP, "Failed to get BundleMgrClient."); - return false; - } + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); if (uid == -1) { userId = IPCSkeleton::GetCallingUid() / AppExecFwk::Constants::BASE_USER_RANGE; @@ -453,13 +450,36 @@ bool AbilityAutoStartupService::GetBundleInfo( userId = abilityMgr->GetUserId(); } TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Current userId: %{public}d.", userId); - auto flags = - AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES | AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO; - if (!IN_PROCESS_CALL(bundleMgrClient->GetBundleInfo( - bundleName, static_cast(flags), bundleInfo, userId))) { - TAG_LOGE(AAFwkTag::AUTO_STARTUP, "Failed to get bundle info."); + auto bundleMgrHelper = DelayedSingleton::GetInstance(); + if (bundleMgrHelper == nullptr) { + TAG_LOGE(AAFwkTag::AUTO_STARTUP, "bundleMgrHelper is nullptr."); return false; } + if (appIndex == 0) { + auto flags = + AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES | AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO; + if (!IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfo( + bundleName, static_cast(flags), bundleInfo, userId))) { + TAG_LOGE(AAFwkTag::AUTO_STARTUP, "Failed to get bundle info."); + return false; + } + } else if (appIndex <= GlobalConstant::MAX_APP_CLONE_INDEX) { + auto bundleFlag = static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) + + static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY) + + static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) + + static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE); + auto bundleMgrResult = IN_PROCESS_CALL( + bundleMgrHelper->GetCloneBundleInfo(bundleName, bundleFlag, appIndex, bundleInfo, userId)); + if (bundleMgrResult != ERR_OK) { + TAG_LOGE(AAFwkTag::AUTO_STARTUP, "bundleMgrResult is not ERR_OK."); + return false; + } + } else { + if (!IN_PROCESS_CALL(bundleMgrHelper->GetSandboxBundleInfo(bundleName, appIndex, userId, bundleInfo))) { + TAG_LOGE(AAFwkTag::AUTO_STARTUP, "fail to GetSandboxBundleInfo."); + return false; + } + } return true; } @@ -474,15 +494,17 @@ bool AbilityAutoStartupService::GetAbilityData(const AutoStartupInfo &info, bool AppExecFwk::BundleInfo bundleInfo; int32_t currentUserId; int32_t uid = bundleInfo.applicationInfo.uid; - if (!GetBundleInfo(info.bundleName, bundleInfo, uid, currentUserId)) { + if (!GetBundleInfo(info.bundleName, bundleInfo, uid, currentUserId, info.appCloneIndex)) { + TAG_LOGE(AAFwkTag::AUTO_STARTUP, "Failed to GetBundleInfo."); return false; } userId = currentUserId; auto accessTokenIdStr = bundleInfo.applicationInfo.accessTokenId; accessTokenId = std::to_string(accessTokenIdStr); - for (auto abilityInfo : bundleInfo.abilityInfos) { - if ((abilityInfo.bundleName == info.bundleName) && (abilityInfo.name == info.abilityName)) { - if (info.moduleName.empty() || (abilityInfo.moduleName == info.moduleName)) { + for (const auto& hapModuleInfo : bundleInfo.hapModuleInfos) { + for (const auto& abilityInfo : hapModuleInfo.abilityInfos) { + if ((abilityInfo.bundleName == info.bundleName) && (abilityInfo.name == info.abilityName) && + (info.moduleName.empty() || (abilityInfo.moduleName == info.moduleName))) { isVisible = abilityInfo.visible; abilityTypeName = GetAbilityTypeName(abilityInfo); TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Get ability info success."); @@ -524,7 +546,7 @@ std::string AbilityAutoStartupService::GetExtensionTypeName(AppExecFwk::Extensio std::shared_ptr AbilityAutoStartupService::GetBundleMgrClient() { - TAG_LOGD(AAFwkTag::AUTO_STARTUP, "Called."); + TAG_LOGD(AAFwkTag::AUTO_STARTUP, "called"); if (bundleMgrClient_ == nullptr) { bundleMgrClient_ = DelayedSingleton::GetInstance(); } diff --git a/services/abilitymgr/src/ability_background_connection.cpp b/services/abilitymgr/src/ability_background_connection.cpp index aab906ee7b..7d7e3facb0 100644 --- a/services/abilitymgr/src/ability_background_connection.cpp +++ b/services/abilitymgr/src/ability_background_connection.cpp @@ -17,7 +17,6 @@ #include "ability_background_connection.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/ability_bundle_event_callback.cpp b/services/abilitymgr/src/ability_bundle_event_callback.cpp index 768c670283..327e4af6ee 100644 --- a/services/abilitymgr/src/ability_bundle_event_callback.cpp +++ b/services/abilitymgr/src/ability_bundle_event_callback.cpp @@ -18,6 +18,7 @@ #include "ability_manager_service.h" #include "ability_util.h" #include "hilog_tag_wrapper.h" +#include "parameters.h" #include "uri_permission_manager_client.h" namespace OHOS { @@ -25,6 +26,9 @@ namespace AAFwk { namespace { constexpr const char* KEY_TOKEN = "accessTokenId"; constexpr const char* KEY_UID = "uid"; +constexpr const char* WEB_BUNDLE_NAME = "com.ohos.nweb"; +constexpr const char* ARKWEB_CORE_PACKAGE_NAME = "persist.arkwebcore.package_name"; + } AbilityBundleEventCallback::AbilityBundleEventCallback( std::shared_ptr taskHandler, std::shared_ptr abilityAutoStartupService) @@ -63,6 +67,10 @@ void AbilityBundleEventCallback::OnReceiveEvent(const EventFwk::CommonEventData // install or uninstall module/bundle HandleUpdatedModuleInfo(bundleName, uid); } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED) { + if (bundleName == WEB_BUNDLE_NAME || + bundleName == system::GetParameter(ARKWEB_CORE_PACKAGE_NAME, "false")) { + HandleRestartResidentProcessDependedOnWeb(); + } HandleUpdatedModuleInfo(bundleName, uid); HandleAppUpgradeCompleted(bundleName, uid); if (abilityAutoStartupService_ == nullptr) { @@ -115,5 +123,18 @@ void AbilityBundleEventCallback::HandleAppUpgradeCompleted(const std::string &bu }; taskHandler_->SubmitTask(task); } + +void AbilityBundleEventCallback::HandleRestartResidentProcessDependedOnWeb() +{ + auto task = []() { + auto abilityMgr = DelayedSingleton::GetInstance(); + if (abilityMgr == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityMgr is nullptr."); + return; + } + abilityMgr->HandleRestartResidentProcessDependedOnWeb(); + }; + taskHandler_->SubmitTask(task); +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/ability_cache_manager.cpp b/services/abilitymgr/src/ability_cache_manager.cpp index 3309a73708..cde717d481 100644 --- a/services/abilitymgr/src/ability_cache_manager.cpp +++ b/services/abilitymgr/src/ability_cache_manager.cpp @@ -21,6 +21,8 @@ namespace OHOS { namespace AAFwk { +const std::string FRS_APP_INDEX = "ohos.extra.param.key.frs_index"; +const std::string FRS_BUNDLE_NAME = "com.ohos.formrenderservice"; AbilityCacheManager::AbilityCacheManager() {} @@ -40,13 +42,10 @@ void AbilityCacheManager::Init(uint32_t devCapacity, uint32_t procCapacity) void AbilityCacheManager::RemoveAbilityRecInDevList(std::shared_ptr abilityRecord) { - AbilityInfo abilityInfo = abilityRecord->GetAbilityInfo(); auto it = devRecLru_.begin(); uint32_t accessTokenId = abilityRecord->GetApplicationInfo().accessTokenId; while (it != devRecLru_.end()) { - if ((*it)->GetAbilityInfo().bundleName == abilityInfo.bundleName && - (*it)->GetAbilityInfo().moduleName == abilityInfo.moduleName && - (*it)->GetApplicationInfo().accessTokenId == accessTokenId) { + if ((*it)->GetRecordId() == abilityRecord->GetRecordId()) { devRecLru_.erase(it); devLruCnt_--; return; @@ -58,7 +57,6 @@ void AbilityCacheManager::RemoveAbilityRecInDevList(std::shared_ptr abilityRecord) { - AbilityInfo abilityInfo = abilityRecord->GetAbilityInfo(); const Want want = abilityRecord->GetWant(); uint32_t accessTokenId = abilityRecord->GetApplicationInfo().accessTokenId; auto findProcInfo = procLruMap_.find(accessTokenId); @@ -69,8 +67,7 @@ void AbilityCacheManager::RemoveAbilityRecInProcList(std::shared_ptrsecond.recList.begin(); while (it != findProcInfo->second.recList.end()) { - if ((*it)->GetAbilityInfo().moduleName == abilityInfo.moduleName && - (*it)->GetWant().GetElement().GetAbilityName() == want.GetElement().GetAbilityName()) { + if ((*it)->GetRecordId() == abilityRecord->GetRecordId()) { findProcInfo->second.recList.erase(it); findProcInfo->second.cnt--; if (findProcInfo->second.cnt == 0) { @@ -130,6 +127,8 @@ std::shared_ptr AbilityCacheManager::Put(std::shared_ptrGetURI().c_str(), abilityRecord->GetAbilityInfo().extensionAbilityType); std::lock_guard lock(mutex_); std::shared_ptr rec = AddToProcLru(abilityRecord); return AddToDevLru(abilityRecord, rec); @@ -141,6 +140,8 @@ void AbilityCacheManager::Remove(std::shared_ptr abilityRecord) TAG_LOGE(AAFwkTag::ABILITYMGR, "The param abilityRecord is nullptr for Remove operation."); return; } + TAG_LOGD(AAFwkTag::ABILITYMGR, "Remove the ability from lru, service:%{public}s, extension type %{public}d", + abilityRecord->GetURI().c_str(), abilityRecord->GetAbilityInfo().extensionAbilityType); std::lock_guard lock(mutex_); RemoveAbilityRecInProcList(abilityRecord); RemoveAbilityRecInDevList(abilityRecord); @@ -164,7 +165,7 @@ std::shared_ptr AbilityCacheManager::GetAbilityRecInProcList(cons auto recIter = procRecordsInfo.recList.begin(); while (recIter != procRecordsInfo.recList.end()) { if (IsRecInfoSame(abilityRequest, *recIter)) { - std::shared_ptr &abilityRecord = *recIter; + std::shared_ptr abilityRecord = *recIter; procRecordsInfo.recList.erase(recIter); procRecordsInfo.cnt--; return abilityRecord; @@ -177,9 +178,12 @@ std::shared_ptr AbilityCacheManager::GetAbilityRecInProcList(cons std::shared_ptr AbilityCacheManager::Get(const AbilityRequest& abilityRequest) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Get the ability from lru, service:%{public}s, extension type %{public}d", + abilityRequest.abilityInfo.uri.c_str(), abilityRequest.abilityInfo.extensionAbilityType); std::lock_guard lock(mutex_); std::shared_ptr abilityRecord = GetAbilityRecInProcList(abilityRequest); if (abilityRecord == nullptr) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Can't found the abilityRecord for get."); return nullptr; } RemoveAbilityRecInDevList(abilityRecord); @@ -192,11 +196,15 @@ std::shared_ptr AbilityCacheManager::FindRecordByToken(const sptr TAG_LOGE(AAFwkTag::ABILITYMGR, "The param token is nullptr for FindRecordByToken operation."); return nullptr; } + std::lock_guard lock(mutex_); auto it = devRecLru_.begin(); while (it != devRecLru_.end()) { sptr srcToken = (*it)->GetToken(); if (srcToken == token) { std::shared_ptr &abilityRecord = *it; + TAG_LOGD(AAFwkTag::ABILITYMGR, + "Find the ability by token from lru, service:%{public}s, extension type %{public}d", + abilityRecord->GetURI().c_str(), abilityRecord->GetAbilityInfo().extensionAbilityType); return abilityRecord; } else { it++; @@ -204,5 +212,96 @@ std::shared_ptr AbilityCacheManager::FindRecordByToken(const sptr } return nullptr; } + +std::list> AbilityCacheManager::GetAbilityList() +{ + std::lock_guard lock(mutex_); + return devRecLru_; +} + +std::shared_ptr AbilityCacheManager::FindRecordBySessionId(const std::string &assertSessionId) +{ + std::lock_guard lock(mutex_); + auto it = devRecLru_.begin(); + while (it != devRecLru_.end()) { + auto assertSessionStr = (*it)->GetWant().GetStringParam(Want::PARAM_ASSERT_FAULT_SESSION_ID); + if (assertSessionStr == assertSessionId) { + std::shared_ptr &abilityRecord = *it; + TAG_LOGD(AAFwkTag::ABILITYMGR, + "Find the ability by sessionId from lru, service:%{public}s, extension type %{public}d", + abilityRecord->GetURI().c_str(), abilityRecord->GetAbilityInfo().extensionAbilityType); + return abilityRecord; + } else { + it++; + } + } + return nullptr; +} + +std::shared_ptr AbilityCacheManager::FindRecordByServiceKey(const std::string &serviceKey) +{ + std::lock_guard lock(mutex_); + auto it = devRecLru_.begin(); + while (it != devRecLru_.end()) { + std::string curServiceKey = (*it)->GetURI(); + if (FRS_BUNDLE_NAME == (*it)->GetAbilityInfo().bundleName) { + curServiceKey = curServiceKey + std::to_string((*it)->GetWant().GetIntParam(FRS_APP_INDEX, 0)); + } + if (curServiceKey.compare(serviceKey) == 0) { + std::shared_ptr &abilityRecord = *it; + TAG_LOGD(AAFwkTag::ABILITYMGR, + "Find the ability by serviceKey from lru, service:%{public}s, extension type %{public}d", + abilityRecord->GetURI().c_str(), abilityRecord->GetAbilityInfo().extensionAbilityType); + return abilityRecord; + } else { + it++; + } + } + return nullptr; +} + +void AbilityCacheManager::RemoveLauncherDeathRecipient() +{ + std::lock_guard lock(mutex_); + auto it = devRecLru_.begin(); + while (it != devRecLru_.end()) { + auto targetExtension = *it; + if (targetExtension != nullptr && targetExtension->GetAbilityInfo().type == AbilityType::EXTENSION && + ((targetExtension->GetAbilityInfo().name == AbilityConfig::LAUNCHER_ABILITY_NAME && + targetExtension->GetAbilityInfo().bundleName == AbilityConfig::LAUNCHER_BUNDLE_NAME) || + targetExtension->IsSceneBoard())) { + targetExtension->RemoveAbilityDeathRecipient(); + return; + } + it++; + } +} + +void AbilityCacheManager::SignRestartAppFlag(const std::string &bundleName) +{ + std::lock_guard lock(mutex_); + auto it = devRecLru_.begin(); + while (it != devRecLru_.end()) { + auto abilityRecord = *it; + if (abilityRecord != nullptr && abilityRecord->GetApplicationInfo().bundleName == bundleName) { + abilityRecord->SetRestartAppFlag(true); + } + it++; + } +} + +void AbilityCacheManager::DeleteInvalidServiceRecord(const std::string &bundleName) +{ + std::lock_guard lock(mutex_); + auto it = devRecLru_.begin(); + while (it != devRecLru_.end()) { + auto abilityRecord = *it; + if (abilityRecord != nullptr && abilityRecord->GetApplicationInfo().bundleName == bundleName) { + RemoveAbilityRecInProcList(abilityRecord); + RemoveAbilityRecInDevList(abilityRecord); + } + it++; + } +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/ability_connect_callback_stub.cpp b/services/abilitymgr/src/ability_connect_callback_stub.cpp index 42d6251a33..89ab053d43 100644 --- a/services/abilitymgr/src/ability_connect_callback_stub.cpp +++ b/services/abilitymgr/src/ability_connect_callback_stub.cpp @@ -17,7 +17,6 @@ #include "ability_connect_callback_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" #include "want.h" diff --git a/services/abilitymgr/src/ability_connect_manager.cpp b/services/abilitymgr/src/ability_connect_manager.cpp index 7c0137b730..5631758800 100644 --- a/services/abilitymgr/src/ability_connect_manager.cpp +++ b/services/abilitymgr/src/ability_connect_manager.cpp @@ -31,7 +31,6 @@ #include "extension_config.h" #include "hitrace_meter.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "in_process_call_wrapper.h" #include "int_wrapper.h" #include "parameter.h" @@ -39,6 +38,7 @@ #include "startup_util.h" #include "extension_record.h" #include "ui_extension_utils.h" +#include "ui_service_extension_connection_constants.h" #include "cache_extension_utils.h" namespace OHOS { @@ -76,8 +76,6 @@ const std::unordered_set FROZEN_WHITE_LIST { }; constexpr char BUNDLE_NAME_DIALOG[] = "com.ohos.amsdialog"; constexpr char ABILITY_NAME_ASSERT_FAULT_DIALOG[] = "AssertFaultDialog"; -constexpr char BUNDLE_NAME_SAMPLE_MANAGEMENT[] = "com.huawei.hmsapp.samplemanagement"; -constexpr char ABILITY_NAME_SAMPLE_MANAGEMENT[] = "MspesService"; bool IsSpecialAbility(const AppExecFwk::AbilityInfo &abilityInfo) { @@ -249,6 +247,8 @@ int AbilityConnectManager::StartAbilityLocked(const AbilityRequest &abilityReque targetService->DoBackgroundAbilityWindowDelayed(false); + targetService->SetSessionInfo(abilityRequest.sessionInfo); + if (IsUIExtensionAbility(targetService) && abilityRequest.sessionInfo && abilityRequest.sessionInfo->sessionToken) { auto &remoteObj = abilityRequest.sessionInfo->sessionToken; { @@ -615,7 +615,8 @@ int AbilityConnectManager::UnloadUIExtensionAbility(const std::shared_ptrGetWant().GetElement().GetModuleName(), hostBundleName); //delete preLoadUIExtensionMap CHECK_POINTER_AND_RETURN(uiExtensionAbilityRecordMgr_, ERR_NULL_OBJECT); - uiExtensionAbilityRecordMgr_->RemoveAllPreloadUIExtensionRecord(preLoadUIExtensionInfo); + auto extensionRecordId = abilityRecord->GetUIExtensionAbilityId(); + uiExtensionAbilityRecordMgr_->RemovePreloadUIExtensionRecordById(preLoadUIExtensionInfo, extensionRecordId); //terminate preload uiextension auto token = abilityRecord->GetToken(); auto result = TerminateAbilityInner(token); @@ -657,6 +658,9 @@ int AbilityConnectManager::ConnectAbilityLocked(const AbilityRequest &abilityReq CHECK_POINTER_AND_RETURN(connectRecord, ERR_INVALID_VALUE); connectRecord->AttachCallerInfo(); connectRecord->SetConnectState(ConnectionState::CONNECTING); + if (targetService->GetAbilityInfo().extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) { + connectRecord->SetConnectWant(abilityRequest.want); + } targetService->AddConnectRecordToList(connectRecord); targetService->SetSessionInfo(sessionInfo); connectRecordList.push_back(connectRecord); @@ -692,7 +696,9 @@ void AbilityConnectManager::HandleActiveAbility(std::shared_ptr & TAG_LOGW(AAFwkTag::ABILITYMGR, "null target service."); return; } - if (targetService->GetConnectRecordList().size() > 1) { + AppExecFwk::ExtensionAbilityType extType = targetService->GetAbilityInfo().extensionAbilityType; + bool isAbilityUIServiceExt = (extType == AppExecFwk::ExtensionAbilityType::UI_SERVICE); + if (targetService->GetConnectRecordList().size() > 1 && !isAbilityUIServiceExt) { if (taskHandler_ != nullptr && targetService->GetConnRemoteObject()) { auto task = [connectRecord]() { connectRecord->CompleteConnect(ERR_OK); }; taskHandler_->SubmitTask(task, TaskQoS::USER_INTERACTIVE); @@ -700,7 +706,12 @@ void AbilityConnectManager::HandleActiveAbility(std::shared_ptr & TAG_LOGI(AAFwkTag::ABILITYMGR, "Target service is connecting, wait for callback"); } } else { - ConnectAbility(targetService); + if (isAbilityUIServiceExt) { + Want want = connectRecord->GetConnectWant(); + ConnectUIServiceExtAbility(targetService, want); + } else { + ConnectAbility(targetService); + } } } @@ -710,7 +721,7 @@ int AbilityConnectManager::DisconnectAbilityLocked(const sptr &connect, bool force) +int AbilityConnectManager::DisconnectAbilityLocked(const sptr &connect, bool callerDied) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); @@ -742,8 +753,8 @@ int AbilityConnectManager::DisconnectAbilityLocked(const sptr abilityRecord) { - if (!GetAbilityRecordById(abilityRecord->GetRecordId())) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "terminate record called."); + if (!GetAbilityRecordById(abilityRecord->GetRecordId()) && + !AbilityCacheManager::GetInstance().FindRecordByToken(abilityRecord->GetToken())) { return; } auto timeoutTask = [abilityRecord, connectManager = shared_from_this()]() { @@ -779,7 +792,7 @@ void AbilityConnectManager::TerminateRecord(std::shared_ptr abili } int AbilityConnectManager::DisconnectRecordNormal(ConnectListType &list, - std::shared_ptr connectRecord) const + std::shared_ptr connectRecord, bool callerDied) const { auto result = connectRecord->DisconnectAbility(); if (result != ERR_OK) { @@ -790,7 +803,7 @@ int AbilityConnectManager::DisconnectRecordNormal(ConnectListType &list, if (connectRecord->GetConnectState() == ConnectionState::DISCONNECTED) { TAG_LOGW(AAFwkTag::ABILITYMGR, "This record: %{public}d complete disconnect directly.", connectRecord->GetRecordId()); - connectRecord->CompleteDisconnect(ERR_OK, false); + connectRecord->CompleteDisconnect(ERR_OK, callerDied); list.emplace_back(connectRecord); } return ERR_OK; @@ -893,6 +906,22 @@ void AbilityConnectManager::OnAppStateChanged(const AppInfo &info) } } }); + + auto cacheAbilityList = AbilityCacheManager::GetInstance().GetAbilityList(); + std::for_each(cacheAbilityList.begin(), cacheAbilityList.end(), [&info](std::shared_ptr &service) { + if (service && (info.processName == service->GetAbilityInfo().process || + info.processName == service->GetApplicationInfo().bundleName)) { + auto appName = service->GetApplicationInfo().name; + auto uid = service->GetAbilityInfo().applicationInfo.uid; + auto isExist = [&appName, &uid](const AppData &appData) { + return appData.appName == appName && appData.uid == uid; + }; + auto iter = std::find_if(info.appData.begin(), info.appData.end(), isExist); + if (iter != info.appData.end()) { + service->SetAppState(info.state); + } + } + }); } int AbilityConnectManager::AbilityTransitionDone(const sptr &token, int state) @@ -1025,6 +1054,7 @@ int AbilityConnectManager::ScheduleConnectAbilityDoneLocked( void AbilityConnectManager::ProcessEliminateAbilityRecord(std::shared_ptr eliminateRecord) { + CHECK_POINTER(eliminateRecord); std::string eliminateKey = eliminateRecord->GetURI(); if (FRS_BUNDLE_NAME == eliminateRecord->GetAbilityInfo().bundleName) { eliminateKey = eliminateKey + @@ -1037,28 +1067,35 @@ void AbilityConnectManager::ProcessEliminateAbilityRecord(std::shared_ptr abilityRecord) { RemoveUIExtensionAbilityRecord(abilityRecord); - if (!abilityRecord->IsSceneBoard()) { - if (IsCacheExtensionAbilityType(abilityRecord)) { - std::string serviceKey = abilityRecord->GetURI(); - auto abilityInfo = abilityRecord->GetAbilityInfo(); - if (FRS_BUNDLE_NAME == abilityInfo.bundleName) { - AppExecFwk::ElementName elementName(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name, - abilityInfo.moduleName); - serviceKey = elementName.GetURI() + - std::to_string(abilityRecord->GetWant().GetIntParam(FRS_APP_INDEX, 0)); - } - { - std::lock_guard lock(serviceMapMutex_); - serviceMap_.erase(serviceKey); - } - auto eliminateRecord = AbilityCacheManager::GetInstance().Put(abilityRecord); - if (eliminateRecord != nullptr) { - ProcessEliminateAbilityRecord(eliminateRecord); - } - } else { - TerminateRecord(abilityRecord); - } + if (abilityRecord->IsSceneBoard()) { + return; } + if (IsCacheExtensionAbilityType(abilityRecord)) { + std::string serviceKey = abilityRecord->GetURI(); + auto abilityInfo = abilityRecord->GetAbilityInfo(); + TAG_LOGD(AAFwkTag::ABILITYMGR, "Cache the ability, service:%{public}s, extension type %{public}d", + serviceKey.c_str(), abilityInfo.extensionAbilityType); + if (FRS_BUNDLE_NAME == abilityInfo.bundleName) { + AppExecFwk::ElementName elementName(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name, + abilityInfo.moduleName); + serviceKey = elementName.GetURI() + + std::to_string(abilityRecord->GetWant().GetIntParam(FRS_APP_INDEX, 0)); + } + { + std::lock_guard lock(serviceMapMutex_); + serviceMap_.erase(serviceKey); + } + auto eliminateRecord = AbilityCacheManager::GetInstance().Put(abilityRecord); + if (eliminateRecord != nullptr) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate the eliminated ability, service:%{public}s.", + eliminateRecord->GetURI().c_str()); + ProcessEliminateAbilityRecord(eliminateRecord); + } + return; + } + TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate the ability, service:%{public}s, extension type %{public}d", + abilityRecord->GetURI().c_str(), abilityRecord->GetAbilityInfo().extensionAbilityType); + TerminateRecord(abilityRecord); } int AbilityConnectManager::ScheduleDisconnectAbilityDoneLocked(const sptr &token) @@ -1328,11 +1365,11 @@ std::shared_ptr AbilityConnectManager::GetUIExtensioBySessionInfo std::shared_ptr AbilityConnectManager::GetExtensionByTokenFromTerminatingMap( const sptr &token) { - auto IsMatch = [token](auto& extension) { - if (extension.second == nullptr) { + auto IsMatch = [token](auto& extensionRecord) { + if (extensionRecord == nullptr) { return false; } - auto terminatingToken = extension.second->GetToken(); + auto terminatingToken = extensionRecord->GetToken(); if (terminatingToken != nullptr) { return terminatingToken->AsObject() == token; } @@ -1341,9 +1378,9 @@ std::shared_ptr AbilityConnectManager::GetExtensionByTokenFromTer std::lock_guard lock(serviceMapMutex_); auto terminatingExtensionRecord = - std::find_if(terminatingExtensionMap_.begin(), terminatingExtensionMap_.end(), IsMatch); - if (terminatingExtensionRecord != terminatingExtensionMap_.end()) { - return terminatingExtensionRecord->second; + std::find_if(terminatingExtensionList_.begin(), terminatingExtensionList_.end(), IsMatch); + if (terminatingExtensionRecord != terminatingExtensionList_.end()) { + return *terminatingExtensionRecord; } return nullptr; } @@ -1702,11 +1739,47 @@ int AbilityConnectManager::DispatchTerminate(const std::shared_ptr &abilityRecord) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + CHECK_POINTER(abilityRecord); + AppExecFwk::ExtensionAbilityType extType = abilityRecord->GetAbilityInfo().extensionAbilityType; + if (extType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) { + ResumeConnectAbility(abilityRecord); + } else { + PostTimeOutTask(abilityRecord, AbilityConnectManager::CONNECT_TIMEOUT_MSG); + abilityRecord->ConnectAbility(); + } +} + +void AbilityConnectManager::ConnectUIServiceExtAbility(const std::shared_ptr &abilityRecord, + const Want &want) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); CHECK_POINTER(abilityRecord); PostTimeOutTask(abilityRecord, AbilityConnectManager::CONNECT_TIMEOUT_MSG); - abilityRecord->ConnectAbility(); + abilityRecord->ConnectUIServiceExtAbility(want); +} + +void AbilityConnectManager::ResumeConnectAbility(const std::shared_ptr &abilityRecord) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "ResumeConnectAbility"); + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + CHECK_POINTER(abilityRecord); + AppExecFwk::ExtensionAbilityType extType = abilityRecord->GetAbilityInfo().extensionAbilityType; + if (extType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "ResumeConnectAbility only support UI_SERVICE"); + return; + } + + PostTimeOutTask(abilityRecord, AbilityConnectManager::CONNECT_TIMEOUT_MSG); + std::list> connectingList = abilityRecord->GetConnectingRecordList(); + for (auto &connectRecord : connectingList) { + if (connectRecord == nullptr) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "ConnectRecord is nullptr."); + continue; + } + abilityRecord->ConnectUIServiceExtAbility(connectRecord->GetConnectWant()); + } } void AbilityConnectManager::CommandAbility(const std::shared_ptr &abilityRecord) @@ -1864,7 +1937,7 @@ void AbilityConnectManager::RemoveServiceAbility(const std::shared_ptrGetURI().c_str()); std::lock_guard lock(serviceMapMutex_); - terminatingExtensionMap_.erase(abilityRecord->GetURI()); + terminatingExtensionList_.remove(abilityRecord); } void AbilityConnectManager::AddConnectDeathRecipient(sptr connectObject) @@ -2005,15 +2078,18 @@ void AbilityConnectManager::OnTimeOut(uint32_t msgId, int64_t abilityRecordId) void AbilityConnectManager::HandleInactiveTimeout(const std::shared_ptr &ability) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "HandleInactiveTimeout start"); + TAG_LOGI(AAFwkTag::ABILITYMGR, "HandleInactiveTimeout start"); CHECK_POINTER(ability); if (ability->GetAbilityInfo().name == AbilityConfig::LAUNCHER_ABILITY_NAME) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle root launcher inactive timeout."); // terminate the timeout root launcher. DelayedSingleton::GetInstance()->AttachTimeOut(ability->GetToken()); } + if (ability->GetAbilityInfo().name == AbilityConfig::CALLUI_ABILITY_NAME && ability->GetStartId() == 0) { + HandleConnectTimeoutTask(ability); + } - TAG_LOGD(AAFwkTag::ABILITYMGR, "HandleInactiveTimeout end"); + TAG_LOGI(AAFwkTag::ABILITYMGR, "HandleInactiveTimeout end"); } bool AbilityConnectManager::IsAbilityNeedKeepAlive(const std::shared_ptr &abilityRecord) @@ -2050,7 +2126,10 @@ void AbilityConnectManager::ClearPreloadUIExtensionRecord(const std::shared_ptr< void AbilityConnectManager::KeepAbilityAlive(const std::shared_ptr &abilityRecord, int32_t currentUserId) { - TAG_LOGI(AAFwkTag::ABILITYMGR, "restart ability: %{public}s", abilityRecord->GetAbilityInfo().name.c_str()); + CHECK_POINTER(abilityRecord); + auto abilityInfo = abilityRecord->GetAbilityInfo(); + TAG_LOGI(AAFwkTag::ABILITYMGR, "restart ability, bundleName: %{public}s, abilityName: %{public}s", + abilityInfo.bundleName.c_str(), abilityInfo.name.c_str()); auto token = abilityRecord->GetToken(); if ((IsLauncher(abilityRecord) || abilityRecord->IsSceneBoard()) && token != nullptr) { IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton::GetInstance()->ClearProcessByToken( @@ -2061,8 +2140,13 @@ void AbilityConnectManager::KeepAbilityAlive(const std::shared_ptr::GetInstance()->IsKilledForUpgradeWeb(abilityInfo.bundleName)) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "bundle is killed for upgrade web"); + return; + } if (DelayedSingleton::GetInstance()->IsMemorySizeSufficent() || - IsLauncher(abilityRecord) || abilityRecord->IsSceneBoard()) { + IsLauncher(abilityRecord) || abilityRecord->IsSceneBoard() || + AppUtils::GetInstance().IsAllowResidentInExtremeMemory(abilityInfo.bundleName, abilityInfo.name)) { RestartAbility(abilityRecord, currentUserId); } } @@ -2135,7 +2219,7 @@ static bool CheckIsNumString(const std::string &numStr) void AbilityConnectManager::HandleNotifyAssertFaultDialogDied(const std::shared_ptr &abilityRecord) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); CHECK_POINTER(abilityRecord); if (abilityRecord->GetAbilityInfo().name != ABILITY_NAME_ASSERT_FAULT_DIALOG || abilityRecord->GetAbilityInfo().bundleName != BUNDLE_NAME_DIALOG) { @@ -2161,7 +2245,7 @@ void AbilityConnectManager::HandleNotifyAssertFaultDialogDied(const std::shared_ void AbilityConnectManager::CloseAssertDialog(const std::string &assertSessionId) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Called"); - sptr token; + std::shared_ptr abilityRecord = nullptr; { std::lock_guard lock(serviceMapMutex_); for (const auto &item : serviceMap_) { @@ -2171,14 +2255,22 @@ void AbilityConnectManager::CloseAssertDialog(const std::string &assertSessionId auto assertSessionStr = item.second->GetWant().GetStringParam(Want::PARAM_ASSERT_FAULT_SESSION_ID); if (assertSessionStr == assertSessionId) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate assert fault dialog called."); - terminatingExtensionMap_.emplace(item.first, item.second); - token = item.second->GetToken(); + abilityRecord = item.second; serviceMap_.erase(item.first); break; } } } + if (abilityRecord == nullptr) { + abilityRecord = AbilityCacheManager::GetInstance().FindRecordBySessionId(assertSessionId); + AbilityCacheManager::GetInstance().Remove(abilityRecord); + } + if (abilityRecord == nullptr) { + return; + } + TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate assert fault dialog called."); + terminatingExtensionList_.push_back(abilityRecord); + sptr token = abilityRecord->GetToken(); if (token != nullptr) { std::lock_guard lock(serialMutex_); TerminateAbilityLocked(token); @@ -2222,6 +2314,7 @@ void AbilityConnectManager::RestartAbility(const std::shared_ptr requestInfo.appInfo = abilityRecord->GetApplicationInfo(); requestInfo.restartTime = abilityRecord->GetRestartTime(); requestInfo.restart = true; + requestInfo.uid = abilityRecord->GetUid(); abilityRecord->SetRestarting(true); if (AppUtils::GetInstance().IsLauncherAbility(abilityRecord->GetAbilityInfo().name)) { @@ -2258,10 +2351,20 @@ void AbilityConnectManager::RestartAbility(const std::shared_ptr } } +std::string AbilityConnectManager::GetServiceKey(const std::shared_ptr &service) +{ + std::string serviceKey = service->GetURI(); + if (FRS_BUNDLE_NAME == service->GetAbilityInfo().bundleName) { + serviceKey = serviceKey + std::to_string(service->GetWant().GetIntParam(FRS_APP_INDEX, 0)); + } + return serviceKey; +} + void AbilityConnectManager::DumpState(std::vector &info, bool isClient, const std::string &args) { TAG_LOGI(AAFwkTag::ABILITYMGR, "args:%{public}s.", args.c_str()); auto serviceMapBack = GetServiceMap(); + auto cacheList = AbilityCacheManager::GetInstance().GetAbilityList(); if (!args.empty()) { auto it = std::find_if(serviceMapBack.begin(), serviceMapBack.end(), [&args](const auto &service) { return service.first.compare(args) == 0; @@ -2272,7 +2375,21 @@ void AbilityConnectManager::DumpState(std::vector &info, bool isCli it->second->DumpService(info, isClient); } } else { - info.emplace_back(args + ": Nothing to dump."); + info.emplace_back(args + ": Nothing to dump from serviceMap."); + } + + std::string serviceKey; + auto iter = std::find_if(cacheList.begin(), cacheList.end(), [&args, &serviceKey, this](const auto &service) { + serviceKey = GetServiceKey(service); + return serviceKey.compare(args) == 0; + }); + if (iter != cacheList.end()) { + info.emplace_back("uri [ " + serviceKey + " ]"); + if (*iter != nullptr) { + (*iter)->DumpService(info, isClient); + } + } else { + info.emplace_back(args + ": Nothing to dump from lru cache."); } } else { info.emplace_back(" ExtensionRecords:"); @@ -2282,6 +2399,13 @@ void AbilityConnectManager::DumpState(std::vector &info, bool isCli service.second->DumpService(info, isClient); } } + for (auto &&service : cacheList) { + std::string serviceKey = GetServiceKey(service); + info.emplace_back(" uri [" + serviceKey + "]"); + if (service != nullptr) { + service->DumpService(info, isClient); + } + } } } @@ -2299,11 +2423,19 @@ void AbilityConnectManager::DumpStateByUri(std::vector &info, bool info.emplace_back("uri [ " + it->first + " ]"); extensionAbilityRecord = it->second; } else { - info.emplace_back(args + ": Nothing to dump."); + info.emplace_back(args + ": Nothing to dump from serviceMap."); } } if (extensionAbilityRecord != nullptr) { extensionAbilityRecord->DumpService(info, params, isClient); + return; + } + extensionAbilityRecord = AbilityCacheManager::GetInstance().FindRecordByServiceKey(args); + if (extensionAbilityRecord != nullptr) { + info.emplace_back("uri [ " + args + " ]"); + extensionAbilityRecord->DumpService(info, params, isClient); + } else { + info.emplace_back(args + ": Nothing to dump from lru cache."); } } @@ -2330,6 +2462,25 @@ void AbilityConnectManager::GetExtensionRunningInfos(int upperLimit, std::vector } }; std::for_each(serviceMapBack.begin(), serviceMapBack.end(), queryInfo); + + auto cacheAbilityList = AbilityCacheManager::GetInstance().GetAbilityList(); + auto queryInfoForCache = [&](std::shared_ptr &service) { + if (static_cast(info.size()) >= upperLimit) { + return; + } + CHECK_POINTER(service); + + if (isPerm) { + GetExtensionRunningInfo(service, userId, info); + } else { + auto callingTokenId = IPCSkeleton::GetCallingTokenID(); + auto tokenID = service->GetApplicationInfo().accessTokenId; + if (callingTokenId == tokenID) { + GetExtensionRunningInfo(service, userId, info); + } + } + }; + std::for_each(cacheAbilityList.begin(), cacheAbilityList.end(), queryInfoForCache); } void AbilityConnectManager::GetAbilityRunningInfos(std::vector &info, bool isPerm) @@ -2394,7 +2545,7 @@ void AbilityConnectManager::PauseExtensions() auto targetExtension = it->second; if (targetExtension != nullptr && targetExtension->GetAbilityInfo().type == AbilityType::EXTENSION && (IsLauncher(targetExtension) || targetExtension->IsSceneBoard())) { - terminatingExtensionMap_.emplace(it->first, it->second); + terminatingExtensionList_.push_back(it->second); it = serviceMap_.erase(it); TAG_LOGI(AAFwkTag::ABILITYMGR, "terminate ability:%{public}s.", targetExtension->GetAbilityInfo().name.c_str()); @@ -2414,15 +2565,18 @@ void AbilityConnectManager::PauseExtensions() void AbilityConnectManager::RemoveLauncherDeathRecipient() { TAG_LOGI(AAFwkTag::ABILITYMGR, "Call."); - std::lock_guard lock(serviceMapMutex_); - for (auto it = serviceMap_.begin(); it != serviceMap_.end(); ++it) { - auto targetExtension = it->second; - if (targetExtension != nullptr && targetExtension->GetAbilityInfo().type == AbilityType::EXTENSION && - (IsLauncher(targetExtension) || targetExtension->IsSceneBoard())) { - targetExtension->RemoveAbilityDeathRecipient(); - break; + { + std::lock_guard lock(serviceMapMutex_); + for (auto it = serviceMap_.begin(); it != serviceMap_.end(); ++it) { + auto targetExtension = it->second; + if (targetExtension != nullptr && targetExtension->GetAbilityInfo().type == AbilityType::EXTENSION && + (IsLauncher(targetExtension) || targetExtension->IsSceneBoard())) { + targetExtension->RemoveAbilityDeathRecipient(); + return; + } } } + AbilityCacheManager::GetInstance().RemoveLauncherDeathRecipient(); } bool AbilityConnectManager::IsLauncher(std::shared_ptr serviceExtension) const @@ -2435,16 +2589,6 @@ bool AbilityConnectManager::IsLauncher(std::shared_ptr serviceExt serviceExtension->GetAbilityInfo().bundleName == AbilityConfig::LAUNCHER_BUNDLE_NAME; } -bool AbilityConnectManager::IsSampleManagement(std::shared_ptr serviceExtension) const -{ - if (serviceExtension == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "param is nullptr"); - return false; - } - return serviceExtension->GetAbilityInfo().name == ABILITY_NAME_SAMPLE_MANAGEMENT && - serviceExtension->GetAbilityInfo().bundleName == BUNDLE_NAME_SAMPLE_MANAGEMENT; -} - void AbilityConnectManager::KillProcessesByUserId() const { auto appScheduler = DelayedSingleton::GetInstance(); @@ -2640,15 +2784,15 @@ void AbilityConnectManager::MoveToTerminatingMap(const std::shared_ptrGetAbilityInfo(); std::lock_guard lock(serviceMapMutex_); - terminatingExtensionMap_.emplace(abilityRecord->GetURI(), abilityRecord); + terminatingExtensionList_.push_back(abilityRecord); + std::string serviceKey = abilityRecord->GetURI(); if (FRS_BUNDLE_NAME == abilityInfo.bundleName) { AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name, abilityInfo.moduleName); - serviceMap_.erase( - element.GetURI() + std::to_string(abilityRecord->GetWant().GetIntParam(FRS_APP_INDEX, 0))); - } else { - serviceMap_.erase(abilityRecord->GetURI()); + serviceKey = element.GetURI() + std::to_string(abilityRecord->GetWant().GetIntParam(FRS_APP_INDEX, 0)); } + serviceMap_.erase(serviceKey); + AbilityCacheManager::GetInstance().Remove(abilityRecord); if (IsSpecialAbility(abilityRecord->GetAbilityInfo())) { TAG_LOGI(AAFwkTag::ABILITYMGR, "Moving ability: %{public}s", abilityRecord->GetURI().c_str()); } @@ -2731,7 +2875,7 @@ void AbilityConnectManager::HandleUIExtWindowDiedTask(const sptr bool AbilityConnectManager::IsUIExtensionFocused(uint32_t uiExtensionTokenId, const sptr& focusToken) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "called, id: %{public}u", uiExtensionTokenId); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); CHECK_POINTER_AND_RETURN(uiExtensionAbilityRecordMgr_, false); std::lock_guard guard(uiExtensionMapMutex_); for (auto& item: uiExtensionMap_) { @@ -2739,7 +2883,7 @@ bool AbilityConnectManager::IsUIExtensionFocused(uint32_t uiExtensionTokenId, co auto sessionInfo = item.second.second; if (uiExtension && uiExtension->GetApplicationInfo().accessTokenId == uiExtensionTokenId) { if (uiExtensionAbilityRecordMgr_->IsFocused(uiExtension->GetUIExtensionAbilityId(), focusToken)) { - TAG_LOGI(AAFwkTag::ABILITYMGR, "id: %{public}u, isFocused.", uiExtensionTokenId); + TAG_LOGI(AAFwkTag::ABILITYMGR, "isFocused."); return true; } if (sessionInfo && sessionInfo->callerToken == focusToken) { @@ -2931,15 +3075,26 @@ std::shared_ptr AbilityConnectManager::GetUIExtensionRootH return uiExtensionAbilityRecordMgr_->GetUIExtensionRootHostInfo(token); } +int32_t AbilityConnectManager::GetUIExtensionSessionInfo(const sptr token, + UIExtensionSessionInfo &uiExtensionSessionInfo) +{ + CHECK_POINTER_AND_RETURN(token, ERR_NULL_OBJECT); + CHECK_POINTER_AND_RETURN(uiExtensionAbilityRecordMgr_, ERR_NULL_OBJECT); + return uiExtensionAbilityRecordMgr_->GetUIExtensionSessionInfo(token, uiExtensionSessionInfo); +} + void AbilityConnectManager::SignRestartAppFlag(const std::string &bundleName) { - std::lock_guard lock(serviceMapMutex_); - for (auto &[key, abilityRecord] : serviceMap_) { - if (abilityRecord == nullptr || abilityRecord->GetApplicationInfo().bundleName != bundleName) { - continue; + { + std::lock_guard lock(serviceMapMutex_); + for (auto &[key, abilityRecord] : serviceMap_) { + if (abilityRecord == nullptr || abilityRecord->GetApplicationInfo().bundleName != bundleName) { + continue; + } + abilityRecord->SetRestartAppFlag(true); } - abilityRecord->SetRestartAppFlag(true); } + AbilityCacheManager::GetInstance().SignRestartAppFlag(bundleName); } void AbilityConnectManager::DeleteInvalidServiceRecord(const std::string &bundleName) @@ -2954,6 +3109,7 @@ void AbilityConnectManager::DeleteInvalidServiceRecord(const std::string &bundle ++it; } } + AbilityCacheManager::GetInstance().DeleteInvalidServiceRecord(bundleName); } bool AbilityConnectManager::AddToServiceMap(const std::string &key, std::shared_ptr abilityRecord) diff --git a/services/abilitymgr/src/ability_debug_deal.cpp b/services/abilitymgr/src/ability_debug_deal.cpp index 37d2511fb1..9e972c3179 100644 --- a/services/abilitymgr/src/ability_debug_deal.cpp +++ b/services/abilitymgr/src/ability_debug_deal.cpp @@ -17,7 +17,6 @@ #include "ability_record.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "in_process_call_wrapper.h" @@ -37,7 +36,7 @@ void AbilityDebugDeal::RegisterAbilityDebugResponse() void AbilityDebugDeal::OnAbilitysDebugStarted(const std::vector> &tokens) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); for (auto &token : tokens) { auto abilityRecord = Token::GetAbilityRecordByToken(token); if (abilityRecord == nullptr) { @@ -50,7 +49,7 @@ void AbilityDebugDeal::OnAbilitysDebugStarted(const std::vector> &tokens) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); for (auto &token : tokens) { auto abilityRecord = Token::GetAbilityRecordByToken(token); if (abilityRecord == nullptr) { diff --git a/services/abilitymgr/src/ability_event_handler.cpp b/services/abilitymgr/src/ability_event_handler.cpp index b38e7d79cb..db84992b17 100644 --- a/services/abilitymgr/src/ability_event_handler.cpp +++ b/services/abilitymgr/src/ability_event_handler.cpp @@ -19,7 +19,6 @@ #include "ability_manager_service.h" #include "ability_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/ability_event_util.cpp b/services/abilitymgr/src/ability_event_util.cpp index 11de71b04e..093c1c74ac 100644 --- a/services/abilitymgr/src/ability_event_util.cpp +++ b/services/abilitymgr/src/ability_event_util.cpp @@ -16,7 +16,6 @@ #include "ability_event_util.h" #include "app_scheduler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/ability_first_frame_state_observer_manager.cpp b/services/abilitymgr/src/ability_first_frame_state_observer_manager.cpp index 4bb65a6ddd..5b5e3881e8 100644 --- a/services/abilitymgr/src/ability_first_frame_state_observer_manager.cpp +++ b/services/abilitymgr/src/ability_first_frame_state_observer_manager.cpp @@ -18,7 +18,6 @@ #include "ability_first_frame_state_data.h" #include "ability_first_frame_state_observer_stub.h" -#include "ability_manager_errors.h" #include "application_info.h" #include "hilog_tag_wrapper.h" #include "permission_verification.h" @@ -52,7 +51,7 @@ int32_t AbilityFirstFrameStateObserverSet::AddAbilityFirstFrameStateObserver( void AbilityFirstFrameStateObserverSet::AddObserverDeathRecipient(const sptr &observer) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (observer == nullptr || observer->AsObject() == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "The param observer or observer->AsObject is nullptr."); return; @@ -158,7 +157,7 @@ void AbilityFirstFrameStateObserverManager::Init() int32_t AbilityFirstFrameStateObserverManager::RegisterAbilityFirstFrameStateObserver( const sptr &observer, const std::string &targetBundleName) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (!PermissionVerification::GetInstance()->IsSystemAppCall()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "verify system app failed"); return ERR_NOT_SYSTEM_APP; @@ -178,7 +177,7 @@ int32_t AbilityFirstFrameStateObserverManager::RegisterAbilityFirstFrameStateObs int32_t AbilityFirstFrameStateObserverManager::UnregisterAbilityFirstFrameStateObserver( const sptr &observer) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (!PermissionVerification::GetInstance()->IsSystemAppCall()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "verify system app failed"); return ERR_NOT_SYSTEM_APP; diff --git a/services/abilitymgr/src/ability_manager_client.cpp b/services/abilitymgr/src/ability_manager_client.cpp index 77440e1943..22e8d694e4 100644 --- a/services/abilitymgr/src/ability_manager_client.cpp +++ b/services/abilitymgr/src/ability_manager_client.cpp @@ -21,7 +21,6 @@ #include "dlp_file_kits.h" #endif // WITH_DLP #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" @@ -1294,11 +1293,12 @@ ErrCode AbilityManagerClient::SetMissionIcon( return abms->SetMissionIcon(abilityToken, icon); } -ErrCode AbilityManagerClient::RegisterWindowManagerServiceHandler(sptr handler) +ErrCode AbilityManagerClient::RegisterWindowManagerServiceHandler(sptr handler, + bool animationEnabled) { auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); - return abms->RegisterWindowManagerServiceHandler(handler); + return abms->RegisterWindowManagerServiceHandler(handler, animationEnabled); } void AbilityManagerClient::CompleteFirstFrameDrawing(sptr abilityToken) @@ -1330,14 +1330,14 @@ ErrCode AbilityManagerClient::PrepareTerminateAbility(sptr token, return abms->PrepareTerminateAbility(token, callback); } -ErrCode AbilityManagerClient::GetDialogSessionInfo(const std::string dialogSessionId, sptr &info) +ErrCode AbilityManagerClient::GetDialogSessionInfo(const std::string &dialogSessionId, sptr &info) { auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->GetDialogSessionInfo(dialogSessionId, info); } -ErrCode AbilityManagerClient::SendDialogResult(const Want &want, const std::string dialogSessionId, const bool isAllow) +ErrCode AbilityManagerClient::SendDialogResult(const Want &want, const std::string &dialogSessionId, const bool isAllow) { auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); @@ -1467,7 +1467,7 @@ AppExecFwk::ElementName AbilityManagerClient::GetTopAbility(bool isNeedLocalDevi { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); { - std::lock_guard lock_l(mutex_); + std::lock_guard lock_l(topAbilityMutex_); #ifdef SUPPORT_SCREEN if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { AppExecFwk::ElementName elementName = {}; @@ -1512,12 +1512,13 @@ void AbilityManagerClient::HandleDlpApp(Want &want) #endif // WITH_DLP } -ErrCode AbilityManagerClient::AddFreeInstallObserver(sptr observer) +ErrCode AbilityManagerClient::AddFreeInstallObserver(const sptr callerToken, + const sptr observer) { TAG_LOGI(AAFwkTag::ABILITYMGR, "call"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); - return abms->AddFreeInstallObserver(observer); + return abms->AddFreeInstallObserver(callerToken, observer); } int32_t AbilityManagerClient::IsValidMissionIds( @@ -1657,7 +1658,7 @@ ErrCode AbilityManagerClient::UnregisterIAbilityManagerCollaborator(int32_t type ErrCode AbilityManagerClient::RegisterStatusBarDelegate(sptr delegate) { - TAG_LOGI(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGI(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->RegisterStatusBarDelegate(delegate); @@ -1665,7 +1666,7 @@ ErrCode AbilityManagerClient::RegisterStatusBarDelegate(sptr& pids) { - TAG_LOGI(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGI(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->KillProcessWithPrepareTerminate(pids); @@ -1673,7 +1674,7 @@ ErrCode AbilityManagerClient::KillProcessWithPrepareTerminate(const std::vector< ErrCode AbilityManagerClient::RegisterAutoStartupSystemCallback(sptr callback) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->RegisterAutoStartupSystemCallback(callback); @@ -1681,7 +1682,7 @@ ErrCode AbilityManagerClient::RegisterAutoStartupSystemCallback(sptr callback) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->UnregisterAutoStartupSystemCallback(callback); @@ -1689,7 +1690,7 @@ ErrCode AbilityManagerClient::UnregisterAutoStartupSystemCallback(sptrSetApplicationAutoStartup(info); @@ -1697,7 +1698,7 @@ ErrCode AbilityManagerClient::SetApplicationAutoStartup(const AutoStartupInfo &i ErrCode AbilityManagerClient::CancelApplicationAutoStartup(const AutoStartupInfo &info) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->CancelApplicationAutoStartup(info); @@ -1705,7 +1706,7 @@ ErrCode AbilityManagerClient::CancelApplicationAutoStartup(const AutoStartupInfo ErrCode AbilityManagerClient::QueryAllAutoStartupApplications(std::vector &infoList) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->QueryAllAutoStartupApplications(infoList); @@ -1730,7 +1731,7 @@ ErrCode AbilityManagerClient::RegisterSessionHandler(sptr object) ErrCode AbilityManagerClient::RegisterAppDebugListener(sptr listener) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->RegisterAppDebugListener(listener); @@ -1738,7 +1739,7 @@ ErrCode AbilityManagerClient::RegisterAppDebugListener(sptr listener) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->UnregisterAppDebugListener(listener); @@ -1746,7 +1747,7 @@ ErrCode AbilityManagerClient::UnregisterAppDebugListener(sptrAttachAppDebug(bundleName); @@ -1754,7 +1755,7 @@ ErrCode AbilityManagerClient::AttachAppDebug(const std::string &bundleName) ErrCode AbilityManagerClient::DetachAppDebug(const std::string &bundleName) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->DetachAppDebug(bundleName); @@ -1763,7 +1764,7 @@ ErrCode AbilityManagerClient::DetachAppDebug(const std::string &bundleName) ErrCode AbilityManagerClient::ExecuteIntent(uint64_t key, sptr callerToken, const InsightIntentExecuteParam ¶m) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->ExecuteIntent(key, callerToken, param); @@ -1783,7 +1784,7 @@ bool AbilityManagerClient::IsAbilityControllerStart(const Want &want) ErrCode AbilityManagerClient::ExecuteInsightIntentDone(sptr token, uint64_t intentId, const InsightIntentExecuteResult &result) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->ExecuteInsightIntentDone(token, intentId, result); @@ -1791,7 +1792,7 @@ ErrCode AbilityManagerClient::ExecuteInsightIntentDone(sptr token int32_t AbilityManagerClient::GetForegroundUIAbilities(std::vector &list) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_INVALID_VALUE(abms); return abms->GetForegroundUIAbilities(list); @@ -1828,7 +1829,7 @@ int32_t AbilityManagerClient::NotifyDebugAssertResult(uint64_t assertFaultSessio int32_t AbilityManagerClient::UpdateSessionInfoBySCB(std::list &sessionInfos, int32_t userId, std::vector &sessionIds) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->UpdateSessionInfoBySCB(sessionInfos, userId, sessionIds); @@ -1843,10 +1844,19 @@ ErrCode AbilityManagerClient::GetUIExtensionRootHostInfo(const sptrGetUIExtensionRootHostInfo(token, hostInfo, userId); } +ErrCode AbilityManagerClient::GetUIExtensionSessionInfo(const sptr token, + UIExtensionSessionInfo &uiExtensionSessionInfo, int32_t userId) +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension session info."); + auto abms = GetAbilityManager(); + CHECK_POINTER_RETURN_NOT_CONNECTED(abms); + return abms->GetUIExtensionSessionInfo(token, uiExtensionSessionInfo, userId); +} + int32_t AbilityManagerClient::RestartApp(const AAFwk::Want &want) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_INVALID_VALUE(abms); return abms->RestartApp(want); @@ -1855,7 +1865,7 @@ int32_t AbilityManagerClient::RestartApp(const AAFwk::Want &want) int32_t AbilityManagerClient::OpenAtomicService(Want& want, const StartOptions &options, sptr callerToken, int32_t requestCode, int32_t userId) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_INVALID_VALUE(abms); return abms->OpenAtomicService(want, options, callerToken, requestCode, userId); @@ -1863,7 +1873,7 @@ int32_t AbilityManagerClient::OpenAtomicService(Want& want, const StartOptions & int32_t AbilityManagerClient::SetResidentProcessEnabled(const std::string &bundleName, bool enable) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_INVALID_VALUE(abms); return abms->SetResidentProcessEnabled(bundleName, enable); @@ -1910,5 +1920,22 @@ void AbilityManagerClient::NotifyFrozenProcessByRSS(const std::vector & CHECK_POINTER_RETURN(abms); return abms->NotifyFrozenProcessByRSS(pidList, uid); } + +ErrCode AbilityManagerClient::PreStartMission(const std::string& bundleName, const std::string& moduleName, + const std::string& abilityName, const std::string& startTime) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + auto abms = GetAbilityManager(); + CHECK_POINTER_RETURN_NOT_CONNECTED(abms); + return abms->PreStartMission(bundleName, moduleName, abilityName, startTime); +} + +ErrCode AbilityManagerClient::OpenLink(const Want& want, sptr callerToken, + int32_t userId, int requestCode) +{ + auto abms = GetAbilityManager(); + CHECK_POINTER_RETURN_INVALID_VALUE(abms); + return abms->OpenLink(want, callerToken, userId, requestCode); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_collaborator_proxy.cpp b/services/abilitymgr/src/ability_manager_collaborator_proxy.cpp index b09bd64921..f50ffc7ec4 100644 --- a/services/abilitymgr/src/ability_manager_collaborator_proxy.cpp +++ b/services/abilitymgr/src/ability_manager_collaborator_proxy.cpp @@ -17,7 +17,6 @@ #include "configuration.h" #include "errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/ability_manager_event_subscriber.cpp b/services/abilitymgr/src/ability_manager_event_subscriber.cpp index 8e85ea1b1b..03d6be3a3b 100644 --- a/services/abilitymgr/src/ability_manager_event_subscriber.cpp +++ b/services/abilitymgr/src/ability_manager_event_subscriber.cpp @@ -17,7 +17,6 @@ #include "common_event_support.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/services/abilitymgr/src/ability_manager_proxy.cpp b/services/abilitymgr/src/ability_manager_proxy.cpp index 2043acb848..758caa021c 100644 --- a/services/abilitymgr/src/ability_manager_proxy.cpp +++ b/services/abilitymgr/src/ability_manager_proxy.cpp @@ -367,7 +367,7 @@ int AbilityManagerProxy::StartAbility(const Want &want, const StartOptions &star } int AbilityManagerProxy::StartAbilityAsCaller(const Want &want, const sptr &callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult) + sptr asCallerSourceToken, int32_t userId, int requestCode) { MessageParcel data; MessageParcel reply; @@ -390,7 +390,6 @@ int AbilityManagerProxy::StartAbilityAsCaller(const Want &want, const sptr &extens return INNER_ERR; } - if (!extensionSessionInfo->isModal) { - error = SendRequest(AbilityManagerInterfaceCode::START_UI_EXTENSION_ABILITY_NON_MODAL, data, reply, option); - } else { + if (extensionSessionInfo->uiExtensionUsage == UIExtensionUsage::EMBEDDED) { + error = SendRequest(AbilityManagerInterfaceCode::START_UI_EXTENSION_ABILITY_EMBEDDED, data, reply, option); + } else if (extensionSessionInfo->uiExtensionUsage == UIExtensionUsage::MODAL) { error = SendRequest(AbilityManagerInterfaceCode::START_UI_EXTENSION_ABILITY, data, reply, option); + } else { + error = SendRequest(AbilityManagerInterfaceCode::START_UI_EXTENSION_CONSTRAINED_EMBEDDED, data, reply, option); } if (error != NO_ERROR) { @@ -1786,6 +1787,11 @@ int AbilityManagerProxy::ForceTimeoutForTest(const std::string &abilityName, con #endif int AbilityManagerProxy::UninstallApp(const std::string &bundleName, int32_t uid) +{ + return UninstallApp(bundleName, uid, 0); +} + +int32_t AbilityManagerProxy::UninstallApp(const std::string &bundleName, int32_t uid, int32_t appIndex) { MessageParcel data; MessageParcel reply; @@ -1802,6 +1808,10 @@ int AbilityManagerProxy::UninstallApp(const std::string &bundleName, int32_t uid TAG_LOGE(AAFwkTag::ABILITYMGR, "uid write failed."); return ERR_INVALID_VALUE; } + if (!data.WriteInt32(appIndex)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "appIndex write failed."); + return ERR_INVALID_VALUE; + } int error = SendRequest(AbilityManagerInterfaceCode::UNINSTALL_APP, data, reply, option); if (error != NO_ERROR) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Send request error: %{public}d", error); @@ -1810,7 +1820,8 @@ int AbilityManagerProxy::UninstallApp(const std::string &bundleName, int32_t uid return reply.ReadInt32(); } -int32_t AbilityManagerProxy::UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg) +int32_t AbilityManagerProxy::UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg, + int32_t appIndex) { MessageParcel data; MessageParcel reply; @@ -1822,6 +1833,7 @@ int32_t AbilityManagerProxy::UpgradeApp(const std::string &bundleName, const int PROXY_WRITE_PARCEL_AND_RETURN_IF_FAIL(data, String16, Str8ToStr16(bundleName)); PROXY_WRITE_PARCEL_AND_RETURN_IF_FAIL(data, Int32, uid); PROXY_WRITE_PARCEL_AND_RETURN_IF_FAIL(data, String16, Str8ToStr16(exitMsg)); + PROXY_WRITE_PARCEL_AND_RETURN_IF_FAIL(data, Int32, appIndex); int error = SendRequest(AbilityManagerInterfaceCode::UPGRADE_APP, data, reply, option); if (error != NO_ERROR) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Send request error: %{public}d", error); @@ -2955,7 +2967,8 @@ int AbilityManagerProxy::SetMissionIcon(const sptr &token, return reply.ReadInt32(); } -int AbilityManagerProxy::RegisterWindowManagerServiceHandler(const sptr& handler) +int AbilityManagerProxy::RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled) { if (!handler) { TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: handler is nullptr.", __func__); @@ -2970,6 +2983,10 @@ int AbilityManagerProxy::RegisterWindowManagerServiceHandler(const sptr &toke return reply.ReadInt32(); } -int AbilityManagerProxy::GetDialogSessionInfo(const std::string dialogSessionId, sptr &info) +int AbilityManagerProxy::GetDialogSessionInfo(const std::string &dialogSessionId, sptr &info) { MessageParcel data; MessageParcel reply; @@ -3065,7 +3082,7 @@ int AbilityManagerProxy::GetDialogSessionInfo(const std::string dialogSessionId, return reply.ReadInt32(); } -int AbilityManagerProxy::SendDialogResult(const Want &want, const std::string dialogSessionId, const bool isAllow) +int AbilityManagerProxy::SendDialogResult(const Want &want, const std::string &dialogSessionId, const bool isAllow) { MessageParcel data; MessageParcel reply; @@ -3096,7 +3113,7 @@ int AbilityManagerProxy::SendDialogResult(const Want &want, const std::string di int32_t AbilityManagerProxy::RegisterAbilityFirstFrameStateObserver( const sptr &observer, const std::string &targetBundleName) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Write interface token failed."); @@ -3126,7 +3143,7 @@ int32_t AbilityManagerProxy::RegisterAbilityFirstFrameStateObserver( int32_t AbilityManagerProxy::UnregisterAbilityFirstFrameStateObserver( const sptr &observer) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Write interface token failed."); @@ -3867,16 +3884,34 @@ int AbilityManagerProxy::FreeInstallAbilityFromRemote(const Want &want, const sp return reply.ReadInt32(); } -int AbilityManagerProxy::AddFreeInstallObserver(const sptr &observer) +int AbilityManagerProxy::AddFreeInstallObserver(const sptr &callerToken, + const sptr &observer) { MessageParcel data; MessageParcel reply; MessageOption option; + if (observer == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "observer is nullptr."); + return INNER_ERR; + } + if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "write interface token failed."); return INNER_ERR; } + if (callerToken) { + if (!data.WriteBool(true) || !data.WriteRemoteObject(callerToken)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to write flag and callerToken."); + return INNER_ERR; + } + } else { + if (!data.WriteBool(false)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to write flag."); + return INNER_ERR; + } + } + if (!data.WriteRemoteObject(observer->AsObject())) { TAG_LOGE(AAFwkTag::ABILITYMGR, "observer write failed."); return INNER_ERR; @@ -4605,7 +4640,7 @@ int AbilityManagerProxy::PrepareTerminateAbilityBySCB(const sptr &s int32_t AbilityManagerProxy::RegisterAppDebugListener(sptr listener) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Write interface token failed."); @@ -4629,7 +4664,7 @@ int32_t AbilityManagerProxy::RegisterAppDebugListener(sptr listener) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Write interface token failed."); @@ -4653,7 +4688,7 @@ int32_t AbilityManagerProxy::UnregisterAppDebugListener(sptr &callerToken, const InsightIntentExecuteParam ¶m) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); MessageParcel data; MessageParcel reply; MessageOption option; @@ -4762,7 +4797,7 @@ bool AbilityManagerProxy::IsAbilityControllerStart(const Want &want) int32_t AbilityManagerProxy::ExecuteInsightIntentDone(const sptr &token, uint64_t intentId, const InsightIntentExecuteResult &result) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Write remote object failed."); @@ -4791,7 +4826,7 @@ int32_t AbilityManagerProxy::ExecuteInsightIntentDone(const sptr int32_t AbilityManagerProxy::GetForegroundUIAbilities(std::vector &list) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); MessageParcel data; if (!WriteInterfaceToken(data)) { return ERR_FLATTEN_OBJECT; @@ -5059,6 +5094,47 @@ int32_t AbilityManagerProxy::GetUIExtensionRootHostInfo(const sptr token, + UIExtensionSessionInfo &uiExtensionSessionInfo, int32_t userId) +{ + if (token == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Input param invalid."); + return ERR_INVALID_VALUE; + } + + MessageParcel data; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Write remote object failed."); + return INNER_ERR; + } + + if (!data.WriteBool(true) || !data.WriteRemoteObject(token)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Write flag and token failed."); + return INNER_ERR; + } + + if (!data.WriteInt32(userId)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Write userId failed."); + return INNER_ERR; + } + + MessageParcel reply; + MessageOption option; + auto error = SendRequest(AbilityManagerInterfaceCode::GET_UI_EXTENSION_SESSION_INFO, data, reply, option); + if (error != NO_ERROR) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Send request error: %{public}d", error); + return error; + } + + std::unique_ptr info(reply.ReadParcelable()); + if (info == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Get host info failed."); + return INNER_ERR; + } + uiExtensionSessionInfo = *info; + return reply.ReadInt32(); +} + int32_t AbilityManagerProxy::RestartApp(const AAFwk::Want &want) { MessageParcel data; @@ -5130,22 +5206,22 @@ int32_t AbilityManagerProxy::SetResidentProcessEnabled(const std::string &bundle { MessageParcel data; if (!WriteInterfaceToken(data)) { - HILOG_ERROR("Write interface token failed."); + TAG_LOGE(AAFwkTag::ABILITYMGR, "Write interface token failed."); return INNER_ERR; } if (!data.WriteString(bundleName)) { - HILOG_ERROR("Write bundl name failed."); + TAG_LOGE(AAFwkTag::ABILITYMGR, "Write bundl name failed."); return INNER_ERR; } if (!data.WriteBool(enable)) { - HILOG_ERROR("Write enable status failed."); + TAG_LOGE(AAFwkTag::ABILITYMGR, "Write enable status failed."); return INNER_ERR; } MessageParcel reply; MessageOption option; auto ret = SendRequest(AbilityManagerInterfaceCode::SET_RESIDENT_PROCESS_ENABLE, data, reply, option); if (ret != NO_ERROR) { - HILOG_ERROR("Send request error: %{public}d.", ret); + TAG_LOGE(AAFwkTag::ABILITYMGR, "Send request error: %{public}d.", ret); return ret; } @@ -5285,5 +5361,75 @@ void AbilityManagerProxy::NotifyFrozenProcessByRSS(const std::vector &p TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerProxy: SendRequest err %{public}d", error); } } + +int32_t AbilityManagerProxy::PreStartMission(const std::string& bundleName, const std::string& moduleName, + const std::string& abilityName, const std::string& startTime) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!WriteInterfaceToken(data)) { + return IPC_PROXY_ERR; + } + if (!data.WriteString(bundleName)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "write bundleName failed."); + return INNER_ERR; + } + if (!data.WriteString(moduleName)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "write moduleName failed."); + return INNER_ERR; + } + if (!data.WriteString(abilityName)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "write abilityName failed."); + return INNER_ERR; + } + if (!data.WriteString(startTime)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "write startTime failed."); + return INNER_ERR; + } + auto error = SendRequest(AbilityManagerInterfaceCode::PRE_START_MISSION, data, reply, option); + if (error != NO_ERROR) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +ErrCode AbilityManagerProxy::OpenLink(const Want& want, sptr callerToken, + int32_t userId, int requestCode) +{ + 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.WriteParcelable(&want)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "want write failed."); + return INNER_ERR; + } + if (!data.WriteRemoteObject(callerToken)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken write failed."); + return INNER_ERR; + } + if (!data.WriteInt32(userId)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "userId write failed."); + return INNER_ERR; + } + if (!data.WriteInt32(requestCode)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "requestCode write failed."); + return INNER_ERR; + } + auto error = SendRequest(AbilityManagerInterfaceCode::OPEN_LINK, data, reply, option); + if (error != NO_ERROR) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Send request error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp index ef821fcb45..2be7e95feb 100644 --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -33,13 +33,16 @@ #include "ability_background_connection.h" #include "ability_connect_manager.h" #include "ability_debug_deal.h" -#include "ability_info.h" #include "ability_manager_constants.h" #include "ability_manager_errors.h" #include "ability_manager_radar.h" #include "ability_resident_process_rdb.h" #include "ability_util.h" #include "accesstoken_kit.h" +#ifdef APP_DOMAIN_VERIFY_ENABLED +#include "ag_convert_callback_impl.h" +#include "app_domain_verify_mgr_client.h" +#endif #include "app_utils.h" #include "app_exit_reason_data_manager.h" #include "app_recovery/default_recovery_config.h" @@ -58,7 +61,6 @@ #include "freeze_util.h" #include "global_constant.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hisysevent.h" #include "hitrace_meter.h" #include "if_system_ability_manager.h" @@ -83,7 +85,6 @@ #include "mock_session_manager_service.h" #include "modal_system_ui_extension.h" #include "os_account_manager_wrapper.h" -#include "modal_system_ui_extension.h" #include "parameters.h" #include "permission_constants.h" #include "process_options.h" @@ -106,6 +107,7 @@ #include "system_ability_token_callback.h" #include "extension_record_manager.h" #include "ui_extension_utils.h" +#include "ui_service_extension_connection_constants.h" #include "unlock_screen_manager.h" #include "uri_permission_manager_client.h" #include "uri_utils.h" @@ -113,9 +115,11 @@ #include "xcollie/watchdog.h" #include "config_policy_utils.h" #include "running_multi_info.h" +#include "utils/dump_utils.h" +#include "utils/extension_permissions_util.h" #include "utils/window_options_utils.h" #ifdef SUPPORT_GRAPHICS -#include "dialog_session_record.h" +#include "dialog_session_manager.h" #include "application_anr_listener.h" #include "input_manager.h" #include "ability_first_frame_state_observer_manager.h" @@ -199,6 +203,7 @@ constexpr const char* FOUNDATION_PROCESS_NAME = "foundation"; constexpr const char* RSS_PROCESS_NAME = "resource_schedule_service"; constexpr const char* IS_PRELOAD_UIEXTENSION_ABILITY = "ability.want.params.is_preload_uiextension_ability"; constexpr const char* UIEXTENSION_MODAL_TYPE = "ability.want.params.modalType"; +constexpr const char* SUPPORT_CLOSE_ON_BLUR = "supportCloseOnBlur"; constexpr const char* ATOMIC_SERVICE_PREFIX = "com.atomicservice."; constexpr const char* PARAM_SPECIFIED_PROCESS_FLAG = "ohosSpecifiedProcessFlag"; @@ -238,6 +243,7 @@ constexpr int32_t SWITCH_ACCOUNT_TRY = 3; #ifdef ABILITY_COMMAND_FOR_TEST constexpr int32_t BLOCK_AMS_SERVICE_TIME = 65; #endif +constexpr int32_t CONVERT_CALLBACK_TIMEOUT_SECONDS = 2; // 2s constexpr const char* EMPTY_DEVICE_ID = ""; constexpr int32_t APP_MEMORY_SIZE = 512; constexpr int32_t GET_PARAMETER_INCORRECT = -9; @@ -277,60 +283,6 @@ nlohmann::json whiteListJsonObj; constexpr int32_t API12 = 12; constexpr int32_t API_VERSION_MOD = 100; constexpr const char* WHITE_LIST = "white_list"; -const std::map AbilityManagerService::dumpMap = { - std::map::value_type("--all", KEY_DUMP_ALL), - std::map::value_type("-a", KEY_DUMP_ALL), - std::map::value_type("--stack-list", KEY_DUMP_STACK_LIST), - std::map::value_type("-l", KEY_DUMP_STACK_LIST), - std::map::value_type("--stack", KEY_DUMP_STACK), - std::map::value_type("-s", KEY_DUMP_STACK), - std::map::value_type("--mission", KEY_DUMP_MISSION), - std::map::value_type("-m", KEY_DUMP_MISSION), - std::map::value_type("--top", KEY_DUMP_TOP_ABILITY), - std::map::value_type("-t", KEY_DUMP_TOP_ABILITY), - std::map::value_type("--waiting-queue", KEY_DUMP_WAIT_QUEUE), - std::map::value_type("-w", KEY_DUMP_WAIT_QUEUE), - std::map::value_type("--serv", KEY_DUMP_SERVICE), - std::map::value_type("-e", KEY_DUMP_SERVICE), - std::map::value_type("--data", KEY_DUMP_DATA), - std::map::value_type("-d", KEY_DUMP_DATA), - std::map::value_type("-focus", KEY_DUMP_FOCUS_ABILITY), - std::map::value_type("-f", KEY_DUMP_FOCUS_ABILITY), - std::map::value_type("--win-mode", KEY_DUMP_WINDOW_MODE), - std::map::value_type("-z", KEY_DUMP_WINDOW_MODE), - std::map::value_type("--mission-list", KEY_DUMP_MISSION_LIST), - std::map::value_type("-L", KEY_DUMP_MISSION_LIST), - std::map::value_type("--mission-infos", KEY_DUMP_MISSION_INFOS), - std::map::value_type("-S", KEY_DUMP_MISSION_INFOS), -}; - -const std::map AbilityManagerService::dumpsysMap = { - std::map::value_type("--all", KEY_DUMPSYS_ALL), - std::map::value_type("-a", KEY_DUMPSYS_ALL), - std::map::value_type("--mission-list", KEY_DUMPSYS_MISSION_LIST), - std::map::value_type("-l", KEY_DUMPSYS_MISSION_LIST), - std::map::value_type("--ability", KEY_DUMPSYS_ABILITY), - std::map::value_type("-i", KEY_DUMPSYS_ABILITY), - std::map::value_type("--extension", KEY_DUMPSYS_SERVICE), - std::map::value_type("-e", KEY_DUMPSYS_SERVICE), - std::map::value_type("--pending", KEY_DUMPSYS_PENDING), - std::map::value_type("-p", KEY_DUMPSYS_PENDING), - std::map::value_type("--process", KEY_DUMPSYS_PROCESS), - std::map::value_type("-r", KEY_DUMPSYS_PROCESS), - std::map::value_type("--data", KEY_DUMPSYS_DATA), - std::map::value_type("-d", KEY_DUMPSYS_DATA), -}; - -const std::map AbilityManagerService::windowModeMap = { - std::map::value_type(MULTI_WINDOW_DISPLAY_FULLSCREEN, - AppExecFwk::SupportWindowMode::FULLSCREEN), - std::map::value_type(MULTI_WINDOW_DISPLAY_PRIMARY, - AppExecFwk::SupportWindowMode::SPLIT), - std::map::value_type(MULTI_WINDOW_DISPLAY_SECONDARY, - AppExecFwk::SupportWindowMode::SPLIT), - std::map::value_type(MULTI_WINDOW_DISPLAY_FLOATING, - AppExecFwk::SupportWindowMode::FLOATING), -}; const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); @@ -345,6 +297,11 @@ AbilityManagerService::AbilityManagerService() AbilityManagerService::~AbilityManagerService() {} +std::shared_ptr AbilityManagerService::GetPubInstance() +{ + return DelayedSingleton::GetInstance(); +} + void AbilityManagerService::OnStart() { if (state_ == ServiceRunningState::STATE_RUNNING) { @@ -374,6 +331,9 @@ void AbilityManagerService::OnStart() AddSystemAbilityListener(BACKGROUND_TASK_MANAGER_SERVICE_ID); AddSystemAbilityListener(DISTRIBUTED_SCHED_SA_ID); AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); +#ifdef SUPPORT_SCREEN + AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID); +#endif TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability manager service start success."); } @@ -394,11 +354,6 @@ bool AbilityManagerService::Init() subManagersHelper_->InitSubManagers(MAIN_USER_ID, true); SwitchManagers(U0_USER_ID, false); #ifdef SUPPORT_SCREEN - auto anrListenerTask = []() { - auto anrListener = std::make_shared(); - MMI::InputManager::GetInstance()->SetAnrObserver(anrListener); - }; - taskHandler_->SubmitTask(anrListenerTask, "AnrListenerTask"); implicitStartProcessor_ = std::make_shared(); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { InitFocusListener(); @@ -414,9 +369,6 @@ bool AbilityManagerService::Init() InitDefaultRecoveryList(); abilityAutoStartupService_ = std::make_shared(); -#ifdef SUPPORT_SCREEN - dialogSessionRecord_ = std::make_shared(); -#endif // SUPPORT_SCREEN InitPushTask(); AbilityCacheManager::GetInstance().Init(AppUtils::GetInstance().GetLimitMaximumExtensionsPerDevice(), AppUtils::GetInstance().GetLimitMaximumExtensionsPerProc()); @@ -611,7 +563,6 @@ int32_t AbilityManagerService::StartAbilityByFreeInstall(const Want &want, sptr< (const_cast(want)).RemoveParam(START_ABILITY_TYPE); CHECK_CALLER_IS_SYSTEM_APP; } - InsightIntentExecuteParam::RemoveInsightIntent(const_cast(want)); auto flags = want.GetFlags(); EventInfo eventInfo = BuildEventInfo(want, userId); SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo); @@ -663,7 +614,7 @@ int AbilityManagerService::StartAbilityWithSpecifyTokenIdInner(const Want &want, "Start ability come, ability is %{public}s, userId is %{public}d, specifyTokenId is %{public}u.", want.GetElement().GetAbilityName().c_str(), userId, specifyTokenId); - int32_t ret = StartAbilityWrap(want, callerToken, requestCode, userId, false, false, specifyTokenId); + int32_t ret = StartAbilityWrap(want, callerToken, requestCode, userId, false, specifyTokenId); if (ret != ERR_OK) { eventInfo.errCode = ret; SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo); @@ -773,20 +724,20 @@ int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, cons } int AbilityManagerService::StartAbilityAsCaller(const Want &want, const sptr &callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult) + sptr asCallerSourceToken, int32_t userId, int requestCode) { - return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId, requestCode, isSendDialogResult); + return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId, requestCode); } int AbilityManagerService::ImplicitStartAbilityAsCaller(const Want &want, const sptr &callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult) + sptr asCallerSourceToken, int32_t userId, int requestCode) { return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId, - requestCode, isSendDialogResult, true); + requestCode, true); } int AbilityManagerService::StartAbilityAsCallerDetails(const Want &want, const sptr &callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult, bool isImplicit) + sptr asCallerSourceToken, int32_t userId, int requestCode, bool isImplicit) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); CHECK_CALLER_IS_SYSTEM_APP; @@ -813,7 +764,7 @@ int AbilityManagerService::StartAbilityAsCallerDetails(const Want &want, const s callerPkg.c_str(), targetPkg.c_str()); AbilityUtil::AddAbilityJumpRuleToBms(callerPkg, targetPkg, GetUserId()); } - int32_t ret = StartAbilityWrap(newWant, callerToken, requestCode, userId, true, isSendDialogResult, + int32_t ret = StartAbilityWrap(newWant, callerToken, requestCode, userId, true, 0, false, isImplicit); if (ret != ERR_OK) { eventInfo.errCode = ret; @@ -888,7 +839,7 @@ bool AbilityManagerService::StartAbilityInChain(StartAbilityParams ¶ms, int } int AbilityManagerService::StartAbilityWrap(const Want &want, const sptr &callerToken, - int requestCode, int32_t userId, bool isStartAsCaller, bool isSendDialogResult, uint32_t specifyToken, + int requestCode, int32_t userId, bool isStartAsCaller, uint32_t specifyToken, bool isForegroundToRestartApp, bool isImplicit) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); @@ -905,7 +856,7 @@ int AbilityManagerService::StartAbilityWrap(const Want &want, const sptrIsSACall(); + auto isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall(); + auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall(); + auto isToPermissionMgr = IsTargetPermission(want); + if (!isSACall && !isSystemAppCall && !isShellCall && !isToPermissionMgr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, + "Cannot start extension by start ability, use startServiceExtensionAbility."); + return ERR_WRONG_INTERFACE_CALL; + } + int result = CheckCallServicePermission(abilityRequest); + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed"); + } + return result; +} + +int AbilityManagerService::CheckServiceCallPermission(const AbilityRequest& abilityRequest, + const AppExecFwk::AbilityInfo& abilityInfo) +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, + "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str()); + int result = CheckCallServicePermission(abilityRequest); + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed"); + } + return result; +} + +int AbilityManagerService::CheckBrokerCallPermission(const AbilityRequest& abilityRequest, + const AppExecFwk::AbilityInfo& abilityInfo) +{ + // temp add for broker, remove when delete issacall + if (abilityRequest.collaboratorType != CollaboratorType::RESERVE_TYPE && !abilityInfo.visible) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Check permission failed"); + return CHECK_PERMISSION_FAILED; + } + TAG_LOGD(AAFwkTag::ABILITYMGR, + "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str()); + auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE); + if (collaborator == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Collaborator is nullptr."); + return CHECK_PERMISSION_FAILED; + } + int result = collaborator->CheckCallAbilityPermission(abilityRequest.want); + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed from broker."); + return CHECK_PERMISSION_FAILED; + } + return result; +} + +int AbilityManagerService::CheckAbilityCallPermission(const AbilityRequest& abilityRequest, + const AppExecFwk::AbilityInfo& abilityInfo, uint32_t specifyTokenId) +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, "Check call ability permission, name is %{public}s.", abilityInfo.name.c_str()); + int result = CheckCallAbilityPermission(abilityRequest, specifyTokenId); + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed"); + } + return result; +} + +int AbilityManagerService::CheckCallPermission(const Want& want, const AppExecFwk::AbilityInfo& abilityInfo, + const AbilityRequest& abilityRequest, bool isForegroundToRestartApp, + bool isSendDialogResult, uint32_t specifyTokenId, + const std::string& callerBundleName) +{ + auto type = abilityInfo.type; + if (type == AppExecFwk::AbilityType::DATA) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot start data ability by start ability."); + return ERR_WRONG_INTERFACE_CALL; + } + if (type == AppExecFwk::AbilityType::EXTENSION) { + return CheckExtensionCallPermission(want, abilityRequest); + } + if (type == AppExecFwk::AbilityType::SERVICE) { + return CheckServiceCallPermission(abilityRequest, abilityInfo); + } + if ((callerBundleName == SHELL_ASSISTANT_BUNDLENAME && AppUtils::GetInstance().IsSupportAncoApp()) || + IPCSkeleton::GetCallingUid() == BROKER_UID) { + return CheckBrokerCallPermission(abilityRequest, abilityInfo); + } + if (!isForegroundToRestartApp && (!isSendDialogResult || want.GetBoolParam("isSelector", false))) { + return CheckAbilityCallPermission(abilityRequest, abilityInfo, specifyTokenId); + } + return ERR_OK; +} + int AbilityManagerService::StartAbilityInner(const Want &want, const sptr &callerToken, - int requestCode, int32_t userId, bool isStartAsCaller, bool isSendDialogResult, uint32_t specifyTokenId, + int requestCode, int32_t userId, bool isStartAsCaller, uint32_t specifyTokenId, bool isForegroundToRestartApp, bool isImplicit) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + // prevent the app from dominating the screen + if (callerToken == nullptr && !IsCallerSceneBoard() && !isForegroundToRestartApp && + !PermissionVerification::GetInstance()->IsSACall() && !PermissionVerification::GetInstance()->IsShellCall()) { + auto callerPid = IPCSkeleton::GetCallingPid(); + AppExecFwk::RunningProcessInfo processInfo; + DelayedSingleton::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo); + bool isDelegatorCall = processInfo.isTestProcess && want.GetBoolParam(IS_DELEGATOR_CALL, false); + std::string bundleName = want.GetElement().GetBundleName(); + std::string abilityName = want.GetElement().GetAbilityName(); + if (!isDelegatorCall && !InsightIntentExecuteParam::IsInsightIntentExecute(want) && + !AppUtils::GetInstance().IsAllowStartAbilityWithoutCallerToken(bundleName, abilityName)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is invalid."); + return ERR_INVALID_CALLER; + } + } { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP"); if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) || @@ -949,9 +1006,10 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptr(want)); std::string dialogSessionId = want.GetStringParam("dialogSessionId"); - isSendDialogResult = false; + bool isSendDialogResult = false; #ifdef SUPPORT_SCREEN - if (!dialogSessionId.empty() && dialogSessionRecord_->GetDialogCallerInfo(dialogSessionId) != nullptr) { + if (!dialogSessionId.empty() && + DialogSessionManager::GetInstance().GetDialogCallerInfo(dialogSessionId) != nullptr) { isSendDialogResult = true; } #endif // SUPPORT_SCREEN @@ -1019,23 +1077,16 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptr(want)).RemoveParam("send_to_erms_embedded"); - Want localWant = want; - if (!localWant.GetDeviceId().empty()) { - localWant.SetDeviceId(""); - } - if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token - UpdateCallerInfoFromToken(localWant, callerToken); - } else if (!isStartAsCaller) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo"); - UpdateCallerInfo(localWant, callerToken); + Want localWant; + auto freeInstallResult = PreStartFreeInstall(want, callerToken, specifyTokenId, isStartAsCaller, localWant); + if (freeInstallResult != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "PreStartFreeInstall failed."); + return freeInstallResult; } if (isStartFreeInstallByWant) { - return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, true); + return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, + callerToken, true, specifyTokenId); } int32_t ret = freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, false); if (ret == ERR_OK) { @@ -1080,60 +1131,11 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptrIsSACall(); - auto isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall(); - auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall(); - auto isToPermissionMgr = IsTargetPermission(want); - if (!isSACall && !isSystemAppCall && !isShellCall && !isToPermissionMgr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, - "Cannot start extension by start ability, use startServiceExtensionAbility."); - return ERR_WRONG_INTERFACE_CALL; - } - result = CheckCallServicePermission(abilityRequest); - if (result != ERR_OK) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed"); - return result; - } - } else if (type == AppExecFwk::AbilityType::SERVICE) { - TAG_LOGD(AAFwkTag::ABILITYMGR, - "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str()); - result = CheckCallServicePermission(abilityRequest); - if (result != ERR_OK) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed"); - return result; - } - } else if ((callerBundleName == SHELL_ASSISTANT_BUNDLENAME && AppUtils::GetInstance().IsSupportAncoApp()) || - IPCSkeleton::GetCallingUid() == BROKER_UID) { - // temp add for broker, remove when delete issacall - if (abilityRequest.collaboratorType != CollaboratorType::RESERVE_TYPE && !abilityInfo.visible) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Check permission failed"); - return CHECK_PERMISSION_FAILED; - } - TAG_LOGD(AAFwkTag::ABILITYMGR, - "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str()); - auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE); - if (collaborator == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Collaborator is nullptr."); - return CHECK_PERMISSION_FAILED; - } - result = collaborator->CheckCallAbilityPermission(abilityRequest.want); - if (result != ERR_OK) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed from broker."); - return CHECK_PERMISSION_FAILED; - } - } else if (!isForegroundToRestartApp && (!isSendDialogResult || want.GetBoolParam("isSelector", false))) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Check call ability permission, name is %{public}s.", abilityInfo.name.c_str()); - result = CheckCallAbilityPermission(abilityRequest, specifyTokenId); - if (result != ERR_OK) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed"); - return result; - } + result = CheckCallPermission(want, abilityInfo, abilityRequest, isForegroundToRestartApp, + isSendDialogResult, specifyTokenId, callerBundleName); + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckCallPermission error, result is %{public}d.", result); + return result; } Want newWant = abilityRequest.want; @@ -1147,19 +1149,17 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptr dialogAppInfos(1); - if (GenerateDialogSessionRecord(abilityRequest, GetUserId(), dialogSessionId, dialogAppInfos, false)) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "create dialog by ui extension"); - return CreateModalDialog(newWant, callerToken, dialogSessionId); - } -#endif // SUPPORT_SCREEN - TAG_LOGE(AAFwkTag::ABILITYMGR, "create dialog by ui extension failed"); - return INNER_ERR; + return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant); } + if (result == ERR_OK && + DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog"); + return CreateCloneSelectorDialog(abilityRequest, GetUserId()); + } +#endif // SUPPORT_SCREEN if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) { TAG_LOGD(AAFwkTag::ABILITYMGR, "PreLoadAppDataAbilities:%{public}s.", abilityInfo.bundleName.c_str()); @@ -1172,16 +1172,9 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptr(want)); - return connectManager->StartAbility(abilityRequest); + if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE || + abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) { + return StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken); } if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) { @@ -1198,7 +1191,7 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptrStartAbility(abilityRequest); } +int AbilityManagerService::PreStartFreeInstall(const Want &want, sptr callerToken, + uint32_t specifyTokenId, bool isStartAsCaller, Want &localWant) +{ + if (freeInstallManager_ == nullptr) { + return ERR_INVALID_VALUE; + } + (const_cast(want)).RemoveParam("send_to_erms_embedded"); + localWant = want; + if (!localWant.GetDeviceId().empty()) { + localWant.SetDeviceId(""); + } + if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token + UpdateCallerInfoFromToken(localWant, callerToken); + } else if (!isStartAsCaller) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo"); + UpdateCallerInfo(localWant, callerToken); + } else { + TAG_LOGD(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!"); + } + return ERR_OK; +} + +int AbilityManagerService::StartAbilityByConnectManager(const Want& want, const AbilityRequest& abilityRequest, + const AppExecFwk::AbilityInfo& abilityInfo, int validUserId, sptr callerToken) +{ + auto connectManager = GetConnectManagerByUserId(validUserId); + if (!connectManager) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId); + return ERR_INVALID_VALUE; + } + TAG_LOGD(AAFwkTag::ABILITYMGR, "Start service or extension, name is %{public}s.", abilityInfo.name.c_str()); + ReportEventToRSS(abilityInfo, callerToken); + InsightIntentExecuteParam::RemoveInsightIntent(const_cast(want)); + return connectManager->StartAbility(abilityRequest); +} + int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, const sptr &callerToken, int32_t userId, int requestCode) { @@ -1452,7 +1481,8 @@ int AbilityManagerService::ImplicitStartAbility(const Want &want, const StartOpt } int AbilityManagerService::StartUIAbilityForOptionWrap(const Want &want, const StartOptions &options, - sptr callerToken, int32_t userId, int requestCode, uint32_t callerTokenId, bool isImplicit) + sptr callerToken, int32_t userId, int requestCode, uint32_t callerTokenId, bool isImplicit, + bool isCallByShortcut) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto ret = CheckProcessOptions(want, options, userId); @@ -1460,7 +1490,7 @@ int AbilityManagerService::StartUIAbilityForOptionWrap(const Want &want, const S return ret; } return StartAbilityForOptionWrap(want, options, callerToken, userId, requestCode, false, - callerTokenId, isImplicit); + callerTokenId, isImplicit, isCallByShortcut); } int AbilityManagerService::StartAbilityAsCaller(const Want &want, const StartOptions &startOptions, @@ -1479,7 +1509,7 @@ int AbilityManagerService::StartAbilityAsCaller(const Want &want, const StartOpt int AbilityManagerService::StartAbilityForResultAsCaller( const Want &want, const sptr &callerToken, int requestCode, int32_t userId) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); CHECK_CALLER_IS_SYSTEM_APP; AbilityUtil::RemoveShowModeKey(const_cast(want)); @@ -1494,7 +1524,7 @@ int AbilityManagerService::StartAbilityForResultAsCaller( int AbilityManagerService::StartAbilityForResultAsCaller(const Want &want, const StartOptions &startOptions, const sptr &callerToken, int requestCode, int32_t userId) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); CHECK_CALLER_IS_SYSTEM_APP; AAFwk::Want newWant = want; @@ -1507,7 +1537,7 @@ int AbilityManagerService::StartAbilityForResultAsCaller(const Want &want, const int AbilityManagerService::StartAbilityForOptionWrap(const Want &want, const StartOptions &startOptions, const sptr &callerToken, int32_t userId, int requestCode, bool isStartAsCaller, - uint32_t callerTokenId, bool isImplicit) + uint32_t callerTokenId, bool isImplicit, bool isCallByShortcut) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); StartAbilityParams startParams(const_cast(want)); @@ -1524,12 +1554,12 @@ int AbilityManagerService::StartAbilityForOptionWrap(const Want &want, const Sta } return StartAbilityForOptionInner(want, startOptions, callerToken, userId, requestCode, isStartAsCaller, - callerTokenId, isImplicit); + callerTokenId, isImplicit, isCallByShortcut); } int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const StartOptions &startOptions, const sptr &callerToken, int32_t userId, int requestCode, bool isStartAsCaller, - uint32_t specifyTokenId, bool isImplicit) + uint32_t specifyTokenId, bool isImplicit, bool isCallByShortcut) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false); @@ -1585,7 +1615,8 @@ int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const St TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo"); UpdateCallerInfo(localWant, callerToken); } - return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, true); + return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, + callerToken, true, specifyTokenId); } if (!JudgeMultiUserConcurrency(validUserId)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied."); @@ -1660,7 +1691,7 @@ int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const St SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo); return ERR_STATIC_CFG_PERMISSION; } - result = CheckCallAbilityPermission(abilityRequest); + result = CheckCallAbilityPermission(abilityRequest, 0, isCallByShortcut); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s CheckCallAbilityPermission error.", __func__); eventInfo.errCode = result; @@ -1729,18 +1760,16 @@ int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const St TAG_LOGE(AAFwkTag::ABILITYMGR, "DoProcess failed or replaceWant not exist"); return result; } - if (result != ERR_OK && isReplaceWantExist) { - std::string dialogSessionId; #ifdef SUPPORT_SCREEN - std::vector dialogAppInfos(1); - if (GenerateDialogSessionRecord(abilityRequest, GetUserId(), dialogSessionId, dialogAppInfos, false)) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "create dialog by ui extension"); - return CreateModalDialog(newWant, callerToken, dialogSessionId); - } -#endif // SUPPORT_GRAPHICS - TAG_LOGE(AAFwkTag::ABILITYMGR, "create dialog by ui extension failed"); - return INNER_ERR; + if (result != ERR_OK && isReplaceWantExist) { + return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant); } + if (result == ERR_OK && + DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog"); + return CreateCloneSelectorDialog(abilityRequest, GetUserId()); + } +#endif // SUPPORT_GRAPHICS abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID); if (specifyTokenId > 0) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId); @@ -1897,7 +1926,7 @@ int32_t AbilityManagerService::RequestDialogServiceInner(const Want &want, const } TAG_LOGD(AAFwkTag::ABILITYMGR, "request dialog service, start service extension,name is %{public}s.", abilityInfo.name.c_str()); - ReportEventToRSS(abilityInfo); + ReportEventToRSS(abilityInfo, callerToken); return connectManager->StartAbility(abilityRequest); } @@ -1928,6 +1957,59 @@ int AbilityManagerService::StartUIAbilityBySCB(sptr sessionInfo, bo return ERR_WRONG_INTERFACE_CALL; } + if (!(sessionInfo->want).HasParameter(KEY_SESSION_ID)) { + return StartUIAbilityBySCBDefault(sessionInfo, isColdStart); + } + + std::string sessionId = (sessionInfo->want).GetStringParam(KEY_SESSION_ID); + if (sessionId.empty()) { + return StartUIAbilityBySCBDefault(sessionInfo, isColdStart); + } + + TAG_LOGI(AAFwkTag::ABILITYMGR, "sessionId=%{public}s", sessionId.c_str()); + + if (freeInstallManager_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr."); + return ERR_INVALID_VALUE; + } + FreeInstallInfo taskInfo; + if (!freeInstallManager_->GetFreeInstallTaskInfo(sessionId, taskInfo)) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "failed to find free isntall task"); + return StartUIAbilityBySCBDefault(sessionInfo, isColdStart); + } + + if (taskInfo.isFreeInstallFinished) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task is already finished"); + if (!taskInfo.isInstalled) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d", + taskInfo.resultCode); + return taskInfo.resultCode; + } + TAG_LOGI(AAFwkTag::ABILITYMGR, "free install succeeds"); + auto err = StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, isColdStart); + if (err != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilityByPreInstallInner failed."); + } + return err; + } + + { + std::lock_guard guard(preStartSessionMapLock_); + preStartSessionMap_.insert(std::make_pair(sessionId, sessionInfo)); + } + + TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task is still in progress"); + const Want& want = sessionInfo->want; + freeInstallManager_->SetSCBCallStatus(want.GetElement().GetBundleName(), want.GetElement().GetAbilityName(), + want.GetStringParam(Want::PARAM_RESV_START_TIME), true); + return ERR_OK; +} + +int AbilityManagerService::StartUIAbilityBySCBDefault(sptr sessionInfo, bool &isColdStart) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + TAG_LOGD(AAFwkTag::ABILITYMGR, "Call."); + auto currentUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE; if (sessionInfo->userId == DEFAULT_INVAL_VALUE) { sessionInfo->userId = currentUserId; @@ -2005,7 +2087,8 @@ int AbilityManagerService::StartUIAbilityBySCB(sptr sessionInfo, bo } auto systemUIExtension = std::make_shared(); (const_cast(newWant)).SetParam(UIEXTENSION_MODAL_TYPE, 1); - return systemUIExtension->CreateModalUIExtension(newWant) ? + (const_cast(newWant)).SetParam(SUPPORT_CLOSE_ON_BLUR, true); + return IN_PROCESS_CALL(systemUIExtension->CreateModalUIExtension(newWant)) ? ERR_ECOLOGICAL_CONTROL_STATUS : INNER_ERR; } } @@ -2148,16 +2231,21 @@ int32_t AbilityManagerService::ForceExitApp(const int32_t pid, const ExitReason return ERR_PERMISSION_DENIED; } - std::string bundleName; - int32_t uid; - DelayedSingleton::GetInstance()->GetBundleNameByPid(pid, bundleName, uid); - if (bundleName.empty()) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Get bundle name by pid failed."); - return ERR_INVALID_VALUE; + AppExecFwk::ApplicationInfo application; + bool debug = false; + auto ret = IN_PROCESS_CALL(DelayedSingleton::GetInstance()->GetApplicationInfoByProcessID(pid, + application, debug)); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "GetApplicationInfoByProcessID failed."); + return ret; } + std::string bundleName = application.bundleName; + int32_t uid = application.uid; + int32_t appIndex = application.appIndex; + CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT); - appExitReasonHelper_->RecordProcessExitReason(bundleName, uid, exitReason); + appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason); return DelayedSingleton::GetInstance()->KillApplication(bundleName); } @@ -2244,6 +2332,13 @@ void AbilityManagerService::OnAddSystemAbility(int32_t systemAbilityId, const st SubscribeBundleEventCallback(); break; } +#ifdef SUPPORT_SCREEN + case MULTIMODAL_INPUT_SERVICE_ID: { + auto anrListener = std::make_shared(); + MMI::InputManager::GetInstance()->SetAnrObserver(anrListener); + break; + } +#endif default: break; } @@ -2368,15 +2463,27 @@ void AbilityManagerService::ReportAbilitAssociatedStartInfoToRSS( ResSchedUtil::GetInstance().ReportAbilitAssociatedStartInfoToRSS(abilityInfo, type, callerUid, callerPid); } -void AbilityManagerService::ReportEventToRSS(const AppExecFwk::AbilityInfo &abilityInfo) +void AbilityManagerService::ReportEventToRSS(const AppExecFwk::AbilityInfo &abilityInfo, + sptr callerToken) { CHECK_POINTER_LOG(taskHandler_, "taskhandler null"); - std::string reason = (abilityInfo.type == AppExecFwk::AbilityType::PAGE) ? - "THAW_BY_START_PAGE_ABILITY" : "THAW_BY_START_NOT_PAGE_ABILITY"; + std::string reason; + if (abilityInfo.type == AppExecFwk::AbilityType::PAGE) { + reason = "THAW_BY_START_PAGE_ABILITY"; + } else if (abilityInfo.type == AppExecFwk::AbilityType::EXTENSION && + abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) { + reason = "THAW_BY_START_SERVICE_EXTENSION"; + } else { + reason = "THAW_BY_START_NOT_PAGE_ABILITY"; + } const auto uid = abilityInfo.applicationInfo.uid; const auto bundleName = abilityInfo.applicationInfo.bundleName; - taskHandler_->SubmitTask([reason, uid, bundleName]() { - ResSchedUtil::GetInstance().ReportEventToRSS(uid, bundleName, reason); + auto callerAbility = Token::GetAbilityRecordByToken(callerToken); + const int32_t callerPid = (callerAbility != nullptr) ? callerAbility->GetPid() : IPCSkeleton::GetCallingPid(); + TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}d_%{public}s reason=%{public}s callerPid=%{public}d", uid, + bundleName.c_str(), reason.c_str(), callerPid); + taskHandler_->SubmitTask([reason, uid, bundleName, callerPid]() { + ResSchedUtil::GetInstance().ReportEventToRSS(uid, bundleName, reason, callerPid); }); } @@ -2497,7 +2604,7 @@ int AbilityManagerService::RequestModalUIExtensionInner(Want want) TAG_LOGD(AAFwkTag::ABILITYMGR, "Window Modal System Create UIExtension is called!"); want.SetParam(UIEXTENSION_MODAL_TYPE, 1); auto connection = std::make_shared(); - return connection->CreateModalUIExtension(want) ? ERR_OK : INNER_ERR; + return IN_PROCESS_CALL(connection->CreateModalUIExtension(want)) ? ERR_OK : INNER_ERR; } int AbilityManagerService::ChangeAbilityVisibility(sptr token, bool isShow) @@ -2633,6 +2740,7 @@ int AbilityManagerService::StartExtensionAbilityInner(const Want &want, const sp } UpdateCallerInfo(abilityRequest.want, callerToken); TAG_LOGD(AAFwkTag::ABILITYMGR, "Start extension begin, name is %{public}s.", abilityInfo.name.c_str()); + SetAbilityRequestSessionInfo(abilityRequest, extensionType); eventInfo.errCode = connectManager->StartAbility(abilityRequest); if (eventInfo.errCode != ERR_OK) { EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo); @@ -2696,7 +2804,7 @@ void AbilityManagerService::SetPickerElementName(const sptr &extens void AbilityManagerService::SetAutoFillElementName(const sptr &extensionSessionInfo) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); CHECK_POINTER_IS_NULLPTR(extensionSessionInfo); std::vector argList; if (extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY) == AUTO_FILL_PASSWORD_TPYE) { @@ -2716,6 +2824,22 @@ void AbilityManagerService::SetAutoFillElementName(const sptr &exte extensionSessionInfo->want.SetModuleName(argList[INDEX_ONE]); } +int AbilityManagerService::CheckUIExtensionUsage(AppExecFwk::UIExtensionUsage uiExtensionUsage, + AppExecFwk::ExtensionAbilityType extensionType) +{ + if (uiExtensionUsage == UIExtensionUsage::EMBEDDED && + !AAFwk::UIExtensionUtils::IsPublicForEmbedded(extensionType)) { + CHECK_CALLER_IS_SYSTEM_APP; + } + + if (uiExtensionUsage == UIExtensionUsage::CONSTRAINED_EMBEDDED && + !AAFwk::UIExtensionUtils::IsPublicForConstrainedEmbedded(extensionType)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "error extension type %u for SecureConstrainedEmbedded.", extensionType); + return ERR_INVALID_VALUE; + } + return ERR_OK; +} + int AbilityManagerService::StartUIExtensionAbility(const sptr &extensionSessionInfo, int32_t userId) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); @@ -2754,12 +2878,17 @@ int AbilityManagerService::StartUIExtensionAbility(const sptr &exte std::string extensionTypeStr = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY); AppExecFwk::ExtensionAbilityType extensionType = extensionTypeStr.empty() ? AppExecFwk::ExtensionAbilityType::UI : AppExecFwk::ConvertToExtensionAbilityType(extensionTypeStr); + if (extensionType == AppExecFwk::ExtensionAbilityType::UNSPECIFIED) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Input extension ability type is invalid."); + return ERR_INVALID_VALUE; + } EventInfo eventInfo = BuildEventInfo(extensionSessionInfo->want, userId); eventInfo.extensionType = static_cast(extensionType); - // non-modal uiextension can only be used by system applications. - if (!extensionSessionInfo->isModal && !AAFwk::UIExtensionUtils::IsPublicCallerForNonModal(extensionType)) { - CHECK_CALLER_IS_SYSTEM_APP; + auto ret = CheckUIExtensionUsage(extensionSessionInfo->uiExtensionUsage, extensionType); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "check usage failed."); + return ret; } if (InsightIntentExecuteParam::IsInsightIntentExecute(extensionSessionInfo->want)) { @@ -2849,7 +2978,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, true); + result = CheckOptExtensionAbility(extensionSessionInfo->want, abilityRequest, validUserId, extensionType); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckOptExtensionAbility error."); eventInfo.errCode = result; @@ -2871,7 +3000,7 @@ int AbilityManagerService::StartUIExtensionAbility(const sptr &exte } AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(), - false, callerToken, std::make_shared(abilityInfo)); + true, callerToken, std::make_shared(abilityInfo)); result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE : afterCheckExecuter_->DoProcess(afterCheckParam); if (result != ERR_OK) { @@ -3325,7 +3454,6 @@ int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode, uint32_t accessToken = IPCSkeleton::GetCallingTokenID(); UriUtils::GetInstance().FilterUriWithPermissionDms(remoteWant, accessToken); DistributedClient dmsClient; - TAG_LOGD(AAFwkTag::ABILITYMGR, "get callerUid = %d, AccessTokenID = %u", callerUid, accessToken); int result = dmsClient.StartRemoteAbility(remoteWant, callerUid, requestCode, accessToken); if (result != ERR_NONE) { TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::StartRemoteAbility failed, result = %{public}d", result); @@ -3745,6 +3873,10 @@ int AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t u if (!UriUtils::GetInstance().CheckNonImplicitShareFileUri(abilityRequest)) { return ERR_SHARE_FILE_URI_NON_IMPLICITLY; } + result = CheckPermissionForUIService(want, abilityRequest); + if (result != ERR_OK) { + return result; + } if (abilityRequest.abilityInfo.isStageBasedModel) { bool isService = @@ -3804,6 +3936,12 @@ int AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t u TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s CheckCallServicePermission error.", __func__); return result; } + + if (!ExtensionPermissionsUtil::CheckSAPermission(targetExtensionType)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "The SA doesn't have permission for target extension."); + return CHECK_PERMISSION_FAILED; + } + result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectAbility: App data ability preloading failed, '%{public}s', %{public}d", @@ -3818,7 +3956,7 @@ int AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t u return ERR_INVALID_VALUE; } - ReportEventToRSS(abilityInfo); + ReportEventToRSS(abilityInfo, callerToken); return connectManager->ConnectAbilityLocked(abilityRequest, connect, callerToken, sessionInfo, connectInfo); } @@ -3849,6 +3987,16 @@ int AbilityManagerService::DisconnectLocalAbility(const sptr return ERR_OK; } + auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE; + if (userId == U0_USER_ID) { + auto connectManagers = GetConnectManagers(); + for (auto& item : connectManagers) { + if (item.second && item.second->DisconnectAbilityLocked(connect) == ERR_OK) { + return ERR_OK; + } + } + } + // EnterpriseAdminExtensionAbility Scene connectManager = GetConnectManagerByUserId(USER_ID_DEFAULT); CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT); @@ -3928,8 +4076,8 @@ int AbilityManagerService::StartContinuation(const Want &want, const sptr samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get samgrProxy"); + return; + } + sptr bmsProxy = samgrProxy->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (bmsProxy == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get bms from samgr"); + return; + } + auto bundleMgr = iface_cast(bmsProxy); + if (bundleMgr == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get bms"); + return; + } + int32_t callerUid = IPCSkeleton::GetCallingUid(); + std::string callerBundleName; + // reset ipc identity + auto identity = IPCSkeleton::ResetCallingIdentity(); + bool result = bundleMgr->GetBundleNameForUid(callerUid, callerBundleName); + // set ipc identity to raw + IPCSkeleton::SetCallingIdentity(identity); + TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName: %{public}s", callerBundleName.c_str()); DistributedClient dmsClient; - dmsClient.NotifyCompleteContinuation(Str8ToStr16(deviceId), sessionId, isSuccess); + dmsClient.NotifyCompleteContinuation(Str8ToStr16(deviceId), sessionId, isSuccess, callerBundleName); } int AbilityManagerService::NotifyContinuationResult(int32_t missionId, int32_t result) @@ -3979,6 +4150,10 @@ int AbilityManagerService::NotifyContinuationResult(int32_t missionId, int32_t r } CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); + if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny."); + return ERR_INVALID_VALUE; + } abilityRecord->NotifyContinuationResult(result); return ERR_OK; } @@ -4602,9 +4777,13 @@ int32_t AbilityManagerService::GetMissionIdByToken(const sptr &to bool AbilityManagerService::IsAbilityControllerStartById(int32_t missionId) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + auto missionListWrap = GetMissionListWrap(); + if (missionListWrap == nullptr) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListWrap null."); + return true; + } InnerMissionInfo innerMissionInfo; - int getMission = DelayedSingleton::GetInstance()->GetInnerMissionInfoById( - missionId, innerMissionInfo); + int getMission = missionListWrap->GetInnerMissionInfoById(missionId, innerMissionInfo); if (getMission != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot find mission info from MissionInfoList by missionId: %{public}d", missionId); @@ -4691,7 +4870,7 @@ sptr AbilityManagerService::AcquireDataAbility( std::shared_ptr dataAbilityManager = GetDataAbilityManagerByUserId(userId); CHECK_POINTER_AND_RETURN(dataAbilityManager, nullptr); - ReportEventToRSS(abilityRequest.abilityInfo); + ReportEventToRSS(abilityRequest.abilityInfo, callerToken); bool isNotHap = isSaCall || isShellCall; UpdateCallerInfo(abilityRequest.want, callerToken); return dataAbilityManager->Acquire(abilityRequest, tryBind, callerToken, isNotHap); @@ -4795,7 +4974,7 @@ void AbilityManagerService::DumpSysMissionListInner( DumpSysMissionListInnerBySCB(args, info, isClient, isUserID, userId); return; } - std::shared_ptr targetManager; + std::shared_ptr targetManager; if (isUserID) { auto missionListManager = GetMissionListManagerByUserId(userId); if (missionListManager == nullptr) { @@ -4855,7 +5034,7 @@ void AbilityManagerService::DumpSysAbilityInner( DumpSysAbilityInnerBySCB(args, info, isClient, isUserID, userId); return; } - std::shared_ptr targetManager; + std::shared_ptr targetManager; if (isUserID) { auto missionListManager = GetMissionListManagerByUserId(userId); if (missionListManager == nullptr) { @@ -5240,28 +5419,27 @@ void AbilityManagerService::DumpState(const std::string &args, std::vectorsecond; - switch (key) { - case KEY_DUMP_SERVICE: + switch (key.second) { + case DumpUtils::KEY_DUMP_SERVICE: DumpStateInner(args, info); break; - case KEY_DUMP_DATA: + case DumpUtils::KEY_DUMP_DATA: DataDumpStateInner(args, info); break; - case KEY_DUMP_ALL: + case DumpUtils::KEY_DUMP_ALL: DumpInner(args, info); break; - case KEY_DUMP_MISSION: + case DumpUtils::KEY_DUMP_MISSION: DumpMissionInner(args, info); break; - case KEY_DUMP_MISSION_LIST: + case DumpUtils::KEY_DUMP_MISSION_LIST: DumpMissionListInner(args, info); break; - case KEY_DUMP_MISSION_INFOS: + case DumpUtils::KEY_DUMP_MISSION_INFOS: DumpMissionInfosInner(args, info); break; default: @@ -5285,31 +5463,30 @@ void AbilityManagerService::DumpSysState( if (argList.empty()) { return; } - auto it = dumpsysMap.find(argList[0]); - if (it == dumpsysMap.end()) { + auto key = DumpUtils::DumpsysMap(argList[0]); + if (!key.first) { return; } - DumpsysKey key = it->second; - switch (key) { - case KEY_DUMPSYS_ALL: + switch (key.second) { + case DumpUtils::KEY_DUMP_SYS_ALL: DumpSysInner(args, info, isClient, isUserID, userId); break; - case KEY_DUMPSYS_SERVICE: + case DumpUtils::KEY_DUMP_SYS_SERVICE: DumpSysStateInner(args, info, isClient, isUserID, userId); break; - case KEY_DUMPSYS_PENDING: + case DumpUtils::KEY_DUMP_SYS_PENDING: DumpSysPendingInner(args, info, isClient, isUserID, userId); break; - case KEY_DUMPSYS_PROCESS: + case DumpUtils::KEY_DUMP_SYS_PROCESS: DumpSysProcess(args, info, isClient, isUserID, userId); break; - case KEY_DUMPSYS_DATA: + case DumpUtils::KEY_DUMP_SYS_DATA: DataDumpSysStateInner(args, info, isClient, isUserID, userId); break; - case KEY_DUMPSYS_MISSION_LIST: + case DumpUtils::KEY_DUMP_SYS_MISSION_LIST: DumpSysMissionListInner(args, info, isClient, isUserID, userId); break; - case KEY_DUMPSYS_ABILITY: + case DumpUtils::KEY_DUMP_SYS_ABILITY: DumpSysAbilityInner(args, info, isClient, isUserID, userId); break; default: @@ -5726,10 +5903,6 @@ int AbilityManagerService::GenerateAbilityRequest(const Want &want, int requestC request.appInfo.name.c_str(), request.abilityInfo.moduleName.c_str(), request.uid); request.want.SetModuleName(request.abilityInfo.moduleName); - request.want.SetParam("send_to_erms_targetBundleType", - static_cast(request.abilityInfo.applicationInfo.bundleType)); - request.want.SetParam("send_to_erms_targetAppProvisionType", request.abilityInfo.applicationInfo.appProvisionType); - request.want.SetParam("send_to_erms_targetAppDistType", request.abilityInfo.applicationInfo.appDistributionType); if (want.GetBoolParam(Want::PARAM_RESV_START_RECENT, false) && AAFwk::PermissionVerification::GetInstance()->VerifyStartRecentAbilityPermission()) { @@ -5783,9 +5956,6 @@ int32_t AbilityManagerService::InitialAbilityRequest(AbilityRequest &request, TAG_LOGD(AAFwkTag::ABILITYMGR, "GenerateExtensionAbilityRequest end, app name: %{public}s, bundle name: %{public}s, uid: %{public}d.", request.appInfo.name.c_str(), request.appInfo.bundleName.c_str(), request.uid); - request.want.SetParam("send_to_erms_targetBundleType", - static_cast(request.abilityInfo.applicationInfo.bundleType)); - request.want.SetParam("send_to_erms_targetAppProvisionType", request.abilityInfo.applicationInfo.appProvisionType); TAG_LOGD(AAFwkTag::ABILITYMGR, "GenerateExtensionAbilityRequest, moduleName: %{public}s.", request.abilityInfo.moduleName.c_str()); @@ -5940,20 +6110,27 @@ int AbilityManagerService::KillProcess(const std::string &bundleName, const bool int AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid) { - TAG_LOGI(AAFwkTag::ABILITYMGR, "Uninstall app, bundleName: %{public}s, uid=%{public}d", bundleName.c_str(), uid); - return UninstallAppInner(bundleName, uid, false, ""); + return UninstallApp(bundleName, uid, 0); } -int32_t AbilityManagerService::UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg) +int32_t AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid, int32_t appIndex) { - TAG_LOGD(AAFwkTag::ABILITYMGR, - "UpgradeApp app, bundleName: %{public}s, uid=%{public}d, exitMsg: %{public}s,", bundleName.c_str(), - uid, exitMsg.c_str()); - return UninstallAppInner(bundleName, uid, true, exitMsg); + TAG_LOGI(AAFwkTag::ABILITYMGR, "Uninstall app, bundleName: %{public}s, uid=%{public}d, appIndex:%{public}d", + bundleName.c_str(), uid, appIndex); + return UninstallAppInner(bundleName, uid, appIndex, false, ""); } -int32_t AbilityManagerService::UninstallAppInner(const std::string &bundleName, const int32_t uid, const bool isUpgrade, - const std::string &exitMsg) +int32_t AbilityManagerService::UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg, + int32_t appIndex) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, + "UpgradeApp app, bundleName: %{public}s, uid=%{public}d, exitMsg: %{public}s, appIndex:%{public}d", + bundleName.c_str(), uid, exitMsg.c_str(), appIndex); + return UninstallAppInner(bundleName, uid, appIndex, true, exitMsg); +} + +int32_t AbilityManagerService::UninstallAppInner(const std::string &bundleName, const int32_t uid, int32_t appIndex, + const bool isUpgrade, const std::string &exitMsg) { pid_t callingPid = IPCSkeleton::GetCallingPid(); pid_t pid = getprocpid(); @@ -5965,7 +6142,7 @@ int32_t AbilityManagerService::UninstallAppInner(const std::string &bundleName, if (isUpgrade) { CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT); AAFwk::ExitReason exitReason = { REASON_UPGRADE, exitMsg }; - appExitReasonHelper_->RecordProcessExitReason(bundleName, uid, exitReason); + appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason); } CHECK_POINTER_AND_RETURN(subManagersHelper_, ERR_NULL_OBJECT); @@ -5975,7 +6152,8 @@ int32_t AbilityManagerService::UninstallAppInner(const std::string &bundleName, return UNINSTALL_APP_FAILED; } if (!isUpgrade) { - DelayedSingleton::GetInstance()->DeleteAppExitReason(bundleName, uid); + DelayedSingleton::GetInstance()->DeleteAppExitReason(bundleName, uid, + appIndex); } return ERR_OK; } @@ -6290,27 +6468,33 @@ std::shared_ptr AbilityManagerService::GetPendingWantManager return subManagersHelper_->GetPendingWantManagerByUserId(userId); } -std::unordered_map> AbilityManagerService::GetMissionListManagers() +std::unordered_map> AbilityManagerService::GetMissionListManagers() { if (subManagersHelper_ == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer is nullptr."); - return std::unordered_map>(); + return std::unordered_map>(); } return subManagersHelper_->GetMissionListManagers(); } -std::shared_ptr AbilityManagerService::GetCurrentMissionListManager() +std::shared_ptr AbilityManagerService::GetCurrentMissionListManager() { CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr); return subManagersHelper_->GetCurrentMissionListManager(); } -std::shared_ptr AbilityManagerService::GetMissionListManagerByUserId(int32_t userId) +std::shared_ptr AbilityManagerService::GetMissionListManagerByUserId(int32_t userId) { CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr); return subManagersHelper_->GetMissionListManagerByUserId(userId); } +std::shared_ptr AbilityManagerService::GetMissionListWrap() +{ + CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr); + return subManagersHelper_->GetMissionListWrap(); +} + std::unordered_map> AbilityManagerService::GetUIAbilityManagers() { if (subManagersHelper_ == nullptr) { @@ -6364,7 +6548,7 @@ void AbilityManagerService::StartResidentApps() void AbilityManagerService::StartAutoStartupApps() { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (abilityAutoStartupService_ == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr."); return; @@ -6421,10 +6605,11 @@ void AbilityManagerService::RetryStartAutoStartupApps( void AbilityManagerService::SubscribeScreenUnlockedEvent() { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); // add listen screen unlocked. EventFwk::MatchingSkills matchingSkills; matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED); EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); auto callback = [abilityManager = weak_from_this()]() { @@ -6471,7 +6656,7 @@ void AbilityManagerService::SubscribeScreenUnlockedEvent() void AbilityManagerService::UnSubscribeScreenUnlockedEvent() { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); bool subResult = EventFwk::CommonEventManager::UnSubscribeCommonEvent(screenSubscriber_); TAG_LOGD(AAFwkTag::ABILITYMGR, "Screen unlocked event subscriber unsubscribe result is %{public}d.", subResult); } @@ -6739,8 +6924,12 @@ int AbilityManagerService::StartAbilityByCall(const Want &want, const sptr(abilityRequest.abilityInfo)); result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE : afterCheckExecuter_->DoProcess(afterCheckParam); + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error."); + return result; + } if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - ReportEventToRSS(abilityRequest.abilityInfo); + ReportEventToRSS(abilityRequest.abilityInfo, callerToken); abilityRequest.want.SetParam(IS_CALL_BY_SCB, false); auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId); CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE); @@ -6752,12 +6941,7 @@ int AbilityManagerService::StartAbilityByCall(const Want &want, const sptrResolveLocked(abilityRequest); } @@ -6768,7 +6952,7 @@ int AbilityManagerService::StartAbilityJust(AbilityRequest &abilityRequest, int3 TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - ReportEventToRSS(abilityRequest.abilityInfo); + ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken); auto uiAbilityManager = GetUIAbilityManagerByUserId(validUserId); CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE); return uiAbilityManager->ResolveLocked(abilityRequest); @@ -6779,7 +6963,7 @@ int AbilityManagerService::StartAbilityJust(AbilityRequest &abilityRequest, int3 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr is Null. Designated User Id=%{public}d", validUserId); return ERR_INVALID_VALUE; } - ReportEventToRSS(abilityRequest.abilityInfo); + ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken); return missionListMgr->ResolveLocked(abilityRequest); } @@ -7084,6 +7268,11 @@ void AbilityManagerService::EnableRecoverAbility(const sptr& toke TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::failed find abilityRecord by given token.", __func__); return; } + if (record->IsClearMissionFlag()) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::not allow EnableRecoverAbility before clearMission.", + __func__); + return; + } auto callingTokenId = IPCSkeleton::GetCallingTokenID(); auto tokenID = record->GetApplicationInfo().accessTokenId; @@ -7141,7 +7330,7 @@ void AbilityManagerService::ScheduleClearRecoveryPageStack() "ScheduleClearRecoveryPageStack bundleName = %{public}s, callerUid = %{public}d, tokenId = %{public}d", bundleName.c_str(), callerUid, tokenId); (void)DelayedSingleton::GetInstance()-> - DeleteAppExitReason(bundleName, callerUid); + DeleteAppExitReason(bundleName, tokenId); (void)DelayedSingleton::GetInstance()-> DeleteAllRecoverInfoByTokenId(tokenId); } @@ -7730,6 +7919,13 @@ int AbilityManagerService::DelegatorMoveMissionToFront(int32_t missionId) void AbilityManagerService::UpdateCallerInfo(Want& want, const sptr &callerToken) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + if (StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) { + int32_t callerUid = want.GetIntParam(Want::PARAM_RESV_CALLER_UID, -1); + TAG_LOGI(AAFwkTag::ABILITYMGR, "call from anco or broker, callerUid: %{public}d.", callerUid); + if (callerUid != -1) { + return; + } + } int32_t tokenId = static_cast(IPCSkeleton::GetCallingTokenID()); int32_t callerUid = IPCSkeleton::GetCallingUid(); int32_t callerPid = IPCSkeleton::GetCallingPid(); @@ -8004,6 +8200,35 @@ int AbilityManagerService::CheckStaticCfgPermission(const AppExecFwk::AbilityReq return CheckStaticCfgPermissionForSkill(abilityRequest, tokenId); } +int AbilityManagerService::CheckPermissionForUIService(const Want &want, const AbilityRequest &abilityRequest) +{ + AppExecFwk::ExtensionAbilityType extType = abilityRequest.abilityInfo.extensionAbilityType; + if (want.HasParameter(UISERVICEHOSTPROXY_KEY) && extType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Target ability is not UI_SERVICE"); + return ERR_WRONG_INTERFACE_CALL; + } else if (!want.HasParameter(UISERVICEHOSTPROXY_KEY) && extType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "need UISERVICEHOSTPROXY_KEY to connect UI_SERVICE"); + return ERR_WRONG_INTERFACE_CALL; + } + + if (extType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) { + return ERR_OK; + } + + AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest); + if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) { + return ERR_INVALID_VALUE; + } + + int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceExtensionPermission(verificationInfo); + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckCallServiceExtensionPermission failed"); + return result; + } + + return ERR_OK; +} + bool AbilityManagerService::IsNeedTimeoutForTest(const std::string &abilityName, const std::string &state) const { for (auto iter = timeoutMap_.begin(); iter != timeoutMap_.end(); iter++) { @@ -8150,6 +8375,15 @@ AppExecFwk::ElementName AbilityManagerService::GetTopAbility(bool isNeedLocalDev HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__); AppExecFwk::ElementName elementName = {}; + if (!PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { + auto callerPid = IPCSkeleton::GetCallingPid(); + AppExecFwk::RunningProcessInfo processInfo; + DelayedSingleton::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo); + if (!processInfo.isTestProcess) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "caller can not use system-api or not test process."); + return elementName; + } + } #ifdef SUPPORT_GRAPHICS sptr token; int ret = IN_PROCESS_CALL(GetTopAbility(token)); @@ -8442,7 +8676,8 @@ int AbilityManagerService::SetMissionIcon(const sptr &token, return missionListManager->SetMissionIcon(token, icon); } -int AbilityManagerService::RegisterWindowManagerServiceHandler(const sptr &handler) +int AbilityManagerService::RegisterWindowManagerServiceHandler(const sptr &handler, + bool animationEnabled) { auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); if (!isSaCall) { @@ -8450,6 +8685,7 @@ int AbilityManagerService::RegisterWindowManagerServiceHandler(const sptrsecond; - for (auto mode : windowModes) { - if (mode == bmsWindowMode) { + + auto bmsWindowMode = WindowOptionsUtils::WindowModeMap(windowMode); + if (bmsWindowMode.first) { + for (const auto& mode : windowModes) { + if (mode == bmsWindowMode.second) { return true; } } @@ -8651,6 +8887,12 @@ int AbilityManagerService::UnregisterAbilityFirstFrameStateObserver( return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance(). UnregisterAbilityFirstFrameStateObserver(observer); } + +bool AbilityManagerService::GetAnimationFlag() +{ + return isAnimationEnabled_; +} + #endif int AbilityManagerService::CheckCallServicePermission(const AbilityRequest &abilityRequest) @@ -8749,13 +8991,6 @@ int AbilityManagerService::CheckCallServiceExtensionPermission(const AbilityRequ verificationInfo.visible = abilityRequest.abilityInfo.visible; verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid()); verificationInfo.isBackgroundCall = false; - if (isParamStartAbilityEnable_) { - bool stopContinuousTaskFlag = ShouldPreventStartAbility(abilityRequest); - if (stopContinuousTaskFlag) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceExtension"); - return CHECK_PERMISSION_FAILED; - } - } int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceExtensionPermission(verificationInfo); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceExtension or DataShareExtension"); @@ -8802,9 +9037,11 @@ int AbilityManagerService::CheckCallOtherExtensionPermission(const AbilityReques if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) { return CheckUIExtensionPermission(abilityRequest); } - if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) { + if (extensionType == AppExecFwk::ExtensionAbilityType::VPN || + extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) { return ERR_OK; } + const std::string fileAccessPermission = "ohos.permission.FILE_ACCESS_MANAGER"; if (extensionType == AppExecFwk::ExtensionAbilityType::FILEACCESS_EXTENSION && AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(fileAccessPermission)) { @@ -8874,7 +9111,8 @@ int AbilityManagerService::CheckCallServiceAbilityPermission(const AbilityReques return result; } -int AbilityManagerService::CheckCallAbilityPermission(const AbilityRequest &abilityRequest, uint32_t specifyTokenId) +int AbilityManagerService::CheckCallAbilityPermission(const AbilityRequest &abilityRequest, uint32_t specifyTokenId, + bool isCallByShortcut) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "Call"); @@ -8888,7 +9126,8 @@ int AbilityManagerService::CheckCallAbilityPermission(const AbilityRequest &abil return ERR_INVALID_VALUE; } - int result = AAFwk::PermissionVerification::GetInstance()->CheckCallAbilityPermission(verificationInfo); + int result = AAFwk::PermissionVerification::GetInstance()->CheckCallAbilityPermission( + verificationInfo, isCallByShortcut); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start PageAbility(FA) or Ability(Stage)"); } @@ -9219,14 +9458,15 @@ int AbilityManagerService::CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId return ERR_OK; } -int AbilityManagerService::AddFreeInstallObserver(const sptr &observer) +int AbilityManagerService::AddFreeInstallObserver(const sptr &callerToken, + const sptr &observer) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (freeInstallManager_ == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr."); return ERR_INVALID_VALUE; } - return freeInstallManager_->AddFreeInstallObserver(observer); + return freeInstallManager_->AddFreeInstallObserver(callerToken, observer); } int32_t AbilityManagerService::IsValidMissionIds( @@ -9273,7 +9513,7 @@ int AbilityManagerService::VerifyPermission(const std::string &permission, int p int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(appInfo.accessTokenId, permission, false); if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission %{public}d: PERMISSION_DENIED", appInfo.accessTokenId); + TAG_LOGE(AAFwkTag::ABILITYMGR, "PERMISSION_DENIED"); return CHECK_PERMISSION_FAILED; } @@ -9293,12 +9533,7 @@ int32_t AbilityManagerService::AcquireShareData( } else { auto missionListManager = GetCurrentMissionListManager(); CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE); - std::shared_ptr mission = missionListManager->GetMissionById(missionId); - if (!mission) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "mission is null."); - return ERR_INVALID_VALUE; - } - abilityRecord = mission->GetAbilityRecord(); + abilityRecord = missionListManager->GetAbilityRecordByMissionId(missionId); } if (!abilityRecord) { TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is null."); @@ -9336,7 +9571,7 @@ int32_t AbilityManagerService::NotifySaveAsResult(const Want &want, int resultCo //caller check if (!DlpUtils::CheckCallerIsDlpManager(GetBundleManager())) { TAG_LOGW(AAFwkTag::ABILITYMGR, "caller check failed"); - return ERR_INVALID_CALLER; + return CHECK_PERMISSION_FAILED; } for (const auto &item : startAbilityChain_) { @@ -9669,7 +9904,7 @@ int32_t AbilityManagerService::CheckProcessOptions(const Want &want, const Start int32_t AbilityManagerService::RegisterAppDebugListener(sptr listener) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed."); return CHECK_PERMISSION_FAILED; @@ -9679,7 +9914,7 @@ int32_t AbilityManagerService::RegisterAppDebugListener(sptr listener) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed."); return CHECK_PERMISSION_FAILED; @@ -9711,7 +9946,7 @@ std::shared_ptr AbilityManagerService::ConnectInitAbilityDebug int32_t AbilityManagerService::AttachAppDebug(const std::string &bundleName) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false."); return ERR_NOT_DEVELOPER_MODE; @@ -9729,7 +9964,7 @@ int32_t AbilityManagerService::AttachAppDebug(const std::string &bundleName) int32_t AbilityManagerService::DetachAppDebug(const std::string &bundleName) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed."); @@ -9742,7 +9977,7 @@ int32_t AbilityManagerService::DetachAppDebug(const std::string &bundleName) int32_t AbilityManagerService::ExecuteIntent(uint64_t key, const sptr &callerToken, const InsightIntentExecuteParam ¶m) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto paramPtr = std::make_shared(param); int32_t ret = DelayedSingleton::GetInstance()->CheckAndUpdateParam(key, callerToken, paramPtr); @@ -9944,7 +10179,7 @@ int32_t AbilityManagerService::CancelApplicationAutoStartupByEDM(const AutoStart int32_t AbilityManagerService::GetForegroundUIAbilities(std::vector &list) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); CHECK_CALLER_IS_SYSTEM_APP; auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm(); if (!isPerm) { @@ -10037,12 +10272,11 @@ int32_t AbilityManagerService::OpenFile(const Uri& uri, uint32_t flag) return collaborator->OpenFile(uri, flag); } #ifdef SUPPORT_SCREEN -int AbilityManagerService::GetDialogSessionInfo(const std::string dialogSessionId, +int AbilityManagerService::GetDialogSessionInfo(const std::string &dialogSessionId, sptr &dialogSessionInfo) { CHECK_CALLER_IS_SYSTEM_APP; - CHECK_POINTER_AND_RETURN(dialogSessionRecord_, ERR_INVALID_VALUE); - dialogSessionInfo = dialogSessionRecord_->GetDialogSessionInfo(dialogSessionId); + dialogSessionInfo = DialogSessionManager::GetInstance().GetDialogSessionInfo(dialogSessionId); if (dialogSessionInfo) { TAG_LOGD(AAFwkTag::ABILITYMGR, "success"); return ERR_OK; @@ -10051,83 +10285,17 @@ int AbilityManagerService::GetDialogSessionInfo(const std::string dialogSessionI return INNER_ERR; } -bool AbilityManagerService::GenerateDialogSessionRecord(AbilityRequest &abilityRequest, int32_t userId, - std::string &dialogSessionId, std::vector &dialogAppInfos, bool isSelector) -{ - CHECK_POINTER_AND_RETURN(dialogSessionRecord_, ERR_INVALID_VALUE); - if (!isSelector && dialogAppInfos.size() == 1) { - dialogAppInfos.front().bundleName = abilityRequest.abilityInfo.bundleName; - dialogAppInfos.front().moduleName = abilityRequest.abilityInfo.moduleName; - dialogAppInfos.front().abilityName = abilityRequest.abilityInfo.name; - dialogAppInfos.front().abilityIconId = abilityRequest.abilityInfo.iconId; - dialogAppInfos.front().abilityLabelId = abilityRequest.abilityInfo.labelId; - dialogAppInfos.front().bundleIconId = abilityRequest.abilityInfo.applicationInfo.iconId; - dialogAppInfos.front().bundleLabelId = abilityRequest.abilityInfo.applicationInfo.labelId; - } - return dialogSessionRecord_->GenerateDialogSessionRecord(abilityRequest, userId, - dialogSessionId, dialogAppInfos, isSelector); -} - -int AbilityManagerService::CreateModalDialog(const Want &replaceWant, sptr callerToken, - std::string dialogSessionId) -{ - HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - (const_cast(replaceWant)).SetParam("dialogSessionId", dialogSessionId); - auto connection = std::make_shared(); - if (callerToken == nullptr) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "create modal ui extension for system"); - (const_cast(replaceWant)).SetParam(UIEXTENSION_MODAL_TYPE, 1); - return connection->CreateModalUIExtension(replaceWant) ? ERR_OK : INNER_ERR; - } - auto callerRecord = Token::GetAbilityRecordByToken(callerToken); - if (!callerRecord) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "callerRecord is nullptr."); - return ERR_INVALID_VALUE; - } - - sptr token; - int ret = IN_PROCESS_CALL(GetTopAbility(token)); - if (ret != ERR_OK || token == nullptr) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "create modal ui extension for system"); - (const_cast(replaceWant)).SetParam(UIEXTENSION_MODAL_TYPE, 1); - return connection->CreateModalUIExtension(replaceWant) ? ERR_OK : INNER_ERR; - } - - if (callerRecord->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE && token == callerToken) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "create modal ui extension for application"); - return callerRecord->CreateModalUIExtension(replaceWant); - } - TAG_LOGD(AAFwkTag::ABILITYMGR, "create modal ui extension for system"); - (const_cast(replaceWant)).SetParam(UIEXTENSION_MODAL_TYPE, 1); - return connection->CreateModalUIExtension(replaceWant) ? ERR_OK : INNER_ERR; -} - -int AbilityManagerService::SendDialogResult(const Want &want, const std::string dialogSessionId, bool isAllowed) +int AbilityManagerService::SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllowed) { CHECK_CALLER_IS_SYSTEM_APP; - CHECK_POINTER_AND_RETURN(dialogSessionRecord_, ERR_INVALID_VALUE); - if (!isAllowed) { - TAG_LOGI(AAFwkTag::ABILITYMGR, "user refuse to jump"); - dialogSessionRecord_->ClearDialogContext(dialogSessionId); - return ERR_OK; - } - std::shared_ptr dialogCallerInfo = dialogSessionRecord_->GetDialogCallerInfo(dialogSessionId); - if (dialogCallerInfo == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "dialog caller info is nullptr"); - dialogSessionRecord_->ClearDialogContext(dialogSessionId); - return ERR_INVALID_VALUE; - } - auto targetWant = dialogCallerInfo->targetWant; - targetWant.SetElement(want.GetElement()); - targetWant.SetParam("isSelector", dialogCallerInfo->isSelector); - targetWant.SetParam("dialogSessionId", dialogSessionId); - sptr callerToken = dialogCallerInfo->callerToken; - int ret = StartAbilityAsCaller(targetWant, callerToken, nullptr, dialogCallerInfo->userId, - dialogCallerInfo->requestCode, true); - if (ret == ERR_OK) { - dialogSessionRecord_->ClearDialogContext(dialogSessionId); - } - return ret; + return DialogSessionManager::GetInstance().SendDialogResult(want, dialogSessionId, isAllowed); +} + +int AbilityManagerService::CreateCloneSelectorDialog(AbilityRequest &request, int32_t userId, + const std::string &replaceWantString) +{ + CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL); + return implicitStartProcessor_->ImplicitStartAbility(request, userId, 0, replaceWantString, true); } #endif // SUPPORT_SCREEN void AbilityManagerService::RemoveLauncherDeathRecipient(int32_t userId) @@ -10163,7 +10331,7 @@ int32_t AbilityManagerService::GenerateEmbeddableUIAbilityRequest( int32_t AbilityManagerService::CheckDebugAssertPermission() { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Product of assert fault dialog is not enabled."); @@ -10208,15 +10376,15 @@ void AbilityManagerService::CloseAssertDialog(const std::string &assertSessionId int32_t AbilityManagerService::SetResidentProcessEnabled(const std::string &bundleName, bool enable) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall()) { - HILOG_ERROR("Permission verification failed."); + TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed."); return ERR_NOT_SYSTEM_APP; } auto residentProcessManager = DelayedSingleton::GetInstance(); if (residentProcessManager == nullptr) { - HILOG_ERROR("Get resident proces mgr is nullptr"); + TAG_LOGE(AAFwkTag::ABILITYMGR, "Get resident proces mgr is nullptr"); return INNER_ERR; } @@ -10225,7 +10393,7 @@ int32_t AbilityManagerService::SetResidentProcessEnabled(const std::string &bund auto callerPid = IPCSkeleton::GetCallingPid(); DelayedSingleton::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid); if (callerName.empty()) { - HILOG_ERROR("Failed to obtain caller name."); + TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to obtain caller name."); return INNER_ERR; } @@ -10409,6 +10577,34 @@ int32_t AbilityManagerService::GetUIExtensionRootHostInfo(const sptr token, + UIExtensionSessionInfo &uiExtensionSessionInfo, int32_t userId) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info."); + CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE); + + if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny."); + return ERR_PERMISSION_DENIED; + } + + auto validUserId = GetValidUserId(userId); + auto connectManager = GetConnectManagerByUserId(validUserId); + if (connectManager == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", validUserId); + return ERR_INVALID_VALUE; + } + + auto ret = connectManager->GetUIExtensionSessionInfo(token, uiExtensionSessionInfo); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Get ui extension session info failed."); + return ret; + } + + return ERR_OK; +} + int32_t AbilityManagerService::RestartApp(const AAFwk::Want &want) { TAG_LOGD(AAFwkTag::ABILITYMGR, "call."); @@ -10445,7 +10641,7 @@ int32_t AbilityManagerService::RestartApp(const AAFwk::Want &want) TAG_LOGD(AAFwkTag::ABILITYMGR, "RestartApp, start ability without CheckCallAbilityPermission."); result = StartAbilityWrap(want, nullptr, - DEFAULT_INVAL_VALUE, DEFAULT_INVAL_VALUE, false, false, 0, isForegroundToRestartApp); + DEFAULT_INVAL_VALUE, DEFAULT_INVAL_VALUE, false, 0, isForegroundToRestartApp); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility error."); return result; @@ -10733,7 +10929,9 @@ int32_t AbilityManagerService::StartShortcut(const Want &want, const StartOption PermissionConstants::PERMISSION_START_SHORTCUT); return ERR_PERMISSION_DENIED; } - return StartAbility(want, startOptions, nullptr); + AbilityUtil::RemoveShowModeKey(const_cast(want)); + return StartUIAbilityForOptionWrap(want, startOptions, nullptr, DEFAULT_INVAL_VALUE, DEFAULT_INVAL_VALUE, + 0, false, true); } int32_t AbilityManagerService::GetAbilityStateByPersistentId(int32_t persistentId, bool &state) @@ -10759,6 +10957,10 @@ int32_t AbilityManagerService::TransferAbilityResultForExtension(const sptrGetAbilityInfo().type; if (type != AppExecFwk::AbilityType::EXTENSION) { TAG_LOGE(AAFwkTag::ABILITYMGR, "type is not uiextension."); @@ -10804,5 +11006,441 @@ void AbilityManagerService::NotifyFrozenProcessByRSS(const std::vector CHECK_POINTER_LOG(connectManager, "can not find user connect manager"); connectManager->HandleProcessFrozen(pidList, uid); } + +void AbilityManagerService::HandleRestartResidentProcessDependedOnWeb() +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); + auto appMgr = GetAppMgr(); + CHECK_POINTER_LOG(appMgr, "get appMgr fail"); + appMgr->RestartResidentProcessDependedOnWeb(); +} + +int32_t AbilityManagerService::PreStartMission(const std::string& bundleName, const std::string& moduleName, + const std::string& abilityName, const std::string& startTime) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "called"); + CHECK_CALLER_IS_SYSTEM_APP; + + if (!PermissionVerification::GetInstance()->VerifyPreStartAtomicServicePermission()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "calling user is not ag."); + return ERR_PERMISSION_DENIED; + } + + if (!freeInstallManager_) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr."); + return ERR_INVALID_VALUE; + } + + FreeInstallInfo taskInfo; + if (!freeInstallManager_->GetFreeInstallTaskInfo(bundleName, abilityName, startTime, taskInfo)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, + "failed to find free install task info:bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s", + bundleName.c_str(), abilityName.c_str(), startTime.c_str()); + return ERR_FREE_INSTALL_TASK_NOT_EXIST; + } + + if (taskInfo.isFreeInstallFinished) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "free install is finished."); + if (!taskInfo.isInstalled) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d", + taskInfo.resultCode); + } else { + TAG_LOGI(AAFwkTag::ABILITYMGR, "free install has succeeded."); + } + // if free install is already finished then either the window is opened (on success) + // or the user is informed of the error (on failure). + return taskInfo.resultCode; + } + + return PreStartInner(taskInfo); +} + +int32_t AbilityManagerService::PreStartInner(const FreeInstallInfo& taskInfo) +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); + + const Want& want = taskInfo.want; + sptr callerToken = taskInfo.callerToken; + + EventInfo eventInfo = BuildEventInfo(want, taskInfo.userId); + SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo); + + if (callerToken != nullptr && !VerificationAllToken(callerToken)) { + eventInfo.errCode = ERR_INVALID_VALUE; + SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo); + return ERR_INVALID_CALLER; + } + + int32_t oriValidUserId = GetValidUserId(taskInfo.userId); + + int32_t appIndex = 0; + StartAbilityInfoWrap threadLocalInfo(want, oriValidUserId, + StartAbilityUtils::GetAppIndex(want, callerToken, appIndex), callerToken); + + AbilityRequest abilityRequest = { + .want = want, + .requestCode = taskInfo.requestCode, + .callerToken = callerToken, + .startSetting = nullptr + }; + + TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo"); + UpdateCallerInfo(abilityRequest.want, callerToken); + + // sceneboard + abilityRequest.userId = oriValidUserId; + abilityRequest.want.SetParam(IS_CALL_BY_SCB, false); + std::string sessionId = std::to_string(std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count()); + abilityRequest.want.SetParam(KEY_SESSION_ID, sessionId); + auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId); + CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE); + sptr sessionInfo = nullptr; + auto errCode = uiAbilityManager->NotifySCBToPreStartUIAbility(abilityRequest, sessionInfo); + if (errCode != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to notify sceneboard to pre-start uiability."); + return errCode; + } + freeInstallManager_->SetFreeInstallTaskSessionId(taskInfo.want.GetElement().GetBundleName(), + taskInfo.want.GetElement().GetAbilityName(), + taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME), sessionId); + + freeInstallManager_->SetPreStartMissionCallStatus(taskInfo.want.GetElement().GetBundleName(), + taskInfo.want.GetElement().GetAbilityName(), + taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME), + true); + return ERR_OK; +} + +int32_t AbilityManagerService::StartUIAbilityByPreInstall(const FreeInstallInfo &taskInfo) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + TAG_LOGI(AAFwkTag::ABILITYMGR, "called"); + if (!taskInfo.isFreeInstallFinished || !taskInfo.isInstalled) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "free install is not finished or has failed."); + return ERR_INVALID_VALUE; + } + if (!taskInfo.isStartUIAbilityBySCBCalled) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "Free install is finished, StartUIAbilityBySCB has not been called."); + return ERR_OK; + } + + const auto& want = taskInfo.want; + auto sessionId = want.GetStringParam(KEY_SESSION_ID); + if (sessionId.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "session id is empty."); + return ERR_INVALID_VALUE; + } + auto bundleName = want.GetElement().GetBundleName(); + auto abilityName = want.GetElement().GetAbilityName(); + auto startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME); + TAG_LOGI(AAFwkTag::ABILITYMGR, "called" + "sessionId=%{public}s,bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s", + sessionId.c_str(), bundleName.c_str(), abilityName.c_str(), startTime.c_str()); + sptr sessionInfo = nullptr; + { + std::lock_guard guard(preStartSessionMapLock_); + auto it = preStartSessionMap_.find(sessionId); + if (it == preStartSessionMap_.end()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find session info with sessionId=%{public}s", + sessionId.c_str()); + return ERR_INVALID_VALUE; + } + sessionInfo = it->second; + (sessionInfo->want).SetElement(want.GetElement()); + } + + int errCode = ERR_OK; + bool isColdStart = true; + if ((errCode = StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, isColdStart)) != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilityByPreInstallInner failed,errCode=%{public}d.", errCode); + } + RemovePreStartSession(sessionId); + return errCode; +} + +// StartUIAbilityByPreInstallInner is called when free install task is already finished +int AbilityManagerService::StartUIAbilityByPreInstallInner(sptr sessionInfo, + uint32_t specifyTokenId, bool &isColdStart) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "called"); + auto callerToken = sessionInfo->callerToken; + const auto& want = sessionInfo->want; + const auto userId = sessionInfo->userId; + const auto requestCode = sessionInfo->requestCode; + bool isStartAsCaller = false; + + if (callerToken != nullptr && !VerificationAllToken(callerToken)) { + auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()-> + CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME); + if (!isSpecificSA) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__); + return ERR_INVALID_CALLER; + } + TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: Caller is specific system ability.", __func__); + } + + int32_t oriValidUserId = GetValidUserId(userId); + int32_t validUserId = oriValidUserId; + + int32_t appIndex = 0; + if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) { + return ERR_APP_CLONE_INDEX_INVALID; + } + StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken); + AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(), + true, nullptr); + auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE : + interceptorExecuter_->DoProcess(interceptorParam); + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error."); + return result; + } + + AbilityRequest abilityRequest; + result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId); + auto abilityRecord = Token::GetAbilityRecordByToken(callerToken); + std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : ""; + + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error."); + return result; + } + if (!UriUtils::GetInstance().CheckNonImplicitShareFileUri(abilityRequest)) { + return ERR_SHARE_FILE_URI_NON_IMPLICITLY; + } + + if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token + UpdateCallerInfoFromToken(abilityRequest.want, callerToken); + } else if (!isStartAsCaller) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo"); + UpdateCallerInfo(abilityRequest.want, callerToken); + } else if (callerBundleName == BUNDLE_NAME_DIALOG) { +#ifdef SUPPORT_SCREEN + CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL); + implicitStartProcessor_->ResetCallingIdentityAsCaller(abilityRequest.want.GetIntParam( + Want::PARAM_RESV_CALLER_TOKEN, 0)); +#endif // SUPPORT_SCREEN + } + + auto abilityInfo = abilityRequest.abilityInfo; + validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId; + TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d", + validUserId, static_cast(abilityInfo.applicationInfo.singleton)); + + result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller, + abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, false); + if (result != AppExecFwk::Constants::PERMISSION_GRANTED) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result); + return ERR_STATIC_CFG_PERMISSION; + } + + result = CheckCallPermission(want, abilityInfo, abilityRequest, false, + false, specifyTokenId, callerBundleName); + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckCallPermission error, result is %{public}d.", result); + return result; + } + + Want newWant = abilityRequest.want; + AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(), + true, callerToken, std::make_shared(abilityInfo), isStartAsCaller); + result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE : + afterCheckExecuter_->DoProcess(afterCheckParam); + bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false); + newWant.RemoveParam("queryWantFromErms"); + if (result != ERR_OK && isReplaceWantExist == false) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "DoProcess failed or replaceWant not exist"); + return result; + } +#ifdef SUPPORT_SCREEN + if (result != ERR_OK && isReplaceWantExist && callerBundleName != BUNDLE_NAME_DIALOG) { + return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant); + } + if (result == ERR_OK && + DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog"); + return CreateCloneSelectorDialog(abilityRequest, GetUserId()); + } +#endif // SUPPORT_SCREEN + + if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE || + abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) { + return StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken); + } + + if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart failed: %{public}s.", abilityInfo.bundleName.c_str()); + return ERR_WOULD_BLOCK; + } + + abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID); + if (specifyTokenId > 0) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId); + abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast(specifyTokenId)); + abilityRequest.specifyTokenId = specifyTokenId; + } + abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG); + + auto uiAbilityManager = GetCurrentUIAbilityManager(); + CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE); + + return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, isColdStart); +} + +void AbilityManagerService::NotifySCBToHandleAtomicServiceException(const std::string& sessionId, int32_t errCode, + const std::string& reason) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "called"); + sptr sessionInfo = nullptr; + { + std::lock_guard guard(preStartSessionMapLock_); + auto it = preStartSessionMap_.find(sessionId); + if (it == preStartSessionMap_.end()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find session info with sessionId=%{public}s", + sessionId.c_str()); + return; + } + sessionInfo = it->second; + preStartSessionMap_.erase(it); + } + if (sessionInfo == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr."); + return; + } + auto uiAbilityManager = GetCurrentUIAbilityManager(); + CHECK_POINTER(uiAbilityManager); + return uiAbilityManager->NotifySCBToHandleAtomicServiceException(sessionInfo, errCode, reason); +} + +void AbilityManagerService::RemovePreStartSession(const std::string& sessionId) +{ + std::lock_guard guard(preStartSessionMapLock_); + preStartSessionMap_.erase(sessionId); +} + +ErrCode AbilityManagerService::OpenLink(const Want& want, sptr callerToken, + int32_t userId, int requestCode) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "called"); + std::string url = want.GetUriString(); + bool isAtomicServiceShortUrl = false; +#ifdef APP_DOMAIN_VERIFY_ENABLED + isAtomicServiceShortUrl = AppDomainVerify::AppDomainVerifyMgrClient::GetInstance()->IsAtomicServiceUrl(url); +#endif + int32_t retCode = ERR_OK; + if (!isAtomicServiceShortUrl) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "not atomic service short url, start ability by default."); + retCode = StartAbility(want, callerToken, userId, requestCode); + CHECK_RET_RETURN_RET(retCode, "StartAbility failed"); + return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK; + } + + Want convertedWant = want; + retCode = ConvertToExplicitWant(convertedWant); + if (retCode != ERR_OK) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "failed to convert to explicit want, start ability by default."); + retCode = StartAbility(want, callerToken, userId, requestCode); + CHECK_RET_RETURN_RET(retCode, "StartAbility failed"); + return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK; + } + + if (!freeInstallManager_) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "free install manager is nullptr, start ability by default."); + retCode = StartAbility(want, callerToken, userId, requestCode); + CHECK_RET_RETURN_RET(retCode, "StartAbility failed"); + return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK; + } + + convertedWant.AddFlags(Want::FLAG_INSTALL_ON_DEMAND); + TAG_LOGD(AAFwkTag::ABILITYMGR, "convertedWant=%{public}s", convertedWant.ToString().c_str()); + retCode = freeInstallManager_->StartFreeInstall(convertedWant, GetValidUserId(userId), + requestCode, callerToken, true, 0, true, std::make_shared(want)); + if (retCode != ERR_OK) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "StartFreeInstall returns errCode=%{public}d.", retCode); + if (retCode == NOT_TOP_ABILITY) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "start from background is not allowed."); + return retCode; + } + TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability by default."); + retCode = StartAbility(want, callerToken, userId, requestCode); + CHECK_RET_RETURN_RET(retCode, "StartAbility failed"); + return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK; + } + return ERR_OK; +} + +ErrCode AbilityManagerService::ConvertToExplicitWant(Want& want) +{ + ErrCode retCode = ERR_OK; +#ifdef APP_DOMAIN_VERIFY_ENABLED + auto bundleMgrHelper = GetBundleManager(); + if (bundleMgrHelper == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "bundleMgrHelper is invalid."); + return ERR_INVALID_VALUE; + } + int32_t callerUid = IPCSkeleton::GetCallingUid(); + std::string callerBundleName; + retCode = IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callerUid, callerBundleName)); + if (retCode != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Get callerBundleName failed,retCode=%{public}d.", retCode); + return retCode; + } + TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName=%{public}s.", callerBundleName.c_str()); + want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName); + + bool isUsed = false; + ffrt::condition_variable callbackDoneCv; + ffrt::mutex callbackDoneMutex; + ConvertCallbackTask task = [&retCode, &isUsed, &callbackDoneCv, &callbackDoneMutex, + &convertedWant = want, this](int resultCode, AAFwk::Want& want) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "in convert callback task, resultCode=%{public}d,want=%{public}s", + resultCode, want.ToString().c_str()); + retCode = resultCode; + convertedWant = want; + { + std::lock_guard lock(callbackDoneMutex); + isUsed = true; + } + TAG_LOGI(AAFwkTag::ABILITYMGR, "start to notify."); + callbackDoneCv.notify_all(); + TAG_LOGI(AAFwkTag::ABILITYMGR, "convert callback task finished"); + }; + sptr callbackTask = new ConvertCallbackImpl(std::move(task)); + sptr callback = callbackTask; + AppDomainVerify::AppDomainVerifyMgrClient::GetInstance()->ConvertToExplicitWant(want, callback); + auto condition = [&isUsed] { return isUsed; }; + std::unique_lock lock(callbackDoneMutex); + TAG_LOGI(AAFwkTag::ABILITYMGR, "start to wait for condition."); + if (!callbackDoneCv.wait_for(lock, seconds(CONVERT_CALLBACK_TIMEOUT_SECONDS), condition)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "convert callback timeout."); + callbackTask->Cancel(); + retCode = ERR_TIMED_OUT; + } + TAG_LOGI(AAFwkTag::ABILITYMGR, "finish wait for condition."); +#endif + return retCode; +} + +void AbilityManagerService::SetAbilityRequestSessionInfo(AbilityRequest &abilityRequest, AppExecFwk::ExtensionAbilityType extensionType) +{ + if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) { + return; + } + sptr sessionInfo = new SessionInfo(); + sessionInfo->callerToken = abilityRequest.callerToken; + auto callerAbilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken); + if(callerAbilityRecord != nullptr) { + sptr callerSessionInfo = callerAbilityRecord->GetSessionInfo(); + TAG_LOGI(AAFwkTag::ABILITYMGR, "CreateSessionInfo %{public}d.", callerSessionInfo->persistentId); + sessionInfo->hostWindowId = callerSessionInfo->persistentId; + } else { + TAG_LOGE(AAFwkTag::ABILITYMGR, "callerAbilityRecord is nullptr"); + } + sessionInfo->want = abilityRequest.want; + sessionInfo->callingTokenId = static_cast(abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, + IPCSkeleton::GetCallingTokenID())); + abilityRequest.sessionInfo = sessionInfo; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index ad1bb836bf..b6c0878759 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -544,6 +544,9 @@ int AbilityManagerStub::OnRemoteRequestInnerFourteenth(uint32_t code, MessagePar if (interfaceCode == AbilityManagerInterfaceCode::GET_UI_EXTENSION_ROOT_HOST_INFO) { return GetUIExtensionRootHostInfoInner(data, reply); } + if (interfaceCode == AbilityManagerInterfaceCode::GET_UI_EXTENSION_SESSION_INFO) { + return GetUIExtensionSessionInfoInner(data, reply); + } if (interfaceCode == AbilityManagerInterfaceCode::PRELOAD_UIEXTENSION_ABILITY) { return PreloadUIExtensionAbilityInner(data, reply); } @@ -606,8 +609,11 @@ int AbilityManagerStub::OnRemoteRequestInnerSixteenth(uint32_t code, MessageParc if (interfaceCode == AbilityManagerInterfaceCode::COMPLETE_FIRST_FRAME_DRAWING_BY_SCB) { return CompleteFirstFrameDrawingBySCBInner(data, reply); } - if (interfaceCode == AbilityManagerInterfaceCode::START_UI_EXTENSION_ABILITY_NON_MODAL) { - return StartUIExtensionAbilityNonModalInner(data, reply); + if (interfaceCode == AbilityManagerInterfaceCode::START_UI_EXTENSION_ABILITY_EMBEDDED) { + return StartUIExtensionAbilityEmbeddedInner(data, reply); + } + if (interfaceCode == AbilityManagerInterfaceCode::START_UI_EXTENSION_CONSTRAINED_EMBEDDED) { + return StartUIExtensionConstrainedEmbeddedInner(data, reply); } #endif if (interfaceCode == AbilityManagerInterfaceCode::REQUEST_DIALOG_SERVICE) { @@ -740,6 +746,12 @@ int AbilityManagerStub::OnRemoteRequestInnerNineteenth(uint32_t code, MessagePar if (interfaceCode == AbilityManagerInterfaceCode::NOTIFY_FROZEN_PROCESS_BY_RSS) { return NotifyFrozenProcessByRSSInner(data, reply); } + if (interfaceCode == AbilityManagerInterfaceCode::PRE_START_MISSION) { + return PreStartMissionInner(data, reply); + } + if (interfaceCode == AbilityManagerInterfaceCode::OPEN_LINK) { + return OpenLinkInner(data, reply); + } return ERR_CODE_NOT_EXIST; } @@ -1117,7 +1129,8 @@ int AbilityManagerStub::UninstallAppInner(MessageParcel &data, MessageParcel &re { std::string bundleName = Str16ToStr8(data.ReadString16()); int32_t uid = data.ReadInt32(); - int result = UninstallApp(bundleName, uid); + int32_t appIndex = data.ReadInt32(); + int32_t result = UninstallApp(bundleName, uid, appIndex); if (!reply.WriteInt32(result)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "remove stack error"); return ERR_INVALID_VALUE; @@ -1130,7 +1143,8 @@ int32_t AbilityManagerStub::UpgradeAppInner(MessageParcel &data, MessageParcel & std::string bundleName = Str16ToStr8(data.ReadString16()); int32_t uid = data.ReadInt32(); std::string exitMsg = Str16ToStr8(data.ReadString16()); - int result = UpgradeApp(bundleName, uid, exitMsg); + int32_t appIndex = data.ReadInt32(); + int32_t result = UpgradeApp(bundleName, uid, exitMsg, appIndex); if (!reply.WriteInt32(result)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "UpgradeAppInner error"); return ERR_INVALID_VALUE; @@ -1330,7 +1344,8 @@ int AbilityManagerStub::StartUIExtensionAbilityInner(MessageParcel &data, Messag TAG_LOGE(AAFwkTag::ABILITYMGR, "read extensionSessionInfo failed."); return ERR_NULL_OBJECT; } - extensionSessionInfo->isModal = true; // To ensure security, this attribute must be rewritten. + // To ensure security, this attribute must be rewritten. + extensionSessionInfo->uiExtensionUsage = UIExtensionUsage::MODAL; } int32_t userId = data.ReadInt32(); @@ -1340,7 +1355,7 @@ int AbilityManagerStub::StartUIExtensionAbilityInner(MessageParcel &data, Messag return NO_ERROR; } -int AbilityManagerStub::StartUIExtensionAbilityNonModalInner(MessageParcel &data, MessageParcel &reply) +int AbilityManagerStub::StartUIExtensionAbilityEmbeddedInner(MessageParcel &data, MessageParcel &reply) { sptr extensionSessionInfo = nullptr; if (data.ReadBool()) { @@ -1349,7 +1364,28 @@ int AbilityManagerStub::StartUIExtensionAbilityNonModalInner(MessageParcel &data TAG_LOGE(AAFwkTag::ABILITYMGR, "read extensionSessionInfo failed."); return ERR_NULL_OBJECT; } - extensionSessionInfo->isModal = false; // To ensure security, this attribute must be rewritten. + // To ensure security, this attribute must be rewritten. + extensionSessionInfo->uiExtensionUsage = UIExtensionUsage::EMBEDDED; + } + + int32_t userId = data.ReadInt32(); + + int32_t result = StartUIExtensionAbility(extensionSessionInfo, userId); + reply.WriteInt32(result); + return NO_ERROR; +} + +int AbilityManagerStub::StartUIExtensionConstrainedEmbeddedInner(MessageParcel &data, MessageParcel &reply) +{ + sptr extensionSessionInfo = nullptr; + if (data.ReadBool()) { + extensionSessionInfo = data.ReadParcelable(); + if (extensionSessionInfo == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "read extensionSessionInfo failed."); + return ERR_NULL_OBJECT; + } + // To ensure security, this attribute must be rewritten. + extensionSessionInfo->uiExtensionUsage = UIExtensionUsage::CONSTRAINED_EMBEDDED; } int32_t userId = data.ReadInt32(); @@ -1416,9 +1452,7 @@ int AbilityManagerStub::StartAbilityAsCallerByTokenInner(MessageParcel &data, Me } int32_t userId = data.ReadInt32(); int requestCode = data.ReadInt32(); - bool isSendDialogResult = data.ReadBool(); - int32_t result = StartAbilityAsCaller(*want, callerToken, asCallerSourceToken, userId, requestCode, - isSendDialogResult); + int32_t result = StartAbilityAsCaller(*want, callerToken, asCallerSourceToken, userId, requestCode); reply.WriteInt32(result); return NO_ERROR; } @@ -2670,13 +2704,21 @@ int AbilityManagerStub::FreeInstallAbilityFromRemoteInner(MessageParcel &data, M int AbilityManagerStub::AddFreeInstallObserverInner(MessageParcel &data, MessageParcel &reply) { + sptr callerToken = nullptr; + if (data.ReadBool()) { + callerToken = data.ReadRemoteObject(); + if (callerToken == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "caller token is nullptr."); + return ERR_INVALID_VALUE; + } + } sptr observer = iface_cast(data.ReadRemoteObject()); if (observer == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "observer is nullptr"); return ERR_INVALID_VALUE; } - int32_t result = AddFreeInstallObserver(observer); + int32_t result = AddFreeInstallObserver(callerToken, observer); if (!reply.WriteInt32(result)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "reply write failed."); return ERR_INVALID_VALUE; @@ -2975,7 +3017,8 @@ int AbilityManagerStub::RegisterWindowManagerServiceHandlerInner(MessageParcel & TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s read WMS handler failed!", __func__); return ERR_NULL_OBJECT; } - return RegisterWindowManagerServiceHandler(handler); + bool animationEnabled = data.ReadBool(); + return RegisterWindowManagerServiceHandler(handler, animationEnabled); } int AbilityManagerStub::CompleteFirstFrameDrawingInner(MessageParcel &data, MessageParcel &reply) @@ -3056,7 +3099,7 @@ int AbilityManagerStub::SendDialogResultInner(MessageParcel &data, MessageParcel int AbilityManagerStub::RegisterAbilityFirstFrameStateObserverInner(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto callback = iface_cast(data.ReadRemoteObject()); if (callback == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Callback is null."); @@ -3074,7 +3117,7 @@ int AbilityManagerStub::RegisterAbilityFirstFrameStateObserverInner(MessageParce int AbilityManagerStub::UnregisterAbilityFirstFrameStateObserverInner(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto callback = iface_cast(data.ReadRemoteObject()); if (callback == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Callback is null."); @@ -3386,7 +3429,7 @@ int AbilityManagerStub::RegisterSessionHandlerInner(MessageParcel &data, Message int32_t AbilityManagerStub::RegisterAppDebugListenerInner(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto appDebugLister = iface_cast(data.ReadRemoteObject()); if (appDebugLister == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "App debug lister is nullptr."); @@ -3403,7 +3446,7 @@ int32_t AbilityManagerStub::RegisterAppDebugListenerInner(MessageParcel &data, M int32_t AbilityManagerStub::UnregisterAppDebugListenerInner(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto appDebugLister = iface_cast(data.ReadRemoteObject()); if (appDebugLister == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "App debug lister is nullptr."); @@ -3485,7 +3528,7 @@ int32_t AbilityManagerStub::ExecuteIntentInner(MessageParcel &data, MessageParce int AbilityManagerStub::StartAbilityForResultAsCallerInner(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); std::unique_ptr want(data.ReadParcelable()); if (want == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "The want is nullptr."); @@ -3504,7 +3547,7 @@ int AbilityManagerStub::StartAbilityForResultAsCallerInner(MessageParcel &data, int AbilityManagerStub::StartAbilityForResultAsCallerForOptionsInner(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); std::unique_ptr want(data.ReadParcelable()); if (want == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "The want is nullptr."); @@ -3549,7 +3592,7 @@ int32_t AbilityManagerStub::StartAbilityByInsightIntentInner(MessageParcel &data int32_t AbilityManagerStub::ExecuteInsightIntentDoneInner(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto token = data.ReadRemoteObject(); if (token == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get remote object."); @@ -3637,7 +3680,7 @@ int32_t AbilityManagerStub::NotifyDebugAssertResultInner(MessageParcel &data, Me int32_t AbilityManagerStub::GetForegroundUIAbilitiesInner(MessageParcel &data, MessageParcel &reply) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); std::vector abilityStateDatas; int32_t result = GetForegroundUIAbilities(abilityStateDatas); if (result != ERR_OK) { @@ -3728,6 +3771,33 @@ int32_t AbilityManagerStub::GetUIExtensionRootHostInfoInner(MessageParcel &data, return NO_ERROR; } +int32_t AbilityManagerStub::GetUIExtensionSessionInfoInner(MessageParcel &data, MessageParcel &reply) +{ + sptr callerToken = nullptr; + if (data.ReadBool()) { + callerToken = data.ReadRemoteObject(); + if (callerToken == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "caller token is nullptr."); + return ERR_INVALID_VALUE; + } + } + + int32_t userId = data.ReadInt32(); + UIExtensionSessionInfo uiExtensionSessionInfo; + auto result = GetUIExtensionSessionInfo(callerToken, uiExtensionSessionInfo, userId); + if (!reply.WriteParcelable(&uiExtensionSessionInfo)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Write ui extension session info failed."); + return ERR_INVALID_VALUE; + } + + if (!reply.WriteInt32(result)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Write result failed."); + return ERR_INVALID_VALUE; + } + + return NO_ERROR; +} + int32_t AbilityManagerStub::RestartAppInner(MessageParcel &data, MessageParcel &reply) { TAG_LOGD(AAFwkTag::ABILITYMGR, "call."); @@ -3780,7 +3850,7 @@ int32_t AbilityManagerStub::SetResidentProcessEnableInner(MessageParcel &data, M bool enable = data.ReadBool(); auto result = SetResidentProcessEnabled(bundleName, enable); if (!reply.WriteInt32(result)) { - HILOG_ERROR("Write result failed."); + TAG_LOGE(AAFwkTag::ABILITYMGR, "Write result failed."); return ERR_INVALID_VALUE; } return NO_ERROR; @@ -3847,6 +3917,10 @@ int32_t AbilityManagerStub::TransferAbilityResultForExtensionInner(MessageParcel sptr callerToken = data.ReadRemoteObject(); int32_t resultCode = data.ReadInt32(); sptr want = data.ReadParcelable(); + if (want == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "want is nullptr"); + return ERR_INVALID_VALUE; + } int32_t result = TransferAbilityResultForExtension(callerToken, resultCode, *want); reply.WriteInt32(result); return NO_ERROR; @@ -3860,5 +3934,35 @@ int32_t AbilityManagerStub::NotifyFrozenProcessByRSSInner(MessageParcel &data, M NotifyFrozenProcessByRSS(pidList, uid); return NO_ERROR; } + +int32_t AbilityManagerStub::PreStartMissionInner(MessageParcel &data, MessageParcel &reply) +{ + std::string bundleName = data.ReadString(); + std::string moduleName = data.ReadString(); + std::string abilityName = data.ReadString(); + std::string startTime = data.ReadString(); + int32_t result = PreStartMission(bundleName, moduleName, abilityName, startTime); + reply.WriteInt32(result); + return NO_ERROR; +} + +int32_t AbilityManagerStub::OpenLinkInner(MessageParcel &data, MessageParcel &reply) +{ + sptr want = data.ReadParcelable(); + if (want == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "want is nullptr."); + return ERR_INVALID_VALUE; + } + sptr callerToken = data.ReadRemoteObject(); + int32_t userId = data.ReadInt32(); + int requestCode = data.ReadInt32(); + + int32_t result = OpenLink(*want, callerToken, userId, requestCode); + if (result != NO_ERROR && result != ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "OpenLink failed."); + } + reply.WriteInt32(result); + return result; +} } // 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 a9ee71c9c8..e5cd51c41b 100644 --- a/services/abilitymgr/src/ability_record.cpp +++ b/services/abilitymgr/src/ability_record.cpp @@ -20,6 +20,7 @@ #include #include +#include "constants.h" #include "ability_event_handler.h" #include "ability_manager_service.h" #include "ability_resident_process_rdb.h" @@ -47,6 +48,7 @@ #include "hilog_tag_wrapper.h" #include "os_account_manager_wrapper.h" #include "parameters.h" +#include "ui_service_extension_connection_constants.h" #include "res_sched_util.h" #include "ui_extension_host_info.h" #include "scene_board_judgement.h" @@ -57,6 +59,7 @@ #include "uri_permission_manager_client.h" #include "permission_constants.h" #include "process_options.h" +#include "utils/state_utils.h" #ifdef SUPPORT_GRAPHICS #include "image_source.h" #include "mission_info_mgr.h" @@ -73,6 +76,7 @@ using namespace OHOS::AAFwk::PermissionConstants; const std::string DEBUG_APP = "debugApp"; const std::string NATIVE_DEBUG = "nativeDebug"; const std::string PERF_CMD = "perfCmd"; +const std::string ERROR_INFO_ENHANCE = "errorInfoEnhance"; const std::string MULTI_THREAD = "multiThread"; const std::string DMS_PROCESS_NAME = "distributedsched"; const std::string DMS_MISSION_ID = "dmsMissionId"; @@ -132,47 +136,6 @@ const int SHAREDATA_TIMEOUT_MULTIPLE = 5; const int32_t TYPE_RESERVE = 1; const int32_t TYPE_OTHERS = 2; #endif -const std::map AbilityRecord::stateToStrMap = { - std::map::value_type(INITIAL, "INITIAL"), - std::map::value_type(INACTIVE, "INACTIVE"), - std::map::value_type(ACTIVE, "ACTIVE"), - std::map::value_type(INACTIVATING, "INACTIVATING"), - std::map::value_type(ACTIVATING, "ACTIVATING"), - std::map::value_type(TERMINATING, "TERMINATING"), - std::map::value_type(FOREGROUND, "FOREGROUND"), - std::map::value_type(BACKGROUND, "BACKGROUND"), - std::map::value_type(FOREGROUNDING, "FOREGROUNDING"), - std::map::value_type(BACKGROUNDING, "BACKGROUNDING"), - std::map::value_type(FOREGROUND_FAILED, "FOREGROUND_FAILED"), - std::map::value_type(FOREGROUND_INVALID_MODE, "FOREGROUND_INVALID_MODE"), - std::map::value_type(FOREGROUND_WINDOW_FREEZED, "FOREGROUND_WINDOW_FREEZED"), - std::map::value_type(FOREGROUND_DO_NOTHING, "FOREGROUND_DO_NOTHING"), - std::map::value_type(BACKGROUND_FAILED, "BACKGROUND_FAILED"), -}; -const std::map AbilityRecord::appStateToStrMap_ = { - std::map::value_type(AppState::BEGIN, "BEGIN"), - std::map::value_type(AppState::READY, "READY"), - std::map::value_type(AppState::FOREGROUND, "FOREGROUND"), - std::map::value_type(AppState::BACKGROUND, "BACKGROUND"), - std::map::value_type(AppState::SUSPENDED, "SUSPENDED"), - std::map::value_type(AppState::TERMINATED, "TERMINATED"), - std::map::value_type(AppState::END, "END"), - std::map::value_type(AppState::FOCUS, "FOCUS"), -}; -const std::map AbilityRecord::convertStateMap = { - std::map::value_type(ABILITY_STATE_INITIAL, INITIAL), - std::map::value_type(ABILITY_STATE_INACTIVE, INACTIVE), - std::map::value_type(ABILITY_STATE_ACTIVE, ACTIVE), - std::map::value_type(ABILITY_STATE_FOREGROUND_NEW, FOREGROUND), - std::map::value_type(ABILITY_STATE_BACKGROUND_NEW, BACKGROUND), - std::map::value_type(ABILITY_STATE_FOREGROUND_FAILED, FOREGROUND_FAILED), - std::map::value_type(ABILITY_STATE_INVALID_WINDOW_MODE, - FOREGROUND_INVALID_MODE), - std::map::value_type(ABILITY_STATE_WINDOW_FREEZED, - FOREGROUND_WINDOW_FREEZED), - std::map::value_type(ABILITY_STATE_DO_NOTHING, FOREGROUND_DO_NOTHING), - std::map::value_type(ABILITY_STATE_BACKGROUND_FAILED, BACKGROUND_FAILED), -}; auto g_addLifecycleEventTask = [](sptr token, FreezeUtil::TimeoutState state, std::string &methodName) { CHECK_POINTER_LOG(token, "token is nullptr"); @@ -430,10 +393,6 @@ bool AbilityRecord::CanRestartResident() void AbilityRecord::ForegroundAbility(uint32_t sceneFlag) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - if (GetAbilityVisibilityState() == AbilityVisibilityState::FOREGROUND_HIDE) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Ability visibility state is FOREGROUND_HIDE, should not do foreground again."); - return; - } isWindowStarted_ = true; TAG_LOGI(AAFwkTag::ABILITYMGR, "ForegroundLifecycle: name:%{public}s.", abilityInfo_.name.c_str()); CHECK_POINTER(lifecycleDeal_); @@ -532,6 +491,7 @@ void AbilityRecord::ProcessForegroundAbility(uint32_t tokenId, uint32_t sceneFla std::string bundleName = GetAbilityInfo().bundleName; int32_t uid = GetUid(); ResSchedUtil::GetInstance().ReportEventToRSS(uid, bundleName, "THAW_BY_FOREGROUND_ABILITY"); + SetAbilityStateInner(AbilityState::FOREGROUNDING); DelayedSingleton::GetInstance()->MoveToForeground(token_); } } else { @@ -698,7 +658,13 @@ void AbilityRecord::StartingWindowHot() return; } - auto pixelMap = DelayedSingleton::GetInstance()->GetSnapshot(missionId_); + auto missionListWrap = DelayedSingleton::GetInstance()->GetMissionListWrap(); + if (missionListWrap == nullptr) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListWrap null."); + return; + } + + auto pixelMap = missionListWrap->GetSnapshot(missionId_); if (!pixelMap) { TAG_LOGW(AAFwkTag::ABILITYMGR, "Get snapshot failed."); } @@ -764,9 +730,14 @@ void AbilityRecord::ProcessForegroundAbility(bool isRecent, const AbilityRequest std::shared_ptr AbilityRecord::GetWantFromMission() const { + auto missionListWrap = DelayedSingleton::GetInstance()->GetMissionListWrap(); + if (missionListWrap == nullptr) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListWrap null."); + return nullptr; + } + InnerMissionInfo innerMissionInfo; - int getMission = DelayedSingleton::GetInstance()->GetInnerMissionInfoById( - missionId_, innerMissionInfo); + int getMission = missionListWrap->GetInnerMissionInfoById(missionId_, innerMissionInfo); if (getMission != ERR_OK) { TAG_LOGE( AAFwkTag::ABILITYMGR, "cannot find mission info from MissionInfoList by missionId: %{public}d", missionId_); @@ -1106,7 +1077,13 @@ void AbilityRecord::StartingWindowHot(const std::shared_ptr &start return; } - auto pixelMap = DelayedSingleton::GetInstance()->GetSnapshot(missionId_); + auto missionListWrap = DelayedSingleton::GetInstance()->GetMissionListWrap(); + if (missionListWrap == nullptr) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListWrap null."); + return; + } + + auto pixelMap = missionListWrap->GetSnapshot(missionId_); if (!pixelMap) { TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, Get snapshot failed.", __func__); } @@ -1404,7 +1381,9 @@ void AbilityRecord::SetAbilityStateInner(AbilityState state) } } - DelayedSingleton::GetInstance()->SetMissionAbilityState(missionId_, currentState_); + auto missionListWrap = DelayedSingleton::GetInstance()->GetMissionListWrap(); + CHECK_POINTER(missionListWrap); + missionListWrap->SetMissionAbilityState(missionId_, currentState_); } #endif // SUPPORT_SCREEN bool AbilityRecord::GetAbilityForegroundingFlag() const @@ -1655,14 +1634,46 @@ void AbilityRecord::ConnectAbility() isConnected = true; } +void AbilityRecord::ConnectUIServiceExtAbility(const Want &want) +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, "Connect ability."); + CHECK_POINTER(lifecycleDeal_); + if (isConnected) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "connect state error."); + } +#ifdef SUPPORT_SCREEN + GrantUriPermissionForServiceExtension(); +#endif // SUPPORT_SCREEN + lifecycleDeal_->ConnectAbility(want); + isConnected = true; +} + void AbilityRecord::DisconnectAbility() { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "ability:%{public}s.", abilityInfo_.name.c_str()); CHECK_POINTER(lifecycleDeal_); lifecycleDeal_->DisconnectAbility(GetWant()); - isConnected = false; + if (GetAbilityInfo().extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) { + if (GetInProgressRecordCount() == 0) { + isConnected = false; + } + } else { + isConnected = false; + } } + +void AbilityRecord::DisconnectUIServiceExtAbility(const Want &want) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + TAG_LOGD(AAFwkTag::ABILITYMGR, "ability:%{public}s.", abilityInfo_.name.c_str()); + CHECK_POINTER(lifecycleDeal_); + lifecycleDeal_->DisconnectAbility(want); + if (GetInProgressRecordCount() == 0) { + isConnected = false; + } +} + #ifdef SUPPORT_SCREEN bool AbilityRecord::GrantUriPermissionForServiceExtension() { @@ -1892,8 +1903,7 @@ void SystemAbilityCallerRecord::SendResultToSystemAbility(int requestCode, callerUid = IPCSkeleton::GetCallingUid(); accessToken = IPCSkeleton::GetCallingTokenID(); } - TAG_LOGI(AAFwkTag::ABILITYMGR, "Try to SendResult, callerUid = %{public}d, AccessTokenId = %{public}u", - callerUid, accessToken); + TAG_LOGI(AAFwkTag::ABILITYMGR, "Try to SendResult"); if (callerToken == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "CallerToken is nullptr"); return; @@ -1950,6 +1960,9 @@ void AbilityRecord::RemoveConnectRecordFromList(const std::shared_ptr> AbilityRecord::GetConnectingRecordL return connectingList; } +uint32_t AbilityRecord::GetInProgressRecordCount() +{ + std::lock_guard guard(connRecordListMutex_); + uint32_t count = 0; + for (auto record : connRecordList_) { + if (record && (record->GetConnectState() == ConnectionState::CONNECTING || + record->GetConnectState() == ConnectionState::CONNECTED)) { + count ++; + } + } + return count; +} + std::shared_ptr AbilityRecord::GetDisconnectingRecord() const { std::lock_guard guard(connRecordListMutex_); @@ -2135,29 +2161,17 @@ void AbilityRecord::GetAbilityTypeString(std::string &typeStr) std::string AbilityRecord::ConvertAbilityState(const AbilityState &state) { - auto it = stateToStrMap.find(state); - if (it != stateToStrMap.end()) { - return it->second; - } - return "INVALIDSTATE"; + return StateUtils::StateToStrMap(state); } std::string AbilityRecord::ConvertAppState(const AppState &state) { - auto it = appStateToStrMap_.find(state); - if (it != appStateToStrMap_.end()) { - return it->second; - } - return "INVALIDSTATE"; + return StateUtils::AppStateToStrMap(state); } int AbilityRecord::ConvertLifeCycleToAbilityState(const AbilityLifeCycleState &state) { - auto it = convertStateMap.find(state); - if (it != convertStateMap.end()) { - return it->second; - } - return DEFAULT_INVAL_VALUE; + return StateUtils::ConvertStateMap(state); } void AbilityRecord::Dump(std::vector &info) @@ -2231,8 +2245,7 @@ void AbilityRecord::DumpUIExtensionRootHostInfo(std::vector &info) } UIExtensionHostInfo hostInfo; - auto ret = IN_PROCESS_CALL(DelayedSingleton::GetInstance()->GetUIExtensionRootHostInfo( - token, hostInfo)); + auto ret = IN_PROCESS_CALL(AAFwk::AbilityManagerClient::GetInstance()->GetUIExtensionRootHostInfo(token, hostInfo)); if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Get ui extension host info failed with %{public}d.", ret); return; @@ -2555,6 +2568,7 @@ void AbilityRecord::SetWant(const Want &want) auto nativeDebug = want_.GetBoolParam(NATIVE_DEBUG, false); auto perfCmd = want_.GetStringParam(PERF_CMD); auto multiThread = want_.GetBoolParam(MULTI_THREAD, false); + auto errorInfoEnhance = want_.GetBoolParam(ERROR_INFO_ENHANCE, false); want_.CloseAllFd(); want_ = want; @@ -2570,6 +2584,12 @@ void AbilityRecord::SetWant(const Want &want) if (multiThread) { want_.SetParam(MULTI_THREAD, true); } + if (errorInfoEnhance) { + want_.SetParam(ERROR_INFO_ENHANCE, true); + } + if (want_.HasParameter(UISERVICEHOSTPROXY_KEY)) { + want_.RemoveParam(UISERVICEHOSTPROXY_KEY); + } } Want AbilityRecord::GetWant() const @@ -3085,12 +3105,17 @@ void AbilityRecord::PublishFileOpenEvent(const Want &want) EventFwk::CommonEventPublishInfo commonEventPublishInfo; std::vector subscriberPermissions = {"ohos.permission.MANAGE_LOCAL_ACCOUNTS"}; commonEventPublishInfo.SetSubscriberPermissions(subscriberPermissions); - EventFwk::CommonEventManager::PublishCommonEvent(commonData, commonEventPublishInfo); + IN_PROCESS_CALL(EventFwk::CommonEventManager::PublishCommonEvent(commonData, commonEventPublishInfo)); } } void AbilityRecord::GrantUriPermission(Want &want, std::string targetBundleName, bool isSandboxApp, uint32_t tokenId) { + if (specifyTokenId_ > 0) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "specifyTokenId is %{public}u, cleaned.", specifyTokenId_); + tokenId = specifyTokenId_; + specifyTokenId_ = 0; + } // reject sandbox to grant uri permission by start ability if (!callerList_.empty() && callerList_.back()) { auto caller = callerList_.back()->GetCaller(); @@ -3136,10 +3161,13 @@ void AbilityRecord::GrantUriPermission(Want &want, std::string targetBundleName, void AbilityRecord::GrantUriPermissionInner(Want &want, std::vector &uriVec, const std::string &targetBundleName, uint32_t tokenId) { - auto callerTokenId = specifyTokenId_ > 0 ? specifyTokenId_ : - static_cast(want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId)); - TAG_LOGI(AAFwkTag::ABILITYMGR, "callerTokenId=%{public}u, tokenId=%{public}u, specifyTokenId=%{public}u", - callerTokenId, tokenId, specifyTokenId_); + auto callerTokenId = tokenId > 0 ? tokenId : + static_cast(want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0)); + TAG_LOGI(AAFwkTag::ABILITYMGR, "callerTokenId=%{public}u, tokenId=%{public}u", callerTokenId, tokenId); + if (callerTokenId == 0) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "callerTokenId is invalid."); + return; + } uint32_t flag = want.GetFlags(); std::vector validUriList = {}; for (auto &&uriStr : uriVec) { diff --git a/services/abilitymgr/src/ability_running_info.cpp b/services/abilitymgr/src/ability_running_info.cpp index b911598dc2..96c2799184 100644 --- a/services/abilitymgr/src/ability_running_info.cpp +++ b/services/abilitymgr/src/ability_running_info.cpp @@ -14,7 +14,6 @@ */ #include "ability_running_info.h" -#include "hilog_wrapper.h" #include "nlohmann/json.hpp" #include "string_ex.h" diff --git a/services/abilitymgr/src/ability_scheduler_proxy.cpp b/services/abilitymgr/src/ability_scheduler_proxy.cpp index 97d783b6b5..ccc2667ff3 100644 --- a/services/abilitymgr/src/ability_scheduler_proxy.cpp +++ b/services/abilitymgr/src/ability_scheduler_proxy.cpp @@ -21,7 +21,6 @@ #include "data_ability_predicates.h" #include "data_ability_result.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "ipc_types.h" #include "ishared_result_set.h" @@ -32,6 +31,9 @@ namespace OHOS { namespace AAFwk { +namespace { +const int64_t SCHEDULE_IPC_LOG_TIME = 10000; +} bool AbilitySchedulerProxy::WriteInterfaceToken(MessageParcel &data) { if (!data.WriteInterfaceToken(AbilitySchedulerProxy::GetDescriptor())) { @@ -44,16 +46,24 @@ bool AbilitySchedulerProxy::WriteInterfaceToken(MessageParcel &data) void AbilitySchedulerProxy::ScheduleAbilityTransaction(const Want &want, const LifeCycleStateInfo &stateInfo, sptr sessionInfo) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + TAG_LOGD(AAFwkTag::ABILITYMGR, "begin"); + int64_t start = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); MessageParcel data; MessageParcel reply; MessageOption option(MessageOption::TF_ASYNC); if (!WriteInterfaceToken(data)) { return; } - data.WriteParcelable(&want); + if (!data.WriteParcelable(&want)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "write want failed"); + return; + } data.WriteParcelable(&stateInfo); if (sessionInfo) { if (!data.WriteBool(true) || !data.WriteParcelable(sessionInfo)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "write sessionInfo failed"); return; } } else { @@ -65,6 +75,17 @@ void AbilitySchedulerProxy::ScheduleAbilityTransaction(const Want &want, const L if (err != NO_ERROR) { TAG_LOGE(AAFwkTag::ABILITYMGR, "ScheduleAbilityTransaction fail to SendRequest. err: %{public}d", err); } + int64_t cost = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count() - start; + if (cost > SCHEDULE_IPC_LOG_TIME) { + TAG_LOGI(AAFwkTag::ABILITYMGR, + "ScheduleAbilityTransaction proxy cost %{public}" PRId64 "mirco seconds, data size: %{public}zu", + cost, data.GetWritePosition()); + } else { + TAG_LOGD(AAFwkTag::ABILITYMGR, + "ScheduleAbilityTransaction proxy cost %{public}" PRId64 "mirco seconds, data size: %{public}zu", + cost, data.GetWritePosition()); + } } void AbilitySchedulerProxy::ScheduleShareData(const int32_t &uniqueId) diff --git a/services/abilitymgr/src/ability_scheduler_stub.cpp b/services/abilitymgr/src/ability_scheduler_stub.cpp index 17d45bbdfa..b293d92489 100644 --- a/services/abilitymgr/src/ability_scheduler_stub.cpp +++ b/services/abilitymgr/src/ability_scheduler_stub.cpp @@ -22,7 +22,6 @@ #include "data_ability_predicates.h" #include "data_ability_result.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "ishared_result_set.h" #include "pac_map.h" diff --git a/services/abilitymgr/src/ability_token_stub.cpp b/services/abilitymgr/src/ability_token_stub.cpp index a86d518107..1930f0fdd9 100644 --- a/services/abilitymgr/src/ability_token_stub.cpp +++ b/services/abilitymgr/src/ability_token_stub.cpp @@ -17,7 +17,6 @@ #include "ability_token_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/acquire_share_data_callback_proxy.cpp b/services/abilitymgr/src/acquire_share_data_callback_proxy.cpp index e2eab82ce3..576247fafe 100644 --- a/services/abilitymgr/src/acquire_share_data_callback_proxy.cpp +++ b/services/abilitymgr/src/acquire_share_data_callback_proxy.cpp @@ -16,7 +16,6 @@ #include "ability_manager_errors.h" #include "acquire_share_data_callback_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "message_parcel.h" #include "peer_holder.h" diff --git a/services/abilitymgr/src/acquire_share_data_callback_stub.cpp b/services/abilitymgr/src/acquire_share_data_callback_stub.cpp index ceddd2bd1a..59fb67d4ca 100644 --- a/services/abilitymgr/src/acquire_share_data_callback_stub.cpp +++ b/services/abilitymgr/src/acquire_share_data_callback_stub.cpp @@ -15,17 +15,12 @@ #include "acquire_share_data_callback_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "message_parcel.h" namespace OHOS { namespace AAFwk { -AcquireShareDataCallbackStub::AcquireShareDataCallbackStub() -{ - vecMemberFunc_.resize(IAcquireShareDataCallback::CODE_MAX); - vecMemberFunc_[ACQUIRE_SHARE_DATA_DONE] = &AcquireShareDataCallbackStub::AcquireShareDataDoneInner; -} +AcquireShareDataCallbackStub::AcquireShareDataCallbackStub() {} AcquireShareDataCallbackStub::~AcquireShareDataCallbackStub() { @@ -43,8 +38,9 @@ int32_t AcquireShareDataCallbackStub::OnRemoteRequest( } if (code < IAcquireShareDataCallback::CODE_MAX) { - auto memberFunc = vecMemberFunc_[code]; - return (this->*memberFunc)(data, reply); + if (code == ACQUIRE_SHARE_DATA_DONE) { + return AcquireShareDataDoneInner(data, reply); + } } return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/services/abilitymgr/src/ag_convert_callback_impl.cpp b/services/abilitymgr/src/ag_convert_callback_impl.cpp new file mode 100644 index 0000000000..cb6cfc2317 --- /dev/null +++ b/services/abilitymgr/src/ag_convert_callback_impl.cpp @@ -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. + */ + +#include "ag_convert_callback_impl.h" + +#include + +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace AAFwk { +void ConvertCallbackImpl::OnConvert(int resultCode, AAFwk::Want& want) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "called"); + std::unique_lock lock(taskMutex_); + if (task_) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "resultCode:%{public}d", resultCode); + task_(resultCode, want); + } +} + +void ConvertCallbackImpl::Cancel() +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "called"); + std::unique_lock lock(taskMutex_); + task_ = nullptr; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/ams_configuration_parameter.cpp b/services/abilitymgr/src/ams_configuration_parameter.cpp index 10a40e1f02..014e6b39a6 100644 --- a/services/abilitymgr/src/ams_configuration_parameter.cpp +++ b/services/abilitymgr/src/ams_configuration_parameter.cpp @@ -18,7 +18,6 @@ #include "app_utils.h" #include "config_policy_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/app_exit_reason_data_manager.cpp b/services/abilitymgr/src/app_exit_reason_data_manager.cpp index 6c24d6ba23..35c17c0cfb 100644 --- a/services/abilitymgr/src/app_exit_reason_data_manager.cpp +++ b/services/abilitymgr/src/app_exit_reason_data_manager.cpp @@ -23,7 +23,6 @@ #include "accesstoken_kit.h" #include "errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "nlohmann/json.hpp" #include "os_account_manager_wrapper.h" @@ -95,7 +94,7 @@ int32_t AppExitReasonDataManager::SetAppExitReason(const std::string &bundleName const std::vector &abilityList, const AAFwk::ExitReason &exitReason) { auto accessTokenIdStr = std::to_string(accessTokenId); - if (bundleName.empty() || accessTokenIdStr.empty()) { + if (bundleName.empty() || accessTokenId == Security::AccessToken::INVALID_TOKENID) { TAG_LOGW(AAFwkTag::ABILITYMGR, "invalid value"); return ERR_INVALID_VALUE; } @@ -124,7 +123,8 @@ int32_t AppExitReasonDataManager::SetAppExitReason(const std::string &bundleName return ERR_OK; } -int32_t AppExitReasonDataManager::DeleteAppExitReason(const std::string &bundleName, int32_t uid) + +int32_t AppExitReasonDataManager::DeleteAppExitReason(const std::string &bundleName, int32_t uid, int32_t appIndex) { int32_t userId; if (DelayedSingleton::GetInstance()-> @@ -132,9 +132,14 @@ int32_t AppExitReasonDataManager::DeleteAppExitReason(const std::string &bundleN TAG_LOGE(AAFwkTag::ABILITYMGR, "Get GetOsAccountLocalIdFromUid failed."); return ERR_INVALID_VALUE; } - uint32_t accessTokenId = Security::AccessToken::AccessTokenKit::GetHapTokenID(userId, bundleName, 0); + uint32_t accessTokenId = Security::AccessToken::AccessTokenKit::GetHapTokenID(userId, bundleName, appIndex); + return DeleteAppExitReason(bundleName, accessTokenId); +} + +int32_t AppExitReasonDataManager::DeleteAppExitReason(const std::string &bundleName, uint32_t accessTokenId) +{ auto accessTokenIdStr = std::to_string(accessTokenId); - if (bundleName.empty() || accessTokenIdStr.empty()) { + if (bundleName.empty() || accessTokenId == Security::AccessToken::INVALID_TOKENID) { TAG_LOGW(AAFwkTag::ABILITYMGR, "invalid value."); return ERR_INVALID_VALUE; } @@ -178,7 +183,7 @@ int32_t AppExitReasonDataManager::GetAppExitReason(const std::string &bundleName const std::string &abilityName, bool &isSetReason, AAFwk::ExitReason &exitReason) { auto accessTokenIdStr = std::to_string(accessTokenId); - if (bundleName.empty() || accessTokenIdStr.empty()) { + if (bundleName.empty() || accessTokenId == Security::AccessToken::INVALID_TOKENID) { TAG_LOGW(AAFwkTag::ABILITYMGR, "invalid value!"); return ERR_INVALID_VALUE; } @@ -507,7 +512,7 @@ int32_t AppExitReasonDataManager::GetAbilitySessionId(uint32_t accessTokenId, int32_t AppExitReasonDataManager::SetUIExtensionAbilityExitReason( const std::string &bundleName, const std::vector &extensionList, const AAFwk::ExitReason &exitReason) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (bundleName.empty()) { TAG_LOGW(AAFwkTag::ABILITYMGR, "Invalid bundle name."); return ERR_INVALID_VALUE; @@ -542,7 +547,7 @@ int32_t AppExitReasonDataManager::SetUIExtensionAbilityExitReason( bool AppExitReasonDataManager::GetUIExtensionAbilityExitReason(const std::string &keyEx, AAFwk::ExitReason &exitReason) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); { std::lock_guard lock(kvStorePtrMutex_); if (!CheckKvStore()) { @@ -670,7 +675,7 @@ DistributedKv::Key AppExitReasonDataManager::GetAbilityRecoverInfoKey(uint32_t a DistributedKv::Value AppExitReasonDataManager::ConvertAppExitReasonInfoToValueOfExtensionName( const std::string &extensionListName, const AAFwk::ExitReason &exitReason) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); std::chrono::milliseconds nowMs = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()); nlohmann::json jsonObject = nlohmann::json { diff --git a/services/abilitymgr/src/app_exit_reason_helper.cpp b/services/abilitymgr/src/app_exit_reason_helper.cpp index b5608752fe..2098f8d3bf 100644 --- a/services/abilitymgr/src/app_exit_reason_helper.cpp +++ b/services/abilitymgr/src/app_exit_reason_helper.cpp @@ -26,7 +26,6 @@ #include "bundle_constants.h" #include "bundle_mgr_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "os_account_manager_wrapper.h" #include "scene_board_judgement.h" @@ -66,14 +65,15 @@ int32_t AppExitReasonHelper::RecordAppExitReason(const ExitReason &exitReason) CHECK_POINTER_AND_RETURN(subManagersHelper_, ERR_NULL_OBJECT); std::vector abilityList; + auto uid = IPCSkeleton::GetCallingUid(); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto uiAbilityManager = subManagersHelper_->GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid()); + auto uiAbilityManager = subManagersHelper_->GetUIAbilityManagerByUid(uid); CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_NULL_OBJECT); - uiAbilityManager->GetActiveAbilityList(bundleName, abilityList); + uiAbilityManager->GetActiveAbilityList(uid, abilityList); } else { - auto missionListManager = subManagersHelper_->GetMissionListManagerByUid(IPCSkeleton::GetCallingUid()); + auto missionListManager = subManagersHelper_->GetMissionListManagerByUid(uid); CHECK_POINTER_AND_RETURN(missionListManager, ERR_NULL_OBJECT); - missionListManager->GetActiveAbilityList(bundleName, abilityList); + missionListManager->GetActiveAbilityList(uid, abilityList); } ret = DelayedSingleton::GetInstance()->NotifyAppMgrRecordExitReason(pid, exitReason.reason, @@ -109,7 +109,7 @@ int32_t AppExitReasonHelper::RecordProcessExitReason(const int32_t pid, const Ex return RecordProcessExitReason(pid, bundleName, application.uid, application.accessTokenId, exitReason); } -int32_t AppExitReasonHelper::RecordProcessExitReason(const std::string &bundleName, int32_t uid, +int32_t AppExitReasonHelper::RecordAppExitReason(const std::string &bundleName, int32_t uid, int32_t appIndex, const ExitReason &exitReason) { int32_t userId; @@ -118,7 +118,7 @@ int32_t AppExitReasonHelper::RecordProcessExitReason(const std::string &bundleNa TAG_LOGE(AAFwkTag::ABILITYMGR, "Get GetOsAccountLocalIdFromUid failed."); return ERR_INVALID_VALUE; } - uint32_t accessTokenId = Security::AccessToken::AccessTokenKit::GetHapTokenID(userId, bundleName, 0); + uint32_t accessTokenId = Security::AccessToken::AccessTokenKit::GetHapTokenID(userId, bundleName, appIndex); return RecordProcessExitReason(NO_PID, bundleName, uid, accessTokenId, exitReason); } @@ -138,11 +138,9 @@ int32_t AppExitReasonHelper::RecordProcessExitReason(const int32_t pid, const st } std::vector abilityLists; if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - GetActiveAbilityListFromUIAabilityManager(bundleName, abilityLists, targetUserId, pid); - } else if (targetUserId == U0_USER_ID) { - GetActiveAbilityListByU0(bundleName, abilityLists, pid); - } else { - GetActiveAbilityListByUser(bundleName, abilityLists, targetUserId, pid); + GetActiveAbilityListFromUIAbilityManager(uid, abilityLists, pid); + } else { + GetActiveAbilityList(uid, abilityLists, pid); } auto ret = DelayedSingleton::GetInstance()->NotifyAppMgrRecordExitReason(pid, exitReason.reason, @@ -162,7 +160,7 @@ int32_t AppExitReasonHelper::RecordProcessExitReason(const int32_t pid, const st int32_t AppExitReasonHelper::RecordProcessExtensionExitReason( const int32_t pid, const std::string &bundleName, const ExitReason &exitReason) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); CHECK_POINTER_AND_RETURN(subManagersHelper_, ERR_NULL_OBJECT); auto connectManager = subManagersHelper_->GetCurrentConnectManager(); CHECK_POINTER_AND_RETURN(connectManager, ERR_NULL_OBJECT); @@ -192,55 +190,66 @@ int32_t AppExitReasonHelper::RecordProcessExtensionExitReason( return appExitReasonDataMgr->SetUIExtensionAbilityExitReason(bundleName, extensionList, exitReason); } -void AppExitReasonHelper::GetActiveAbilityListByU0(const std::string bundleName, - std::vector &abilityLists, const int32_t pid) +void AppExitReasonHelper::GetActiveAbilityList(int32_t uid, std::vector &abilityLists, + const int32_t pid) { - CHECK_POINTER(subManagersHelper_); - auto missionListManagers = subManagersHelper_->GetMissionListManagers(); - for (auto& item: missionListManagers) { - if (!item.second) { - continue; - } - std::vector abilityList; - item.second->GetActiveAbilityList(bundleName, abilityList, pid); - if (!abilityList.empty()) { - abilityLists.insert(abilityLists.end(), abilityList.begin(), abilityList.end()); - } + int32_t targetUserId; + if (DelayedSingleton::GetInstance()-> + GetOsAccountLocalIdFromUid(uid, targetUserId) != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Get GetOsAccountLocalIdFromUid failed."); + return; } + CHECK_POINTER(subManagersHelper_); + if (targetUserId == U0_USER_ID) { + auto missionListManagers = subManagersHelper_->GetMissionListManagers(); + for (auto& item: missionListManagers) { + CHECK_POINTER_CONTINUE(item.second); + std::vector abilityList; + item.second->GetActiveAbilityList(uid, abilityList, pid); + if (!abilityList.empty()) { + abilityLists.insert(abilityLists.end(), abilityList.begin(), abilityList.end()); + } + } + return; + } + + auto listManager = subManagersHelper_->GetMissionListManagerByUserId(targetUserId); + CHECK_POINTER(listManager); + listManager->GetActiveAbilityList(uid, abilityLists, pid); } -void AppExitReasonHelper::GetActiveAbilityListByUser(const std::string bundleName, - std::vector &abilityLists, const int32_t targetUserId, const int32_t pid) +void AppExitReasonHelper::GetActiveAbilityListFromUIAbilityManager(int32_t uid, std::vector &abilityLists, + const int32_t pid) { CHECK_POINTER(subManagersHelper_); - auto listManager = subManagersHelper_->GetMissionListManagerByUserId(targetUserId); - if (listManager) { - listManager->GetActiveAbilityList(bundleName, abilityLists, pid); + int32_t targetUserId; + if (DelayedSingleton::GetInstance()-> + GetOsAccountLocalIdFromUid(uid, targetUserId) != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Get GetOsAccountLocalIdFromUid failed."); + return; } + if (targetUserId == U0_USER_ID) { + auto uiAbilityManagers = subManagersHelper_->GetUIAbilityManagers(); + for (auto& item: uiAbilityManagers) { + CHECK_POINTER_CONTINUE(item.second); + std::vector abilityList; + item.second->GetActiveAbilityList(uid, abilityList, pid); + if (!abilityList.empty()) { + abilityLists.insert(abilityLists.end(), abilityList.begin(), abilityList.end()); + } + } + return; + } + + auto uiAbilityManager = subManagersHelper_->GetUIAbilityManagerByUserId(targetUserId); + CHECK_POINTER(uiAbilityManager); + uiAbilityManager->GetActiveAbilityList(uid, abilityLists, pid); } bool AppExitReasonHelper::IsExitReasonValid(const ExitReason &exitReason) { const Reason reason = exitReason.reason; - return reason >= REASON_MIN || reason <= REASON_MAX; -} - -void AppExitReasonHelper::GetActiveAbilityListFromUIAabilityManager(const std::string bundleName, - std::vector &abilityLists, const int32_t targetUserId, const int32_t pid) -{ - CHECK_POINTER(subManagersHelper_); - if (targetUserId == U0_USER_ID) { - auto uiAbilityManagers = subManagersHelper_->GetUIAbilityManagers(); - for (auto& item: uiAbilityManagers) { - if (item.second) { - item.second->GetActiveAbilityList(bundleName, abilityLists, pid); - } - } - } else { - auto uiAbilityManager = subManagersHelper_->GetUIAbilityManagerByUserId(targetUserId); - CHECK_POINTER(uiAbilityManager); - uiAbilityManager->GetActiveAbilityList(bundleName, abilityLists, pid); - } + return reason >= REASON_MIN && reason <= REASON_MAX; } } // namespace AppExecFwk } // namespace OHOS diff --git a/services/abilitymgr/src/app_recovery/default_recovery_config.cpp b/services/abilitymgr/src/app_recovery/default_recovery_config.cpp index 964dfb3fe0..bcab228543 100755 --- a/services/abilitymgr/src/app_recovery/default_recovery_config.cpp +++ b/services/abilitymgr/src/app_recovery/default_recovery_config.cpp @@ -21,7 +21,6 @@ #include "config_policy_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/services/abilitymgr/src/app_scheduler.cpp b/services/abilitymgr/src/app_scheduler.cpp index 9238942850..c7d868f8c8 100644 --- a/services/abilitymgr/src/app_scheduler.cpp +++ b/services/abilitymgr/src/app_scheduler.cpp @@ -22,7 +22,6 @@ #include "appmgr/app_mgr_constants.h" #include "hitrace_meter.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "in_process_call_wrapper.h" namespace OHOS { @@ -259,6 +258,20 @@ int AppScheduler::KillApplication(const std::string &bundleName, const bool clea return ERR_OK; } +int AppScheduler::ForceKillApplication(const std::string &bundleName, + const int userId, const int appIndex) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "Called."); + CHECK_POINTER_AND_RETURN(appMgrClient_, INNER_ERR); + int ret = (int)appMgrClient_->ForceKillApplication(bundleName, userId, appIndex); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Fail to force kill application."); + return INNER_ERR; + } + + return ERR_OK; +} + int AppScheduler::KillApplicationByUid(const std::string &bundleName, int32_t uid) { TAG_LOGI(AAFwkTag::ABILITYMGR, "[%{public}s(%{public}s)] enter", __FILE__, __FUNCTION__); @@ -278,10 +291,10 @@ void AppScheduler::AttachTimeOut(const sptr &token) IN_PROCESS_CALL_WITHOUT_RET(appMgrClient_->AbilityAttachTimeOut(token)); } -void AppScheduler::PrepareTerminate(const sptr &token) +void AppScheduler::PrepareTerminate(const sptr &token, bool clearMissionFlag) { CHECK_POINTER(appMgrClient_); - IN_PROCESS_CALL_WITHOUT_RET(appMgrClient_->PrepareTerminate(token)); + IN_PROCESS_CALL_WITHOUT_RET(appMgrClient_->PrepareTerminate(token, clearMissionFlag)); } void AppScheduler::OnAppStateChanged(const AppExecFwk::AppProcessData &appData) @@ -601,5 +614,21 @@ void AppScheduler::AttachedToStatusBar(const sptr &token) CHECK_POINTER(appMgrClient_); appMgrClient_->AttachedToStatusBar(token); } + +void AppScheduler::BlockProcessCacheByPids(const std::vector &pids) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "called."); + CHECK_POINTER(appMgrClient_); + appMgrClient_->BlockProcessCacheByPids(pids); +} + +bool AppScheduler::IsKilledForUpgradeWeb(const std::string &bundleName) +{ + if (!appMgrClient_) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "appMgrClient is nullptr"); + return false; + } + return appMgrClient_->IsKilledForUpgradeWeb(bundleName); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/assert_fault_callback_death_mgr.cpp b/services/abilitymgr/src/assert_fault_callback_death_mgr.cpp index c9d92d6913..53e3cc9cfb 100644 --- a/services/abilitymgr/src/assert_fault_callback_death_mgr.cpp +++ b/services/abilitymgr/src/assert_fault_callback_death_mgr.cpp @@ -16,7 +16,6 @@ #include "app_scheduler.h" #include "assert_fault_callback_death_mgr.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "in_process_call_wrapper.h" @@ -37,7 +36,7 @@ AssertFaultCallbackDeathMgr::~AssertFaultCallbackDeathMgr() void AssertFaultCallbackDeathMgr::AddAssertFaultCallback(sptr &remote, CallbackTask callback) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (remote == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Params remote is nullptr."); @@ -69,7 +68,7 @@ void AssertFaultCallbackDeathMgr::AddAssertFaultCallback(sptr &re void AssertFaultCallbackDeathMgr::RemoveAssertFaultCallback(const wptr &remote, bool isCallbackDeath) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto callback = remote.promote(); if (callback == nullptr) { @@ -99,7 +98,7 @@ void AssertFaultCallbackDeathMgr::RemoveAssertFaultCallback(const wptr ModalSystemAssertUIEx bool ModalSystemAssertUIExtension::CreateModalUIExtension(const AAFwk::Want &want) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); std::unique_lock lockAssertResult(assertResultMutex_); if (reqeustCount_++ != 0) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Task busy, waiting for processing."); @@ -109,9 +109,9 @@ bool ModalSystemAssertUIExtension::CreateModalUIExtension(const AAFwk::Want &wan return false; } callback->SetReqeustAssertDialogWant(want); - auto abilityMs = DelayedSingleton::GetInstance(); - if (abilityMs == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectSystemUi abilityMs is nullptr"); + auto abilityManagerClient = AAFwk::AbilityManagerClient::GetInstance(); + if (abilityManagerClient == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectSystemUi AbilityManagerClient is nullptr"); TryNotifyOneWaitingThread(); return false; } @@ -121,7 +121,7 @@ bool ModalSystemAssertUIExtension::CreateModalUIExtension(const AAFwk::Want &wan } else { systemUIWant.SetElementName("com.ohos.systemui", "com.ohos.systemui.dialog"); } - auto result = abilityMs->ConnectAbility(systemUIWant, callback, nullptr, INVALID_USERID); + 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(); @@ -132,12 +132,12 @@ bool ModalSystemAssertUIExtension::CreateModalUIExtension(const AAFwk::Want &wan bool ModalSystemAssertUIExtension::DisconnectSystemUI() { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); bool retVal = true; do { - auto abilityMs = DelayedSingleton::GetInstance(); - if (abilityMs == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityMs is nullptr"); + auto abilityManagerClient = AAFwk::AbilityManagerClient::GetInstance(); + if (abilityManagerClient == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerClient is nullptr"); retVal = false; break; } @@ -147,7 +147,7 @@ bool ModalSystemAssertUIExtension::DisconnectSystemUI() retVal = false; break; } - auto result = abilityMs->DisconnectAbility(callback); + auto result = abilityManagerClient->DisconnectAbility(callback); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "DisconnectAbility dialog failed, result = %{public}d", result); retVal = false; @@ -189,7 +189,7 @@ void ModalSystemAssertUIExtension::AssertDialogConnection::SetReqeustAssertDialo void ModalSystemAssertUIExtension::AssertDialogConnection::OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remote, int resultCode) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (remote == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Input remote object is nullptr."); return; @@ -223,7 +223,7 @@ void ModalSystemAssertUIExtension::AssertDialogConnection::OnAbilityConnectDone( void ModalSystemAssertUIExtension::AssertDialogConnection::OnAbilityDisconnectDone( const AppExecFwk::ElementName &element, int resultCode) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); ModalSystemAssertUIExtension::GetInstance().TryNotifyOneWaitingThread(); } } // namespace AbilityRuntime diff --git a/services/abilitymgr/src/atomic_service_status_callback.cpp b/services/abilitymgr/src/atomic_service_status_callback.cpp index 346dec3741..d3dc914271 100644 --- a/services/abilitymgr/src/atomic_service_status_callback.cpp +++ b/services/abilitymgr/src/atomic_service_status_callback.cpp @@ -17,12 +17,12 @@ #include "ability_util.h" #include "free_install_manager.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { -AtomicServiceStatusCallback::AtomicServiceStatusCallback(const std::weak_ptr &server, bool isAsync) - : server_(server), isAsync_(isAsync) +AtomicServiceStatusCallback::AtomicServiceStatusCallback( + const std::weak_ptr &server, bool isAsync, int32_t recordId) + : server_(server), isAsync_(isAsync), recordId_(recordId) { } @@ -30,21 +30,14 @@ void AtomicServiceStatusCallback::OnInstallFinished(int resultCode, const Want & { auto server = server_.lock(); CHECK_POINTER(server); - server->OnInstallFinished(resultCode, want, userId, isAsync_); + server->OnInstallFinished(recordId_, resultCode, want, userId, isAsync_); } void AtomicServiceStatusCallback::OnRemoteInstallFinished(int resultCode, const Want &want, int32_t userId) { auto server = server_.lock(); CHECK_POINTER(server); - server->OnRemoteInstallFinished(resultCode, want, userId); -} - -void AtomicServiceStatusCallback::OnRemoveTimeoutTask(const Want &want) -{ - auto server = server_.lock(); - CHECK_POINTER(server); - server->OnRemoveTimeoutTask(want); + server->OnRemoteInstallFinished(recordId_, resultCode, want, userId); } } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/atomic_service_status_callback_proxy.cpp b/services/abilitymgr/src/atomic_service_status_callback_proxy.cpp index 67c076a4df..d30cdf5e9c 100644 --- a/services/abilitymgr/src/atomic_service_status_callback_proxy.cpp +++ b/services/abilitymgr/src/atomic_service_status_callback_proxy.cpp @@ -16,7 +16,6 @@ #include "atomic_service_status_callback_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" @@ -95,29 +94,6 @@ void AtomicServiceStatusCallbackProxy::OnRemoteInstallFinished(int resultCode, c } } -void AtomicServiceStatusCallbackProxy::OnRemoveTimeoutTask(const Want &want) -{ - MessageParcel data; - MessageParcel reply; - MessageOption option; - - if (!data.WriteInterfaceToken(IAtomicServiceStatusCallback::GetDescriptor())) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Write interface token failed."); - return; - } - - if (!data.WriteParcelable(&want)) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Write want error."); - return; - } - - int32_t error = SendTransactCmd(ON_REMOVE_TIMEOUT_TASK, data, reply, option); - if (error != NO_ERROR) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "OnFinished fail, error: %{public}d", error); - return; - } -} - int32_t AtomicServiceStatusCallbackProxy::SendTransactCmd(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { diff --git a/services/abilitymgr/src/atomic_service_status_callback_stub.cpp b/services/abilitymgr/src/atomic_service_status_callback_stub.cpp index 18d866353f..144350fa84 100644 --- a/services/abilitymgr/src/atomic_service_status_callback_stub.cpp +++ b/services/abilitymgr/src/atomic_service_status_callback_stub.cpp @@ -17,22 +17,12 @@ #include "ability_manager_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" namespace OHOS { namespace AAFwk { -AtomicServiceStatusCallbackStub::AtomicServiceStatusCallbackStub() -{ - vecMemberFunc_.resize(IAtomicServiceStatusCallbackCmd::CMD_MAX); - vecMemberFunc_[IAtomicServiceStatusCallbackCmd::ON_FREE_INSTALL_DONE] = - &AtomicServiceStatusCallbackStub::OnInstallFinishedInner; - vecMemberFunc_[IAtomicServiceStatusCallbackCmd::ON_REMOTE_FREE_INSTALL_DONE] = - &AtomicServiceStatusCallbackStub::OnRemoteInstallFinishedInner; - vecMemberFunc_[IAtomicServiceStatusCallbackCmd::ON_REMOVE_TIMEOUT_TASK] = - &AtomicServiceStatusCallbackStub::OnRemoveTimeoutTaskInner; -} +AtomicServiceStatusCallbackStub::AtomicServiceStatusCallbackStub() {} int AtomicServiceStatusCallbackStub::OnInstallFinishedInner(MessageParcel &data, MessageParcel &reply) { @@ -63,18 +53,6 @@ int AtomicServiceStatusCallbackStub::OnRemoteInstallFinishedInner(MessageParcel return NO_ERROR; } -int AtomicServiceStatusCallbackStub::OnRemoveTimeoutTaskInner(MessageParcel &data, MessageParcel &reply) -{ - std::unique_ptr want(data.ReadParcelable()); - if (want == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "AtomicServiceStatusCallbackStub want is nullptr."); - return ERR_INVALID_VALUE; - } - - OnRemoveTimeoutTask(*want); - return NO_ERROR; -} - int AtomicServiceStatusCallbackStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -86,8 +64,14 @@ int AtomicServiceStatusCallbackStub::OnRemoteRequest( } if (code < IAtomicServiceStatusCallbackCmd::CMD_MAX && code >= 0) { - auto memberFunc = vecMemberFunc_[code]; - return (this->*memberFunc)(data, reply); + switch (code) { + case IAtomicServiceStatusCallbackCmd::ON_FREE_INSTALL_DONE: + return OnInstallFinishedInner(data, reply); + break; + case IAtomicServiceStatusCallbackCmd::ON_REMOTE_FREE_INSTALL_DONE: + return OnRemoteInstallFinishedInner(data, reply); + break; + } } return IPCObjectStub::OnRemoteRequest(code, data, reply, option); diff --git a/services/abilitymgr/src/background_task_observer.cpp b/services/abilitymgr/src/background_task_observer.cpp index 646415e439..2d4b4fb5e9 100644 --- a/services/abilitymgr/src/background_task_observer.cpp +++ b/services/abilitymgr/src/background_task_observer.cpp @@ -15,7 +15,6 @@ #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE #include "background_task_observer.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include #include "sa_mgr_client.h" #include "system_ability_definition.h" diff --git a/services/abilitymgr/src/call_container.cpp b/services/abilitymgr/src/call_container.cpp index c9341e5763..ae659dd19c 100644 --- a/services/abilitymgr/src/call_container.cpp +++ b/services/abilitymgr/src/call_container.cpp @@ -16,7 +16,6 @@ #include "call_container.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ability_manager_errors.h" #include "ability_connect_callback_stub.h" #include "ability_util.h" diff --git a/services/abilitymgr/src/call_record.cpp b/services/abilitymgr/src/call_record.cpp index 604cf7dc4c..af2f42223b 100644 --- a/services/abilitymgr/src/call_record.cpp +++ b/services/abilitymgr/src/call_record.cpp @@ -16,7 +16,6 @@ #include "call_record.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ability_util.h" #include "ability_manager_service.h" #include "ability_record.h" diff --git a/services/abilitymgr/src/caller_info.cpp b/services/abilitymgr/src/caller_info.cpp index fe858ab9dd..bfcd9044dd 100644 --- a/services/abilitymgr/src/caller_info.cpp +++ b/services/abilitymgr/src/caller_info.cpp @@ -16,7 +16,6 @@ #include "caller_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "nlohmann/json.hpp" #include "string_ex.h" diff --git a/services/abilitymgr/src/connection_observer_controller.cpp b/services/abilitymgr/src/connection_observer_controller.cpp index 3f6cff377a..52cbe86dab 100644 --- a/services/abilitymgr/src/connection_observer_controller.cpp +++ b/services/abilitymgr/src/connection_observer_controller.cpp @@ -17,7 +17,6 @@ #include "connection_observer_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/connection_record.cpp b/services/abilitymgr/src/connection_record.cpp index 1ef70860ac..b2f936688c 100644 --- a/services/abilitymgr/src/connection_record.cpp +++ b/services/abilitymgr/src/connection_record.cpp @@ -20,7 +20,7 @@ #include "ability_util.h" #include "connection_state_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" +#include "ui_service_extension_connection_constants.h" namespace OHOS { namespace AAFwk { @@ -99,7 +99,9 @@ int ConnectionRecord::DisconnectAbility() SetConnectState(ConnectionState::DISCONNECTING); CHECK_POINTER_AND_RETURN(targetService_, ERR_INVALID_VALUE); std::size_t connectNums = targetService_->GetConnectRecordList().size(); - if (connectNums == 1) { + AppExecFwk::ExtensionAbilityType extAbilityType = targetService_->GetAbilityInfo().extensionAbilityType; + bool isAbilityUIServiceExt = (extAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE); + if (connectNums == 1 || isAbilityUIServiceExt) { /* post timeout task to taskhandler */ auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); if (handler == nullptr) { @@ -116,7 +118,12 @@ int ConnectionRecord::DisconnectAbility() handler->SubmitTask(disconnectTask, taskName, disconnectTimeout); } /* schedule disconnect to target ability */ - targetService_->DisconnectAbility(); + if (isAbilityUIServiceExt) { + TAG_LOGI(AAFwkTag::CONNECTION, "Disconnect UIServiceExtension ability, set correct want"); + targetService_->DisconnectUIServiceExtAbility(GetConnectWant()); + } else { + targetService_->DisconnectAbility(); + } } else { TAG_LOGD(AAFwkTag::CONNECTION, "The current connection count is %{public}zu, no need to disconnect, just remove connection.", connectNums); @@ -205,7 +212,7 @@ void ConnectionRecord::ScheduleDisconnectAbilityDone() handler->CancelTask(taskName); } - CompleteDisconnect(ERR_OK, false); + CompleteDisconnect(ERR_OK, GetAbilityConnectCallback() == nullptr); } void ConnectionRecord::ScheduleConnectAbilityDone() @@ -318,5 +325,15 @@ sptr ConnectionRecord::GetConnection() const return callback->AsObject(); } + +void ConnectionRecord::SetConnectWant(const Want &want) +{ + connectWant_ = want; +} + +Want ConnectionRecord::GetConnectWant() +{ + return connectWant_; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/connection_state_item.cpp b/services/abilitymgr/src/connection_state_item.cpp index 9064030822..3b2cee90b3 100644 --- a/services/abilitymgr/src/connection_state_item.cpp +++ b/services/abilitymgr/src/connection_state_item.cpp @@ -16,7 +16,6 @@ #include "connection_state_item.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/connection_state_manager.cpp b/services/abilitymgr/src/connection_state_manager.cpp index 7489c2d1fb..790d5315a3 100644 --- a/services/abilitymgr/src/connection_state_manager.cpp +++ b/services/abilitymgr/src/connection_state_manager.cpp @@ -21,7 +21,6 @@ #include "connection_observer_errors.h" #include "global_constant.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "system_ability_definition.h" diff --git a/services/abilitymgr/src/data_ability_caller_recipient.cpp b/services/abilitymgr/src/data_ability_caller_recipient.cpp index 8a101619df..bfa0d63743 100644 --- a/services/abilitymgr/src/data_ability_caller_recipient.cpp +++ b/services/abilitymgr/src/data_ability_caller_recipient.cpp @@ -15,7 +15,6 @@ #include "data_ability_caller_recipient.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/data_ability_manager.cpp b/services/abilitymgr/src/data_ability_manager.cpp index 6d61a7d52a..24d0cd9506 100644 --- a/services/abilitymgr/src/data_ability_manager.cpp +++ b/services/abilitymgr/src/data_ability_manager.cpp @@ -23,7 +23,6 @@ #include "ability_util.h" #include "connection_state_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/data_ability_record.cpp b/services/abilitymgr/src/data_ability_record.cpp index 12bb7e70ef..ae9355dd52 100644 --- a/services/abilitymgr/src/data_ability_record.cpp +++ b/services/abilitymgr/src/data_ability_record.cpp @@ -22,7 +22,6 @@ #include "app_scheduler.h" #include "connection_state_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/deeplink_reserve/deeplink_reserve_config.cpp b/services/abilitymgr/src/deeplink_reserve/deeplink_reserve_config.cpp index 02f889cae8..3800df1efa 100644 --- a/services/abilitymgr/src/deeplink_reserve/deeplink_reserve_config.cpp +++ b/services/abilitymgr/src/deeplink_reserve/deeplink_reserve_config.cpp @@ -21,7 +21,6 @@ #include "config_policy_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/dialog_session_info.cpp b/services/abilitymgr/src/dialog_session/dialog_session_info.cpp similarity index 90% rename from services/abilitymgr/src/dialog_session_info.cpp rename to services/abilitymgr/src/dialog_session/dialog_session_info.cpp index fa46604fb7..b1fd746cea 100644 --- a/services/abilitymgr/src/dialog_session_info.cpp +++ b/services/abilitymgr/src/dialog_session/dialog_session_info.cpp @@ -18,21 +18,22 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parcel_macro.h" #include "string_ex.h" namespace OHOS { namespace AAFwk { constexpr int32_t CYCLE_LIMIT = 1000; -constexpr size_t MEMBER_NUM = 8; +constexpr size_t MEMBER_NUM = 11; 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(visible); + std::to_string(visible) + "/" + std::to_string(appIndex) + "/" + + std::to_string(static_cast(multiAppMode.multiAppModeType)) + "/" + + std::to_string(multiAppMode.maxCount); } bool DialogAbilityInfo::ParseURI(const std::string &uri) @@ -55,6 +56,9 @@ bool DialogAbilityInfo::ParseURI(const std::string &uri) abilityIconId = static_cast(std::stoi(uriVec[index++])); abilityLabelId = static_cast(std::stoi(uriVec[index++])); visible = std::stoi(uriVec[index++]); + appIndex = static_cast(std::stoi(uriVec[index++])); + multiAppMode.multiAppModeType = static_cast(std::stoi(uriVec[index++])); + multiAppMode.maxCount = static_cast(std::stoi(uriVec[index++])); return true; } diff --git a/services/abilitymgr/src/dialog_session/dialog_session_manager.cpp b/services/abilitymgr/src/dialog_session/dialog_session_manager.cpp new file mode 100644 index 0000000000..06170ed9ed --- /dev/null +++ b/services/abilitymgr/src/dialog_session/dialog_session_manager.cpp @@ -0,0 +1,396 @@ +/* + * 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 "dialog_session_manager.h" + +#include +#include +#include +#include "ability_manager_service.h" +#include "ability_record.h" +#include "ability_util.h" +#include "hilog_tag_wrapper.h" +#include "hitrace_meter.h" +#include "int_wrapper.h" +#include "modal_system_ui_extension.h" +#include "parameters.h" +#include "start_ability_utils.h" +#include "string_wrapper.h" +#include "want.h" +#include "want_params_wrapper.h" + +namespace OHOS { +namespace AAFwk { +using OHOS::AppExecFwk::BundleInfo; +namespace { +constexpr const char* UIEXTENSION_MODAL_TYPE = "ability.want.params.modalType"; +constexpr int32_t ERMS_ISALLOW_RESULTCODE = 10; +constexpr const char* SUPPORT_CLOSE_ON_BLUR = "supportCloseOnBlur"; +} + +DialogSessionManager &DialogSessionManager::GetInstance() +{ + static DialogSessionManager instance; + return instance; +} + +std::string DialogSessionManager::GenerateDialogSessionId() +{ + auto timestamp = std::chrono::system_clock::now().time_since_epoch(); + auto time = std::chrono::duration_cast(timestamp).count(); + std::random_device seed; + std::mt19937 rng(seed()); + std::uniform_int_distribution uni(0, INT_MAX); + int randomDigit = uni(rng); + return std::to_string(time) + "_" + std::to_string(randomDigit); + std::string dialogSessionId = std::to_string(time) + "_" + std::to_string(randomDigit); + + std::lock_guard guard(dialogSessionRecordLock_); + auto iter = dialogSessionInfoMap_.find(dialogSessionId); + while (iter != dialogSessionInfoMap_.end()) { + dialogSessionId += "_1"; + iter = dialogSessionInfoMap_.find(dialogSessionId); + } + return dialogSessionId; +} + +void DialogSessionManager::SetDialogSessionInfo(const std::string &dialogSessionId, + sptr &dilogSessionInfo, std::shared_ptr &dialogCallerInfo) +{ + std::lock_guard guard(dialogSessionRecordLock_); + dialogSessionInfoMap_[dialogSessionId] = dilogSessionInfo; + dialogCallerInfoMap_[dialogSessionId] = dialogCallerInfo; +} + +sptr DialogSessionManager::GetDialogSessionInfo(const std::string &dialogSessionId) const +{ + std::lock_guard guard(dialogSessionRecordLock_); + auto it = dialogSessionInfoMap_.find(dialogSessionId); + if (it != dialogSessionInfoMap_.end()) { + return it->second; + } + TAG_LOGI(AAFwkTag::DIALOG, "not find"); + return nullptr; +} + +std::shared_ptr DialogSessionManager::GetDialogCallerInfo(const std::string &dialogSessionId) const +{ + std::lock_guard guard(dialogSessionRecordLock_); + auto it = dialogCallerInfoMap_.find(dialogSessionId); + if (it != dialogCallerInfoMap_.end()) { + return it->second; + } + TAG_LOGI(AAFwkTag::DIALOG, "not find"); + return nullptr; +} + +void DialogSessionManager::ClearDialogContext(const std::string &dialogSessionId) +{ + std::lock_guard guard(dialogSessionRecordLock_); + auto it = dialogSessionInfoMap_.find(dialogSessionId); + if (it != dialogSessionInfoMap_.end()) { + dialogSessionInfoMap_.erase(it); + } + auto iter = dialogCallerInfoMap_.find(dialogSessionId); + if (iter != dialogCallerInfoMap_.end()) { + dialogCallerInfoMap_.erase(iter); + } + return; +} + +void DialogSessionManager::ClearAllDialogContexts() +{ + std::lock_guard guard(dialogSessionRecordLock_); + dialogSessionInfoMap_.clear(); + dialogCallerInfoMap_.clear(); +} + +void DialogSessionManager::GenerateCallerAbilityInfo(AbilityRequest &abilityRequest, + DialogAbilityInfo &callerAbilityInfo) +{ + sptr callerToken = abilityRequest.callerToken; + if (callerToken != nullptr) { + auto callerRecord = Token::GetAbilityRecordByToken(callerToken); + CHECK_POINTER(callerRecord); + callerAbilityInfo.bundleName = callerRecord->GetAbilityInfo().bundleName; + callerAbilityInfo.moduleName = callerRecord->GetAbilityInfo().moduleName; + callerAbilityInfo.abilityName = callerRecord->GetAbilityInfo().name; + callerAbilityInfo.abilityIconId = callerRecord->GetAbilityInfo().iconId; + callerAbilityInfo.abilityLabelId = callerRecord->GetAbilityInfo().labelId; + callerAbilityInfo.bundleIconId = callerRecord->GetApplicationInfo().iconId; + callerAbilityInfo.bundleLabelId = callerRecord->GetApplicationInfo().labelId; + callerAbilityInfo.visible = callerRecord->GetAbilityInfo().visible; + callerAbilityInfo.appIndex = callerRecord->GetApplicationInfo().appIndex; + callerAbilityInfo.multiAppMode = callerRecord->GetApplicationInfo().multiAppMode; + } +} + +void DialogSessionManager::GenerateSelectorTargetAbilityInfos(std::vector &dialogAppInfos, + std::vector &targetAbilityInfos) +{ + for (auto &dialogAppInfo : dialogAppInfos) { + DialogAbilityInfo targetDialogAbilityInfo; + targetDialogAbilityInfo.bundleName = dialogAppInfo.bundleName; + targetDialogAbilityInfo.moduleName = dialogAppInfo.moduleName; + targetDialogAbilityInfo.abilityName = dialogAppInfo.abilityName; + targetDialogAbilityInfo.abilityIconId = dialogAppInfo.abilityIconId; + targetDialogAbilityInfo.abilityLabelId = dialogAppInfo.abilityLabelId; + targetDialogAbilityInfo.bundleIconId = dialogAppInfo.bundleIconId; + targetDialogAbilityInfo.bundleLabelId = dialogAppInfo.bundleLabelId; + targetDialogAbilityInfo.visible = dialogAppInfo.visible; + targetDialogAbilityInfo.appIndex = dialogAppInfo.appIndex; + targetDialogAbilityInfo.multiAppMode = dialogAppInfo.multiAppMode; + targetAbilityInfos.emplace_back(targetDialogAbilityInfo); + } +} + +void DialogSessionManager::GenerateJumpTargetAbilityInfos(AbilityRequest &abilityRequest, + std::vector &targetAbilityInfos) +{ + DialogAbilityInfo targetDialogAbilityInfo; + targetDialogAbilityInfo.bundleName = abilityRequest.abilityInfo.bundleName; + targetDialogAbilityInfo.moduleName = abilityRequest.abilityInfo.moduleName; + targetDialogAbilityInfo.abilityName = abilityRequest.abilityInfo.name; + targetDialogAbilityInfo.abilityIconId = abilityRequest.abilityInfo.iconId; + targetDialogAbilityInfo.abilityLabelId = abilityRequest.abilityInfo.labelId; + targetDialogAbilityInfo.bundleIconId = abilityRequest.abilityInfo.applicationInfo.iconId; + targetDialogAbilityInfo.bundleLabelId = abilityRequest.abilityInfo.applicationInfo.labelId; + targetDialogAbilityInfo.visible = abilityRequest.abilityInfo.visible; + targetDialogAbilityInfo.appIndex = abilityRequest.abilityInfo.applicationInfo.appIndex; + targetDialogAbilityInfo.multiAppMode = abilityRequest.abilityInfo.applicationInfo.multiAppMode; + targetAbilityInfos.emplace_back(targetDialogAbilityInfo); +} + +void DialogSessionManager::GenerateDialogCallerInfo(AbilityRequest &abilityRequest, int32_t userId, + std::shared_ptr dialogCallerInfo, bool isSelector) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + CHECK_POINTER(dialogCallerInfo); + dialogCallerInfo->isSelector = isSelector; + dialogCallerInfo->callerToken = abilityRequest.callerToken; + dialogCallerInfo->requestCode = abilityRequest.requestCode; + dialogCallerInfo->targetWant = abilityRequest.want; + dialogCallerInfo->userId = userId; +} + +int DialogSessionManager::SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllowed) +{ + if (!isAllowed) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "user refuse to jump"); + ClearDialogContext(dialogSessionId); + return ERR_OK; + } + std::shared_ptr dialogCallerInfo = GetDialogCallerInfo(dialogSessionId); + if (dialogCallerInfo == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "dialog caller info is nullptr"); + ClearDialogContext(dialogSessionId); + return ERR_INVALID_VALUE; + } + auto targetWant = dialogCallerInfo->targetWant; + targetWant.SetElement(want.GetElement()); + targetWant.SetParam("isSelector", dialogCallerInfo->isSelector); + targetWant.SetParam("dialogSessionId", dialogSessionId); + if (want.HasParameter(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY)) { + int32_t appIndex = want.GetIntParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, 0); + targetWant.SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, appIndex); + } + if (!targetWant.HasParameter(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY)) { + targetWant.SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, 0); + } + sptr callerToken = dialogCallerInfo->callerToken; + auto abilityMgr = DelayedSingleton::GetInstance(); + if (!abilityMgr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityMgr is nullptr."); + return INNER_ERR; + } + int ret = abilityMgr->StartAbilityAsCaller(targetWant, callerToken, callerToken, dialogCallerInfo->userId, + dialogCallerInfo->requestCode); + if (ret == ERR_OK) { + ClearDialogContext(dialogSessionId); + } + return ret; +} + +std::string DialogSessionManager::GenerateDialogSessionRecordCommon(AbilityRequest &abilityRequest, int32_t userId, + const AAFwk::WantParams ¶meters, std::vector &dialogAppInfos, bool isSelector) +{ + auto dialogSessionInfo = sptr::MakeSptr(); + CHECK_POINTER_AND_RETURN(dialogSessionInfo, ""); + + GenerateCallerAbilityInfo(abilityRequest, dialogSessionInfo->callerAbilityInfo); + + if (isSelector) { + GenerateSelectorTargetAbilityInfos(dialogAppInfos, dialogSessionInfo->targetAbilityInfos); + } else { + GenerateJumpTargetAbilityInfos(abilityRequest, dialogSessionInfo->targetAbilityInfos); + } + + dialogSessionInfo->parameters = parameters; + + std::shared_ptr dialogCallerInfo = std::make_shared(); + GenerateDialogCallerInfo(abilityRequest, userId, dialogCallerInfo, isSelector); + + std::string dialogSessionId = GenerateDialogSessionId(); + SetDialogSessionInfo(dialogSessionId, dialogSessionInfo, dialogCallerInfo); + + return dialogSessionId; +} + +int DialogSessionManager::CreateJumpModalDialog(AbilityRequest &abilityRequest, int32_t userId, + const Want &replaceWant) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + + AAFwk::WantParams parameters; + + parameters.SetParam("deviceType", AAFwk::String::Box(OHOS::system::GetDeviceType())); + parameters.SetParam("userId", AAFwk::Integer::Box(userId)); + + std::vector dialogAppInfos; + std::string dialogSessionId = GenerateDialogSessionRecordCommon(abilityRequest, userId, parameters, + dialogAppInfos, false); + if (dialogSessionId == "") { + TAG_LOGE(AAFwkTag::ABILITYMGR, "generate dialog session record failed"); + return ERR_INVALID_VALUE; + } + + return CreateModalDialogCommon(replaceWant, abilityRequest.callerToken, dialogSessionId); +} + +int DialogSessionManager::CreateImplicitSelectorModalDialog(AbilityRequest &abilityRequest, const Want &want, + int32_t userId, std::vector &dialogAppInfos) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + + AAFwk::Want sessionWant; + + sessionWant.SetParam("deviceType", OHOS::system::GetDeviceType()); + sessionWant.SetParam("userId", userId); + sessionWant.SetParam("action", abilityRequest.want.GetAction()); + sessionWant.SetParam("wantType", abilityRequest.want.GetType()); + sessionWant.SetParam("uri", abilityRequest.want.GetUriString()); + sessionWant.SetParam("entities", abilityRequest.want.GetEntities()); + sessionWant.SetParam("appselector.selectorType", static_cast(SelectorType::IMPLICIT_START_SELECTOR)); + bool showCaller = abilityRequest.want.GetBoolParam("showCaller", false); + sessionWant.SetParam("showCaller", showCaller); + + std::string dialogSessionId = GenerateDialogSessionRecordCommon(abilityRequest, userId, sessionWant.GetParams(), + dialogAppInfos, true); + if (dialogSessionId == "") { + TAG_LOGE(AAFwkTag::ABILITYMGR, "generate dialog session record failed"); + return ERR_INVALID_VALUE; + } + + return CreateModalDialogCommon(want, abilityRequest.callerToken, dialogSessionId); +} + +int DialogSessionManager::CreateCloneSelectorModalDialog(AbilityRequest &abilityRequest, const Want &want, + int32_t userId, std::vector &dialogAppInfos, const std::string &replaceWant) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + AAFwk::WantParams parameters; + + parameters.SetParam("deviceType", AAFwk::String::Box(OHOS::system::GetDeviceType())); + parameters.SetParam("userId", AAFwk::Integer::Box(userId)); + parameters.SetParam("appselector.selectorType", + AAFwk::Integer::Box(static_cast(SelectorType::APP_CLONR_SELECTOR))); + if (replaceWant != "") { + parameters.SetParam("replaceWant", AAFwk::String::Box(replaceWant)); + } + + std::string dialogSessionId = GenerateDialogSessionRecordCommon(abilityRequest, userId, parameters, + dialogAppInfos, true); + if (dialogSessionId == "") { + TAG_LOGE(AAFwkTag::ABILITYMGR, "generate dialog session record failed"); + return ERR_INVALID_VALUE; + } + + return CreateModalDialogCommon(want, abilityRequest.callerToken, dialogSessionId); +} + +int DialogSessionManager::CreateModalDialogCommon(const Want &replaceWant, sptr callerToken, + const std::string &dialogSessionId) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + (const_cast(replaceWant)).SetParam("dialogSessionId", dialogSessionId); + auto connection = std::make_shared(); + if (callerToken == nullptr) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "create modal ui extension for system"); + (const_cast(replaceWant)).SetParam(UIEXTENSION_MODAL_TYPE, 1); + (const_cast(replaceWant)).SetParam(SUPPORT_CLOSE_ON_BLUR, true); + return IN_PROCESS_CALL(connection->CreateModalUIExtension(replaceWant)) ? ERR_OK : INNER_ERR; + } + auto callerRecord = Token::GetAbilityRecordByToken(callerToken); + if (!callerRecord) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "callerRecord is nullptr."); + return ERR_INVALID_VALUE; + } + + sptr token; + auto abilityMgr = DelayedSingleton::GetInstance(); + if (!abilityMgr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityMgr is nullptr."); + return INNER_ERR; + } + int ret = IN_PROCESS_CALL(abilityMgr->GetTopAbility(token)); + if (ret != ERR_OK || token == nullptr) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "create modal ui extension for system"); + (const_cast(replaceWant)).SetParam(UIEXTENSION_MODAL_TYPE, 1); + (const_cast(replaceWant)).SetParam(SUPPORT_CLOSE_ON_BLUR, true); + return IN_PROCESS_CALL(connection->CreateModalUIExtension(replaceWant)) ? ERR_OK : INNER_ERR; + } + + if (callerRecord->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE && token == callerToken) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "create modal ui extension for application"); + return callerRecord->CreateModalUIExtension(replaceWant); + } + TAG_LOGD(AAFwkTag::ABILITYMGR, "create modal ui extension for system"); + (const_cast(replaceWant)).SetParam(UIEXTENSION_MODAL_TYPE, 1); + (const_cast(replaceWant)).SetParam(SUPPORT_CLOSE_ON_BLUR, true); + return IN_PROCESS_CALL(connection->CreateModalUIExtension(replaceWant)) ? ERR_OK : INNER_ERR; +} + +int DialogSessionManager::HandleErmsResult(AbilityRequest &abilityRequest, int32_t userId, + const Want &replaceWant) +{ + std::string bundleName = abilityRequest.abilityInfo.bundleName; + if (StartAbilityUtils::ermsResultCode < ERMS_ISALLOW_RESULTCODE || + !IsCreateCloneSelectorDialog(bundleName, userId)) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "create jump modal dialog"); + return CreateJumpModalDialog(abilityRequest, userId, replaceWant); + } + auto abilityMgr = DelayedSingleton::GetInstance(); + if (!abilityMgr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityMgr is nullptr."); + return INNER_ERR; + } + return abilityMgr->CreateCloneSelectorDialog(abilityRequest, userId, replaceWant.ToString()); +} + +bool DialogSessionManager::IsCreateCloneSelectorDialog(const std::string &bundleName, int32_t userId) +{ + if (StartAbilityUtils::isWantWithAppCloneIndex) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "want with app clone index."); + return false; + } + auto appIndexes = StartAbilityUtils::GetCloneAppIndexes(bundleName, userId); + if (appIndexes.empty()) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "The application do not create clone index."); + return false; + } + return true; +} +} // namespace AAFwk +} // namespace OHOS diff --git a/services/abilitymgr/src/dialog_session_record.cpp b/services/abilitymgr/src/dialog_session_record.cpp deleted file mode 100644 index 591805f41d..0000000000 --- a/services/abilitymgr/src/dialog_session_record.cpp +++ /dev/null @@ -1,153 +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 "dialog_session_record.h" - -#include -#include -#include -#include "ability_record.h" -#include "ability_util.h" -#include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" -#include "hitrace_meter.h" -#include "int_wrapper.h" -#include "parameters.h" -#include "string_wrapper.h" -#include "want_params_wrapper.h" - -namespace OHOS { -namespace AAFwk { -using OHOS::AppExecFwk::BundleInfo; -std::string DialogSessionRecord::GenerateDialogSessionId() -{ - auto timestamp = std::chrono::system_clock::now().time_since_epoch(); - auto time = std::chrono::duration_cast(timestamp).count(); - std::random_device seed; - std::mt19937 rng(seed()); - std::uniform_int_distribution uni(0, INT_MAX); - int randomDigit = uni(rng); - return std::to_string(time) + "_" + std::to_string(randomDigit); - std::string dialogSessionId = std::to_string(time) + "_" + std::to_string(randomDigit); - - std::lock_guard guard(dialogSessionRecordLock_); - auto iter = dialogSessionInfoMap_.find(dialogSessionId); - while (iter != dialogSessionInfoMap_.end()) { - dialogSessionId += "_1"; - iter = dialogSessionInfoMap_.find(dialogSessionId); - } - return dialogSessionId; -} - -void DialogSessionRecord::SetDialogSessionInfo(const std::string dialogSessionId, - sptr &dilogSessionInfo, std::shared_ptr &dialogCallerInfo) -{ - std::lock_guard guard(dialogSessionRecordLock_); - dialogSessionInfoMap_[dialogSessionId] = dilogSessionInfo; - dialogCallerInfoMap_[dialogSessionId] = dialogCallerInfo; -} - -sptr DialogSessionRecord::GetDialogSessionInfo(const std::string dialogSessionId) const -{ - std::lock_guard guard(dialogSessionRecordLock_); - auto it = dialogSessionInfoMap_.find(dialogSessionId); - if (it != dialogSessionInfoMap_.end()) { - return it->second; - } - TAG_LOGI(AAFwkTag::DIALOG, "not find"); - return nullptr; -} - -std::shared_ptr DialogSessionRecord::GetDialogCallerInfo(const std::string dialogSessionId) const -{ - std::lock_guard guard(dialogSessionRecordLock_); - auto it = dialogCallerInfoMap_.find(dialogSessionId); - if (it != dialogCallerInfoMap_.end()) { - return it->second; - } - TAG_LOGI(AAFwkTag::DIALOG, "not find"); - return nullptr; -} - -void DialogSessionRecord::ClearDialogContext(const std::string dialogSessionId) -{ - std::lock_guard guard(dialogSessionRecordLock_); - auto it = dialogSessionInfoMap_.find(dialogSessionId); - if (it != dialogSessionInfoMap_.end()) { - dialogSessionInfoMap_.erase(it); - } - auto iter = dialogCallerInfoMap_.find(dialogSessionId); - if (iter != dialogCallerInfoMap_.end()) { - dialogCallerInfoMap_.erase(iter); - } - return; -} - -void DialogSessionRecord::ClearAllDialogContexts() -{ - std::lock_guard guard(dialogSessionRecordLock_); - dialogSessionInfoMap_.clear(); - dialogCallerInfoMap_.clear(); -} - -bool DialogSessionRecord::GenerateDialogSessionRecord(AbilityRequest &abilityRequest, int32_t userId, - std::string &dialogSessionId, std::vector &dialogAppInfos, bool isSelector) -{ - HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - auto dialogSessionInfo = sptr::MakeSptr(); - CHECK_POINTER_AND_RETURN(dialogSessionInfo, ERR_INVALID_VALUE); - sptr callerToken = abilityRequest.callerToken; - if (callerToken != nullptr) { - auto callerRecord = Token::GetAbilityRecordByToken(callerToken); - CHECK_POINTER_AND_RETURN(callerRecord, ERR_INVALID_VALUE); - dialogSessionInfo->callerAbilityInfo.bundleName = callerRecord->GetAbilityInfo().bundleName; - dialogSessionInfo->callerAbilityInfo.moduleName = callerRecord->GetAbilityInfo().moduleName; - dialogSessionInfo->callerAbilityInfo.abilityName = callerRecord->GetAbilityInfo().name; - dialogSessionInfo->callerAbilityInfo.abilityIconId = callerRecord->GetAbilityInfo().iconId; - dialogSessionInfo->callerAbilityInfo.abilityLabelId = callerRecord->GetAbilityInfo().labelId; - dialogSessionInfo->callerAbilityInfo.bundleIconId = callerRecord->GetApplicationInfo().iconId; - dialogSessionInfo->callerAbilityInfo.bundleLabelId = callerRecord->GetApplicationInfo().labelId; - } - dialogSessionInfo->parameters.SetParam("deviceType", AAFwk::String::Box(OHOS::system::GetDeviceType())); - dialogSessionInfo->parameters.SetParam("userId", AAFwk::Integer::Box(userId)); - for (auto &dialogAppInfo : dialogAppInfos) { - DialogAbilityInfo targetDialogAbilityInfo; - targetDialogAbilityInfo.bundleName = dialogAppInfo.bundleName; - targetDialogAbilityInfo.moduleName = dialogAppInfo.moduleName; - targetDialogAbilityInfo.abilityName = dialogAppInfo.abilityName; - targetDialogAbilityInfo.abilityIconId = dialogAppInfo.abilityIconId; - 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(); - if (isSelector) { - dialogSessionInfo->parameters.SetParam("action", AAFwk::String::Box(abilityRequest.want.GetAction())); - dialogSessionInfo->parameters.SetParam("wantType", AAFwk::String::Box(abilityRequest.want.GetType())); - dialogSessionInfo->parameters.SetParam("uri", AAFwk::String::Box(abilityRequest.want.GetUriString())); - dialogCallerInfo->isSelector = true; - } - dialogCallerInfo->callerToken = callerToken; - dialogCallerInfo->requestCode = abilityRequest.requestCode; - dialogCallerInfo->targetWant = abilityRequest.want; - dialogCallerInfo->userId = userId; - dialogSessionId = GenerateDialogSessionId(); - SetDialogSessionInfo(dialogSessionId, dialogSessionInfo, dialogCallerInfo); - return true; -} -} // namespace AAFwk -} // namespace OHOS diff --git a/services/abilitymgr/src/disposed_observer.cpp b/services/abilitymgr/src/disposed_observer.cpp index 96b3616dca..7aa336961b 100644 --- a/services/abilitymgr/src/disposed_observer.cpp +++ b/services/abilitymgr/src/disposed_observer.cpp @@ -15,7 +15,6 @@ #include "disposed_observer.h" -#include "ability_manager_service.h" #include "interceptor/disposed_rule_interceptor.h" #include "ability_record.h" #include "hilog_tag_wrapper.h" @@ -43,7 +42,7 @@ void DisposedObserver::OnAbilityStateChanged(const AppExecFwk::AbilityStateData auto systemUIExtension = std::make_shared(); Want want = *disposedRule_.want; want.SetParam(UIEXTENSION_MODAL_TYPE, 1); - bool ret = systemUIExtension->CreateModalUIExtension(want); + bool ret = IN_PROCESS_CALL(systemUIExtension->CreateModalUIExtension(want)); if (!ret) { TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to start system UIExtension"); } @@ -56,8 +55,7 @@ void DisposedObserver::OnPageShow(const AppExecFwk::PageStateData &pageStateData { TAG_LOGD(AAFwkTag::ABILITYMGR, "Call"); if (disposedRule_.componentType == AppExecFwk::ComponentType::UI_ABILITY) { - int ret = IN_PROCESS_CALL(DelayedSingleton::GetInstance()->StartAbility( - *disposedRule_.want)); + int ret = IN_PROCESS_CALL(AbilityManagerClient::GetInstance()->StartAbility(*disposedRule_.want)); if (ret != ERR_OK) { interceptor_->UnregisterObserver(pageStateData.bundleName); TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to start disposed ability"); @@ -69,7 +67,7 @@ void DisposedObserver::OnPageShow(const AppExecFwk::PageStateData &pageStateData auto systemUIExtension = std::make_shared(); Want want = *disposedRule_.want; want.SetParam(UIEXTENSION_MODAL_TYPE, 1); - bool ret = systemUIExtension->CreateModalUIExtension(want); + bool ret = IN_PROCESS_CALL(systemUIExtension->CreateModalUIExtension(want)); if (!ret) { interceptor_->UnregisterObserver(pageStateData.bundleName); TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to start system UIExtension"); diff --git a/services/abilitymgr/src/dlp_state_item.cpp b/services/abilitymgr/src/dlp_state_item.cpp index 2d6e9860aa..2e8fcb184b 100644 --- a/services/abilitymgr/src/dlp_state_item.cpp +++ b/services/abilitymgr/src/dlp_state_item.cpp @@ -17,7 +17,6 @@ #include "global_constant.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/ecological_rule/ability_ecological_rule_mgr_service.cpp b/services/abilitymgr/src/ecological_rule/ability_ecological_rule_mgr_service.cpp index 9a7fd455b0..626227843a 100644 --- a/services/abilitymgr/src/ecological_rule/ability_ecological_rule_mgr_service.cpp +++ b/services/abilitymgr/src/ecological_rule/ability_ecological_rule_mgr_service.cpp @@ -19,7 +19,6 @@ #include "iservice_registry.h" #include "iremote_broker.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" namespace OHOS { @@ -145,8 +144,8 @@ int32_t AbilityEcologicalRuleMgrServiceClient::QueryStartExperience(const OHOS:: if (rule.replaceWant != nullptr) { rule.replaceWant->SetParam(ERMS_ORIGINAL_TARGET, want.ToString()); TAG_LOGD(AAFwkTag::ECOLOGICAL_RULE, - "queryStart finish: isAllow = %{public}d, sceneCode = %{public}s, replaceWant = %{public}s", rule.isAllow, - rule.sceneCode.c_str(), (*(rule.replaceWant)).ToString().c_str()); + "queryStart finish: resultCode = %{public}d, sceneCode = %{public}s, replaceWant = %{public}s", + rule.resultCode, rule.sceneCode.c_str(), (*(rule.replaceWant)).ToString().c_str()); } int64_t cost = GetCurrentTimeMicro() - start; TAG_LOGD(AAFwkTag::ECOLOGICAL_RULE, 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 704a24832a..e841cbf30f 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 @@ -22,7 +22,6 @@ #include "iremote_object.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace EcologicalRuleMgrService { @@ -35,7 +34,7 @@ AbilityExperienceRule *AbilityExperienceRule::Unmarshalling(Parcel &in) return nullptr; } - if (!in.ReadBool(rule->isAllow)) { + if (!in.ReadInt32(rule->resultCode)) { delete rule; return nullptr; } @@ -52,8 +51,8 @@ AbilityExperienceRule *AbilityExperienceRule::Unmarshalling(Parcel &in) bool AbilityExperienceRule::Marshalling(Parcel &parcel) const { - if (!parcel.WriteBool(isAllow)) { - TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "write isAllow failed"); + if (!parcel.WriteInt32(resultCode)) { + TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "write resultCode failed"); return false; } @@ -131,6 +130,8 @@ AbilityCallerInfo *AbilityCallerInfo::Unmarshalling(Parcel &in) info->callerAppProvisionType = in.ReadString(); info->targetAppProvisionType = in.ReadString(); info->callerExtensionAbilityType = static_cast(in.ReadInt32()); + info->targetAbilityType = static_cast(in.ReadInt32()); + info->targetExtensionAbilityType = static_cast(in.ReadInt32()); return info; } @@ -159,6 +160,16 @@ bool AbilityCallerInfo::Marshalling(Parcel &parcel) const TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "write callerExtensionAbilityType failed"); return false; } + + if (!parcel.WriteInt32(static_cast(targetAbilityType))) { + TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "write targetAbilityType failed"); + return false; + } + + if (!parcel.WriteInt32(static_cast(targetExtensionAbilityType))) { + TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "write targetExtensionAbilityType failed"); + return false; + } return true; } @@ -227,7 +238,9 @@ std::string AbilityCallerInfo::ToString() const std::to_string(static_cast(callerAbilityType)) + ",callerExtensionAbilityType:" + std::to_string(static_cast(callerExtensionAbilityType)) + ",embedded:" + std::to_string(embedded) + ",callerAppProvisionType:" + callerAppProvisionType + ",targetAppProvisionType:" + - targetAppProvisionType + "}"; + targetAppProvisionType + ",targetAbilityType:" + + std::to_string(static_cast(targetAbilityType)) + ",targetExtensionAbilityType:" + + std::to_string(static_cast(targetExtensionAbilityType)) + "}"; return str; } } // namespace EcologicalRuleMgrService diff --git a/services/abilitymgr/src/exit_reason.cpp b/services/abilitymgr/src/exit_reason.cpp index e71f9cf7d3..aa95e03d15 100644 --- a/services/abilitymgr/src/exit_reason.cpp +++ b/services/abilitymgr/src/exit_reason.cpp @@ -16,7 +16,6 @@ #include "exit_reason.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "nlohmann/json.hpp" #include "parcel_macro_base.h" #include "string_ex.h" diff --git a/services/abilitymgr/src/extension_config.cpp b/services/abilitymgr/src/extension_config.cpp index 53225eae73..7786c1c5ca 100644 --- a/services/abilitymgr/src/extension_config.cpp +++ b/services/abilitymgr/src/extension_config.cpp @@ -22,7 +22,6 @@ #include "config_policy_utils.h" #include "element_name.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/extension_record.cpp b/services/abilitymgr/src/extension_record.cpp index d9b2e2f899..cb201bd70f 100644 --- a/services/abilitymgr/src/extension_record.cpp +++ b/services/abilitymgr/src/extension_record.cpp @@ -18,7 +18,6 @@ #include "ability_util.h" #include "errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/services/abilitymgr/src/extension_record_manager.cpp b/services/abilitymgr/src/extension_record_manager.cpp index 69ed57db37..1c320f8775 100644 --- a/services/abilitymgr/src/extension_record_manager.cpp +++ b/services/abilitymgr/src/extension_record_manager.cpp @@ -17,7 +17,6 @@ #include "ability_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ui_extension_utils.h" #include "ui_extension_record.h" #include "ui_extension_record_factory.h" @@ -123,7 +122,7 @@ bool ExtensionRecordManager::IsBelongToManager(const AppExecFwk::AbilityInfo &ab int32_t ExtensionRecordManager::GetActiveUIExtensionList(const int32_t pid, std::vector &extensionList) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); std::lock_guard lock(mutex_); for (const auto &it : extensionRecords_) { if (it.second == nullptr || it.second->abilityRecord_ == nullptr || @@ -140,7 +139,7 @@ int32_t ExtensionRecordManager::GetActiveUIExtensionList(const int32_t pid, std: int32_t ExtensionRecordManager::GetActiveUIExtensionList( const std::string &bundleName, std::vector &extensionList) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); std::lock_guard lock(mutex_); for (const auto &it : extensionRecords_) { if (it.second == nullptr || it.second->abilityRecord_ == nullptr || @@ -534,6 +533,8 @@ int32_t ExtensionRecordManager::CreateExtensionRecord(const AAFwk::AbilityReques extensionRecord->hostBundleName_ = hostBundleName; abilityRecord->SetOwnerMissionUserId(userId_); abilityRecord->SetUIExtensionAbilityId(extensionRecordId); + pid_t hostPid = IPCSkeleton::GetCallingPid(); + extensionRecord->hostPid_ = hostPid; //add uiextension record register state observer object. if (abilityRecord->GetWant().GetBoolParam(IS_PRELOAD_UIEXTENSION_ABILITY, false)) { auto ret = extensionRecord->RegisterStateObserver(hostBundleName); @@ -589,6 +590,37 @@ std::shared_ptr ExtensionRecordManager::GetUIExtensionRoot return AAFwk::Token::GetAbilityRecordByToken(rootCallerToken); } +int32_t ExtensionRecordManager::GetUIExtensionSessionInfo( + const sptr token, UIExtensionSessionInfo &uiExtensionSessionInfo) +{ + if (token == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Input param invalid."); + return ERR_NULL_OBJECT; + } + + auto abilityRecord = AAFwk::Token::GetAbilityRecordByToken(token); + if (abilityRecord == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Get ability record failed."); + return ERR_NULL_OBJECT; + } + + if (!AAFwk::UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) { + TAG_LOGW(AAFwkTag::ABILITYMGR, "Not ui extension ability."); + return ERR_INVALID_VALUE; + } + + auto sessionInfo = abilityRecord->GetSessionInfo(); + if (sessionInfo == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "session info is null."); + return ERR_NULL_OBJECT; + } + + uiExtensionSessionInfo.persistentId = sessionInfo->persistentId; + uiExtensionSessionInfo.hostWindowId = sessionInfo->hostWindowId; + uiExtensionSessionInfo.uiExtensionUsage = sessionInfo->uiExtensionUsage; + return ERR_OK; +} + std::shared_ptr ExtensionRecordManager::GetExtensionRecordById(int32_t extensionRecordId) { std::lock_guard lock(mutex_); @@ -607,7 +639,7 @@ std::shared_ptr ExtensionRecordManager::GetExtensionRecordById( void ExtensionRecordManager::LoadTimeout(int32_t extensionRecordId) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto uiExtensionRecord = std::static_pointer_cast(GetExtensionRecordById(extensionRecordId)); if (uiExtensionRecord == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Parsing ui extension record failed."); @@ -619,7 +651,7 @@ void ExtensionRecordManager::LoadTimeout(int32_t extensionRecordId) void ExtensionRecordManager::ForegroundTimeout(int32_t extensionRecordId) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto uiExtensionRecord = std::static_pointer_cast(GetExtensionRecordById(extensionRecordId)); if (uiExtensionRecord == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Parsing ui extension record failed."); @@ -631,7 +663,7 @@ void ExtensionRecordManager::ForegroundTimeout(int32_t extensionRecordId) void ExtensionRecordManager::BackgroundTimeout(int32_t extensionRecordId) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto uiExtensionRecord = std::static_pointer_cast(GetExtensionRecordById(extensionRecordId)); if (uiExtensionRecord == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Parsing ui extension record failed."); @@ -643,7 +675,7 @@ void ExtensionRecordManager::BackgroundTimeout(int32_t extensionRecordId) void ExtensionRecordManager::TerminateTimeout(int32_t extensionRecordId) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto uiExtensionRecord = std::static_pointer_cast(GetExtensionRecordById(extensionRecordId)); if (uiExtensionRecord == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Parsing ui extension record failed."); diff --git a/services/abilitymgr/src/extension_running_info.cpp b/services/abilitymgr/src/extension_running_info.cpp index d2cc1fd51d..2463c9a2c9 100644 --- a/services/abilitymgr/src/extension_running_info.cpp +++ b/services/abilitymgr/src/extension_running_info.cpp @@ -15,7 +15,6 @@ #include "extension_running_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "nlohmann/json.hpp" #include "string_ex.h" diff --git a/services/abilitymgr/src/free_install_manager.cpp b/services/abilitymgr/src/free_install_manager.cpp index 0613d673b1..b888841906 100644 --- a/services/abilitymgr/src/free_install_manager.cpp +++ b/services/abilitymgr/src/free_install_manager.cpp @@ -25,9 +25,15 @@ #include "distributed_client.h" #include "free_install_observer_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" +#include "insight_intent_execute_manager.h" +#include "insight_intent_execute_param.h" +#include "insight_intent_execute_result.h" +#include "insight_intent_utils.h" #include "in_process_call_wrapper.h" +#include "permission_constants.h" +#include "start_ability_utils.h" +#include "utils/app_mgr_util.h" #include "uri_utils.h" namespace OHOS { @@ -39,6 +45,7 @@ const std::string PARAM_FREEINSTALL_BUNDLENAMES = "ohos.freeinstall.params.calli const std::string PARAM_FREEINSTALL_UID = "ohos.freeinstall.params.callingUid"; constexpr uint32_t IDMS_CALLBACK_ON_FREE_INSTALL_DONE = 0; constexpr uint32_t UPDATE_ATOMOIC_SERVICE_TASK_TIMER = 24 * 60 * 60 * 1000; /* 24h */ +constexpr const char* KEY_IS_APP_RUNNING = "com.ohos.param.isAppRunning"; FreeInstallManager::FreeInstallManager(const std::weak_ptr &server) : server_(server) @@ -83,26 +90,34 @@ bool FreeInstallManager::IsTopAbility(const sptr &callerToken) } int FreeInstallManager::StartFreeInstall(const Want &want, int32_t userId, int requestCode, - const sptr &callerToken, bool isAsync) + const sptr &callerToken, bool isAsync, uint32_t specifyTokenId, bool isOpenAtomicServiceShortUrl, + std::shared_ptr originalWant) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::FREE_INSTALL, "StartFreeInstall called"); - auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); - if (!isSaCall && !IsTopAbility(callerToken)) { + if (!VerifyStartFreeInstallPermission(callerToken)) { return NOT_TOP_ABILITY; } - FreeInstallInfo info = BuildFreeInstallInfo(want, userId, requestCode, callerToken, isAsync); + FreeInstallInfo info = BuildFreeInstallInfo(want, userId, requestCode, callerToken, + isAsync, specifyTokenId, isOpenAtomicServiceShortUrl, originalWant); { std::lock_guard lock(freeInstallListLock_); freeInstallList_.push_back(info); } - sptr callback = new AtomicServiceStatusCallback(weak_from_this(), isAsync); + int32_t recordId = GetRecordIdByToken(callerToken); + sptr callback = new AtomicServiceStatusCallback(weak_from_this(), isAsync, recordId); auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper(); CHECK_POINTER_AND_RETURN(bundleMgrHelper, GET_ABILITY_SERVICE_FAILED); AppExecFwk::AbilityInfo abilityInfo = {}; constexpr auto flag = AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION; info.want.SetParam(PARAM_FREEINSTALL_UID, IPCSkeleton::GetCallingUid()); + int result = SetAppRunningState(info.want); + if (result != ERR_OK) { + TAG_LOGE(AAFwkTag::FREE_INSTALL, "SetAppRunningState failed."); + return result; + } + if (IN_PROCESS_CALL(bundleMgrHelper->QueryAbilityInfo(info.want, flag, info.userId, abilityInfo, callback))) { TAG_LOGI(AAFwkTag::FREE_INSTALL, "The app has installed."); } @@ -143,7 +158,8 @@ int FreeInstallManager::RemoteFreeInstall(const Want &want, int32_t userId, int std::lock_guard lock(freeInstallListLock_); freeInstallList_.push_back(info); } - sptr callback = new AtomicServiceStatusCallback(weak_from_this(), false); + int32_t recordId = GetRecordIdByToken(callerToken); + sptr callback = new AtomicServiceStatusCallback(weak_from_this(), false, recordId); int32_t callerUid = IPCSkeleton::GetCallingUid(); uint32_t accessToken = IPCSkeleton::GetCallingTokenID(); UriUtils::GetInstance().FilterUriWithPermissionDms(info.want, accessToken); @@ -162,13 +178,17 @@ int FreeInstallManager::RemoteFreeInstall(const Want &want, int32_t userId, int } FreeInstallInfo FreeInstallManager::BuildFreeInstallInfo(const Want &want, int32_t userId, int requestCode, - const sptr &callerToken, bool isAsync) + const sptr &callerToken, bool isAsync, uint32_t specifyTokenId, bool isOpenAtomicServiceShortUrl, + std::shared_ptr originalWant) { FreeInstallInfo info = { .want = want, .userId = userId, .requestCode = requestCode, - .callerToken = callerToken + .callerToken = callerToken, + .specifyTokenId = specifyTokenId, + .isOpenAtomicServiceShortUrl = isOpenAtomicServiceShortUrl, + .originalWant = originalWant }; if (!isAsync) { auto promise = std::make_shared>(); @@ -247,7 +267,7 @@ int FreeInstallManager::NotifyDmsCallback(const Want &want, int resultCode) return reply.ReadInt32(); } -void FreeInstallManager::NotifyFreeInstallResult(const Want &want, int resultCode, bool isAsync) +void FreeInstallManager::NotifyFreeInstallResult(int32_t recordId, const Want &want, int resultCode, bool isAsync) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard lock(freeInstallListLock_); @@ -259,42 +279,94 @@ void FreeInstallManager::NotifyFreeInstallResult(const Want &want, int resultCod bool isFromRemote = want.GetBoolParam(FROM_REMOTE_KEY, false); TAG_LOGI(AAFwkTag::FREE_INSTALL, "isFromRemote = %{public}d", isFromRemote); for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) { - std::string bundleName = (*it).want.GetElement().GetBundleName(); - std::string abilityName = (*it).want.GetElement().GetAbilityName(); - std::string startTime = (*it).want.GetStringParam(Want::PARAM_RESV_START_TIME); + FreeInstallInfo &freeInstallInfo = *it; + std::string bundleName = freeInstallInfo.want.GetElement().GetBundleName(); + std::string abilityName = freeInstallInfo.want.GetElement().GetAbilityName(); + std::string startTime = freeInstallInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME); + std::string url = freeInstallInfo.want.GetUriString(); if (want.GetElement().GetBundleName().compare(bundleName) != 0 || want.GetElement().GetAbilityName().compare(abilityName) != 0 || - want.GetStringParam(Want::PARAM_RESV_START_TIME).compare(startTime) != 0) { + want.GetStringParam(Want::PARAM_RESV_START_TIME).compare(startTime) != 0 || + want.GetUriString().compare(url) != 0) { it++; continue; } - if (!isAsync && (*it).promise == nullptr) { + if (!isAsync && freeInstallInfo.promise == nullptr) { it++; continue; } - - if (resultCode == ERR_OK) { - TAG_LOGI(AAFwkTag::FREE_INSTALL, "FreeInstall success."); - if (isAsync) { - StartAbilityByFreeInstall(*it, bundleName, abilityName, startTime); - } else { - (*it).promise->set_value(resultCode); - } - } else { - TAG_LOGI(AAFwkTag::FREE_INSTALL, "FreeInstall failed."); - if (isAsync) { - DelayedSingleton::GetInstance()->OnInstallFinished( - bundleName, abilityName, startTime, resultCode); - } else { - (*it).promise->set_value(resultCode); - } - } - + freeInstallInfo.isFreeInstallFinished = true; + freeInstallInfo.resultCode = resultCode; + HandleFreeInstallResult(recordId, freeInstallInfo, resultCode, isAsync); it = freeInstallList_.erase(it); } } +void FreeInstallManager::HandleOnFreeInstallSuccess(int32_t recordId, FreeInstallInfo &freeInstallInfo, bool isAsync) +{ + TAG_LOGI(AAFwkTag::FREE_INSTALL, "FreeInstall success."); + freeInstallInfo.isInstalled = true; + + if (isAsync) { + std::string startTime = freeInstallInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME); + std::string bundleName = freeInstallInfo.want.GetElement().GetBundleName(); + std::string abilityName = freeInstallInfo.want.GetElement().GetAbilityName(); + if (freeInstallInfo.isPreStartMissionCalled) { + StartAbilityByPreInstall(recordId, freeInstallInfo, bundleName, abilityName, startTime); + return; + } + if (freeInstallInfo.isOpenAtomicServiceShortUrl) { + StartAbilityByConvertedWant(freeInstallInfo, startTime); + return; + } + StartAbilityByFreeInstall(freeInstallInfo, bundleName, abilityName, startTime); + return; + } + freeInstallInfo.promise->set_value(ERR_OK); +} + +void FreeInstallManager::HandleOnFreeInstallFail(int32_t recordId, FreeInstallInfo &freeInstallInfo, int resultCode, + bool isAsync) +{ + TAG_LOGI(AAFwkTag::FREE_INSTALL, "FreeInstall failed."); + freeInstallInfo.isInstalled = false; + + if (isAsync) { + if (freeInstallInfo.isPreStartMissionCalled && + freeInstallInfo.want.HasParameter(KEY_SESSION_ID) && + !freeInstallInfo.want.GetStringParam(KEY_SESSION_ID).empty() && + freeInstallInfo.isStartUIAbilityBySCBCalled) { + DelayedSingleton::GetInstance()->NotifySCBToHandleAtomicServiceException( + freeInstallInfo.want.GetStringParam(KEY_SESSION_ID), + resultCode, "free install failed"); + } + std::string startTime = freeInstallInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME); + if (freeInstallInfo.isOpenAtomicServiceShortUrl + && resultCode != CONCURRENT_TASKS_WAITING_FOR_RETRY) { + StartAbilityByOriginalWant(freeInstallInfo, startTime); + return; + } + + std::string bundleName = freeInstallInfo.want.GetElement().GetBundleName(); + std::string abilityName = freeInstallInfo.want.GetElement().GetAbilityName(); + DelayedSingleton::GetInstance()->OnInstallFinished( + recordId, bundleName, abilityName, startTime, resultCode); + return; + } + freeInstallInfo.promise->set_value(resultCode); +} + +void FreeInstallManager::HandleFreeInstallResult(int32_t recordId, FreeInstallInfo &freeInstallInfo, int resultCode, + bool isAsync) +{ + if (resultCode == ERR_OK) { + HandleOnFreeInstallSuccess(recordId, freeInstallInfo, isAsync); + return; + } + HandleOnFreeInstallFail(recordId, freeInstallInfo, resultCode, isAsync); +} + void FreeInstallManager::StartAbilityByFreeInstall(FreeInstallInfo &info, std::string &bundleName, std::string &abilityName, std::string &startTime) { @@ -310,9 +382,75 @@ void FreeInstallManager::StartAbilityByFreeInstall(FreeInstallInfo &info, std::s info.callerToken, info.userId, info.requestCode); } IPCSkeleton::SetCallingIdentity(identity); + int32_t recordId = GetRecordIdByToken(info.callerToken); TAG_LOGI(AAFwkTag::FREE_INSTALL, "The result of StartAbility is %{public}d.", result); DelayedSingleton::GetInstance()->OnInstallFinished( - bundleName, abilityName, startTime, result); + recordId, bundleName, abilityName, startTime, result); +} + +void FreeInstallManager::StartAbilityByPreInstall(int32_t recordId, FreeInstallInfo &info, std::string &bundleName, + std::string &abilityName, std::string &startTime) +{ + info.want.SetFlags(info.want.GetFlags() ^ Want::FLAG_INSTALL_ON_DEMAND); + auto identity = IPCSkeleton::ResetCallingIdentity(); + IPCSkeleton::SetCallingIdentity(info.identity); + int32_t result = ERR_OK; + if (info.want.GetElement().GetAbilityName().empty()) { + result = UpdateElementName(info.want, info.userId); + } + if (result == ERR_OK) { + result = DelayedSingleton::GetInstance()->StartUIAbilityByPreInstall(info); + } + if (result != ERR_OK && info.isStartUIAbilityBySCBCalled) { + DelayedSingleton::GetInstance()->NotifySCBToHandleAtomicServiceException( + info.want.GetStringParam(KEY_SESSION_ID), + result, "start ability failed"); + } + IPCSkeleton::SetCallingIdentity(identity); + TAG_LOGI(AAFwkTag::FREE_INSTALL, "The result of StartAbility is %{public}d.", result); + DelayedSingleton::GetInstance()->OnInstallFinished( + recordId, bundleName, abilityName, startTime, result); +} + +void FreeInstallManager::StartAbilityByConvertedWant(FreeInstallInfo &info, const std::string &startTime) +{ + info.want.SetFlags(info.want.GetFlags() ^ Want::FLAG_INSTALL_ON_DEMAND); + auto identity = IPCSkeleton::ResetCallingIdentity(); + IPCSkeleton::SetCallingIdentity(info.identity); + int32_t result = ERR_OK; + if (info.want.GetElement().GetAbilityName().empty()) { + result = UpdateElementName(info.want, info.userId); + } + if (result == ERR_OK) { + result = DelayedSingleton::GetInstance()->StartAbility(info.want, + info.callerToken, info.userId, info.requestCode); + } + IPCSkeleton::SetCallingIdentity(identity); + TAG_LOGI(AAFwkTag::FREE_INSTALL, "The result of StartAbility is %{public}d.", result); + auto url = info.want.GetUriString(); + int32_t recordId = GetRecordIdByToken(info.callerToken); + DelayedSingleton::GetInstance()->OnInstallFinishedByUrl(recordId, startTime, + url, result); +} + +void FreeInstallManager::StartAbilityByOriginalWant(FreeInstallInfo &info, const std::string &startTime) +{ + auto identity = IPCSkeleton::ResetCallingIdentity(); + IPCSkeleton::SetCallingIdentity(info.identity); + int result = ERR_INVALID_VALUE; + if (info.originalWant) { + TAG_LOGI(AAFwkTag::FREE_INSTALL, "starting ability by the original want."); + result = DelayedSingleton::GetInstance()->StartAbility(*(info.originalWant), + info.callerToken, info.userId, info.requestCode); + } else { + TAG_LOGE(AAFwkTag::FREE_INSTALL, "The original want is nullptr."); + } + IPCSkeleton::SetCallingIdentity(identity); + TAG_LOGI(AAFwkTag::FREE_INSTALL, "The result of StartAbility is %{public}d.", result); + auto url = info.want.GetUriString(); + int32_t recordId = GetRecordIdByToken(info.callerToken); + DelayedSingleton::GetInstance()->OnInstallFinishedByUrl(recordId, startTime, + url, result); } int32_t FreeInstallManager::UpdateElementName(Want &want, int32_t userId) const @@ -411,13 +549,18 @@ std::time_t FreeInstallManager::GetTimeStamp() return timestamp; } -void FreeInstallManager::OnInstallFinished(int resultCode, const Want &want, int32_t userId, bool isAsync) +void FreeInstallManager::OnInstallFinished(int32_t recordId, int resultCode, const Want &want, + int32_t userId, bool isAsync) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::FREE_INSTALL, "%{public}s resultCode = %{public}d", __func__, resultCode); - NotifyDmsCallback(want, resultCode); - NotifyFreeInstallResult(want, resultCode, isAsync); + if (!InsightIntentExecuteParam::IsInsightIntentExecute(want)) { + NotifyDmsCallback(want, resultCode); + NotifyFreeInstallResult(recordId, want, resultCode, isAsync); + } else { + NotifyInsightIntentFreeInstallResult(want, resultCode); + } PostUpgradeAtomicServiceTask(resultCode, want, userId); } @@ -448,70 +591,25 @@ void FreeInstallManager::PostUpgradeAtomicServiceTask(int resultCode, const Want } } -void FreeInstallManager::OnRemoteInstallFinished(int resultCode, const Want &want, int32_t userId) +void FreeInstallManager::OnRemoteInstallFinished(int32_t recordId, int resultCode, const Want &want, int32_t userId) { TAG_LOGI(AAFwkTag::FREE_INSTALL, "%{public}s resultCode = %{public}d", __func__, resultCode); - NotifyFreeInstallResult(want, resultCode); + NotifyFreeInstallResult(recordId, want, resultCode); } -int FreeInstallManager::AddFreeInstallObserver(const sptr &observer) +int FreeInstallManager::AddFreeInstallObserver(const sptr &callerToken, + const sptr &observer) { TAG_LOGI(AAFwkTag::FREE_INSTALL, "Add FreeInstallObserver"); - return DelayedSingleton::GetInstance()->AddObserver(observer); -} - -void FreeInstallManager::PostTimeoutTask(const Want &want) -{ - TAG_LOGI(AAFwkTag::FREE_INSTALL, "PostTimeoutTask begin."); - std::string bundleName = want.GetElement().GetBundleName(); - std::string abilityName = want.GetElement().GetAbilityName(); - std::string startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME); - auto task = [weak = weak_from_this(), bundleName, abilityName, startTime]() { - auto self = weak.lock(); - if (!self) { - TAG_LOGE(AAFwkTag::FREE_INSTALL, "this is nullptr"); - return; - } - DelayedSingleton::GetInstance()->OnInstallFinished(bundleName, abilityName, - startTime, FREE_INSTALL_TIMEOUT); - self->RemoveFreeInstallInfo(bundleName, abilityName, startTime); - }; - std::string taskName = std::string("FreeInstallTimeout_") + bundleName + std::string("_") + - abilityName + std::string("_") + startTime; - auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); - CHECK_POINTER_LOG(handler, "Fail to get AbilityTaskHandler."); - handler->SubmitTask(task, taskName, DELAY_LOCAL_FREE_INSTALL_TIMEOUT); -} - -void FreeInstallManager::RemoveTimeoutTask(const std::string &bundleName, const std::string &abilityName, - const std::string &startTime) -{ - // remove timeout task - std::string taskName = std::string("FreeInstallTimeout_") + bundleName + std::string("_") + - abilityName + std::string("_") + startTime; - TAG_LOGI(AAFwkTag::FREE_INSTALL, "RemoveTimeoutTask task name:%{public}s", taskName.c_str()); - auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); - CHECK_POINTER_LOG(handler, "Fail to get AbilityTaskHandler."); - handler->CancelTask(taskName); -} - -void FreeInstallManager::OnRemoveTimeoutTask(const Want &want) -{ - // only SA can call this interface - TAG_LOGI(AAFwkTag::FREE_INSTALL, "OnRemoveTimeoutTask begin."); - auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); - if (!isSaCall) { - TAG_LOGE(AAFwkTag::FREE_INSTALL, "Permission verification failed."); - return; + auto abilityRecord = Token::GetAbilityRecordByToken(callerToken); + if (abilityRecord != nullptr) { + return DelayedSingleton::GetInstance()->AddObserver(abilityRecord->GetRecordId(), + observer); } - std::string bundleName = want.GetElement().GetBundleName(); - std::string abilityName = want.GetElement().GetAbilityName(); - std::string startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME); - if (bundleName.empty() || abilityName.empty()) { - TAG_LOGE(AAFwkTag::FREE_INSTALL, "wantBundleName or wantAbilityName is empty"); - return; + if (AAFwk::PermissionVerification::GetInstance()->IsSACall()) { + return DelayedSingleton::GetInstance()->AddObserver(-1, observer); } - RemoveTimeoutTask(bundleName, abilityName, startTime); + return CHECK_PERMISSION_FAILED; } void FreeInstallManager::RemoveFreeInstallInfo(const std::string &bundleName, const std::string &abilityName, @@ -528,5 +626,175 @@ void FreeInstallManager::RemoveFreeInstallInfo(const std::string &bundleName, co } } } + +bool FreeInstallManager::GetFreeInstallTaskInfo(const std::string& bundleName, const std::string& abilityName, + const std::string& startTime, FreeInstallInfo& taskInfo) +{ + std::lock_guard lock(freeInstallListLock_); + for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) { + if ((*it).want.GetElement().GetBundleName() == bundleName && + (*it).want.GetElement().GetAbilityName() == abilityName && + (*it).want.GetStringParam(Want::PARAM_RESV_START_TIME) == startTime) { + taskInfo = *it; + return true; + } + it++; + } + return false; +} + +bool FreeInstallManager::GetFreeInstallTaskInfo(const std::string& sessionId, FreeInstallInfo& taskInfo) +{ + std::lock_guard lock(freeInstallListLock_); + for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) { + if ((*it).want.GetStringParam(KEY_SESSION_ID) == sessionId) { + taskInfo = *it; + return true; + } + it++; + } + return false; +} + +void FreeInstallManager::SetSCBCallStatus(const std::string& bundleName, const std::string& abilityName, + const std::string& startTime, bool scbCallStatus) +{ + std::lock_guard lock(freeInstallListLock_); + for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) { + if ((*it).want.GetElement().GetBundleName() == bundleName && + (*it).want.GetElement().GetAbilityName() == abilityName && + (*it).want.GetStringParam(Want::PARAM_RESV_START_TIME) == startTime) { + (*it).isStartUIAbilityBySCBCalled = scbCallStatus; + return; + } + it++; + } +} + +void FreeInstallManager::SetPreStartMissionCallStatus(const std::string& bundleName, const std::string& abilityName, + const std::string& startTime, bool preStartMissionCallStatus) +{ + std::lock_guard lock(freeInstallListLock_); + for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) { + if ((*it).want.GetElement().GetBundleName() == bundleName && + (*it).want.GetElement().GetAbilityName() == abilityName && + (*it).want.GetStringParam(Want::PARAM_RESV_START_TIME) == startTime) { + (*it).isPreStartMissionCalled = preStartMissionCallStatus; + return; + } + it++; + } +} + +void FreeInstallManager::SetFreeInstallTaskSessionId(const std::string& bundleName, const std::string& abilityName, + const std::string& startTime, const std::string& sessionId) +{ + std::lock_guard lock(freeInstallListLock_); + for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) { + if ((*it).want.GetElement().GetBundleName() == bundleName && + (*it).want.GetElement().GetAbilityName() == abilityName && + (*it).want.GetStringParam(Want::PARAM_RESV_START_TIME) == startTime) { + (*it).want.SetParam(KEY_SESSION_ID, sessionId); + return; + } + it++; + } +} + +int FreeInstallManager::SetAppRunningState(Want &want) +{ + auto appMgr = AppMgrUtil::GetAppMgr(); + if (appMgr == nullptr) { + TAG_LOGE(AAFwkTag::FREE_INSTALL, "appMgr is nullptr."); + return ERR_INVALID_VALUE; + } + + bool isAppRunning = appMgr->GetAppRunningStateByBundleName(want.GetElement().GetBundleName()); + TAG_LOGI(AAFwkTag::FREE_INSTALL, "isAppRunning=%{public}d.", static_cast(isAppRunning)); + want.SetParam(KEY_IS_APP_RUNNING, isAppRunning); + return ERR_OK; +} + +bool FreeInstallManager::VerifyStartFreeInstallPermission(const sptr &callerToken) +{ + auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); + if (isSaCall || IsTopAbility(callerToken)) { + return true; + } + + if (AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission( + PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) { + return true; + } + + return false; +} + +int32_t FreeInstallManager::GetRecordIdByToken(const sptr &callerToken) +{ + auto abilityRecord = Token::GetAbilityRecordByToken(callerToken); + int recordId = -1; + if (abilityRecord != nullptr) { + recordId = abilityRecord->GetRecordId(); + } + return recordId; +} + +void FreeInstallManager::NotifyInsightIntentFreeInstallResult(const Want &want, int resultCode) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + TAG_LOGI(AAFwkTag::FREE_INSTALL, "Insight intent free install result %{public}d.", resultCode); + if (resultCode != ERR_OK) { + RemoveFreeInstallInfo(want.GetElement().GetBundleName(), want.GetElement().GetAbilityName(), + want.GetStringParam(Want::PARAM_RESV_START_TIME)); + NotifyInsightIntentExecuteDone(want, ERR_INVALID_VALUE); + return; + } + + std::lock_guard lock(freeInstallListLock_); + if (freeInstallList_.empty()) { + TAG_LOGI(AAFwkTag::FREE_INSTALL, "Free install list empty."); + return; + } + + for (auto it = freeInstallList_.begin(); it != freeInstallList_.end();) { + std::string bundleName = (*it).want.GetElement().GetBundleName(); + std::string abilityName = (*it).want.GetElement().GetAbilityName(); + std::string startTime = (*it).want.GetStringParam(Want::PARAM_RESV_START_TIME); + if (want.GetElement().GetBundleName().compare(bundleName) != 0 || + want.GetElement().GetAbilityName().compare(abilityName) != 0 || + want.GetStringParam(Want::PARAM_RESV_START_TIME).compare(startTime) != 0) { + it++; + continue; + } + + auto moduleName = (*it).want.GetElement().GetModuleName(); + auto insightIntentName = (*it).want.GetStringParam(AppExecFwk::INSIGHT_INTENT_EXECUTE_PARAM_NAME); + auto srcEntry = AbilityRuntime::InsightIntentUtils::GetSrcEntry(bundleName, moduleName, insightIntentName); + if (srcEntry.empty()) { + TAG_LOGE(AAFwkTag::FREE_INSTALL, "Get srcEntry failed after free install. bundleName: %{public}s, " + "moduleName: %{public}s, insightIntentName: %{public}s.", bundleName.c_str(), moduleName.c_str(), + insightIntentName.c_str()); + NotifyInsightIntentExecuteDone(want, ERR_INVALID_VALUE); + } else { + (*it).want.SetParam(AppExecFwk::INSIGHT_INTENT_SRC_ENTRY, srcEntry); + StartAbilityByFreeInstall(*it, bundleName, abilityName, startTime); + } + + it = freeInstallList_.erase(it); + } +} + +void FreeInstallManager::NotifyInsightIntentExecuteDone(const Want &want, int resultCode) +{ + InsightIntentExecuteParam executeParam; + InsightIntentExecuteParam::GenerateFromWant(want, executeParam); + AppExecFwk::InsightIntentExecuteResult result; + auto ret = DelayedSingleton::GetInstance()->ExecuteIntentDone( + executeParam.insightIntentId_, resultCode, result); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::FREE_INSTALL, "Execute intent done failed with %{public}d.", ret); + } +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/free_install_observer_manager.cpp b/services/abilitymgr/src/free_install_observer_manager.cpp index 1a6d092a31..1c5d7a5036 100644 --- a/services/abilitymgr/src/free_install_observer_manager.cpp +++ b/services/abilitymgr/src/free_install_observer_manager.cpp @@ -21,7 +21,6 @@ #include "ability_manager_errors.h" #include "ability_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { @@ -31,7 +30,7 @@ FreeInstallObserverManager::FreeInstallObserverManager() FreeInstallObserverManager::~FreeInstallObserverManager() {} -int32_t FreeInstallObserverManager::AddObserver(const sptr &observer) +int32_t FreeInstallObserverManager::AddObserver(int32_t recordId, const sptr &observer) { TAG_LOGD(AAFwkTag::FREE_INSTALL, "AddObserver begin."); if (observer == nullptr) { @@ -39,12 +38,8 @@ int32_t FreeInstallObserverManager::AddObserver(const sptr return ERR_INVALID_VALUE; } std::lock_guard lock(observerLock_); - if (ObserverExistLocked(observer)) { - TAG_LOGE(AAFwkTag::FREE_INSTALL, "Observer exist."); - return ERR_INVALID_VALUE; - } - observerList_.emplace_back(observer); - TAG_LOGD(AAFwkTag::FREE_INSTALL, "observerList_ size:%{public}zu", observerList_.size()); + observerMap_[recordId] = observer; + TAG_LOGD(AAFwkTag::FREE_INSTALL, "observerMap_ size:%{public}zu", observerMap_.size()); if (!deathRecipient_) { std::weak_ptr thisWeakPtr(shared_from_this()); @@ -74,30 +69,28 @@ int32_t FreeInstallObserverManager::RemoveObserver(const sptr lock(observerLock_); - auto it = std::find_if(observerList_.begin(), observerList_.end(), - [&observer](const sptr &item) { - return (item && item->AsObject() == observer->AsObject()); - }); - if (it != observerList_.end()) { - observerList_.erase(it); - TAG_LOGI(AAFwkTag::FREE_INSTALL, "observerList_ size:%{public}zu", observerList_.size()); - return ERR_OK; + for (auto &item : observerMap_) { + if (item.second && item.second->AsObject() == observer->AsObject()) { + observerMap_.erase(item.first); + TAG_LOGI(AAFwkTag::FREE_INSTALL, "observerMap_ size:%{public}zu", observerMap_.size()); + return ERR_OK; + } } TAG_LOGE(AAFwkTag::FREE_INSTALL, "Observer not exist or has been removed."); return ERR_INVALID_VALUE; } -void FreeInstallObserverManager::OnInstallFinished(const std::string &bundleName, const std::string &abilityName, - const std::string &startTime, const int &resultCode) +void FreeInstallObserverManager::OnInstallFinished(int32_t recordId, const std::string &bundleName, + const std::string &abilityName, const std::string &startTime, const int &resultCode) { - auto task = [weak = weak_from_this(), bundleName, abilityName, startTime, resultCode]() { + auto task = [weak = weak_from_this(), recordId, bundleName, abilityName, startTime, resultCode]() { auto self = weak.lock(); if (self == nullptr) { TAG_LOGE(AAFwkTag::FREE_INSTALL, "self is nullptr, OnInstallFinished failed."); return; } TAG_LOGI(AAFwkTag::FREE_INSTALL, "OnInstallFinished come."); - self->HandleOnInstallFinished(bundleName, abilityName, startTime, resultCode); + self->HandleOnInstallFinished(recordId, bundleName, abilityName, startTime, resultCode); }; auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); @@ -105,30 +98,42 @@ void FreeInstallObserverManager::OnInstallFinished(const std::string &bundleName handler->SubmitTask(task); } -void FreeInstallObserverManager::HandleOnInstallFinished(const std::string &bundleName, const std::string &abilityName, - const std::string &startTime, const int &resultCode) +void FreeInstallObserverManager::OnInstallFinishedByUrl(int32_t recordId, const std::string &startTime, + const std::string &url, const int &resultCode) +{ + auto task = [weak = weak_from_this(), recordId, startTime, url, resultCode]() { + auto self = weak.lock(); + if (self == nullptr) { + TAG_LOGE(AAFwkTag::FREE_INSTALL, "self is nullptr, OnInstallFinished failed."); + return; + } + TAG_LOGI(AAFwkTag::FREE_INSTALL, "OnInstallFinishedByUrl come."); + self->HandleOnInstallFinishedByUrl(recordId, startTime, url, resultCode); + }; + + auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); + CHECK_POINTER_LOG(handler, "Fail to get Ability task handler."); + handler->SubmitTask(task); +} + +void FreeInstallObserverManager::HandleOnInstallFinished(int32_t recordId, const std::string &bundleName, + const std::string &abilityName, const std::string &startTime, const int &resultCode) { TAG_LOGD(AAFwkTag::FREE_INSTALL, "HandleOnInstallFinished begin."); - for (auto it = observerList_.begin(); it != observerList_.end(); ++it) { - if ((*it) == nullptr) { - continue; - } - (*it)->OnInstallFinished(bundleName, abilityName, startTime, resultCode); + auto iter = observerMap_.find(recordId); + if (iter != observerMap_.end() && iter->second != nullptr) { + (iter->second)->OnInstallFinished(bundleName, abilityName, startTime, resultCode); } } -bool FreeInstallObserverManager::ObserverExistLocked(const sptr &observer) +void FreeInstallObserverManager::HandleOnInstallFinishedByUrl(int32_t recordId, const std::string &startTime, + const std::string &url, const int &resultCode) { - TAG_LOGD(AAFwkTag::FREE_INSTALL, "ObserExist begin."); - if (observer == nullptr) { - TAG_LOGE(AAFwkTag::FREE_INSTALL, "The param observer is nullptr."); - return false; + TAG_LOGD(AAFwkTag::FREE_INSTALL, "HandleOnInstallFinishedByUrl begin."); + auto iter = observerMap_.find(recordId); + if (iter != observerMap_.end() && iter->second != nullptr) { + (iter->second)->OnInstallFinishedByUrl(startTime, url, resultCode); } - auto it = std::find_if(observerList_.begin(), observerList_.end(), - [&observer](const sptr &item) { - return (item && item->AsObject() == observer->AsObject()); - }); - return it != observerList_.end(); } void FreeInstallObserverManager::OnObserverDied(const wptr &remote) @@ -142,12 +147,12 @@ void FreeInstallObserverManager::OnObserverDied(const wptr &remot remoteObj->RemoveDeathRecipient(deathRecipient_); std::lock_guard lock(observerLock_); - auto it = std::find_if(observerList_.begin(), observerList_.end(), [&remoteObj] - (const sptr item) { - return (item && item->AsObject() == remoteObj); - }); - if (it != observerList_.end()) { - observerList_.erase(it); + for (auto &item : observerMap_) { + if (item.second && item.second->AsObject() == remoteObj) { + observerMap_.erase(item.first); + TAG_LOGI(AAFwkTag::FREE_INSTALL, "observerMap_ size:%{public}zu", observerMap_.size()); + return; + } } } diff --git a/services/abilitymgr/src/implicit_start_processor.cpp b/services/abilitymgr/src/implicit_start_processor.cpp index 7c517a12fd..16ded7359a 100644 --- a/services/abilitymgr/src/implicit_start_processor.cpp +++ b/services/abilitymgr/src/implicit_start_processor.cpp @@ -21,21 +21,23 @@ #include "app_gallery_enable_util.h" #include "app_utils.h" #include "default_app_interface.h" +#include "dialog_session_manager.h" #include "errors.h" #include "ecological_rule/ability_ecological_rule_mgr_service.h" #include "event_report.h" +#include "global_constant.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "in_process_call_wrapper.h" #include "parameters.h" #include "scene_board_judgement.h" +#include "start_ability_utils.h" +#include "startup_util.h" #include "want.h" namespace OHOS { namespace AAFwk { const size_t IDENTITY_LIST_MAX_SIZE = 10; -const int32_t BROKER_UID = 5557; const std::string BLACK_ACTION_SELECT_DATA = "ohos.want.action.select"; const std::string ACTION_VIEW = "ohos.want.action.viewData"; @@ -45,13 +47,13 @@ const std::string TYPE_ONLY_MATCH_WILDCARD = "reserved/wildcard"; const std::string SHOW_DEFAULT_PICKER_FLAG = "ohos.ability.params.showDefaultPicker"; const std::string PARAM_ABILITY_APPINFOS = "ohos.ability.params.appInfos"; const std::string ANCO_PENDING_REQUEST = "ancoPendingRequest"; -const std::string SHELL_ASSISTANT_BUNDLENAME = "com.huawei.shell_assistant"; const int NFC_CALLER_UID = 1027; const int NFC_QUERY_LENGTH = 2; const std::string OPEN_LINK_APP_LINKING_ONLY = "appLinkingOnly"; const std::string HTTP_SCHEME_NAME = "http"; const std::string HTTPS_SCHEME_NAME = "https"; const std::string APP_CLONE_INDEX = "ohos.extra.param.key.appCloneIndex"; +constexpr const char* SUPPORT_ACTION_START_SELECTOR = "persist.sys.ability.support.action_start_selector"; const std::vector ImplicitStartProcessor::blackList = { std::vector::value_type(BLACK_ACTION_SELECT_DATA), @@ -86,7 +88,8 @@ bool ImplicitStartProcessor::IsImplicitStartAction(const Want &want) return false; } -int ImplicitStartProcessor::ImplicitStartAbility(AbilityRequest &request, int32_t userId, int32_t windowMode) +int ImplicitStartProcessor::ImplicitStartAbility(AbilityRequest &request, int32_t userId, int32_t windowMode, + const std::string &replaceWantString, bool isAppCloneSelector) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "implicit start ability by type: %{public}d", request.callType); @@ -95,9 +98,15 @@ int ImplicitStartProcessor::ImplicitStartAbility(AbilityRequest &request, int32_ std::vector dialogAppInfos; request.want.RemoveParam(APP_CLONE_INDEX); - auto ret = GenerateAbilityRequestByAction(userId, request, dialogAppInfos, false); + bool findDefaultApp = false; + int32_t ret = ERR_OK; + if (isAppCloneSelector) { + ret = GenerateAbilityRequestByAppIndexes(userId, request, dialogAppInfos); + } else { + ret = GenerateAbilityRequestByAction(userId, request, dialogAppInfos, false, findDefaultApp); + } if (ret != ERR_OK) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request by action failed."); + TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request failed."); return ret; } AbilityUtil::WantSetParameterWindowMode(request.want, windowMode); @@ -135,7 +144,8 @@ int ImplicitStartProcessor::ImplicitStartAbility(AbilityRequest &request, int32_ } if (want.GetBoolParam("isCreateAppGallerySelector", false)) { want.RemoveParam("isCreateAppGallerySelector"); - NotifyCreateModalDialog(request, want, userId, dialogAppInfos); + DialogSessionManager::GetInstance().CreateImplicitSelectorModalDialog(request, want, userId, + dialogAppInfos); return ERR_IMPLICIT_START_ABILITY_FAIL; } TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit query ability infos failed, show tips dialog."); @@ -152,12 +162,13 @@ int ImplicitStartProcessor::ImplicitStartAbility(AbilityRequest &request, int32_ } if (want.GetBoolParam("isCreateAppGallerySelector", false)) { want.RemoveParam("isCreateAppGallerySelector"); - NotifyCreateModalDialog(request, want, userId, dialogAppInfos); + DialogSessionManager::GetInstance().CreateImplicitSelectorModalDialog(request, want, userId, + dialogAppInfos); return ERR_IMPLICIT_START_ABILITY_FAIL; } std::vector dialogAllAppInfos; bool isMoreHapList = true; - ret = GenerateAbilityRequestByAction(userId, request, dialogAllAppInfos, isMoreHapList); + ret = GenerateAbilityRequestByAction(userId, request, dialogAllAppInfos, isMoreHapList, findDefaultApp); if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request by action failed."); return ret; @@ -186,11 +197,14 @@ int ImplicitStartProcessor::ImplicitStartAbility(AbilityRequest &request, int32_ //There is a default opening method add Only one application supports bool defaultPicker = false; defaultPicker = request.want.GetBoolParam(SHOW_DEFAULT_PICKER_FLAG, defaultPicker); - if (dialogAppInfos.size() == 1 && (!defaultPicker || AppUtils::GetInstance().IsSelectorDialogDefaultPossion())) { + if (dialogAppInfos.size() == 1 && !defaultPicker) { auto info = dialogAppInfos.front(); - TAG_LOGI( - AAFwkTag::ABILITYMGR, "ImplicitQueryInfos success, target ability: %{public}s", info.abilityName.data()); - return IN_PROCESS_CALL(startAbilityTask(info.bundleName, info.abilityName)); + // Compatible with the action's sunset scene + if (!IsActionImplicitStart(request.want, findDefaultApp)) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "ImplicitQueryInfos success, target ability: %{public}s", + info.abilityName.data()); + return IN_PROCESS_CALL(startAbilityTask(info.bundleName, info.abilityName)); + } } if (AppUtils::GetInstance().IsSelectorDialogDefaultPossion()) { @@ -202,7 +216,12 @@ int ImplicitStartProcessor::ImplicitStartAbility(AbilityRequest &request, int32_ } if (want.GetBoolParam("isCreateAppGallerySelector", false)) { want.RemoveParam("isCreateAppGallerySelector"); - return NotifyCreateModalDialog(request, want, userId, dialogAppInfos); + if (isAppCloneSelector) { + return DialogSessionManager::GetInstance().CreateCloneSelectorModalDialog(request, want, + userId, dialogAppInfos, replaceWantString); + } + return DialogSessionManager::GetInstance().CreateImplicitSelectorModalDialog(request, + want, userId, dialogAppInfos); } ret = abilityMgr->ImplicitStartAbilityAsCaller(request.want, request.callerToken, nullptr); // reset calling indentity @@ -221,7 +240,12 @@ int ImplicitStartProcessor::ImplicitStartAbility(AbilityRequest &request, int32_ } if (want.GetBoolParam("isCreateAppGallerySelector", false)) { want.RemoveParam("isCreateAppGallerySelector"); - return NotifyCreateModalDialog(request, want, userId, dialogAppInfos); + if (isAppCloneSelector) { + return DialogSessionManager::GetInstance().CreateCloneSelectorModalDialog(request, want, userId, + dialogAppInfos, replaceWantString); + } + return DialogSessionManager::GetInstance().CreateImplicitSelectorModalDialog(request, want, userId, + dialogAppInfos); } ret = abilityMgr->ImplicitStartAbilityAsCaller(request.want, request.callerToken, nullptr); // reset calling indentity @@ -229,20 +253,6 @@ int ImplicitStartProcessor::ImplicitStartAbility(AbilityRequest &request, int32_ return ret; } -int ImplicitStartProcessor::NotifyCreateModalDialog(AbilityRequest &abilityRequest, const Want &want, int32_t userId, - std::vector &dialogAppInfos) -{ - HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - auto abilityMgr = DelayedSingleton::GetInstance(); - std::string dialogSessionId; - if (abilityMgr->GenerateDialogSessionRecord(abilityRequest, userId, dialogSessionId, dialogAppInfos, true)) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "create dialog by ui extension"); - return abilityMgr->CreateModalDialog(want, abilityRequest.callerToken, dialogSessionId); - } - TAG_LOGE(AAFwkTag::ABILITYMGR, "create dialog by ui extension failed"); - return INNER_ERR; -} - std::string ImplicitStartProcessor::MatchTypeAndUri(const AAFwk::Want &want) { std::string type = want.GetType(); @@ -327,7 +337,7 @@ void ImplicitStartProcessor::OnlyKeepReserveApp(std::vector &dialogAppInfos, bool isMoreHapList) + AbilityRequest &request, std::vector &dialogAppInfos, bool isMoreHapList, bool &findDefaultApp) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s.", __func__); @@ -349,10 +359,10 @@ int ImplicitStartProcessor::GenerateAbilityRequestByAction(int32_t userId, if (IPCSkeleton::GetCallingUid() == NFC_CALLER_UID && !request.want.GetStringArrayParam(PARAM_ABILITY_APPINFOS).empty()) { TAG_LOGI(AAFwkTag::ABILITYMGR, "The NFCNeed caller source is NFC."); - ImplicitStartProcessor::QueryBmsAppInfos(request, userId, dialogAppInfos); + QueryBmsAppInfos(request, userId, dialogAppInfos); } - if (!IsCallFromAncoShellOrBroker(request.callerToken)) { + if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(request.callerToken)) { request.want.RemoveParam(ANCO_PENDING_REQUEST); } @@ -366,8 +376,15 @@ int ImplicitStartProcessor::GenerateAbilityRequestByAction(int32_t userId, static_cast(AppExecFwk::GetAbilityInfoFlag::GET_ABILITY_INFO_ONLY_SYSTEM_APP); } + if (isOpenLink) { + std::string linkUriScheme = request.want.GetUri().GetScheme(); + if (linkUriScheme == HTTPS_SCHEME_NAME || linkUriScheme == HTTP_SCHEME_NAME) { + request.want.SetAction(ACTION_VIEW); + } + } + IN_PROCESS_CALL_WITHOUT_RET(bundleMgrHelper->ImplicitQueryInfos( - request.want, abilityInfoFlag, userId, withDefault, abilityInfos, extensionInfos)); + request.want, abilityInfoFlag, userId, withDefault, abilityInfos, extensionInfos, findDefaultApp)); OnlyKeepReserveApp(abilityInfos, extensionInfos); if (isOpenLink && extensionInfos.size() > 0) { @@ -407,7 +424,7 @@ int ImplicitStartProcessor::GenerateAbilityRequestByAction(int32_t userId, std::vector infoNames; if (!AppUtils::GetInstance().IsSelectorDialogDefaultPossion()) { IN_PROCESS_CALL_WITHOUT_RET(bundleMgrHelper->ImplicitQueryInfos(implicitwant, abilityInfoFlag, userId, - withDefault, implicitAbilityInfos, implicitExtensionInfos)); + withDefault, implicitAbilityInfos, implicitExtensionInfos, findDefaultApp)); if (implicitAbilityInfos.size() != 0 && typeName != TYPE_ONLY_MATCH_WILDCARD) { for (auto implicitAbilityInfo : implicitAbilityInfos) { infoNames.emplace_back(implicitAbilityInfo.bundleName + "#" + @@ -416,13 +433,6 @@ int ImplicitStartProcessor::GenerateAbilityRequestByAction(int32_t userId, } } - if (isOpenLink) { - std::string linkUriScheme = request.want.GetUri().GetScheme(); - if (linkUriScheme == HTTPS_SCHEME_NAME || linkUriScheme == HTTP_SCHEME_NAME) { - request.want.SetAction(ACTION_VIEW); - } - } - if (abilityInfos.size() == 1) { auto skillUri = abilityInfos.front().skillUri; SetTargetLinkInfo(skillUri, request.want); @@ -456,12 +466,78 @@ int ImplicitStartProcessor::GenerateAbilityRequestByAction(int32_t userId, dialogAppInfo.bundleIconId = info.applicationInfo.iconId; dialogAppInfo.bundleLabelId = info.applicationInfo.labelId; dialogAppInfo.visible = info.visible; + dialogAppInfo.appIndex = info.applicationInfo.appIndex; + dialogAppInfo.multiAppMode = info.applicationInfo.multiAppMode; dialogAppInfos.emplace_back(dialogAppInfo); } return ERR_OK; } +int ImplicitStartProcessor::GenerateAbilityRequestByAppIndexes(int32_t userId, AbilityRequest &request, + std::vector &dialogAppInfos) +{ + auto appIndexes = StartAbilityUtils::GetCloneAppIndexes(request.want.GetBundle(), userId); + if (appIndexes.size() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "The size of appIndexes is too large."); + return ERR_INVALID_VALUE; + } + auto bms = GetBundleManagerHelper(); + CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED); + auto abilityInfoFlag = static_cast(AbilityRuntime::StartupUtil::BuildAbilityInfoFlag()) | + static_cast(AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_SKILL); + std::vector abilityInfos; + abilityInfos.emplace_back(request.abilityInfo); + for (auto &appIndex: appIndexes) { + AppExecFwk::AbilityInfo abilityInfo; + IN_PROCESS_CALL_WITHOUT_RET(bms->QueryCloneAbilityInfo(request.want.GetElement(), abilityInfoFlag, appIndex, + abilityInfo, userId)); + if (abilityInfo.name.empty() || abilityInfo.bundleName.empty()) { + int32_t ret = FindExtensionInfo(request.want, abilityInfoFlag, userId, appIndex, abilityInfo); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "query clone extension info failed."); + return ret; + } + } + abilityInfos.emplace_back(abilityInfo); + } + for (const auto &info : abilityInfos) { + DialogAppInfo dialogAppInfo; + dialogAppInfo.abilityName = info.name; + dialogAppInfo.bundleName = info.bundleName; + dialogAppInfo.moduleName = info.moduleName; + dialogAppInfo.abilityIconId = info.iconId; + dialogAppInfo.abilityLabelId = info.labelId; + dialogAppInfo.bundleIconId = info.applicationInfo.iconId; + dialogAppInfo.bundleLabelId = info.applicationInfo.labelId; + dialogAppInfo.visible = info.visible; + dialogAppInfo.appIndex = info.applicationInfo.appIndex; + dialogAppInfo.multiAppMode = info.applicationInfo.multiAppMode; + dialogAppInfos.emplace_back(dialogAppInfo); + } + return ERR_OK; +} + +int ImplicitStartProcessor::FindExtensionInfo(const Want &want, int32_t flags, int32_t userId, + int32_t appIndex, AppExecFwk::AbilityInfo &abilityInfo) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + auto bms = GetBundleManagerHelper(); + CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED); + AppExecFwk::ExtensionAbilityInfo extensionInfo; + IN_PROCESS_CALL_WITHOUT_RET(bms->QueryCloneExtensionAbilityInfoWithAppIndex(want.GetElement(), + flags, appIndex, extensionInfo, userId)); + if (extensionInfo.bundleName.empty() || extensionInfo.name.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "extensionInfo empty."); + return RESOLVE_ABILITY_ERR; + } + if (AbilityRuntime::StartupUtil::IsSupportAppClone(extensionInfo.type)) { + AbilityRuntime::StartupUtil::InitAbilityInfoFromExtension(extensionInfo, abilityInfo); + return ERR_OK; + } + return ERR_APP_CLONE_INDEX_INVALID; +} + int ImplicitStartProcessor::QueryBmsAppInfos(AbilityRequest &request, int32_t userId, std::vector &dialogAppInfos) { @@ -499,6 +575,9 @@ int ImplicitStartProcessor::QueryBmsAppInfos(AbilityRequest &request, int32_t us dialogAppInfo.abilityLabelId = abilityInfo.labelId; dialogAppInfo.bundleIconId = abilityInfo.applicationInfo.iconId; dialogAppInfo.bundleLabelId = abilityInfo.applicationInfo.labelId; + dialogAppInfo.visible = abilityInfo.visible; + dialogAppInfo.appIndex = abilityInfo.applicationInfo.appIndex; + dialogAppInfo.multiAppMode = abilityInfo.applicationInfo.multiAppMode; dialogAppInfos.emplace_back(dialogAppInfo); } } @@ -562,7 +641,7 @@ int32_t ImplicitStartProcessor::ImplicitStartAbilityInner(const Want &targetWant break; default: result = abilityMgr->StartAbilityWrap( - targetWant, request.callerToken, request.requestCode, userId, false, false, 0, false, true); + targetWant, request.callerToken, request.requestCode, userId, false, 0, false, true); break; } @@ -730,6 +809,8 @@ void ImplicitStartProcessor::AddAbilityInfoToDialogInfos(const AddInfoParam &par dialogAppInfo.bundleIconId = param.info.applicationInfo.iconId; dialogAppInfo.bundleLabelId = param.info.applicationInfo.labelId; dialogAppInfo.visible = param.info.visible; + dialogAppInfo.appIndex = param.info.applicationInfo.appIndex; + dialogAppInfo.multiAppMode = param.info.applicationInfo.multiAppMode; dialogAppInfos.emplace_back(dialogAppInfo); } @@ -755,23 +836,6 @@ bool ImplicitStartProcessor::IsExistDefaultApp(int32_t userId, const std::string } } -bool ImplicitStartProcessor::IsCallFromAncoShellOrBroker(const sptr &token) -{ - auto callingUid = IPCSkeleton::GetCallingUid(); - if (callingUid == BROKER_UID) { - return true; - } - auto abilityRecord = Token::GetAbilityRecordByToken(token); - if (!abilityRecord) { - return false; - } - std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName; - if (callerBundleName == SHELL_ASSISTANT_BUNDLENAME) { - return true; - } - return false; -} - void ImplicitStartProcessor::SetTargetLinkInfo(const std::vector &skillUri, Want &want) { @@ -792,5 +856,31 @@ void ImplicitStartProcessor::SetTargetLinkInfo(const std::vectorsecond; - if (requestFunc != nullptr) { - return (this->*requestFunc)(data, reply); - } + if (code == ON_INSIGHT_INTENT_EXECUTE_DONE) { + return OnExecuteDoneInner(data, reply); } + TAG_LOGW(AAFwkTag::INTENT, "default case, need check."); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/services/abilitymgr/src/insight_intent_execute_manager.cpp b/services/abilitymgr/src/insight_intent_execute_manager.cpp index a1c520b202..3dc52f54d2 100644 --- a/services/abilitymgr/src/insight_intent_execute_manager.cpp +++ b/services/abilitymgr/src/insight_intent_execute_manager.cpp @@ -15,11 +15,11 @@ #include "insight_intent_execute_manager.h" +#include #include #include "ability_manager_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "insight_intent_execute_callback_interface.h" #include "insight_intent_utils.h" #include "permission_verification.h" @@ -224,11 +224,18 @@ int32_t InsightIntentExecuteManager::GenerateWant( auto srcEntry = AbilityRuntime::InsightIntentUtils::GetSrcEntry(param->bundleName_, param->moduleName_, param->insightIntentName_); - if (srcEntry.empty()) { - TAG_LOGE(AAFwkTag::INTENT, "Insight intent srcEntry invalid."); + if (!srcEntry.empty()) { + want.SetParam(INSIGHT_INTENT_SRC_ENTRY, srcEntry); + } else if (param->executeMode_ == AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND) { + TAG_LOGI(AAFwkTag::INTENT, "Insight intent srcEntry invalid, may need free install on demand"); + std::string startTime = std::to_string(std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count()); + want.SetParam(Want::PARAM_RESV_START_TIME, startTime); + want.AddFlags(Want::FLAG_INSTALL_ON_DEMAND); + } else { + TAG_LOGE(AAFwkTag::INTENT, "Insight intent srcEntry invalid"); return ERR_INVALID_VALUE; } - want.SetParam(INSIGHT_INTENT_SRC_ENTRY, srcEntry); want.SetParam(INSIGHT_INTENT_EXECUTE_PARAM_NAME, param->insightIntentName_); want.SetParam(INSIGHT_INTENT_EXECUTE_PARAM_MODE, param->executeMode_); diff --git a/services/abilitymgr/src/insight_intent_execute_param.cpp b/services/abilitymgr/src/insight_intent_execute_param.cpp index 72968123ad..545e6ff889 100644 --- a/services/abilitymgr/src/insight_intent_execute_param.cpp +++ b/services/abilitymgr/src/insight_intent_execute_param.cpp @@ -15,7 +15,6 @@ #include "insight_intent_execute_param.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "int_wrapper.h" #include "string_wrapper.h" diff --git a/services/abilitymgr/src/insight_intent_profile.cpp b/services/abilitymgr/src/insight_intent_profile.cpp index 9052e09a86..2388b3cc42 100644 --- a/services/abilitymgr/src/insight_intent_profile.cpp +++ b/services/abilitymgr/src/insight_intent_profile.cpp @@ -16,7 +16,6 @@ #include "insight_intent_profile.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "json_util.h" #include "nlohmann/json.hpp" diff --git a/services/abilitymgr/src/insight_intent_utils.cpp b/services/abilitymgr/src/insight_intent_utils.cpp index 08eae05b34..9193667706 100644 --- a/services/abilitymgr/src/insight_intent_utils.cpp +++ b/services/abilitymgr/src/insight_intent_utils.cpp @@ -17,7 +17,6 @@ #include "bundle_mgr_helper.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "in_process_call_wrapper.h" #include "insight_intent_profile.h" diff --git a/services/abilitymgr/src/interceptor/ability_interceptor_executer.cpp b/services/abilitymgr/src/interceptor/ability_interceptor_executer.cpp index be44f64183..87fabc7d48 100644 --- a/services/abilitymgr/src/interceptor/ability_interceptor_executer.cpp +++ b/services/abilitymgr/src/interceptor/ability_interceptor_executer.cpp @@ -14,7 +14,6 @@ */ #include "interceptor/ability_interceptor_executer.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" namespace OHOS { diff --git a/services/abilitymgr/src/interceptor/ability_jump_interceptor.cpp b/services/abilitymgr/src/interceptor/ability_jump_interceptor.cpp index 8b77ea4c59..eb7e9c8a21 100644 --- a/services/abilitymgr/src/interceptor/ability_jump_interceptor.cpp +++ b/services/abilitymgr/src/interceptor/ability_jump_interceptor.cpp @@ -15,7 +15,6 @@ #include "interceptor/ability_jump_interceptor.h" -#include "ability_manager_service.h" #include "ability_util.h" #include "accesstoken_kit.h" #include "app_jump_control_rule.h" @@ -75,7 +74,7 @@ ErrCode AbilityJumpInterceptor::DoProcess(AbilityInterceptorParam param) Want dialogWant = sysDialogScheduler->GetJumpInterceptorDialogWant(targetWant); AbilityUtil::ParseJumpInterceptorWant(dialogWant, controlRule.callerPkg); LoadAppLabelInfo(dialogWant, controlRule, param.userId); - int ret = IN_PROCESS_CALL(DelayedSingleton::GetInstance()->StartAbility(dialogWant, + int ret = IN_PROCESS_CALL(AbilityManagerClient::GetInstance()->StartAbility(dialogWant, param.requestCode, param.userId)); if (ret != ERR_OK) { TAG_LOGI(AAFwkTag::ABILITYMGR, "appInterceptor Dialog StartAbility error, ret:%{public}d", ret); @@ -161,7 +160,7 @@ bool AbilityJumpInterceptor::CheckIfExemptByBundleName(const std::string &bundle } int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(appInfo.accessTokenId, permission, false); if (ret == Security::AccessToken::PermissionState::PERMISSION_DENIED) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "VerifyPermission %{public}d: PERMISSION_DENIED.", appInfo.accessTokenId); + TAG_LOGD(AAFwkTag::ABILITYMGR, "PERMISSION_DENIED."); return false; } TAG_LOGI(AAFwkTag::ABILITYMGR, diff --git a/services/abilitymgr/src/interceptor/control_interceptor.cpp b/services/abilitymgr/src/interceptor/control_interceptor.cpp index 7a88aadb91..d08c99b9ef 100644 --- a/services/abilitymgr/src/interceptor/control_interceptor.cpp +++ b/services/abilitymgr/src/interceptor/control_interceptor.cpp @@ -15,7 +15,6 @@ #include "interceptor/control_interceptor.h" -#include "ability_manager_service.h" #include "ability_util.h" #include "app_running_control_rule_result.h" #include "hilog_tag_wrapper.h" @@ -57,8 +56,8 @@ ErrCode ControlInterceptor::DoProcess(AbilityInterceptorParam param) controlWant->SetParam(INTERCEPT_MODULE_NAME, param.want.GetElement().GetModuleName()); controlRule.controlWant = controlWant; } - int ret = IN_PROCESS_CALL(DelayedSingleton::GetInstance()->StartAbility( - *controlRule.controlWant, param.requestCode, param.userId)); + int ret = IN_PROCESS_CALL(AbilityManagerClient::GetInstance()->StartAbility(*controlRule.controlWant, + param.requestCode, param.userId)); if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Control implicit start appgallery failed."); return ret; diff --git a/services/abilitymgr/src/interceptor/crowd_test_interceptor.cpp b/services/abilitymgr/src/interceptor/crowd_test_interceptor.cpp index 1f699e965f..75a58d96b5 100644 --- a/services/abilitymgr/src/interceptor/crowd_test_interceptor.cpp +++ b/services/abilitymgr/src/interceptor/crowd_test_interceptor.cpp @@ -16,7 +16,6 @@ #include "interceptor/crowd_test_interceptor.h" #include "ability_util.h" -#include "ability_service_util.h" #include "hilog_tag_wrapper.h" #include "in_process_call_wrapper.h" #include "start_ability_utils.h" diff --git a/services/abilitymgr/src/interceptor/disposed_rule_interceptor.cpp b/services/abilitymgr/src/interceptor/disposed_rule_interceptor.cpp index 63122088e1..0780bfacc0 100644 --- a/services/abilitymgr/src/interceptor/disposed_rule_interceptor.cpp +++ b/services/abilitymgr/src/interceptor/disposed_rule_interceptor.cpp @@ -15,7 +15,6 @@ #include "interceptor/disposed_rule_interceptor.h" -#include "ability_manager_service.h" #include "ability_record.h" #include "ability_util.h" #include "hilog_tag_wrapper.h" @@ -24,6 +23,7 @@ #include "iservice_registry.h" #include "modal_system_ui_extension.h" #include "task_utils_wrap.h" +#include "ui_extension_utils.h" namespace OHOS { namespace AAFwk { @@ -60,8 +60,8 @@ ErrCode DisposedRuleInterceptor::DoProcess(AbilityInterceptorParam param) } SetInterceptInfo(param.want, disposedRule); if (disposedRule.componentType == AppExecFwk::ComponentType::UI_ABILITY) { - int ret = IN_PROCESS_CALL(DelayedSingleton::GetInstance()->StartAbility( - *disposedRule.want, param.requestCode, param.userId)); + int ret = IN_PROCESS_CALL(AbilityManagerClient::GetInstance()->StartAbility(*disposedRule.want, + param.requestCode, param.userId)); if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "DisposedRuleInterceptor start ability failed."); return ret; @@ -107,7 +107,7 @@ bool DisposedRuleInterceptor::CheckControl(const Want &want, int32_t userId, auto ret = IN_PROCESS_CALL(appControlMgr->GetAbilityRunningControlRule(bundleName, userId, disposedRuleList)); if (ret != ERR_OK || disposedRuleList.empty()) { - HILOG_DEBUG("Get No DisposedRule"); + TAG_LOGD(AAFwkTag::ABILITYMGR, "Get No DisposedRule"); return false; } } @@ -251,7 +251,7 @@ ErrCode DisposedRuleInterceptor::CreateModalUIExtension(const Want &want, const if (abilityRecord == nullptr) { auto systemUIExtension = std::make_shared(); (const_cast(want)).SetParam(UIEXTENSION_MODAL_TYPE, 1); - return systemUIExtension->CreateModalUIExtension(want) ? ERR_OK : INNER_ERR; + return IN_PROCESS_CALL(systemUIExtension->CreateModalUIExtension(want)) ? ERR_OK : INNER_ERR; } else { return abilityRecord->CreateModalUIExtension(want); } diff --git a/services/abilitymgr/src/interceptor/ecological_rule_interceptor.cpp b/services/abilitymgr/src/interceptor/ecological_rule_interceptor.cpp index 594f9f2349..6cb141e264 100644 --- a/services/abilitymgr/src/interceptor/ecological_rule_interceptor.cpp +++ b/services/abilitymgr/src/interceptor/ecological_rule_interceptor.cpp @@ -19,7 +19,6 @@ #include "ability_util.h" #include "ecological_rule/ability_ecological_rule_mgr_service.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "in_process_call_wrapper.h" #include "ipc_skeleton.h" @@ -32,6 +31,7 @@ namespace { constexpr const char* ABILITY_SUPPORT_ECOLOGICAL_RULEMGRSERVICE = "persist.sys.abilityms.support.ecologicalrulemgrservice"; constexpr const char* BUNDLE_NAME_SCENEBOARD = "com.ohos.sceneboard"; +constexpr int32_t ERMS_ISALLOW_RESULTCODE = 10; } ErrCode EcologicalRuleInterceptor::DoProcess(AbilityInterceptorParam param) { @@ -55,12 +55,7 @@ ErrCode EcologicalRuleInterceptor::DoProcess(AbilityInterceptorParam param) } AAFwk::Want newWant = param.want; newWant.RemoveAllFd(); - 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."); - return ERR_OK; - } + InitErmsCallerInfo(newWant, param.abilityInfo, callerInfo, param.userId, param.callerToken); int ret = IN_PROCESS_CALL(AbilityEcologicalRuleMgrServiceClient::GetInstance()->QueryStartExperience(newWant, callerInfo, rule)); @@ -69,10 +64,17 @@ ErrCode EcologicalRuleInterceptor::DoProcess(AbilityInterceptorParam param) return ERR_OK; } TAG_LOGD(AAFwkTag::ECOLOGICAL_RULE, "check ecological rule success"); - if (rule.isAllow) { + StartAbilityUtils::ermsResultCode = rule.resultCode; + if (rule.resultCode == ERMS_ISALLOW_RESULTCODE) { TAG_LOGD(AAFwkTag::ECOLOGICAL_RULE, "ecological rule is allow, keep going."); return ERR_OK; } + + 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."); + return ERR_OK; + } #ifdef SUPPORT_GRAPHICS if (param.isWithUI && rule.replaceWant) { (const_cast(param.want)) = *rule.replaceWant; @@ -105,18 +107,17 @@ bool EcologicalRuleInterceptor::DoProcess(Want &want, int32_t userId) } want.SetElement(launchWant.GetElement()); - AppExecFwk::ApplicationInfo targetAppInfo; - bool getCallerResult = IN_PROCESS_CALL(bundleMgrHelper->GetApplicationInfo(want.GetBundle(), - AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, targetAppInfo)); - if (!getCallerResult) { + int32_t appIndex = 0; + StartAbilityUtils::startAbilityInfo = StartAbilityInfo::CreateStartAbilityInfo(want, + userId, appIndex); + if (StartAbilityUtils::startAbilityInfo->status != ERR_OK) { TAG_LOGE(AAFwkTag::ECOLOGICAL_RULE, "Get targetApplicationInfo failed."); return false; } - want.SetParam("send_to_erms_targetAppProvisionType", targetAppInfo.appProvisionType); - want.SetParam("send_to_erms_targetBundleType", static_cast(targetAppInfo.bundleType)); ErmsCallerInfo callerInfo; - GetEcologicalCallerInfo(want, callerInfo, userId); + InitErmsCallerInfo(want, nullptr, callerInfo, userId); + ExperienceRule rule; AAFwk::Want newWant = want; newWant.RemoveAllFd(); @@ -126,14 +127,37 @@ bool EcologicalRuleInterceptor::DoProcess(Want &want, int32_t userId) TAG_LOGD(AAFwkTag::ECOLOGICAL_RULE, "check ecological rule failed, keep going."); return true; } - return rule.isAllow; + return rule.resultCode == ERMS_ISALLOW_RESULTCODE; +} + +void EcologicalRuleInterceptor::GetEcologicalTargetInfo(const Want &want, + const std::shared_ptr &abilityInfo, ErmsCallerInfo &callerInfo) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + callerInfo.targetLinkFeature = want.GetStringParam("send_to_erms_targetLinkFeature"); + callerInfo.targetLinkType = want.GetIntParam("send_to_erms_targetLinkType", 0); + if (StartAbilityUtils::startAbilityInfo) { + AppExecFwk::AbilityInfo targetAbilityInfo = StartAbilityUtils::startAbilityInfo->abilityInfo; + callerInfo.targetAppDistType = targetAbilityInfo.applicationInfo.appDistributionType; + callerInfo.targetAppProvisionType = targetAbilityInfo.applicationInfo.appProvisionType; + callerInfo.targetAppType = GetAppTypeByBundleType(static_cast( + targetAbilityInfo.applicationInfo.bundleType)); + callerInfo.targetAbilityType = targetAbilityInfo.type; + callerInfo.targetExtensionAbilityType = targetAbilityInfo.extensionAbilityType; + } else if (abilityInfo != nullptr) { + callerInfo.targetAppDistType = abilityInfo->applicationInfo.appDistributionType; + callerInfo.targetAppProvisionType = abilityInfo->applicationInfo.appProvisionType; + callerInfo.targetAppType = GetAppTypeByBundleType(static_cast( + abilityInfo->applicationInfo.bundleType)); + callerInfo.targetAbilityType = abilityInfo->type; + callerInfo.targetExtensionAbilityType = abilityInfo->extensionAbilityType; + } } 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); AppExecFwk::ApplicationInfo callerAppInfo; AppExecFwk::AbilityInfo callerAbilityInfo; @@ -178,39 +202,32 @@ void EcologicalRuleInterceptor::GetEcologicalCallerInfo(const Want &want, ErmsCa } } -void EcologicalRuleInterceptor::InitErmsCallerInfo(Want &want, ErmsCallerInfo &callerInfo) const +void EcologicalRuleInterceptor::InitErmsCallerInfo(const Want &want, + const std::shared_ptr &abilityInfo, + ErmsCallerInfo &callerInfo, int32_t userId, const sptr &callerToken) { callerInfo.packageName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME); callerInfo.uid = want.GetIntParam(Want::PARAM_RESV_CALLER_UID, IPCSkeleton::GetCallingUid()); callerInfo.pid = want.GetIntParam(Want::PARAM_RESV_CALLER_PID, IPCSkeleton::GetCallingPid()); - callerInfo.targetAppType = ErmsCallerInfo::TYPE_INVALID; - callerInfo.callerAppType = ErmsCallerInfo::TYPE_INVALID; - callerInfo.targetLinkFeature = want.GetStringParam("send_to_erms_targetLinkFeature"); - callerInfo.targetAppDistType = want.GetStringParam("send_to_erms_targetAppDistType"); - callerInfo.targetLinkType = want.GetIntParam("send_to_erms_targetLinkType", 0); - want.RemoveParam("send_to_erms_targetLinkFeature"); - want.RemoveParam("send_to_erms_targetAppDistType"); - want.RemoveParam("send_to_erms_targetLinkType"); - HILOG_INFO( - "get callerInfo targetLinkFeature is %{public}s, targetAppDistType is %{public}s, targetLinkType is %{public}d", - callerInfo.targetLinkFeature.c_str(), callerInfo.targetAppDistType.c_str(), callerInfo.targetLinkType); callerInfo.embedded = want.GetIntParam("send_to_erms_embedded", 0); - callerInfo.targetAppProvisionType = want.GetStringParam("send_to_erms_targetAppProvisionType"); + + GetEcologicalTargetInfo(want, abilityInfo, callerInfo); + GetEcologicalCallerInfo(want, callerInfo, userId, callerToken); + TAG_LOGI(AAFwkTag::ECOLOGICAL_RULE, "The ERMS's %{public}s", callerInfo.ToString().c_str()); +} - auto targetBundleType = want.GetIntParam("send_to_erms_targetBundleType", -1); - want.RemoveParam("send_to_erms_targetBundleType"); - if (targetBundleType == static_cast(AppExecFwk::BundleType::ATOMIC_SERVICE)) { - TAG_LOGD(AAFwkTag::ECOLOGICAL_RULE, "the target type is atomic service"); - callerInfo.targetAppType = ErmsCallerInfo::TYPE_ATOM_SERVICE; +int32_t EcologicalRuleInterceptor::GetAppTypeByBundleType(int32_t bundleType) +{ + if (bundleType == static_cast(AppExecFwk::BundleType::ATOMIC_SERVICE)) { + return ErmsCallerInfo::TYPE_ATOM_SERVICE; } - if (targetBundleType == static_cast(AppExecFwk::BundleType::APP)) { - TAG_LOGD(AAFwkTag::ECOLOGICAL_RULE, "the target type is app"); - callerInfo.targetAppType = ErmsCallerInfo::TYPE_HARMONY_APP; + if (bundleType == static_cast(AppExecFwk::BundleType::APP)) { + return ErmsCallerInfo::TYPE_HARMONY_APP; } - if (targetBundleType == static_cast(AppExecFwk::BundleType::APP_SERVICE_FWK)) { - TAG_LOGD(AAFwkTag::ECOLOGICAL_RULE, "the target type is app service"); - callerInfo.targetAppType = ErmsCallerInfo::TYPE_APP_SERVICE; + if (bundleType == static_cast(AppExecFwk::BundleType::APP_SERVICE_FWK)) { + return ErmsCallerInfo::TYPE_APP_SERVICE; } + return ErmsCallerInfo::TYPE_INVALID; } } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/interceptor/screen_unlock_interceptor.cpp b/services/abilitymgr/src/interceptor/screen_unlock_interceptor.cpp index 2ffe41b8c3..cd6df53240 100644 --- a/services/abilitymgr/src/interceptor/screen_unlock_interceptor.cpp +++ b/services/abilitymgr/src/interceptor/screen_unlock_interceptor.cpp @@ -20,6 +20,10 @@ #include "hilog_tag_wrapper.h" #include "parameters.h" #include "start_ability_utils.h" +#ifdef SUPPORT_SCREEN +#include "screenlock_manager.h" +#include "screenlock_common.h" +#endif namespace OHOS { namespace AAFwk { @@ -41,14 +45,14 @@ ErrCode ScreenUnlockInterceptor::DoProcess(AbilityInterceptorParam param) } else { auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper(); if (bundleMgrHelper == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "The bundleMgrHelper is nullptr."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "The bundleMgrHelper is nullptr."); return ERR_OK; } IN_PROCESS_CALL_WITHOUT_RET(bundleMgrHelper->QueryAbilityInfo(param.want, AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, param.userId, targetAbilityInfo)); if (targetAbilityInfo.applicationInfo.name.empty() || targetAbilityInfo.applicationInfo.bundleName.empty()) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot find targetAbilityInfo, element uri: %{public}s", + TAG_LOGD(AAFwkTag::ABILITYMGR, "Cannot find targetAbilityInfo, element uri: %{public}s", param.want.GetElement().GetURI().c_str()); return ERR_OK; } @@ -59,6 +63,11 @@ ErrCode ScreenUnlockInterceptor::DoProcess(AbilityInterceptorParam param) targetAbilityInfo.applicationInfo.allowAppRunWhenDeviceFirstLocked) { return ERR_OK; } +#ifdef SUPPORT_SCREEN + if (OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked()) { + return ERR_OK; + } +#endif TAG_LOGE(AAFwkTag::ABILITYMGR, "Can not startup when device first locked."); return ERR_BLOCK_START_FIRST_BOOT_SCREEN_UNLOCK; } diff --git a/services/abilitymgr/src/launch_param.cpp b/services/abilitymgr/src/launch_param.cpp index 94d3a39dc8..d9969d4200 100644 --- a/services/abilitymgr/src/launch_param.cpp +++ b/services/abilitymgr/src/launch_param.cpp @@ -16,7 +16,6 @@ #include "launch_param.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "string_ex.h" namespace OHOS { diff --git a/services/abilitymgr/src/lifecycle_deal.cpp b/services/abilitymgr/src/lifecycle_deal.cpp index 7a15e9548f..75e4283ee5 100644 --- a/services/abilitymgr/src/lifecycle_deal.cpp +++ b/services/abilitymgr/src/lifecycle_deal.cpp @@ -18,7 +18,6 @@ #include "ability_record.h" #include "ability_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/mission_data_storage.cpp b/services/abilitymgr/src/mission_data_storage.cpp index d2f7bc7e41..d250a77e04 100644 --- a/services/abilitymgr/src/mission_data_storage.cpp +++ b/services/abilitymgr/src/mission_data_storage.cpp @@ -18,7 +18,6 @@ #include "directory_ex.h" #include "file_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "image_packer.h" #include "image_source.h" diff --git a/services/abilitymgr/src/mission_info_mgr.cpp b/services/abilitymgr/src/mission_info_mgr.cpp index 7f9041ed8f..7584afd786 100644 --- a/services/abilitymgr/src/mission_info_mgr.cpp +++ b/services/abilitymgr/src/mission_info_mgr.cpp @@ -18,7 +18,6 @@ #include "ability_manager_service.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "nlohmann/json.hpp" #ifdef SUPPORT_GRAPHICS diff --git a/services/abilitymgr/src/mission_list.cpp b/services/abilitymgr/src/mission_list.cpp index ecb7d609b8..87f0ac5460 100644 --- a/services/abilitymgr/src/mission_list.cpp +++ b/services/abilitymgr/src/mission_list.cpp @@ -16,7 +16,6 @@ #include "mission_list.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" namespace OHOS { @@ -464,8 +463,7 @@ int32_t MissionList::GetMissionCount() const return static_cast(missions_.size()); } -void MissionList::GetActiveAbilityList(const std::string &bundleName, std::vector &abilityList, - int32_t pid) +void MissionList::GetActiveAbilityList(int32_t uid, std::vector &abilityList, int32_t pid) { for (auto mission : missions_) { if (!mission) { @@ -482,7 +480,7 @@ void MissionList::GetActiveAbilityList(const std::string &bundleName, std::vecto } const AppExecFwk::AbilityInfo &abilityInfo = abilityRecord->GetAbilityInfo(); - if (abilityInfo.bundleName == bundleName && !abilityInfo.name.empty()) { + if (abilityInfo.applicationInfo.uid == uid && !abilityInfo.name.empty()) { TAG_LOGD(AAFwkTag::ABILITYMGR, "find ability name is %{public}s", abilityInfo.name.c_str()); abilityList.push_back(abilityInfo.name); } diff --git a/services/abilitymgr/src/mission_list_manager.cpp b/services/abilitymgr/src/mission_list_manager.cpp index d8b1bf0be3..65d75753d3 100644 --- a/services/abilitymgr/src/mission_list_manager.cpp +++ b/services/abilitymgr/src/mission_list_manager.cpp @@ -26,7 +26,6 @@ #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" @@ -454,7 +453,7 @@ int MissionListManager::StartAbilityLocked(const std::shared_ptr if (supportBackToOtherMissionStack && needBackToOtherMissionStack) { // mark if need back to other mission stack targetAbilityRecord->SetNeedBackToOtherMissionStack(true); - auto focusAbility = OHOS::DelayedSingleton::GetInstance()->GetFocusAbility(); + auto focusAbility = AbilityManagerService::GetPubInstance()->GetFocusAbility(); if (focusAbility && (GetMissionIdByAbilityTokenInner(focusAbility->GetToken()) != -1)) { targetAbilityRecord->SetOtherMissionStackAbilityRecord(focusAbility); } else { @@ -465,8 +464,7 @@ int MissionListManager::StartAbilityLocked(const std::shared_ptr NotifyAbilityToken(targetAbilityRecord->GetToken(), abilityRequest); - TAG_LOGD(AAFwkTag::ABILITYMGR, "StartAbilityLocked, abilityRequest.specifyTokenId is %{public}u.", - abilityRequest.specifyTokenId); + TAG_LOGD(AAFwkTag::ABILITYMGR, "StartAbilityLocked, abilityRequest."); targetAbilityRecord->SetSpecifyTokenId(abilityRequest.specifyTokenId); targetAbilityRecord->SetAbilityForegroundingFlag(); @@ -751,10 +749,11 @@ std::shared_ptr MissionListManager::GetTargetMissionListByDefault( return nullptr; } - auto missionListMgr = DelayedSingleton::GetInstance()->GetMissionListManagerByUserId( + auto missionListMgr = AbilityManagerService::GetPubInstance()->GetMissionListManagerByUserId( callerAbility->GetOwnerMissionUserId()); CHECK_POINTER_AND_RETURN(missionListMgr, nullptr); - auto callerMission = missionListMgr->GetMissionById(callerAbility->GetMissionId()); + auto callerMission = reinterpret_cast(missionListMgr.get())->GetMissionById( + callerAbility->GetMissionId()); CHECK_POINTER_AND_RETURN(callerMission, nullptr); auto callerList = callerMission->GetMissionList(); CHECK_POINTER_AND_RETURN(callerList, nullptr); @@ -1009,7 +1008,7 @@ int MissionListManager::AttachAbilityThread(const sptr &sched TAG_LOGD(AAFwkTag::ABILITYMGR, "AbilityMS attach abilityThread, name is %{public}s.", abilityRecord->GetAbilityInfo().name.c_str()); - auto eventHandler = DelayedSingleton::GetInstance()->GetEventHandler(); + auto eventHandler = AbilityManagerService::GetPubInstance()->GetEventHandler(); CHECK_POINTER_AND_RETURN_LOG(eventHandler, ERR_INVALID_VALUE, "Fail to get AbilityEventHandler."); eventHandler->RemoveEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecord->GetAbilityRecordId()); abilityRecord->SetLoading(false); @@ -1034,7 +1033,7 @@ int MissionListManager::AttachAbilityThread(const sptr &sched abilityRecord->CallRequest(); } - auto taskHandler = DelayedSingleton::GetInstance()->GetTaskHandler(); + auto taskHandler = AbilityManagerService::GetPubInstance()->GetTaskHandler(); CHECK_POINTER_AND_RETURN_LOG(taskHandler, ERR_INVALID_VALUE, "Fail to get AbilityTaskHandler."); auto taskName = std::to_string(abilityRecord->GetMissionId()) + "_cold"; taskHandler->CancelTask(taskName); @@ -1047,7 +1046,7 @@ int MissionListManager::AttachAbilityThread(const sptr &sched return ERR_OK; } -void MissionListManager::OnAbilityRequestDone(const sptr &token, const int32_t state) +void MissionListManager::OnAbilityRequestDone(const sptr &token, int32_t state) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Ability request state %{public}d done.", state); std::lock_guard guard(managerLock_); @@ -1123,7 +1122,7 @@ void MissionListManager::OnAppStateChanged(const AppInfo &info) } std::shared_ptr MissionListManager::GetAbilityRecordByToken( - const sptr &token) const + const sptr &token) { std::lock_guard guard(managerLock_); return GetAbilityRecordByTokenInner(token); @@ -1250,12 +1249,12 @@ int MissionListManager::DispatchForeground(const std::shared_ptr AbilityState::FOREGROUNDING, abilityRecord->GetAbilityState()); return ERR_INVALID_VALUE; } - auto eventHandler = DelayedSingleton::GetInstance()->GetEventHandler(); + auto eventHandler = AbilityManagerService::GetPubInstance()->GetEventHandler(); CHECK_POINTER_AND_RETURN_LOG(eventHandler, ERR_INVALID_VALUE, "Fail to get AbilityEventHandler."); eventHandler->RemoveEvent(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecord->GetAbilityRecordId()); g_deleteLifecycleEventTask(abilityRecord->GetToken(), FreezeUtil::TimeoutState::FOREGROUND); auto self(weak_from_this()); - auto taskHandler = DelayedSingleton::GetInstance()->GetTaskHandler(); + auto taskHandler = AbilityManagerService::GetPubInstance()->GetTaskHandler(); CHECK_POINTER_AND_RETURN_LOG(taskHandler, ERR_INVALID_VALUE, "Fail to get AbilityTaskHandler."); if (success) { #ifdef SUPPORT_SCREEN @@ -1377,7 +1376,7 @@ void MissionListManager::TerminatePreviousAbility(const std::shared_ptr &abilityRecord) { - auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); + auto handler = AbilityManagerService::GetPubInstance()->GetTaskHandler(); CHECK_POINTER_AND_RETURN_LOG(handler, ERR_INVALID_VALUE, "Fail to get AbilityTasktHandler."); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); @@ -1759,7 +1758,7 @@ int MissionListManager::DispatchTerminate(const std::shared_ptr & } // remove terminate timeout task. - auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); + auto handler = AbilityManagerService::GetPubInstance()->GetTaskHandler(); CHECK_POINTER_AND_RETURN_LOG(handler, ERR_INVALID_VALUE, "Fail to get AbilityTasktHandler."); handler->CancelTask("terminate_" + std::to_string(abilityRecord->GetAbilityRecordId())); auto self(shared_from_this()); @@ -1771,7 +1770,7 @@ int MissionListManager::DispatchTerminate(const std::shared_ptr & void MissionListManager::DelayCompleteTerminate(const std::shared_ptr &abilityRecord) { - auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); + auto handler = AbilityManagerService::GetPubInstance()->GetTaskHandler(); CHECK_POINTER(handler); PrintTimeOutLog(abilityRecord, AbilityManagerService::TERMINATE_TIMEOUT_MSG); @@ -1977,7 +1976,7 @@ void MissionListManager::ClearAllMissionsLocked(std::list::GetInstance(); + auto abilityMs_ = AbilityManagerService::GetPubInstance(); if (abilityMs_->IsBackgroundTaskUid(mission->GetAbilityRecord()->GetUid())) { TAG_LOGI(AAFwkTag::ABILITYMGR, "the mission is background task, do not need clear"); continue; @@ -2082,7 +2081,8 @@ void MissionListManager::MoveToBackgroundTask(const std::shared_ptrGetAbilityInfo().name.c_str()); abilityRecord->SetIsNewWant(false); if (abilityRecord->lifeCycleStateInfo_.sceneFlag != SCENE_FLAG_KEYGUARD && - !abilityRecord->IsClearMissionFlag() && !isClose) { + !abilityRecord->IsClearMissionFlag() && + !(isClose && AbilityManagerService::GetPubInstance()->GetAnimationFlag())) { UpdateMissionSnapshot(abilityRecord); } @@ -2116,7 +2116,7 @@ void MissionListManager::NotifyMissionCreated(const std::shared_ptr::GetInstance()->GetTaskHandler(); + auto handler = AbilityManagerService::GetPubInstance()->GetTaskHandler(); if (handler == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Fail to get EventHandler, do not post mission label update message."); return; @@ -2392,7 +2392,7 @@ void MissionListManager::HandleTimeoutAndResumeAbility(const std::shared_ptr &callerAbility) { - auto abilityManagerService = DelayedSingleton::GetInstance(); + auto abilityManagerService = AbilityManagerService::GetPubInstance(); CHECK_POINTER(abilityManagerService); auto handler = abilityManagerService->GetTaskHandler(); CHECK_POINTER(handler); @@ -2536,7 +2536,7 @@ void MissionListManager::OnAbilityDied(std::shared_ptr abilityRec return; } - auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); + auto handler = AbilityManagerService::GetPubInstance()->GetEventHandler(); CHECK_POINTER_LOG(handler, "Get AbilityEventHandler failed."); if (abilityRecord->GetAbilityState() == AbilityState::INITIAL) { handler->RemoveEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecord->GetAbilityRecordId()); @@ -2545,7 +2545,7 @@ void MissionListManager::OnAbilityDied(std::shared_ptr abilityRec if (abilityRecord->GetAbilityState() == AbilityState::FOREGROUNDING) { handler->RemoveEvent(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecord->GetAbilityRecordId()); } - auto taskHandler = DelayedSingleton::GetInstance()->GetTaskHandler(); + auto taskHandler = AbilityManagerService::GetPubInstance()->GetTaskHandler(); CHECK_POINTER_LOG(taskHandler, "Fail to get AbilityTaskHandler."); if (abilityRecord->GetAbilityState() == AbilityState::BACKGROUNDING) { taskHandler->CancelTask("background_" + std::to_string(abilityRecord->GetAbilityRecordId())); @@ -2605,7 +2605,7 @@ std::shared_ptr MissionListManager::GetTargetMissionList(int missio // generate a new mission and missionList AbilityRequest abilityRequest; - int generateAbility = DelayedSingleton::GetInstance()->GenerateAbilityRequest( + int generateAbility = AbilityManagerService::GetPubInstance()->GenerateAbilityRequest( innerMissionInfo.missionInfo.want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr, userId_); if (generateAbility != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot find generate ability request, missionId: %{public}d", missionId); @@ -2668,12 +2668,17 @@ sptr MissionListManager::GetAbilityTokenByMissionId(int32_t missi return defaultStandardList_->GetAbilityTokenByMissionId((missionId)); } +std::shared_ptr MissionListManager::GetAbilityRecordByMissionId(int32_t missionId) +{ + return Token::GetAbilityRecordByToken(GetAbilityTokenByMissionId(missionId)); +} + void MissionListManager::PostStartWaitingAbility() { auto self(shared_from_this()); auto startWaitingAbilityTask = [self]() { self->StartWaitingAbility(); }; - auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); + auto handler = AbilityManagerService::GetPubInstance()->GetTaskHandler(); CHECK_POINTER_LOG(handler, "Fail to get AbilityTaskHandler."); /* PostTask to trigger start Ability from waiting queue */ @@ -2778,7 +2783,7 @@ void MissionListManager::HandleAbilityDiedByDefault(std::shared_ptr::GetInstance(); + auto abilityManagerService = AbilityManagerService::GetPubInstance(); CHECK_POINTER(abilityManagerService); auto handler = abilityManagerService->GetTaskHandler(); CHECK_POINTER(handler); @@ -2824,7 +2829,7 @@ void MissionListManager::BackToLauncher() launcherRootAbility->ProcessForegroundAbility(0); } -int MissionListManager::SetMissionContinueState(const sptr &token, const int32_t missionId, +int MissionListManager::SetMissionContinueState(const sptr &token, int32_t missionId, const AAFwk::ContinueState &state) { TAG_LOGD(AAFwkTag::ABILITYMGR, "SetMissionContinueState start. Mission id: %{public}d, state: %{public}d", @@ -2895,7 +2900,7 @@ int MissionListManager::SetMissionIcon(const sptr &token, const s return 0; } -void MissionListManager::CompleteFirstFrameDrawing(const sptr &abilityToken) const +void MissionListManager::CompleteFirstFrameDrawing(const sptr &abilityToken) { FinishAsyncTrace(HITRACE_TAG_ABILITY_MANAGER, TRACE_ATOMIC_SERVICE, TRACE_ATOMIC_SERVICE_ID); TAG_LOGD(AAFwkTag::ABILITYMGR, "CompleteFirstFrameDrawing called."); @@ -2918,7 +2923,7 @@ void MissionListManager::CompleteFirstFrameDrawing(const sptr &ab abilityRecord->SetCompleteFirstFrameDrawing(true); AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance(). HandleOnFirstFrameState(abilityRecord); - auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); + auto handler = AbilityManagerService::GetPubInstance()->GetTaskHandler(); if (handler == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Fail to get Ability task handler."); return; @@ -2931,7 +2936,7 @@ void MissionListManager::CompleteFirstFrameDrawing(const sptr &ab return; } mgr->NotifyMissionCreated(abilityRecord); - if (DelayedSingleton::GetInstance()->IsDmsAlive()) { + if (AbilityManagerService::GetPubInstance()->IsDmsAlive()) { mgr->UpdateMissionSnapshot(abilityRecord); } }; @@ -2961,7 +2966,7 @@ void MissionListManager::ProcessPreload(const std::shared_ptr &re Closure MissionListManager::GetCancelStartingWindowTask(const std::shared_ptr &abilityRecord) const { - auto windowHandler = DelayedSingleton::GetInstance()->GetWMSHandler(); + auto windowHandler = AbilityManagerService::GetPubInstance()->GetWMSHandler(); if (!windowHandler) { TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s, Get WMS handler failed.", __func__); return nullptr; @@ -2979,7 +2984,7 @@ Closure MissionListManager::GetCancelStartingWindowTask(const std::shared_ptr &abilityRecord) const { TAG_LOGI(AAFwkTag::ABILITYMGR, "call"); - auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); + auto handler = AbilityManagerService::GetPubInstance()->GetTaskHandler(); if (!handler) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Fail to get AbilityTaskHandler."); return; @@ -3273,8 +3278,18 @@ int MissionListManager::CallAbilityLocked(const AbilityRequest &abilityRequest) TAG_LOGD(AAFwkTag::ABILITYMGR, "target ability has been resolved."); if (targetAbilityRecord->GetWant().GetBoolParam(Want::PARAM_RESV_CALL_TO_FOREGROUND, false)) { TAG_LOGD(AAFwkTag::ABILITYMGR, "target ability needs to be switched to foreground."); - targetAbilityRecord->PostForegroundTimeoutTask(); - DelayedSingleton::GetInstance()->MoveToForeground(targetAbilityRecord->GetToken()); + if (targetAbilityRecord->GetPendingState() != AbilityState::INITIAL) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "pending state is FOREGROUND or BACKGROUND, dropped."); + targetAbilityRecord->SetPendingState(AbilityState::FOREGROUND); + return ERR_OK; + } +#ifdef SUPPORT_SCREEN + std::shared_ptr startOptions = nullptr; + auto callerAbility = GetAbilityRecordByTokenInner(abilityRequest.callerToken); + targetAbilityRecord->ProcessForegroundAbility(false, abilityRequest, startOptions, callerAbility); +#else + targetAbilityRecord->ProcessForegroundAbility(0); +#endif } return ERR_OK; } else if (ret == ResolveResultType::NG_INNER_ERROR) { @@ -3602,7 +3617,7 @@ bool MissionListManager::CheckLimit() if (IsAppLastAbility(earliestMission->GetAbilityRecord())) { ExitReason exitReason = { REASON_RESOURCE_CONTROL, "Already reach ability max limit, terminate earliest ability." }; - OHOS::DelayedSingleton::GetInstance()->RecordAppExitReason(exitReason); + AbilityManagerService::GetPubInstance()->RecordAppExitReason(exitReason); } TAG_LOGI(AAFwkTag::ABILITYMGR, "already reach limit instance. limit: %{public}d, and terminate earliestAbility success.", @@ -3685,12 +3700,12 @@ void MissionListManager::GetAbilityRunningInfos(std::vector } if (isPerm) { - DelayedSingleton::GetInstance()->GetAbilityRunningInfo(info, ability); + AbilityManagerService::GetPubInstance()->GetAbilityRunningInfo(info, ability); } else { auto callingTokenId = IPCSkeleton::GetCallingTokenID(); auto tokenID = ability->GetApplicationInfo().accessTokenId; if (callingTokenId == tokenID) { - DelayedSingleton::GetInstance()->GetAbilityRunningInfo(info, ability); + AbilityManagerService::GetPubInstance()->GetAbilityRunningInfo(info, ability); } } }; @@ -3714,7 +3729,7 @@ void MissionListManager::GetAbilityRunningInfos(std::vector void MissionListManager::UninstallApp(const std::string &bundleName, int32_t uid) { TAG_LOGI(AAFwkTag::ABILITYMGR, "Uninstall app, bundleName: %{public}s, uid:%{public}d", bundleName.c_str(), uid); - auto abilityManagerService = DelayedSingleton::GetInstance(); + auto abilityManagerService = AbilityManagerService::GetPubInstance(); CHECK_POINTER(abilityManagerService); auto handler = abilityManagerService->GetTaskHandler(); CHECK_POINTER(handler); @@ -3958,8 +3973,9 @@ bool MissionListManager::UpdateAbilityRecordLaunchReason( return true; } - if (abilityRequest.IsContinuation()) { - abilityRecord->SetLaunchReason(LaunchReason::LAUNCHREASON_CONTINUATION); + auto res = abilityRequest.IsContinuation(); + if (res.first) { + abilityRecord->SetLaunchReason(res.second); return true; } @@ -3972,7 +3988,7 @@ bool MissionListManager::UpdateAbilityRecordLaunchReason( return true; } -void MissionListManager::NotifyMissionFocused(const int32_t missionId) +void MissionListManager::NotifyMissionFocused(int32_t missionId) { if (listenerController_) { listenerController_->NotifyMissionFocused(missionId); @@ -3981,7 +3997,7 @@ void MissionListManager::NotifyMissionFocused(const int32_t missionId) } } -void MissionListManager::NotifyMissionUnfocused(const int32_t missionId) +void MissionListManager::NotifyMissionUnfocused(int32_t missionId) { if (listenerController_) { listenerController_->NotifyMissionUnfocused(missionId); @@ -4027,14 +4043,13 @@ int MissionListManager::DoAbilityForeground(std::shared_ptr &abil return ERR_OK; } -void MissionListManager::GetActiveAbilityList(const std::string &bundleName, std::vector &abilityList, - int32_t pid) +void MissionListManager::GetActiveAbilityList(int32_t uid, std::vector &abilityList, int32_t pid) { std::lock_guard guard(managerLock_); for (auto missionList : currentMissionLists_) { if (missionList != nullptr) { std::vector currentActiveAbilities; - missionList->GetActiveAbilityList(bundleName, currentActiveAbilities, pid); + missionList->GetActiveAbilityList(uid, currentActiveAbilities, pid); if (!currentActiveAbilities.empty()) { abilityList.insert(abilityList.end(), currentActiveAbilities.begin(), currentActiveAbilities.end()); } @@ -4043,7 +4058,7 @@ void MissionListManager::GetActiveAbilityList(const std::string &bundleName, std if (defaultStandardList_ != nullptr) { std::vector defaultActiveStandardList; - defaultStandardList_->GetActiveAbilityList(bundleName, defaultActiveStandardList, pid); + defaultStandardList_->GetActiveAbilityList(uid, defaultActiveStandardList, pid); if (!defaultActiveStandardList.empty()) { abilityList.insert(abilityList.end(), defaultActiveStandardList.begin(), defaultActiveStandardList.end()); } @@ -4051,7 +4066,7 @@ void MissionListManager::GetActiveAbilityList(const std::string &bundleName, std if (defaultSingleList_ != nullptr) { std::vector defaultActiveSingleList; - defaultSingleList_->GetActiveAbilityList(bundleName, defaultActiveSingleList, pid); + defaultSingleList_->GetActiveAbilityList(uid, defaultActiveSingleList, pid); if (!defaultActiveSingleList.empty()) { abilityList.insert(abilityList.end(), defaultActiveSingleList.begin(), defaultActiveSingleList.end()); } @@ -4094,16 +4109,12 @@ bool MissionListManager::IsAppLastAbility(const std::shared_ptr & return false; } - std::string bundleName = abilityRecord->GetAbilityInfo().bundleName; - if (bundleName.empty()) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "bundleName is empty."); - return false; - } + auto uid = abilityRecord->GetAbilityInfo().applicationInfo.uid; std::vector abilityList; for (auto missionList : currentMissionLists_) { if (missionList != nullptr) { - missionList->GetActiveAbilityList(bundleName, abilityList); + missionList->GetActiveAbilityList(uid, abilityList); } } @@ -4134,7 +4145,7 @@ int MissionListManager::PrepareClearMissionLocked(int missionId, const std::shar mgr->ClearMissionLocking(missionId, mission); } }; - auto handler = DelayedSingleton::GetInstance()->GetTaskHandler(); + auto handler = AbilityManagerService::GetPubInstance()->GetTaskHandler(); int prepareTerminateTimeout = AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * PREPARE_TERMINATE_TIMEOUT_MULTIPLE; if (handler) { @@ -4221,5 +4232,47 @@ void MissionListManager::SignRestartAppFlag(const std::string &bundleName) defaultSingleList_->SignRestartAppFlag(bundleName); } } + +class MissionListWrapImpl : public MissionListWrap { +public: + ~MissionListWrapImpl() = default; + + std::shared_ptr CreateMissionListManager(int32_t userId) override + { + return std::make_shared(userId); + } + + void RemoveUserDir(int32_t userId) override + { + DelayedSingleton::GetInstance()->RemoveUserDir(userId); + } + + void InitMissionInfoMgr(int32_t userId) override + { + DelayedSingleton::GetInstance()->Init(userId); + } + + void SetMissionAbilityState(int32_t missionId, AbilityState state) override + { + DelayedSingleton::GetInstance()->SetMissionAbilityState(missionId, state); + } + + int32_t GetInnerMissionInfoById(int32_t missionId, InnerMissionInfo &innerMissionInfo) override + { + return DelayedSingleton::GetInstance()->GetInnerMissionInfoById( + missionId, innerMissionInfo); + } +#ifdef SUPPORT_SCREEN + std::shared_ptr GetSnapshot(int32_t missionId) override + { + return DelayedSingleton::GetInstance()->GetSnapshot(missionId); + } +#endif +}; } // namespace AAFwk } // namespace OHOS + +extern "C" __attribute__((visibility("default"))) OHOS::AAFwk::MissionListWrap* CreateMissionListWrap() +{ + return new OHOS::AAFwk::MissionListWrapImpl(); +} \ No newline at end of file diff --git a/services/abilitymgr/src/mission_listener_controller.cpp b/services/abilitymgr/src/mission_listener_controller.cpp index ebb43b81c0..dc993b7950 100644 --- a/services/abilitymgr/src/mission_listener_controller.cpp +++ b/services/abilitymgr/src/mission_listener_controller.cpp @@ -16,7 +16,6 @@ #include "mission_listener_controller.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/mission_listener_proxy.cpp b/services/abilitymgr/src/mission_listener_proxy.cpp index bd00b04d93..f5e8a241ef 100644 --- a/services/abilitymgr/src/mission_listener_proxy.cpp +++ b/services/abilitymgr/src/mission_listener_proxy.cpp @@ -16,7 +16,6 @@ #include "mission_listener_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" diff --git a/services/abilitymgr/src/mission_listener_stub.cpp b/services/abilitymgr/src/mission_listener_stub.cpp index 20f7371e7a..41603dc991 100644 --- a/services/abilitymgr/src/mission_listener_stub.cpp +++ b/services/abilitymgr/src/mission_listener_stub.cpp @@ -16,25 +16,12 @@ #include "mission_listener_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" namespace OHOS { namespace AAFwk { -MissionListenerStub::MissionListenerStub() -{ - vecMemberFunc_.resize(IMissionListener::MISSION_LINSTENER_CMD_MAX); - vecMemberFunc_[ON_MISSION_CREATED] = &MissionListenerStub::OnMissionCreatedInner; - vecMemberFunc_[ON_MISSION_DESTROYED] = &MissionListenerStub::OnMissionDestroyedInner; - vecMemberFunc_[ON_MISSION_SNAPSHOT_CHANGED] = &MissionListenerStub::OnMissionSnapshotChangedInner; - vecMemberFunc_[ON_MISSION_MOVED_TO_FRONT] = &MissionListenerStub::OnMissionMovedToFrontInner; - vecMemberFunc_[ON_MISSION_ICON_UPDATED] = &MissionListenerStub::OnMissionIconUpdatedInner; - vecMemberFunc_[ON_MISSION_CLOSED] = &MissionListenerStub::OnMissionClosedInner; - vecMemberFunc_[ON_MISSION_LABEL_UPDATED] = &MissionListenerStub::OnMissionLabelUpdatedInner; - vecMemberFunc_[ON_MISSION_FOCUSED] = &MissionListenerStub::OnMissionFocusedInner; - vecMemberFunc_[ON_MISSION_UNFOCUSED] = &MissionListenerStub::OnMissionUnfocusedInner; -} +MissionListenerStub::MissionListenerStub() {} int MissionListenerStub::OnMissionCreatedInner(MessageParcel &data, MessageParcel &reply) { @@ -112,12 +99,37 @@ int MissionListenerStub::OnRemoteRequest( TAG_LOGI(AAFwkTag::ABILITYMGR, "Local descriptor is not equal to remote"); return ERR_INVALID_STATE; } - if (code < IMissionListener::MISSION_LINSTENER_CMD_MAX && code >= 0) { - auto memberFunc = vecMemberFunc_[code]; - return (this->*memberFunc)(data, reply); + switch (code) { + case ON_MISSION_CREATED: + return OnMissionCreatedInner(data, reply); + break; + case ON_MISSION_DESTROYED: + return OnMissionDestroyedInner(data, reply); + break; + case ON_MISSION_SNAPSHOT_CHANGED: + return OnMissionSnapshotChangedInner(data, reply); + break; + case ON_MISSION_MOVED_TO_FRONT: + return OnMissionMovedToFrontInner(data, reply); + break; + case ON_MISSION_ICON_UPDATED: + return OnMissionIconUpdatedInner(data, reply); + break; + case ON_MISSION_CLOSED: + return OnMissionClosedInner(data, reply); + break; + case ON_MISSION_LABEL_UPDATED: + return OnMissionLabelUpdatedInner(data, reply); + break; + case ON_MISSION_FOCUSED: + return OnMissionFocusedInner(data, reply); + break; + case ON_MISSION_UNFOCUSED: + return OnMissionUnfocusedInner(data, reply); + break; + } } - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } } // namespace AAFwk diff --git a/services/abilitymgr/src/pending_want_common_event.cpp b/services/abilitymgr/src/pending_want_common_event.cpp index 20916d2ed0..0617a14b20 100644 --- a/services/abilitymgr/src/pending_want_common_event.cpp +++ b/services/abilitymgr/src/pending_want_common_event.cpp @@ -15,7 +15,6 @@ #include "pending_want_common_event.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/pending_want_manager.cpp b/services/abilitymgr/src/pending_want_manager.cpp index 4262988431..12f8371013 100644 --- a/services/abilitymgr/src/pending_want_manager.cpp +++ b/services/abilitymgr/src/pending_want_manager.cpp @@ -21,13 +21,12 @@ #include "ability_manager_service.h" #include "ability_util.h" -#include "common_event_manager.h" #include "distributed_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "in_process_call_wrapper.h" #include "permission_verification.h" +#include "permission_constants.h" namespace OHOS { namespace AAFwk { @@ -293,6 +292,9 @@ int32_t PendingWantManager::PendingWantStartAbility(const Want &want, const sptr const sptr &callerToken, int32_t requestCode, const int32_t callerUid, int32_t callerTokenId) { TAG_LOGI(AAFwkTag::WANTAGENT, "begin"); + if (!CheckCallerPermission()) { + return ERR_INVALID_VALUE; + } int32_t result = DeviceIdDetermine(want, startOptions, callerToken, requestCode, callerUid, callerTokenId); return result; } @@ -303,6 +305,9 @@ int32_t PendingWantManager::PendingWantStartAbilitys(const std::vector::GetInstance()->PublishCommonEvent( eventData, eventPublishData, nullptr, callerUid, callerTokenId)); return ((result == true) ? ERR_OK : (-1)); } @@ -614,6 +619,24 @@ void PendingWantManager::ClearPendingWantRecordTask(const std::string &bundleNam } } +bool PendingWantManager::CheckCallerPermission() +{ + auto callerPid = IPCSkeleton::GetCallingPid(); + AppExecFwk::RunningProcessInfo processInfo; + DelayedSingleton::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo); + if (!processInfo.isFocused && !processInfo.isAbilityForegrounding) { + TAG_LOGW(AAFwkTag::WANTAGENT, "caller is not focused."); + auto permission = DelayedSingleton::GetInstance(); + if (!permission->VerifyCallingPermission(PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND) && + !permission->VerifyCallingPermission(PermissionConstants::PERMISSION_START_ABILIIES_FROM_BACKGROUND) && + !permission->IsSACall()) { + TAG_LOGW(AAFwkTag::WANTAGENT, "caller is PERMISSION_DENIED."); + return false; + } + } + return true; +} + void PendingWantManager::Dump(std::vector &info) { TAG_LOGD(AAFwkTag::WANTAGENT, "dump begin."); diff --git a/services/abilitymgr/src/pending_want_record.cpp b/services/abilitymgr/src/pending_want_record.cpp index 5fddf9c1db..3f4c5beb08 100644 --- a/services/abilitymgr/src/pending_want_record.cpp +++ b/services/abilitymgr/src/pending_want_record.cpp @@ -16,7 +16,6 @@ #include "pending_want_record.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "pending_want_manager.h" #include "int_wrapper.h" diff --git a/services/abilitymgr/src/preload_uiext_state_observer.cpp b/services/abilitymgr/src/preload_uiext_state_observer.cpp index 4965c7f114..81dc573cf6 100644 --- a/services/abilitymgr/src/preload_uiext_state_observer.cpp +++ b/services/abilitymgr/src/preload_uiext_state_observer.cpp @@ -16,7 +16,6 @@ #include "extension_record.h" #include "preload_uiext_state_observer.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { @@ -26,9 +25,17 @@ PreLoadUIExtStateObserver::PreLoadUIExtStateObserver( void PreLoadUIExtStateObserver::OnProcessDied(const AppExecFwk::ProcessData &processData) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "called."); + auto diedProcessName = processData.processName; + TAG_LOGI(AAFwkTag::ABILITYMGR, "DiedProcessName is %{public}s.", diedProcessName.c_str()); auto extensionRecord = extensionRecord_.lock(); if (extensionRecord != nullptr) { + auto hostPid = extensionRecord->hostPid_; + int32_t diedPid = processData.pid; + TAG_LOGD(AAFwkTag::ABILITYMGR, "Host pid is %{public}d, died pid is %{public}d.", hostPid, diedPid); + if (static_cast(hostPid) != diedPid) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Host pid is not equals to died pid."); + return; + } extensionRecord->UnloadUIExtensionAbility(); } else { TAG_LOGW(AAFwkTag::ABILITYMGR, "extensionRecord null"); diff --git a/services/abilitymgr/src/prepare_terminate_callback_proxy.cpp b/services/abilitymgr/src/prepare_terminate_callback_proxy.cpp index 979810a9e2..6d548807b8 100644 --- a/services/abilitymgr/src/prepare_terminate_callback_proxy.cpp +++ b/services/abilitymgr/src/prepare_terminate_callback_proxy.cpp @@ -16,7 +16,6 @@ #include "ability_manager_errors.h" #include "prepare_terminate_callback_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "message_parcel.h" #include "peer_holder.h" diff --git a/services/abilitymgr/src/prepare_terminate_callback_stub.cpp b/services/abilitymgr/src/prepare_terminate_callback_stub.cpp index e2d4f763e9..499cc5a653 100644 --- a/services/abilitymgr/src/prepare_terminate_callback_stub.cpp +++ b/services/abilitymgr/src/prepare_terminate_callback_stub.cpp @@ -15,20 +15,15 @@ #include "prepare_terminate_callback_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { -PrepareTerminateCallbackStub::PrepareTerminateCallbackStub() -{ - requestFuncMap_[ON_DO_PREPARE_TERMINATE] = &PrepareTerminateCallbackStub::DoPrepareTerminateInner; -} +PrepareTerminateCallbackStub::PrepareTerminateCallbackStub() {} PrepareTerminateCallbackStub::~PrepareTerminateCallbackStub() { TAG_LOGI(AAFwkTag::ABILITYMGR, "call"); - requestFuncMap_.clear(); } int32_t PrepareTerminateCallbackStub::OnRemoteRequest( @@ -39,13 +34,10 @@ int32_t PrepareTerminateCallbackStub::OnRemoteRequest( return ERR_INVALID_STATE; } - auto itFunc = requestFuncMap_.find(code); - if (itFunc != requestFuncMap_.end()) { - auto requestFunc = itFunc->second; - if (requestFunc != nullptr) { - return (this->*requestFunc)(data, reply); - } + if (code == ON_DO_PREPARE_TERMINATE) { + return DoPrepareTerminateInner(data, reply); } + TAG_LOGW(AAFwkTag::ABILITYMGR, "default case, needs to be checked."); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } diff --git a/services/abilitymgr/src/process_options.cpp b/services/abilitymgr/src/process_options.cpp index 47163efec5..3c1ffb4ea4 100644 --- a/services/abilitymgr/src/process_options.cpp +++ b/services/abilitymgr/src/process_options.cpp @@ -16,7 +16,6 @@ #include "process_options.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/remote_mission_listener_proxy.cpp b/services/abilitymgr/src/remote_mission_listener_proxy.cpp index 38667305a1..0b4a20d5c8 100644 --- a/services/abilitymgr/src/remote_mission_listener_proxy.cpp +++ b/services/abilitymgr/src/remote_mission_listener_proxy.cpp @@ -16,7 +16,6 @@ #include "remote_mission_listener_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" diff --git a/services/abilitymgr/src/remote_mission_listener_stub.cpp b/services/abilitymgr/src/remote_mission_listener_stub.cpp index abb05a7894..ca6403bbe9 100644 --- a/services/abilitymgr/src/remote_mission_listener_stub.cpp +++ b/services/abilitymgr/src/remote_mission_listener_stub.cpp @@ -17,7 +17,6 @@ #include "remote_mission_listener_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" diff --git a/services/abilitymgr/src/remote_on_listener_proxy.cpp b/services/abilitymgr/src/remote_on_listener_proxy.cpp index 682e9cb127..921c6c6f40 100644 --- a/services/abilitymgr/src/remote_on_listener_proxy.cpp +++ b/services/abilitymgr/src/remote_on_listener_proxy.cpp @@ -17,7 +17,6 @@ #include "remote_on_listener_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" diff --git a/services/abilitymgr/src/remote_on_listener_stub.cpp b/services/abilitymgr/src/remote_on_listener_stub.cpp index b148b7caea..1d24d9e8e8 100644 --- a/services/abilitymgr/src/remote_on_listener_stub.cpp +++ b/services/abilitymgr/src/remote_on_listener_stub.cpp @@ -17,7 +17,6 @@ #include "remote_on_listener_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" diff --git a/services/abilitymgr/src/resident_process_manager.cpp b/services/abilitymgr/src/resident_process_manager.cpp index e1a039038b..97b7c65dd8 100644 --- a/services/abilitymgr/src/resident_process_manager.cpp +++ b/services/abilitymgr/src/resident_process_manager.cpp @@ -189,7 +189,7 @@ int32_t ResidentProcessManager::SetResidentProcessEnabled( void ResidentProcessManager::UpdateResidentProcessesStatus( const std::string &bundleName, bool localEnable, bool updateEnable) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (bundleName.empty()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Bundle name is empty!"); return; diff --git a/services/abilitymgr/src/restart_app_manager.cpp b/services/abilitymgr/src/restart_app_manager.cpp index c64bb13605..63efd27285 100644 --- a/services/abilitymgr/src/restart_app_manager.cpp +++ b/services/abilitymgr/src/restart_app_manager.cpp @@ -17,7 +17,6 @@ #include "app_scheduler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" namespace OHOS { @@ -55,8 +54,7 @@ bool RestartAppManager::IsForegroundToRestartApp() const auto callerPid = IPCSkeleton::GetCallingPid(); AppExecFwk::RunningProcessInfo processInfo; DelayedSingleton::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo); - if (processInfo.state_ == AppProcessState::APP_STATE_FOREGROUND || processInfo.isFocused || - processInfo.isAbilityForegrounding) { + if (processInfo.isFocused || processInfo.isAbilityForegrounding) { return true; } TAG_LOGE(AAFwkTag::ABILITYMGR, "IsForegroundToRestartApp, app stae is not foreground."); 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 076ffceb93..c1640cbd1b 100644 --- a/services/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp +++ b/services/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp @@ -24,7 +24,6 @@ #include "errors.h" #include "exit_reason.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "iability_info_callback.h" #include "in_process_call_wrapper.h" @@ -113,20 +112,16 @@ int UIAbilityLifecycleManager::StartUIAbility(AbilityRequest &abilityRequest, sp UpdateProcessName(abilityRequest, uiAbilityRecord); } CHECK_POINTER_AND_RETURN(uiAbilityRecord, ERR_INVALID_VALUE); - TAG_LOGD(AAFwkTag::ABILITYMGR, "StartUIAbility, specifyTokenId is %{public}u.", abilityRequest.specifyTokenId); + TAG_LOGD(AAFwkTag::ABILITYMGR, "StartUIAbility"); uiAbilityRecord->SetSpecifyTokenId(abilityRequest.specifyTokenId); - if (uiAbilityRecord->GetPendingState() == AbilityState::FOREGROUND) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "pending state is FOREGROUND."); + if (uiAbilityRecord->GetPendingState() != AbilityState::INITIAL) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "pending state is FOREGROUND or BACKGROUND, dropped."); uiAbilityRecord->SetPendingState(AbilityState::FOREGROUND); return ERR_OK; } else { - TAG_LOGD(AAFwkTag::ABILITYMGR, "pending state is not FOREGROUND."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "pending state is not FOREGROUND or BACKGROUND."); uiAbilityRecord->SetPendingState(AbilityState::FOREGROUND); - if (uiAbilityRecord->IsLoading()) { - TAG_LOGI(AAFwkTag::ABILITYMGR, "ability: %{public}s is loading.", abilityRequest.abilityInfo.name.c_str()); - return ERR_OK; - } } if (iter == sessionAbilityMap_.end()) { @@ -276,11 +271,18 @@ void UIAbilityLifecycleManager::OnAbilityRequestDone(const sptr & { TAG_LOGD(AAFwkTag::ABILITYMGR, "Ability request state %{public}d done.", state); HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - std::lock_guard guard(sessionLock_); AppAbilityState abilityState = DelayedSingleton::GetInstance()->ConvertToAppAbilityState(state); if (abilityState == AppAbilityState::ABILITY_STATE_FOREGROUND) { + std::lock_guard guard(sessionLock_); auto abilityRecord = GetAbilityRecordByToken(token); CHECK_POINTER(abilityRecord); + if (abilityRecord->IsTerminating()) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "ability is on terminating"); + auto handler = DelayedSingleton::GetInstance()->GetEventHandler(); + CHECK_POINTER(handler); + handler->RemoveEvent(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecord->GetAbilityRecordId()); + return; + } std::string element = abilityRecord->GetElementName().GetURI(); TAG_LOGD(AAFwkTag::ABILITYMGR, "Ability is %{public}s, start to foreground.", element.c_str()); abilityRecord->ForegroundAbility(); @@ -345,6 +347,7 @@ int UIAbilityLifecycleManager::NotifySCBToStartUIAbility(const AbilityRequest &a sessionInfo->persistentId = GetPersistentIdByAbilityRequest(abilityRequest, sessionInfo->reuse); sessionInfo->userId = userId_; sessionInfo->processOptions = abilityRequest.processOptions; + sessionInfo->isAtomicService = (abilityInfo.applicationInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE); TAG_LOGI( AAFwkTag::ABILITYMGR, "Reused sessionId: %{public}d, userId: %{public}d.", sessionInfo->persistentId, userId_); int ret = NotifySCBPendingActivation(sessionInfo, abilityRequest); @@ -352,6 +355,18 @@ int UIAbilityLifecycleManager::NotifySCBToStartUIAbility(const AbilityRequest &a return ret; } +int UIAbilityLifecycleManager::NotifySCBToPreStartUIAbility(const AbilityRequest &abilityRequest, + sptr &sessionInfo) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + + std::lock_guard guard(sessionLock_); + sessionInfo = CreateSessionInfo(abilityRequest); + sessionInfo->requestCode = abilityRequest.requestCode; + sessionInfo->isAtomicService = true; + return NotifySCBPendingActivation(sessionInfo, abilityRequest); +} + int UIAbilityLifecycleManager::DispatchState(const std::shared_ptr &abilityRecord, int state) { switch (state) { @@ -673,8 +688,9 @@ void UIAbilityLifecycleManager::UpdateAbilityRecordLaunchReason( return; } - if (abilityRequest.IsContinuation()) { - abilityRecord->SetLaunchReason(LaunchReason::LAUNCHREASON_CONTINUATION); + auto res = abilityRequest.IsContinuation(); + if (res.first) { + abilityRecord->SetLaunchReason(res.second); return; } @@ -735,12 +751,17 @@ int UIAbilityLifecycleManager::MinimizeUIAbility(const std::shared_ptrGetAbilityInfo().name.c_str()); abilityRecord->SetMinimizeReason(fromUser); - abilityRecord->SetPendingState(AbilityState::BACKGROUND); + if (abilityRecord->GetPendingState() != AbilityState::INITIAL) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "pending state is FOREGROUND or BACKGROUND, dropped."); + abilityRecord->SetPendingState(AbilityState::BACKGROUND); + return ERR_OK; + } if (!abilityRecord->IsAbilityState(AbilityState::FOREGROUND)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "ability state is not foreground: %{public}d", abilityRecord->GetAbilityState()); return ERR_OK; } + abilityRecord->SetPendingState(AbilityState::BACKGROUND); MoveToBackground(abilityRecord); return ERR_OK; } @@ -820,6 +841,7 @@ int UIAbilityLifecycleManager::CallAbilityLocked(const AbilityRequest &abilityRe NotifyAbilityToken(uiAbilityRecord->GetToken(), abilityRequest); // new version started by call type + const auto& abilityInfo = abilityRequest.abilityInfo; auto ret = ResolveAbility(uiAbilityRecord, abilityRequest); if (ret == ResolveResultType::OK_HAS_REMOTE_OBJ) { TAG_LOGD(AAFwkTag::ABILITYMGR, "target ability has been resolved."); @@ -830,8 +852,14 @@ int UIAbilityLifecycleManager::CallAbilityLocked(const AbilityRequest &abilityRe sessionInfo->state = CallToState::FOREGROUND; sessionInfo->reuse = reuse; sessionInfo->uiAbilityId = uiAbilityRecord->GetAbilityRecordId(); - uiAbilityRecord->PostForegroundTimeoutTask(); - DelayedSingleton::GetInstance()->MoveToForeground(uiAbilityRecord->GetToken()); + sessionInfo->isAtomicService = + (abilityInfo.applicationInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE); + if (uiAbilityRecord->GetPendingState() != AbilityState::INITIAL) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "pending state is FOREGROUND or BACKGROUND, dropped."); + uiAbilityRecord->SetPendingState(AbilityState::FOREGROUND); + return NotifySCBPendingActivation(sessionInfo, abilityRequest); + } + uiAbilityRecord->ProcessForegroundAbility(sessionInfo->callingTokenId); return NotifySCBPendingActivation(sessionInfo, abilityRequest); } return ERR_OK; @@ -844,6 +872,7 @@ int UIAbilityLifecycleManager::CallAbilityLocked(const AbilityRequest &abilityRe sessionInfo->persistentId = persistentId; sessionInfo->reuse = reuse; sessionInfo->uiAbilityId = uiAbilityRecord->GetAbilityRecordId(); + sessionInfo->isAtomicService = (abilityInfo.applicationInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE); if (abilityRequest.want.GetBoolParam(Want::PARAM_RESV_CALL_TO_FOREGROUND, false)) { sessionInfo->state = CallToState::FOREGROUND; } else { @@ -913,11 +942,14 @@ int UIAbilityLifecycleManager::NotifySCBPendingActivation(sptr &ses { CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE); TAG_LOGD(AAFwkTag::ABILITYMGR, "windowLeft=%{public}d,windowTop=%{public}d," - "windowHeight=%{public}d,windowWidth=%{public}d", + "windowHeight=%{public}d,windowWidth=%{public}d,windowMode=%{public}d", (sessionInfo->want).GetIntParam(Want::PARAM_RESV_WINDOW_LEFT, 0), (sessionInfo->want).GetIntParam(Want::PARAM_RESV_WINDOW_TOP, 0), (sessionInfo->want).GetIntParam(Want::PARAM_RESV_WINDOW_HEIGHT, 0), - (sessionInfo->want).GetIntParam(Want::PARAM_RESV_WINDOW_WIDTH, 0)); + (sessionInfo->want).GetIntParam(Want::PARAM_RESV_WINDOW_WIDTH, 0), + (sessionInfo->want).GetIntParam(Want::PARAM_RESV_WINDOW_MODE, 0)); + TAG_LOGI(AAFwkTag::ABILITYMGR, "appCloneIndex: %{public}d.", + (sessionInfo->want).GetIntParam(Want::PARAM_APP_CLONE_INDEX_KEY, 0)); auto abilityRecord = GetAbilityRecordByToken(abilityRequest.callerToken); if (abilityRecord != nullptr && !abilityRecord->GetRestartAppFlag()) { auto callerSessionInfo = abilityRecord->GetSessionInfo(); @@ -1069,6 +1101,7 @@ void UIAbilityLifecycleManager::CompleteBackground(const std::shared_ptr::GetInstance()->MoveToBackground(abilityRecord->GetToken()); if (abilityRecord->GetPendingState() == AbilityState::FOREGROUND) { + abilityRecord->PostForegroundTimeoutTask(); DelayedSingleton::GetInstance()->MoveToForeground(abilityRecord->GetToken()); } else if (abilityRecord->GetPendingState() == AbilityState::BACKGROUND) { TAG_LOGD(AAFwkTag::ABILITYMGR, "not continuous startup."); @@ -1114,7 +1147,7 @@ int UIAbilityLifecycleManager::CloseUIAbilityInner(std::shared_ptr::GetInstance()->PrepareTerminate(abilityRecord->GetToken()); + DelayedSingleton::GetInstance()->PrepareTerminate(abilityRecord->GetToken(), isClearSession); abilityRecord->SetTerminatingState(); abilityRecord->SetClearMissionFlag(isClearSession); // save result to caller AbilityRecord @@ -1360,7 +1393,7 @@ void UIAbilityLifecycleManager::SetRootSceneSession(const sptr &r } void UIAbilityLifecycleManager::NotifySCBToHandleException(const std::shared_ptr &abilityRecord, - int32_t errorCode, std::string errorReason) + int32_t errorCode, const std::string& errorReason) { TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); if (abilityRecord == nullptr) { @@ -1379,6 +1412,19 @@ void UIAbilityLifecycleManager::NotifySCBToHandleException(const std::shared_ptr EraseAbilityRecord(abilityRecord); } +void UIAbilityLifecycleManager::NotifySCBToHandleAtomicServiceException(sptr sessionInfo, + int32_t errorCode, const std::string& errorReason) +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); + CHECK_POINTER(sessionInfo); + CHECK_POINTER(sessionInfo->sessionToken); + auto session = iface_cast(sessionInfo->sessionToken); + TAG_LOGI(AAFwkTag::ABILITYMGR, "call notifySessionException"); + sessionInfo->errorCode = errorCode; + sessionInfo->errorReason = errorReason; + session->NotifySessionException(sessionInfo); +} + void UIAbilityLifecycleManager::HandleLoadTimeout(const std::shared_ptr &abilityRecord) { TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); @@ -1512,6 +1558,8 @@ void UIAbilityLifecycleManager::OnStartSpecifiedProcessResponse(const AAFwk::Wan sessionInfo->requestCode = abilityRequest.requestCode; sessionInfo->persistentId = GetPersistentIdByAbilityRequest(abilityRequest, sessionInfo->reuse); sessionInfo->userId = abilityRequest.userId; + sessionInfo->isAtomicService = + (abilityRequest.abilityInfo.applicationInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE); TAG_LOGI(AAFwkTag::ABILITYMGR, "Reused sessionId: %{public}d, userId: %{public}d.", sessionInfo->persistentId, abilityRequest.userId); NotifySCBPendingActivation(sessionInfo, abilityRequest); @@ -1903,8 +1951,7 @@ std::shared_ptr UIAbilityLifecycleManager::GetAbilityRecordsById( return search->second; } -void UIAbilityLifecycleManager::GetActiveAbilityList(const std::string &bundleName, - std::vector &abilityList, int32_t pid) +void UIAbilityLifecycleManager::GetActiveAbilityList(int32_t uid, std::vector &abilityList, int32_t pid) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard guard(sessionLock_); @@ -1918,7 +1965,7 @@ void UIAbilityLifecycleManager::GetActiveAbilityList(const std::string &bundleNa continue; } const auto &abilityInfo = abilityRecord->GetAbilityInfo(); - if (abilityInfo.bundleName == bundleName && !abilityInfo.name.empty()) { + if (abilityInfo.applicationInfo.uid == uid && !abilityInfo.name.empty()) { std::string abilityName = abilityInfo.name; if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD && abilityRecord->GetSessionInfo() != nullptr) { @@ -2266,6 +2313,7 @@ int32_t UIAbilityLifecycleManager::KillProcessWithPrepareTerminate(const std::ve HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "do prepare terminate."); std::vector pidsToKill; + IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton::GetInstance()->BlockProcessCacheByPids(pids)); for (const auto& pid: pids) { bool needKillProcess = true; std::unordered_set> abilitysToTerminate; @@ -2452,6 +2500,8 @@ int UIAbilityLifecycleManager::StartWithPersistentIdByDistributed(const AbilityR sessionInfo->persistentId = persistentId; sessionInfo->userId = userId_; sessionInfo->processOptions = abilityRequest.processOptions; + sessionInfo->isAtomicService = + (abilityRequest.abilityInfo.applicationInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE); return NotifySCBPendingActivation(sessionInfo, abilityRequest); } diff --git a/services/abilitymgr/src/sender_info.cpp b/services/abilitymgr/src/sender_info.cpp index db85a5fcc3..bc8a4fda0a 100644 --- a/services/abilitymgr/src/sender_info.cpp +++ b/services/abilitymgr/src/sender_info.cpp @@ -16,7 +16,6 @@ #include "sender_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "nlohmann/json.hpp" #include "string_ex.h" 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 45b98e40e9..a9f53d6071 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 @@ -16,7 +16,6 @@ #include "start_ability_sandbox_savefile.h" #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "ability_manager_errors.h" #include "ability_util.h" diff --git a/services/abilitymgr/src/start_ability_utils.cpp b/services/abilitymgr/src/start_ability_utils.cpp index 3100b5b4ae..81c39edd36 100644 --- a/services/abilitymgr/src/start_ability_utils.cpp +++ b/services/abilitymgr/src/start_ability_utils.cpp @@ -21,7 +21,6 @@ #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" @@ -31,12 +30,17 @@ namespace AAFwk { namespace { constexpr const char* SCREENSHOT_BUNDLE_NAME = "com.huawei.ohos.screenshot"; constexpr const char* SCREENSHOT_ABILITY_NAME = "com.huawei.ohos.screenshot.ServiceExtAbility"; +constexpr int32_t ERMS_ISALLOW_RESULTCODE = 10; +constexpr const char* SHELL_ASSISTANT_BUNDLENAME = "com.huawei.shell_assistant"; +constexpr int32_t BROKER_UID = 5557; } 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; +thread_local int32_t StartAbilityUtils::ermsResultCode = ERMS_ISALLOW_RESULTCODE; +thread_local bool StartAbilityUtils::isWantWithAppCloneIndex = false; bool StartAbilityUtils::GetAppIndex(const Want &want, sptr callerToken, int32_t &appIndex) { @@ -46,6 +50,7 @@ bool StartAbilityUtils::GetAppIndex(const Want &want, sptr caller appIndex = abilityRecord->GetAppIndex(); return true; } + TAG_LOGI(AAFwkTag::ABILITYMGR, "appCloneIndex: %{public}d.", want.GetIntParam(Want::PARAM_APP_CLONE_INDEX_KEY, 0)); return AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex); } @@ -56,6 +61,9 @@ bool StartAbilityUtils::GetApplicationInfo(const std::string &bundleName, int32_ StartAbilityUtils::startAbilityInfo->GetAppBundleName() == bundleName) { appInfo = StartAbilityUtils::startAbilityInfo->abilityInfo.applicationInfo; } else { + if (bundleName.empty()) { + return false; + } auto bms = AbilityUtil::GetBundleManagerHelper(); CHECK_POINTER_AND_RETURN(bms, false); bool result = IN_PROCESS_CALL( @@ -112,6 +120,15 @@ int32_t StartAbilityUtils::CheckAppProvisionMode(const Want& want, int32_t userI return ERR_OK; } +std::vector StartAbilityUtils::GetCloneAppIndexes(const std::string &bundleName, int32_t userId) +{ + std::vector appIndexes; + auto bms = AbilityUtil::GetBundleManagerHelper(); + CHECK_POINTER_AND_RETURN(bms, appIndexes); + IN_PROCESS_CALL_WITHOUT_RET(bms->GetCloneAppIndexes(bundleName, appIndexes, userId)); + return appIndexes; +} + StartAbilityInfoWrap::StartAbilityInfoWrap(const Want &want, int32_t validUserId, int32_t appIndex, const sptr &callerToken, bool isExtension) { @@ -125,11 +142,19 @@ StartAbilityInfoWrap::StartAbilityInfoWrap(const Want &want, int32_t validUserId isExtension = true; StartAbilityUtils::skipErms = true; } + Want localWant = want; + if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) { + localWant.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN); + localWant.RemoveParam(Want::PARAM_RESV_CALLER_UID); + localWant.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME); + localWant.SetParam(Want::PARAM_RESV_CALLER_TOKEN, static_cast(IPCSkeleton::GetCallingTokenID())); + localWant.SetParam(Want::PARAM_RESV_CALLER_UID, IPCSkeleton::GetCallingUid()); + } if (isExtension) { - StartAbilityUtils::startAbilityInfo = StartAbilityInfo::CreateStartExtensionInfo(want, + StartAbilityUtils::startAbilityInfo = StartAbilityInfo::CreateStartExtensionInfo(localWant, validUserId, appIndex); } else { - StartAbilityUtils::startAbilityInfo = StartAbilityInfo::CreateStartAbilityInfo(want, + StartAbilityUtils::startAbilityInfo = StartAbilityInfo::CreateStartAbilityInfo(localWant, validUserId, appIndex); } if (StartAbilityUtils::startAbilityInfo != nullptr && @@ -142,6 +167,13 @@ StartAbilityInfoWrap::StartAbilityInfoWrap(const Want &want, int32_t validUserId TAG_LOGW(AAFwkTag::ABILITYMGR, "callerAbilityInfo has been created"); } StartAbilityUtils::callerAbilityInfo = StartAbilityInfo::CreateCallerAbilityInfo(callerToken); + + StartAbilityUtils::ermsResultCode = ERMS_ISALLOW_RESULTCODE; + StartAbilityUtils::isWantWithAppCloneIndex = false; + if (want.HasParameter(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY) && appIndex >= 0 && + appIndex < AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { + StartAbilityUtils::isWantWithAppCloneIndex = true; + } } StartAbilityInfoWrap::~StartAbilityInfoWrap() @@ -151,6 +183,8 @@ StartAbilityInfoWrap::~StartAbilityInfoWrap() StartAbilityUtils::skipCrowTest = false; StartAbilityUtils::skipStartOther = false; StartAbilityUtils::skipErms = false; + StartAbilityUtils::ermsResultCode = ERMS_ISALLOW_RESULTCODE; + StartAbilityUtils::isWantWithAppCloneIndex = false; } std::shared_ptr StartAbilityInfo::CreateStartAbilityInfo(const Want &want, int32_t userId, @@ -285,5 +319,18 @@ std::shared_ptr StartAbilityInfo::CreateCallerAbilityInfo(cons request->abilityInfo = abilityRecord->GetAbilityInfo(); return request; } + +bool StartAbilityUtils::IsCallFromAncoShellOrBroker(const sptr &callerToken) +{ + auto callingUid = IPCSkeleton::GetCallingUid(); + if (callingUid == BROKER_UID) { + return true; + } + AppExecFwk::AbilityInfo callerAbilityInfo; + if (GetCallerAbilityInfo(callerToken, callerAbilityInfo)) { + return callerAbilityInfo.bundleName == SHELL_ASSISTANT_BUNDLENAME; + } + return false; +} } } \ No newline at end of file diff --git a/services/abilitymgr/src/start_options.cpp b/services/abilitymgr/src/start_options.cpp index 552e8a54f9..75959f07eb 100644 --- a/services/abilitymgr/src/start_options.cpp +++ b/services/abilitymgr/src/start_options.cpp @@ -16,7 +16,6 @@ #include "start_options.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "process_options.h" namespace OHOS { diff --git a/services/abilitymgr/src/sub_managers_helper.cpp b/services/abilitymgr/src/sub_managers_helper.cpp index 59fe7f1dc7..09fac18cd8 100644 --- a/services/abilitymgr/src/sub_managers_helper.cpp +++ b/services/abilitymgr/src/sub_managers_helper.cpp @@ -15,6 +15,8 @@ #include "sub_managers_helper.h" +#include + #include "hilog_tag_wrapper.h" #include "hitrace_meter.h" #include "mission_info_mgr.h" @@ -30,6 +32,15 @@ SubManagersHelper::SubManagersHelper( std::shared_ptr taskHandler, std::shared_ptr eventHandler) : taskHandler_(taskHandler), eventHandler_(eventHandler) {} +SubManagersHelper::~SubManagersHelper() +{ + if (missionLibHandle_ != nullptr) { + missionListWrap_ = nullptr; + dlclose(missionLibHandle_); + missionLibHandle_ = nullptr; + } +} + void SubManagersHelper::InitSubManagers(int userId, bool switchUser) { InitConnectManager(userId, switchUser); @@ -103,12 +114,19 @@ void SubManagersHelper::InitMissionListManager(int userId, bool switchUser) auto it = missionListManagers_.find(userId); if (it != missionListManagers_.end()) { if (switchUser) { - DelayedSingleton::GetInstance()->Init(userId); + auto missionListWrap = GetMissionListWrap(); + if (missionListWrap) { + missionListWrap->InitMissionInfoMgr(userId); + } currentMissionListManager_ = it->second; } return; } - auto manager = std::make_shared(userId); + auto manager = CreateMissionListMgr(userId); + if (manager == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to create mission list manager"); + return; + } manager->Init(); missionListManagers_.emplace(userId, manager); if (switchUser) { @@ -249,19 +267,19 @@ std::shared_ptr SubManagersHelper::GetPendingWantManagerByUs return nullptr; } -std::unordered_map> SubManagersHelper::GetMissionListManagers() +std::unordered_map> SubManagersHelper::GetMissionListManagers() { std::lock_guard lock(managersMutex_); return missionListManagers_; } -std::shared_ptr SubManagersHelper::GetCurrentMissionListManager() +std::shared_ptr SubManagersHelper::GetCurrentMissionListManager() { std::lock_guard lock(managersMutex_); return currentMissionListManager_; } -std::shared_ptr SubManagersHelper::GetMissionListManagerByUserId(int32_t userId) +std::shared_ptr SubManagersHelper::GetMissionListManagerByUserId(int32_t userId) { std::lock_guard lock(managersMutex_); auto it = missionListManagers_.find(userId); @@ -272,7 +290,7 @@ std::shared_ptr SubManagersHelper::GetMissionListManagerByUs return nullptr; } -std::shared_ptr SubManagersHelper::GetMissionListManagerByUid(int32_t uid) +std::shared_ptr SubManagersHelper::GetMissionListManagerByUid(int32_t uid) { int32_t userId = INVALID_USER_ID; if (DelayedSingleton::GetInstance()->GetOsAccountLocalIdFromUid( @@ -431,5 +449,47 @@ bool SubManagersHelper::VerificationAllToken(const sptr &token) TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to verify all token."); return false; } + +std::shared_ptr SubManagersHelper::GetMissionListWrap() +{ + if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { + return nullptr; + } + + std::lock_guard lock(missionListWrapMutex_); + if (missionListWrap_) { + return missionListWrap_; + } + + if (missionLibHandle_ == nullptr) { + missionLibHandle_ = dlopen("libmission_list.z.so", RTLD_NOW | RTLD_GLOBAL); + if (missionLibHandle_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to open mission_list library"); + return nullptr; + } + } + + auto createMissionListWrapFunc = reinterpret_cast(dlsym(missionLibHandle_, + "CreateMissionListWrap")); + if (createMissionListWrapFunc == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get create func"); + dlclose(missionLibHandle_); + missionLibHandle_ = nullptr; + return nullptr; + } + + missionListWrap_ = std::shared_ptr(createMissionListWrapFunc()); + return missionListWrap_; +} + +std::shared_ptr SubManagersHelper::CreateMissionListMgr(int32_t userId) +{ + auto missionListWrap = GetMissionListWrap(); + if (missionListWrap != nullptr) { + return missionListWrap->CreateMissionListManager(userId); + } + + return nullptr; +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/system_ability_token_callback_stub.cpp b/services/abilitymgr/src/system_ability_token_callback_stub.cpp index e568ee43bc..6e31fa8075 100644 --- a/services/abilitymgr/src/system_ability_token_callback_stub.cpp +++ b/services/abilitymgr/src/system_ability_token_callback_stub.cpp @@ -17,7 +17,6 @@ #include "errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "ipc_types.h" #include "want.h" diff --git a/services/abilitymgr/src/system_dialog_scheduler.cpp b/services/abilitymgr/src/system_dialog_scheduler.cpp index 9adc899c15..46d05dde2b 100644 --- a/services/abilitymgr/src/system_dialog_scheduler.cpp +++ b/services/abilitymgr/src/system_dialog_scheduler.cpp @@ -19,6 +19,7 @@ #include "app_utils.h" #include "display_info.h" +#include "constants.h" #include "ability_record.h" #include "ability_util.h" #include "app_gallery_enable_util.h" @@ -27,7 +28,6 @@ #include "display_manager.h" #include "errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "in_process_call_wrapper.h" #include "locale_config.h" @@ -38,99 +38,98 @@ namespace OHOS { namespace AAFwk { -constexpr int32_t UI_SELECTOR_DIALOG_WIDTH = 328 * 2; -constexpr int32_t UI_SELECTOR_DIALOG_HEIGHT = 350 * 2; -constexpr int32_t UI_SELECTOR_DIALOG_HEIGHT_NARROW = 350 * 2; -constexpr int32_t UI_SELECTOR_DIALOG_WIDTH_NARROW = 328 * 2; -constexpr int32_t UI_SELECTOR_DIALOG_PHONE_H1 = 240 * 2; -constexpr int32_t UI_SELECTOR_DIALOG_PHONE_H2 = 340 * 2; -constexpr int32_t UI_SELECTOR_DIALOG_PHONE_H3 = 350 * 2; -constexpr int32_t UI_SELECTOR_DIALOG_PC_H0 = 1; -constexpr int32_t UI_SELECTOR_DIALOG_PC_H2 = (64 * 2 + 56 + 48 + 54 + 64 + 48 + 2) * 2; -constexpr int32_t UI_SELECTOR_DIALOG_PC_H3 = (64 * 3 + 56 + 48 + 54 + 64 + 48 + 2) * 2; -constexpr int32_t UI_SELECTOR_DIALOG_PC_H4 = (64 * 4 + 56 + 48 + 54 + 64 + 48 + 2) * 2; -constexpr int32_t UI_SELECTOR_DIALOG_PC_H5 = (64 * 4 + 56 + 48 + 54 + 64 + 48 + 58 + 2) * 2; +const int32_t UI_SELECTOR_DIALOG_WIDTH = 328 * 2; +const int32_t UI_SELECTOR_DIALOG_HEIGHT = 350 * 2; +const int32_t UI_SELECTOR_DIALOG_HEIGHT_NARROW = 350 * 2; +const int32_t UI_SELECTOR_DIALOG_WIDTH_NARROW = 328 * 2; +const int32_t UI_SELECTOR_DIALOG_PHONE_H1 = 240 * 2; +const int32_t UI_SELECTOR_DIALOG_PHONE_H2 = 340 * 2; +const int32_t UI_SELECTOR_DIALOG_PHONE_H3 = 350 * 2; +const int32_t UI_SELECTOR_DIALOG_PC_H0 = 1; +const int32_t UI_SELECTOR_DIALOG_PC_H2 = (64 * 2 + 56 + 48 + 54 + 64 + 48 + 2) * 2; +const int32_t UI_SELECTOR_DIALOG_PC_H3 = (64 * 3 + 56 + 48 + 54 + 64 + 48 + 2) * 2; +const int32_t UI_SELECTOR_DIALOG_PC_H4 = (64 * 4 + 56 + 48 + 54 + 64 + 48 + 2) * 2; +const int32_t UI_SELECTOR_DIALOG_PC_H5 = (64 * 4 + 56 + 48 + 54 + 64 + 48 + 58 + 2) * 2; -constexpr int32_t UI_SELECTOR_PORTRAIT_PHONE_H1 = 280; -constexpr int32_t UI_SELECTOR_PORTRAIT_PHONE_H2 = 400; -constexpr int32_t UI_SELECTOR_PORTRAIT_PHONE_H3 = 410; -constexpr int32_t UI_SELECTOR_LANDSCAPE_SIGNAL_BAR = 24; -constexpr int32_t UI_SELECTOR_LANDSCAPE_HEIGHT = 350; -constexpr int32_t UI_SELECTOR_LANDSCAPE_HEIGHT_NARROW = 350; -constexpr int32_t UI_SELECTOR_LANDSCAPE_PHONE_H1 = 280; -constexpr int32_t UI_SELECTOR_LANDSCAPE_PHONE_H2 = 400; -constexpr int32_t UI_SELECTOR_LANDSCAPE_PHONE_H3 = 410; -constexpr int32_t UI_SELECTOR_LANDSCAPE_COUNT_THREE = 3; -constexpr int32_t UI_SELECTOR_LANDSCAPE_COUNT_FOUR = 4; -constexpr float UI_SELECTOR_LANDSCAPE_GRILLE_LARGE = 0.107692; -constexpr float UI_SELECTOR_LANDSCAPE_GRILLE_SAMLL = 0.015385; -constexpr float UI_SELECTOR_LANDSCAPE_MAX_RATIO = 0.9; -constexpr float UI_SELECTOR_PORTRAIT_WIDTH_RATIO = 0.8; -constexpr float UI_SELECTOR_PORTRAIT_WIDTH_EDGE_RATIO = 0.1; -constexpr float UI_SELECTOR_PORTRAIT_HEIGHT_RATIO = 0.98; +const int32_t UI_SELECTOR_PORTRAIT_PHONE_H1 = 280; +const int32_t UI_SELECTOR_PORTRAIT_PHONE_H2 = 400; +const int32_t UI_SELECTOR_PORTRAIT_PHONE_H3 = 410; +const int32_t UI_SELECTOR_LANDSCAPE_SIGNAL_BAR = 24; +const int32_t UI_SELECTOR_LANDSCAPE_HEIGHT = 350; +const int32_t UI_SELECTOR_LANDSCAPE_HEIGHT_NARROW = 350; +const int32_t UI_SELECTOR_LANDSCAPE_PHONE_H1 = 280; +const int32_t UI_SELECTOR_LANDSCAPE_PHONE_H2 = 400; +const int32_t UI_SELECTOR_LANDSCAPE_PHONE_H3 = 410; +const int32_t UI_SELECTOR_LANDSCAPE_COUNT_THREE = 3; +const int32_t UI_SELECTOR_LANDSCAPE_COUNT_FOUR = 4; +const float UI_SELECTOR_LANDSCAPE_GRILLE_LARGE = 0.107692; +const float UI_SELECTOR_LANDSCAPE_GRILLE_SAMLL = 0.015385; +const float UI_SELECTOR_LANDSCAPE_MAX_RATIO = 0.9; +const float UI_SELECTOR_PORTRAIT_WIDTH_RATIO = 0.8; +const float UI_SELECTOR_PORTRAIT_WIDTH_EDGE_RATIO = 0.1; +const float UI_SELECTOR_PORTRAIT_HEIGHT_RATIO = 0.98; -constexpr int32_t UI_TIPS_DIALOG_WIDTH = 328 * 2; -constexpr int32_t UI_TIPS_DIALOG_HEIGHT = 135 * 2; -constexpr int32_t UI_TIPS_DIALOG_HEIGHT_NARROW = 135 * 2; -constexpr int32_t UI_TIPS_DIALOG_WIDTH_NARROW = 328 * 2; +const int32_t UI_TIPS_DIALOG_WIDTH = 328 * 2; +const int32_t UI_TIPS_DIALOG_HEIGHT = 135 * 2; +const int32_t UI_TIPS_DIALOG_HEIGHT_NARROW = 135 * 2; +const int32_t UI_TIPS_DIALOG_WIDTH_NARROW = 328 * 2; -constexpr int32_t UI_JUMP_INTERCEPTOR_DIALOG_WIDTH = 328 * 2; -constexpr int32_t UI_JUMP_INTERCEPTOR_DIALOG_HEIGHT = 135 * 2; -constexpr int32_t UI_JUMP_INTERCEPTOR_DIALOG_HEIGHT_NARROW = 135 * 2; -constexpr int32_t UI_JUMP_INTERCEPTOR_DIALOG_WIDTH_NARROW = 328 * 2; +const int32_t UI_JUMP_INTERCEPTOR_DIALOG_WIDTH = 328 * 2; +const int32_t UI_JUMP_INTERCEPTOR_DIALOG_HEIGHT = 135 * 2; +const int32_t UI_JUMP_INTERCEPTOR_DIALOG_HEIGHT_NARROW = 135 * 2; +const int32_t UI_JUMP_INTERCEPTOR_DIALOG_WIDTH_NARROW = 328 * 2; -constexpr int32_t UI_DIALOG_WIDTH = 328 * 2; -constexpr int32_t UI_DIALOG_HEIGHT = 192 * 2; -constexpr const char* APP_NAME = "appName"; -constexpr const char* IS_DEFAULT_SELECTOR = "isDefaultSelector"; -constexpr const char* OFF_SET_X = "offsetX"; -constexpr const char* OFF_SET_Y = "offsetY"; -constexpr const char* WIDTH = "width"; -constexpr const char* HEIGHT = "height"; -constexpr const char* MODEL_FLAG = "modelFlag"; -constexpr const char* ACTION = "action"; -constexpr const char* OVERSIZE_HEIGHT = "oversizeHeight"; +const int32_t UI_ANR_DIALOG_WIDTH = 328 * 2; +const int32_t UI_ANR_DIALOG_HEIGHT = 192 * 2; +const std::string APP_NAME = "appName"; +const std::string IS_DEFAULT_SELECTOR = "isDefaultSelector"; +const std::string OFF_SET_X = "offsetX"; +const std::string OFF_SET_Y = "offsetY"; +const std::string WIDTH = "width"; +const std::string HEIGHT = "height"; +const std::string MODEL_FLAG = "modelFlag"; +const std::string ACTION = "action"; +const std::string OVERSIZE_HEIGHT = "oversizeHeight"; -constexpr int32_t UI_HALF = 2; -constexpr int32_t UI_DEFAULT_BUTTOM_CLIP = 100; -constexpr int32_t UI_WIDTH_780DP = 1560; -constexpr int32_t UI_DEFAULT_WIDTH = 2560; -constexpr int32_t UI_DEFAULT_HEIGHT = 1600; +const int32_t UI_HALF = 2; +const int32_t UI_DEFAULT_BUTTOM_CLIP = 100; +const int32_t UI_WIDTH_780DP = 1560; +const int32_t UI_DEFAULT_WIDTH = 2560; +const int32_t UI_DEFAULT_HEIGHT = 1600; -constexpr const char* STR_PHONE = "phone"; -constexpr const char* STR_DEFAULT = "default"; -constexpr const char* DIALOG_NAME_TIPS = "dialog_tips_service"; -constexpr const char* DIALOG_SELECTOR_NAME = "dialog_selector_service"; -constexpr const char* DIALOG_JUMP_INTERCEPTOR_NAME = "dialog_jump_interceptor_service"; +const std::string STR_PHONE = "phone"; +const std::string STR_DEFAULT = "default"; +const std::string DIALOG_NAME_ANR = "dialog_anr_service"; +const std::string DIALOG_NAME_TIPS = "dialog_tips_service"; +const std::string DIALOG_SELECTOR_NAME = "dialog_selector_service"; +const std::string DIALOG_JUMP_INTERCEPTOR_NAME = "dialog_jump_interceptor_service"; -constexpr const char* BUNDLE_NAME = "bundleName"; -constexpr const char* BUNDLE_NAME_DIALOG = "com.ohos.amsdialog"; -constexpr const char* DIALOG_PARAMS = "params"; -constexpr const char* DIALOG_POSITION = "position"; -constexpr const char* VERTICAL_SCREEN_DIALOG_POSITION = "landscapeScreen"; -constexpr const char* ABILITY_NAME_FREEZE_DIALOG = "SwitchUserDialog"; -constexpr const char* ABILITY_NAME_ASSERT_FAULT_DIALOG = "AssertFaultDialog"; -constexpr const char* ABILITY_NAME_TIPS_DIALOG = "TipsDialog"; -constexpr const char* ABILITY_NAME_SELECTOR_DIALOG = "SelectorDialog"; -constexpr const char* ABILITY_NAME_APPGALLERY_SELECTOR_DIALOG = "AppSelectorExtensionAbility"; -constexpr const char* UIEXTENSION_TYPE_KEY = "ability.want.params.uiExtensionType"; -constexpr const char* UIEXTENSION_SYS_COMMON_UI = "sys/commonUI"; -constexpr const char* CALLER_TOKEN = "callerToken"; -constexpr const char* ABILITY_NAME_JUMP_INTERCEPTOR_DIALOG = "JumpInterceptorDialog"; -constexpr const char* TYPE_ONLY_MATCH_WILDCARD = "reserved/wildcard"; -constexpr const char* ORIENTATION = "orientation"; -constexpr const char* ABS_CODE_PATH = "/data/app/el1/bundle/public"; -constexpr const char* FILE_SEPARATOR = "/"; +const std::string BUNDLE_NAME = "bundleName"; +const std::string BUNDLE_NAME_DIALOG = "com.ohos.amsdialog"; +const std::string DIALOG_PARAMS = "params"; +const std::string DIALOG_POSITION = "position"; +const std::string VERTICAL_SCREEN_DIALOG_POSITION = "landscapeScreen"; +const std::string ABILITY_NAME_FREEZE_DIALOG = "SwitchUserDialog"; +const std::string ABILITY_NAME_ASSERT_FAULT_DIALOG = "AssertFaultDialog"; +const std::string ABILITY_NAME_TIPS_DIALOG = "TipsDialog"; +const std::string ABILITY_NAME_SELECTOR_DIALOG = "SelectorDialog"; +const std::string ABILITY_NAME_APPGALLERY_SELECTOR_DIALOG = "AppSelectorExtensionAbility"; +const std::string UIEXTENSION_TYPE_KEY = "ability.want.params.uiExtensionType"; +const std::string UIEXTENSION_SYS_COMMON_UI = "sys/commonUI"; +const std::string CALLER_TOKEN = "callerToken"; +const std::string ABILITY_NAME_JUMP_INTERCEPTOR_DIALOG = "JumpInterceptorDialog"; +const std::string TYPE_ONLY_MATCH_WILDCARD = "reserved/wildcard"; +const std::string ORIENTATION = "orientation"; -constexpr int32_t LINE_NUMS_ZERO = 0; -constexpr int32_t LINE_NUMS_TWO = 2; -constexpr int32_t LINE_NUMS_THREE = 3; -constexpr int32_t LINE_NUMS_FOUR = 4; -constexpr int32_t LINE_NUMS_EIGHT = 8; +const int32_t LINE_NUMS_ZERO = 0; +const int32_t LINE_NUMS_TWO = 2; +const int32_t LINE_NUMS_THREE = 3; +const int32_t LINE_NUMS_FOUR = 4; +const int32_t LINE_NUMS_EIGHT = 8; -constexpr float WIDTH_MULTIPLE = 0.8; -constexpr float HEIGHT_MULTIPLE = 0.3; -constexpr float SETX_WIDTH_MULTIPLE = 0.1; +const float WIDTH_MULTIPLE = 0.8; +const float HEIGHT_MULTIPLE = 0.3; +const float SETX_WIDTH_MULTIPLE = 0.1; Want SystemDialogScheduler::GetTipsDialogWant(const sptr &callerToken) { @@ -352,6 +351,9 @@ const std::string SystemDialogScheduler::GetSelectorParams(const std::vectorGetWidth(); position.height = display->GetHeight(); position.width_narrow = display->GetWidth(); position.height_narrow = display->GetHeight(); - position.window_width = UI_DIALOG_WIDTH; - position.window_height = UI_DIALOG_HEIGHT; + position.window_width = UI_ANR_DIALOG_WIDTH; + position.window_height = UI_ANR_DIALOG_HEIGHT; position.align = DialogAlign::CENTER; } break; diff --git a/services/abilitymgr/src/task_data_persistence_mgr.cpp b/services/abilitymgr/src/task_data_persistence_mgr.cpp index b843d01103..135cc34f95 100644 --- a/services/abilitymgr/src/task_data_persistence_mgr.cpp +++ b/services/abilitymgr/src/task_data_persistence_mgr.cpp @@ -17,7 +17,6 @@ #include "ability_util.h" #include "directory_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" namespace OHOS { diff --git a/services/abilitymgr/src/ui_extension_ability_connect_info.cpp b/services/abilitymgr/src/ui_extension_ability_connect_info.cpp index c1e6053c08..c3490258a8 100644 --- a/services/abilitymgr/src/ui_extension_ability_connect_info.cpp +++ b/services/abilitymgr/src/ui_extension_ability_connect_info.cpp @@ -15,7 +15,6 @@ #include "ui_extension_ability_connect_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/services/abilitymgr/src/ui_extension_host_info.cpp b/services/abilitymgr/src/ui_extension_host_info.cpp index 6608b78e8d..65a5465cae 100755 --- a/services/abilitymgr/src/ui_extension_host_info.cpp +++ b/services/abilitymgr/src/ui_extension_host_info.cpp @@ -15,7 +15,6 @@ #include "ui_extension_host_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { diff --git a/services/abilitymgr/src/ui_extension_record.cpp b/services/abilitymgr/src/ui_extension_record.cpp index 83c314e4ca..a7773c04f8 100644 --- a/services/abilitymgr/src/ui_extension_record.cpp +++ b/services/abilitymgr/src/ui_extension_record.cpp @@ -56,28 +56,28 @@ void UIExtensionRecord::HandleNotifyUIExtensionTimeout(ErrorCode code) void UIExtensionRecord::LoadTimeout() { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); HandleNotifyUIExtensionTimeout(ErrorCode::LOAD_TIMEOUT); TAG_LOGD(AAFwkTag::ABILITYMGR, "Notify wms, the uiextension load time out."); } void UIExtensionRecord::ForegroundTimeout() { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); HandleNotifyUIExtensionTimeout(ErrorCode::FOREGROUND_TIMEOUT); TAG_LOGD(AAFwkTag::ABILITYMGR, "Notify wms, the uiextension move foreground time out."); } void UIExtensionRecord::BackgroundTimeout() { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); HandleNotifyUIExtensionTimeout(ErrorCode::BACKGROUND_TIMEOUT); TAG_LOGD(AAFwkTag::ABILITYMGR, "Notify wms, the uiextension move background time out."); } void UIExtensionRecord::TerminateTimeout() { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); HandleNotifyUIExtensionTimeout(ErrorCode::TERMINATE_TIMEOUT); TAG_LOGD(AAFwkTag::ABILITYMGR, "Notify wms, the uiextension terminate time out."); } diff --git a/services/abilitymgr/src/ui_extension_session_info.cpp b/services/abilitymgr/src/ui_extension_session_info.cpp new file mode 100755 index 0000000000..4eb5a8249e --- /dev/null +++ b/services/abilitymgr/src/ui_extension_session_info.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 "ui_extension_session_info.h" + +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace AbilityRuntime { +UIExtensionSessionInfo *UIExtensionSessionInfo::Unmarshalling(Parcel &parcel) +{ + UIExtensionSessionInfo *info = new (std::nothrow) UIExtensionSessionInfo(); + if (info == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Create ui extension session info failed."); + return nullptr; + } + info->persistentId = parcel.ReadInt32(); + info->hostWindowId = parcel.ReadUint32(); + info->uiExtensionUsage = static_cast(parcel.ReadUint32()); + return info; +} + +bool UIExtensionSessionInfo::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(persistentId)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Write persistent id failed."); + return false; + } + + if (!parcel.WriteUint32(hostWindowId)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Write host window id failed."); + return false; + } + + if (!parcel.WriteUint32(static_cast(uiExtensionUsage))) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Write uiExtensionUsage failed."); + return false; + } + + return true; +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/services/abilitymgr/src/user_callback_proxy.cpp b/services/abilitymgr/src/user_callback_proxy.cpp index 3278f99cec..49f03e03ee 100644 --- a/services/abilitymgr/src/user_callback_proxy.cpp +++ b/services/abilitymgr/src/user_callback_proxy.cpp @@ -16,7 +16,6 @@ #include "user_callback_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" diff --git a/services/abilitymgr/src/user_callback_stub.cpp b/services/abilitymgr/src/user_callback_stub.cpp index 21030cfa39..b4f56f3840 100644 --- a/services/abilitymgr/src/user_callback_stub.cpp +++ b/services/abilitymgr/src/user_callback_stub.cpp @@ -16,18 +16,12 @@ #include "user_callback_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" namespace OHOS { namespace AAFwk { -UserCallbackStub::UserCallbackStub() -{ - vecMemberFunc_.resize(UserCallbackCmd::CMD_MAX); - vecMemberFunc_[UserCallbackCmd::ON_STOP_USER_DONE] = &UserCallbackStub::OnStopUserDoneInner; - vecMemberFunc_[UserCallbackCmd::ON_START_USER_DONE] = &UserCallbackStub::OnStartUserDoneInner; -} +UserCallbackStub::UserCallbackStub() {} int UserCallbackStub::OnStopUserDoneInner(MessageParcel &data, MessageParcel &reply) { @@ -56,8 +50,14 @@ int UserCallbackStub::OnRemoteRequest( } if (code < UserCallbackCmd::CMD_MAX && code >= 0) { - auto memberFunc = vecMemberFunc_[code]; - return (this->*memberFunc)(data, reply); + switch (code) { + case UserCallbackCmd::ON_STOP_USER_DONE: + return OnStopUserDoneInner(data, reply); + break; + case UserCallbackCmd::ON_START_USER_DONE: + return OnStartUserDoneInner(data, reply); + break; + } } return IPCObjectStub::OnRemoteRequest(code, data, reply, option); diff --git a/services/abilitymgr/src/user_controller.cpp b/services/abilitymgr/src/user_controller.cpp index 156c0a6a5f..fe0f8c449c 100644 --- a/services/abilitymgr/src/user_controller.cpp +++ b/services/abilitymgr/src/user_controller.cpp @@ -18,7 +18,6 @@ #include "ability_manager_service.h" #include "app_scheduler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "mock_session_manager_service.h" #include "os_account_manager_wrapper.h" @@ -175,20 +174,21 @@ int32_t UserController::StopUser(int32_t userId) } appScheduler->KillProcessesByUserId(userId); - if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto taskDataPersistenceMgr = DelayedSingleton::GetInstance(); - if (!taskDataPersistenceMgr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "taskDataPersistenceMgr is null"); - return -1; - } - taskDataPersistenceMgr->RemoveUserDir(userId); - } - auto abilityManagerService = DelayedSingleton::GetInstance(); if (!abilityManagerService) { TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityManagerService is null"); return -1; } + + if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { + auto missionListWrap = abilityManagerService->GetMissionListWrap(); + if (!missionListWrap) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListWrap is null"); + return -1; + } + missionListWrap->RemoveUserDir(userId); + } + abilityManagerService->ClearUserData(userId); BroadcastUserStopped(userId); diff --git a/services/abilitymgr/src/user_event_handler.cpp b/services/abilitymgr/src/user_event_handler.cpp index 47431296c3..416b02f11d 100644 --- a/services/abilitymgr/src/user_event_handler.cpp +++ b/services/abilitymgr/src/user_event_handler.cpp @@ -16,7 +16,6 @@ #include "user_event_handler.h" #include "user_controller.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/utils/app_mgr_util.cpp b/services/abilitymgr/src/utils/app_mgr_util.cpp new file mode 100644 index 0000000000..b2d6d96968 --- /dev/null +++ b/services/abilitymgr/src/utils/app_mgr_util.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 "utils/app_mgr_util.h" + +#include "sys_mgr_client.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AAFwk { +sptr AppMgrUtil::appMgr_ = nullptr; + +OHOS::sptr AppMgrUtil::GetAppMgr() +{ + if (appMgr_) { + return appMgr_; + } + + auto sysMgrClient = DelayedSingleton::GetInstance(); + if (sysMgrClient == nullptr) { + return nullptr; + } + auto object = sysMgrClient->GetSystemAbility(APP_MGR_SERVICE_ID); + if (object == nullptr) { + return nullptr; + } + appMgr_ = OHOS::iface_cast(object); + return appMgr_; +} +} // namespace AAFwk +} // namespace OHOS diff --git a/services/abilitymgr/src/utils/dump_utils.cpp b/services/abilitymgr/src/utils/dump_utils.cpp new file mode 100644 index 0000000000..465d4ddf90 --- /dev/null +++ b/services/abilitymgr/src/utils/dump_utils.cpp @@ -0,0 +1,116 @@ +/* +* 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 "utils/dump_utils.h" + +namespace OHOS { +namespace AAFwk { +std::pair DumpUtils::DumpMapOne(std::string argString) +{ + std::pair result(false, KEY_DUMP_ALL); + + if (argString.compare("-a") || argString.compare("--all")) { + result.first = true; + result.second = KEY_DUMP_ALL; + } else if (argString.compare("-l") || argString.compare("--stack-list")) { + result.first = true; + result.second = KEY_DUMP_STACK_LIST; + } else if (argString.compare("-s") || argString.compare("--stack")) { + result.first = true; + result.second = KEY_DUMP_STACK; + } else if (argString.compare("-m") || argString.compare("--mission")) { + result.first = true; + result.second = KEY_DUMP_MISSION; + } else if (argString.compare("-t") || argString.compare("--top")) { + result.first = true; + result.second = KEY_DUMP_TOP_ABILITY; + } else if (argString.compare("-w") || argString.compare("--waiting-queue")) { + result.first = true; + result.second = KEY_DUMP_WAIT_QUEUE; + } else if (argString.compare("-e") || argString.compare("--serv")) { + result.first = true; + result.second = KEY_DUMP_SERVICE; + } else if (argString.compare("-d") || argString.compare("--data")) { + result.first = true; + result.second = KEY_DUMP_DATA; + } else if (argString.compare("-f") || argString.compare("-focus")) { + result.first = true; + result.second = KEY_DUMP_FOCUS_ABILITY; + } + return result; +} + +std::pair DumpUtils::DumpMapTwo(std::string argString) +{ + std::pair result(false, KEY_DUMP_ALL); + + if (argString.compare("-z") || argString.compare("--win-mode")) { + result.first = true; + result.second = KEY_DUMP_WINDOW_MODE; + } else if (argString.compare("-L") || argString.compare("--mission-list")) { + result.first = true; + result.second = KEY_DUMP_MISSION_LIST; + } else if (argString.compare("-S") || argString.compare("--mission-infos")) { + result.first = true; + result.second = KEY_DUMP_MISSION_INFOS; + } + return result; +} + +std::pair DumpUtils::DumpMap(std::string argString) +{ + std::pair result(false, KEY_DUMP_ALL); + + auto dumpMapOne = DumpMapOne(argString); + if (dumpMapOne.first) { + return dumpMapOne; + } + auto dumpMapTwo = DumpMapTwo(argString); + if (dumpMapTwo.first) { + return dumpMapTwo; + } + return result; +} + +std::pair DumpUtils::DumpsysMap(std::string argString) +{ + std::pair result(false, KEY_DUMP_SYS_ALL); + + if (argString.compare("-a") || argString.compare("--all")) { + result.first = true; + result.second = KEY_DUMP_SYS_ALL; + } else if (argString.compare("-l") || argString.compare("--mission-list")) { + result.first = true; + result.second = KEY_DUMP_SYS_MISSION_LIST; + } else if (argString.compare("-i") || argString.compare("--ability")) { + result.first = true; + result.second = KEY_DUMP_SYS_ABILITY; + } else if (argString.compare("-e") || argString.compare("--extension")) { + result.first = true; + result.second = KEY_DUMP_SYS_SERVICE; + } else if (argString.compare("-p") || argString.compare("--pending")) { + result.first = true; + result.second = KEY_DUMP_SYS_PENDING; + } else if (argString.compare("-r") || argString.compare("--process")) { + result.first = true; + result.second = KEY_DUMP_SYS_PROCESS; + } else if (argString.compare("-d") || argString.compare("--data")) { + result.first = true; + result.second = KEY_DUMP_SYS_DATA; + } + return result; +} +} // namespace AAFwk +} // namespace OHOS diff --git a/services/abilitymgr/src/utils/extension_permissions_util.cpp b/services/abilitymgr/src/utils/extension_permissions_util.cpp new file mode 100644 index 0000000000..cb0934ad99 --- /dev/null +++ b/services/abilitymgr/src/utils/extension_permissions_util.cpp @@ -0,0 +1,96 @@ +/* + * 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 "utils/extension_permissions_util.h" + +#include "hilog_tag_wrapper.h" +#include "permission_verification.h" + +namespace OHOS { +namespace AAFwk { + +bool ExtensionPermissionsUtil::CheckSAPermission(const AppExecFwk::ExtensionAbilityType &extensionType) +{ + auto checkRet = false; + if (!PermissionVerification::GetInstance()->IsSACall()) { + return true; + } + TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckSAPermission, extensionType: %{public}d.", extensionType); + if (extensionType == AppExecFwk::ExtensionAbilityType::FORM) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_FORM_EXTENSION"); + } else if (extensionType == AppExecFwk::ExtensionAbilityType::WORK_SCHEDULER) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_WORK_SCHEDULER_EXTENSION"); + } else if (extensionType == AppExecFwk::ExtensionAbilityType::INPUTMETHOD) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_INPUT_METHOD_EXTENSION"); + } else if (extensionType == AppExecFwk::ExtensionAbilityType::ACCESSIBILITY) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_ACCESSIBILITY_EXTENSION"); + } else if (extensionType == AppExecFwk::ExtensionAbilityType::STATICSUBSCRIBER) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_STATIC_SUBSCRIBER_EXTENSION"); + } else if (extensionType == AppExecFwk::ExtensionAbilityType::WALLPAPER) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_WALLPAPER_EXTENSION"); + } else if (extensionType == AppExecFwk::ExtensionAbilityType::BACKUP) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_BACKUP_EXTENSION"); + } else if (extensionType == AppExecFwk::ExtensionAbilityType::ENTERPRISE_ADMIN) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_ENTERPRISE_ADMIN_EXTENSION"); + } else if (extensionType == AppExecFwk::ExtensionAbilityType::PRINT) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_PRINT_EXTENSION"); + } else if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_VPN_EXTENSION"); + } else { + checkRet = CheckSAPermissionMore(extensionType); + } + if (!checkRet) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "SA connect permission verification failed."); + return false; + } + + return true; +} + +bool ExtensionPermissionsUtil::CheckSAPermissionMore(const AppExecFwk::ExtensionAbilityType &extensionType) +{ + auto checkRet = false; + if (extensionType == AppExecFwk::ExtensionAbilityType::FILEACCESS_EXTENSION) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_FILE_ACCESS_EXTENSION"); + } else if (extensionType == AppExecFwk::ExtensionAbilityType::REMOTE_NOTIFICATION) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_REMOTE_NOTIFICATION_EXTENSION"); + } else if (extensionType == AppExecFwk::ExtensionAbilityType::REMOTE_LOCATION) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_REMOTE_LOCATION_EXTENSION"); + } else if (extensionType == AppExecFwk::ExtensionAbilityType::DRIVER) { + checkRet = PermissionVerification::GetInstance()->VerifyCallingPermission( + "ohos.permission.CONNECT_DRIVER_EXTENSION"); + } else { + TAG_LOGI(AAFwkTag::ABILITYMGR, "No need connect permission for extension type %{public}d.", extensionType); + return true; + } + + return checkRet; +} + +} // namespace AAFwk +} // namespace OHOS diff --git a/services/abilitymgr/src/utils/state_utils.cpp b/services/abilitymgr/src/utils/state_utils.cpp new file mode 100644 index 0000000000..dc3f36be71 --- /dev/null +++ b/services/abilitymgr/src/utils/state_utils.cpp @@ -0,0 +1,75 @@ +/* +* 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 "utils/state_utils.h" + +namespace OHOS { +namespace AAFwk { +std::string StateUtils::StateToStrMap(const AbilityState &state) +{ + switch (state) { + case INITIAL: return "INITIAL"; + case INACTIVE: return "INACTIVE"; + case ACTIVE: return "ACTIVE"; + case INACTIVATING: return "INACTIVATING"; + case ACTIVATING: return "ACTIVATING"; + case TERMINATING: return "TERMINATING"; + case FOREGROUND: return "FOREGROUND"; + case BACKGROUND: return "BACKGROUND"; + case FOREGROUNDING: return "FOREGROUNDING"; + case BACKGROUNDING: return "BACKGROUNDING"; + case FOREGROUND_FAILED: return "FOREGROUND_FAILED"; + case FOREGROUND_INVALID_MODE: return "FOREGROUND_INVALID_MODE"; + case FOREGROUND_WINDOW_FREEZED: return "FOREGROUND_WINDOW_FREEZED"; + case FOREGROUND_DO_NOTHING: return "FOREGROUND_DO_NOTHING"; + case BACKGROUND_FAILED: return "BACKGROUND_FAILED"; + default: return "INVALIDSTATE"; + } +} + +std::string StateUtils::AppStateToStrMap(const AppState &state) +{ + switch (state) { + case AppState::BEGIN: return "BEGIN"; + case AppState::READY: return "READY"; + case AppState::FOREGROUND: return "FOREGROUND"; + case AppState::BACKGROUND: return "BACKGROUND"; + case AppState::SUSPENDED: return "SUSPENDED"; + case AppState::TERMINATED: return "TERMINATED"; + case AppState::END: return "END"; + case AppState::FOCUS: return "FOCUS"; + default: return "INVALIDSTATE"; + } +} + +int StateUtils::ConvertStateMap(const AbilityLifeCycleState &state) +{ + switch (state) { + case ABILITY_STATE_INITIAL: return INITIAL; + case ABILITY_STATE_INACTIVE: return INACTIVE; + case ABILITY_STATE_ACTIVE: return ACTIVE; + case ABILITY_STATE_FOREGROUND_NEW: return FOREGROUND; + case ABILITY_STATE_BACKGROUND_NEW: return BACKGROUND; + case ABILITY_STATE_FOREGROUND_FAILED: return FOREGROUND_FAILED; + case ABILITY_STATE_INVALID_WINDOW_MODE: return FOREGROUND_INVALID_MODE; + case ABILITY_STATE_WINDOW_FREEZED: return FOREGROUND_WINDOW_FREEZED; + case ABILITY_STATE_DO_NOTHING: return FOREGROUND_DO_NOTHING; + case ABILITY_STATE_BACKGROUND_FAILED: return BACKGROUND_FAILED; + default: return DEFAULT_INVAL_VALUE; + } +} +} // namespace AAFwk +} // namespace OHOS + diff --git a/services/abilitymgr/src/utils/window_options_utils.cpp b/services/abilitymgr/src/utils/window_options_utils.cpp index 205bd80eb4..d05c8e03ba 100644 --- a/services/abilitymgr/src/utils/window_options_utils.cpp +++ b/services/abilitymgr/src/utils/window_options_utils.cpp @@ -45,5 +45,25 @@ void WindowOptionsUtils::SetWindowPositionAndSize(Want& want, want.SetParam(Want::PARAM_RESV_WITH_ANIMATION, withAnimation); } } + +std::pair WindowOptionsUtils::WindowModeMap(int32_t windowMode) +{ + std::pair result(false, AppExecFwk::SupportWindowMode::FULLSCREEN); + + if (windowMode == MULTI_WINDOW_DISPLAY_FULLSCREEN) { + result.first = true; + result.second = AppExecFwk::SupportWindowMode::FULLSCREEN; + } else if (windowMode == MULTI_WINDOW_DISPLAY_PRIMARY) { + result.first = true; + result.second = AppExecFwk::SupportWindowMode::SPLIT; + } else if (windowMode == MULTI_WINDOW_DISPLAY_SECONDARY) { + result.first = true; + result.second = AppExecFwk::SupportWindowMode::SPLIT; + } else if (windowMode == MULTI_WINDOW_DISPLAY_FLOATING) { + result.first = true; + result.second = AppExecFwk::SupportWindowMode::FLOATING; + } + return result; +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/want_receiver_proxy.cpp b/services/abilitymgr/src/want_receiver_proxy.cpp index df35da4c69..62168ec8de 100644 --- a/services/abilitymgr/src/want_receiver_proxy.cpp +++ b/services/abilitymgr/src/want_receiver_proxy.cpp @@ -16,7 +16,6 @@ #include "want_receiver_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { diff --git a/services/abilitymgr/src/want_receiver_stub.cpp b/services/abilitymgr/src/want_receiver_stub.cpp index cfa86f9b2e..c4099c7706 100644 --- a/services/abilitymgr/src/want_receiver_stub.cpp +++ b/services/abilitymgr/src/want_receiver_stub.cpp @@ -16,23 +16,15 @@ #include "want_receiver_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "pac_map.h" namespace OHOS { namespace AAFwk { -WantReceiverStub::WantReceiverStub() -{ - requestFuncMap_[WANT_RECEIVER_SEND] = &WantReceiverStub::SendInner; - requestFuncMap_[WANT_RECEIVER_PERFORM_RECEIVE] = &WantReceiverStub::PerformReceiveInner; -} +WantReceiverStub::WantReceiverStub() {} -WantReceiverStub::~WantReceiverStub() -{ - requestFuncMap_.clear(); -} +WantReceiverStub::~WantReceiverStub() {} int WantReceiverStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -44,12 +36,11 @@ int WantReceiverStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Messag return ERR_INVALID_STATE; } - auto itFunc = requestFuncMap_.find(code); - if (itFunc != requestFuncMap_.end()) { - auto requestFunc = itFunc->second; - if (requestFunc != nullptr) { - return (this->*requestFunc)(data, reply); - } + switch (code) { + case WANT_RECEIVER_SEND: + return SendInner(data, reply); + case WANT_RECEIVER_PERFORM_RECEIVE: + return PerformReceiveInner(data, reply); } TAG_LOGW(AAFwkTag::WANTAGENT, "WantReceiverStub::OnRemoteRequest, default case, need check."); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); diff --git a/services/abilitymgr/src/want_sender_info.cpp b/services/abilitymgr/src/want_sender_info.cpp index 79c8e35826..d5506a9d4c 100644 --- a/services/abilitymgr/src/want_sender_info.cpp +++ b/services/abilitymgr/src/want_sender_info.cpp @@ -16,7 +16,6 @@ #include "want_sender_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "nlohmann/json.hpp" #include "string_ex.h" diff --git a/services/abilitymgr/src/want_sender_proxy.cpp b/services/abilitymgr/src/want_sender_proxy.cpp index 2b172c47eb..c7c9779cdf 100644 --- a/services/abilitymgr/src/want_sender_proxy.cpp +++ b/services/abilitymgr/src/want_sender_proxy.cpp @@ -16,7 +16,6 @@ #include "want_sender_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { diff --git a/services/abilitymgr/src/want_sender_stub.cpp b/services/abilitymgr/src/want_sender_stub.cpp index 8e071ad9b3..15f8adfb24 100644 --- a/services/abilitymgr/src/want_sender_stub.cpp +++ b/services/abilitymgr/src/want_sender_stub.cpp @@ -16,20 +16,13 @@ #include "want_sender_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" namespace OHOS { namespace AAFwk { -WantSenderStub::WantSenderStub() -{ - requestFuncMap_[WANT_SENDER_SEND] = &WantSenderStub::SendInner; -} +WantSenderStub::WantSenderStub() {} -WantSenderStub::~WantSenderStub() -{ - requestFuncMap_.clear(); -} +WantSenderStub::~WantSenderStub() {} int WantSenderStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -41,12 +34,8 @@ int WantSenderStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageP return ERR_INVALID_STATE; } - auto itFunc = requestFuncMap_.find(code); - if (itFunc != requestFuncMap_.end()) { - auto requestFunc = itFunc->second; - if (requestFunc != nullptr) { - return (this->*requestFunc)(data, reply); - } + if (code == (WANT_SENDER_SEND)) { + return SendInner(data, reply); } TAG_LOGW(AAFwkTag::WANTAGENT, "WantSenderStub::OnRemoteRequest, default case, need check."); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); diff --git a/services/abilitymgr/src/wants_info.cpp b/services/abilitymgr/src/wants_info.cpp index f7ed9bf3b2..99a1e930d3 100644 --- a/services/abilitymgr/src/wants_info.cpp +++ b/services/abilitymgr/src/wants_info.cpp @@ -15,7 +15,6 @@ #include "wants_info.h" -#include "hilog_wrapper.h" #include "nlohmann/json.hpp" #include "string_ex.h" diff --git a/services/appdfr/include/appfreeze_manager.h b/services/appdfr/include/appfreeze_manager.h index 60b85fca99..0a6b615bba 100644 --- a/services/appdfr/include/appfreeze_manager.h +++ b/services/appdfr/include/appfreeze_manager.h @@ -50,6 +50,8 @@ public: enum AppFreezeState { APPFREEZE_STATE_IDLE = 0, APPFREEZE_STATE_FREEZE = 1, + APPFREEZE_STATE_CANCELING = 2, + APPFREEZE_STATE_CANCELED = 3, }; struct AppFreezeInfo { @@ -79,6 +81,10 @@ public: bool IsProcessDebug(int32_t pid, std::string processName); bool IsNeedIgnoreFreezeEvent(int32_t pid); void DeleteStack(int pid); + bool CancelAppFreezeDetect(int32_t pid, const std::string& bundleName); + void RemoveDeathProcess(std::string bundleName); + void ResetAppfreezeState(int32_t pid, const std::string& bundleName); + bool IsValidFreezeFilter(int32_t pid, const std::string& bundleName); private: AppfreezeManager& operator=(const AppfreezeManager&) = delete; @@ -106,6 +112,8 @@ private: std::map appfreezeInfo_; static ffrt::mutex catchStackMutex_; static std::map catchStackMap_; + static ffrt::mutex freezeFilterMutex_; + std::map appfreezeFilterMap_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appdfr/include/application_anr_listener.h b/services/appdfr/include/application_anr_listener.h index 73316584a2..791d2769aa 100644 --- a/services/appdfr/include/application_anr_listener.h +++ b/services/appdfr/include/application_anr_listener.h @@ -30,7 +30,7 @@ class ApplicationAnrListener : public MMI::IAnrObserver { public: ApplicationAnrListener(); virtual ~ApplicationAnrListener(); - void OnAnr(int32_t pid) const override; + void OnAnr(int32_t pid, int32_t eventId) const override; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/appdfr/src/appfreeze_manager.cpp b/services/appdfr/src/appfreeze_manager.cpp index 3faa55f0e1..2f8cf3e95a 100644 --- a/services/appdfr/src/appfreeze_manager.cpp +++ b/services/appdfr/src/appfreeze_manager.cpp @@ -34,13 +34,13 @@ #include "app_mgr_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { namespace { constexpr char EVENT_UID[] = "UID"; constexpr char EVENT_PID[] = "PID"; +constexpr char EVENT_INPUT_ID[] = "INPUT_ID"; constexpr char EVENT_MESSAGE[] = "MSG"; constexpr char EVENT_PACKAGE_NAME[] = "PACKAGE_NAME"; constexpr char EVENT_PROCESS_NAME[] = "PROCESS_NAME"; @@ -59,6 +59,7 @@ ffrt::mutex AppfreezeManager::singletonMutex_; ffrt::mutex AppfreezeManager::freezeMutex_; ffrt::mutex AppfreezeManager::catchStackMutex_; std::map AppfreezeManager::catchStackMap_; +ffrt::mutex AppfreezeManager::freezeFilterMutex_; AppfreezeManager::AppfreezeManager() { @@ -133,10 +134,11 @@ int AppfreezeManager::AppfreezeHandleWithStack(const FaultData& faultData, const faultNotifyData.errorObject.message = faultData.errorObject.message; faultNotifyData.errorObject.stack = faultData.errorObject.stack; faultNotifyData.faultType = FaultDataType::APP_FREEZE; + faultNotifyData.eventId = faultData.eventId; 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 + if (faultData.errorObject.name == AppFreezeType::LIFECYCLE_TIMEOUT || faultData.errorObject.name == AppFreezeType::APP_INPUT_BLOCK || faultData.errorObject.name == AppFreezeType::THREAD_BLOCK_6S) { if (AppExecFwk::AppfreezeManager::GetInstance()->IsNeedIgnoreFreezeEvent(appInfo.pid)) { @@ -177,9 +179,13 @@ std::string AppfreezeManager::WriteToFile(const std::string& fileName, std::stri OHOS::ForceCreateDirectory(dir_path); OHOS::ChangeModeDirectory(dir_path, defaultLogDirMode); } - - std::string stackPath = dir_path + "/" + fileName; - constexpr mode_t defaultLogFileMode = 0664; + std::string realPath; + if (!OHOS::PathToRealPath(dir_path, realPath)) { + TAG_LOGE(AAFwkTag::APPDFR, "PathToRealPath Failed:%{public}s.", dir_path.c_str()); + return ""; + } + std::string stackPath = realPath + "/" + fileName; + constexpr mode_t defaultLogFileMode = 0644; auto fd = open(stackPath.c_str(), O_CREAT | O_WRONLY | O_TRUNC, defaultLogFileMode); if (fd < 0) { TAG_LOGI(AAFwkTag::APPDFR, "Failed to create stackPath"); @@ -233,6 +239,7 @@ int AppfreezeManager::AcquireStack(const FaultData& faultData, const AppfreezeMa faultNotifyData.errorObject.message = faultData.errorObject.message; faultNotifyData.errorObject.stack = faultData.errorObject.stack; faultNotifyData.faultType = FaultDataType::APP_FREEZE; + faultNotifyData.eventId = faultData.eventId; std::string binderInfo; std::set pids = GetBinderPeerPids(binderInfo, pid); if (pids.empty()) { @@ -261,17 +268,25 @@ int AppfreezeManager::NotifyANR(const FaultData& faultData, const AppfreezeManag std::string appRunningUniqueId = ""; DelayedSingleton::GetInstance()->GetAppRunningUniqueIdByPid(appInfo.pid, appRunningUniqueId); - - int ret = HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, faultData.errorObject.name, - OHOS::HiviewDFX::HiSysEvent::EventType::FAULT, EVENT_UID, appInfo.uid, EVENT_PID, appInfo.pid, - EVENT_PACKAGE_NAME, appInfo.bundleName, EVENT_PROCESS_NAME, appInfo.processName, EVENT_MESSAGE, - faultData.errorObject.message, EVENT_STACK, faultData.errorObject.stack, BINDER_INFO, binderInfo, - APP_RUNNING_UNIQUE_ID, appRunningUniqueId); - + int ret = 0; + if (faultData.errorObject.name == AppFreezeType::APP_INPUT_BLOCK) { + ret = HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, faultData.errorObject.name, + OHOS::HiviewDFX::HiSysEvent::EventType::FAULT, EVENT_UID, appInfo.uid, EVENT_PID, appInfo.pid, + EVENT_PACKAGE_NAME, appInfo.bundleName, EVENT_PROCESS_NAME, appInfo.processName, EVENT_MESSAGE, + faultData.errorObject.message, EVENT_STACK, faultData.errorObject.stack, BINDER_INFO, binderInfo, + APP_RUNNING_UNIQUE_ID, appRunningUniqueId, EVENT_INPUT_ID, faultData.eventId); + } else { + ret = HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, faultData.errorObject.name, + OHOS::HiviewDFX::HiSysEvent::EventType::FAULT, EVENT_UID, appInfo.uid, EVENT_PID, appInfo.pid, + EVENT_PACKAGE_NAME, appInfo.bundleName, EVENT_PROCESS_NAME, appInfo.processName, EVENT_MESSAGE, + faultData.errorObject.message, EVENT_STACK, faultData.errorObject.stack, BINDER_INFO, binderInfo, + APP_RUNNING_UNIQUE_ID, appRunningUniqueId); + } TAG_LOGI(AAFwkTag::APPDFR, - "reportEvent:%{public}s, pid:%{public}d, bundleName:%{public}s, appRunningUniqueId:%{public}s " - "hisysevent write ret = %{public}d.", - faultData.errorObject.name.c_str(), appInfo.pid, appInfo.bundleName.c_str(), appRunningUniqueId.c_str(), ret); + "reportEvent:%{public}s, pid:%{public}d, bundleName:%{public}s, appRunningUniqueId:%{public}s" + ", eventId:%{public}d hisysevent write ret = %{public}d.", + faultData.errorObject.name.c_str(), appInfo.pid, appInfo.bundleName.c_str(), appRunningUniqueId.c_str(), + faultData.eventId, ret); return 0; } @@ -410,6 +425,7 @@ std::string AppfreezeManager::CatchJsonStacktrace(int pid, const std::string& fa std::string msg; size_t defaultMaxFaultNum = 256; if (!dumplog.DumpCatch(pid, 0, msg, defaultMaxFaultNum, true)) { + TAG_LOGI(AAFwkTag::APPDFR, "appfreeze catch stack failed"); FindStackByPid(ret, pid, msg); } else { ret = msg; @@ -437,17 +453,19 @@ std::string AppfreezeManager::CatcherStacktrace(int pid) const bool AppfreezeManager::IsProcessDebug(int32_t pid, std::string processName) { - const int buffSize = 128; - char param[buffSize] = {0}; - std::string filter = "hiviewdfx.freeze.filter." + processName; - GetParameter(filter.c_str(), "", param, buffSize - 1); - int32_t debugPid = atoi(param); - if (debugPid == pid) { - TAG_LOGI(AAFwkTag::APPDFR, "appfreeze filtration %{public}s_%{public}d don't exit.", - processName.c_str(), debugPid); - return true; + std::lock_guard lock(freezeFilterMutex_); + auto it = appfreezeFilterMap_.find(processName); + if (it != appfreezeFilterMap_.end() && it->second.pid == pid) { + if (it->second.state == AppFreezeState::APPFREEZE_STATE_CANCELED) { + TAG_LOGI(AAFwkTag::APPDFR, "appfreeze filtration only once in a lifecycle."); + return false; + } else { + TAG_LOGI(AAFwkTag::APPDFR, "appfreeze filtration %{public}s", processName.c_str()); + return true; + } } + const int buffSize = 128; char paramBundle[buffSize] = {0}; GetParameter("hiviewdfx.appfreeze.filter_bundle_name", "", paramBundle, buffSize - 1); std::string debugBundle(paramBundle); @@ -544,5 +562,48 @@ bool AppfreezeManager::IsNeedIgnoreFreezeEvent(int32_t pid) return false; } } + +bool AppfreezeManager::CancelAppFreezeDetect(int32_t pid, const std::string& bundleName) +{ + if (bundleName.empty()) { + return false; + } + std::lock_guard lock(freezeFilterMutex_); + AppFreezeInfo info; + info.pid = pid; + info.state = AppFreezeState::APPFREEZE_STATE_CANCELING; + appfreezeFilterMap_.emplace(bundleName, info); + return true; +} + +void AppfreezeManager::RemoveDeathProcess(std::string bundleName) +{ + std::lock_guard lock(freezeFilterMutex_); + auto it = appfreezeFilterMap_.find(bundleName); + if (it != appfreezeFilterMap_.end()) { + TAG_LOGD(AAFwkTag::APPDFR, "RemoveDeathProcess bundleName: %{public}s", + bundleName.c_str()); + appfreezeFilterMap_.erase(it); + } +} + +void AppfreezeManager::ResetAppfreezeState(int32_t pid, const std::string& bundleName) +{ + std::lock_guard lock(freezeFilterMutex_); + if (appfreezeFilterMap_.find(bundleName) != appfreezeFilterMap_.end()) { + TAG_LOGD(AAFwkTag::APPDFR, "ResetAppfreezeState bundleName: %{public}s", + bundleName.c_str()); + appfreezeFilterMap_[bundleName].state = AppFreezeState::APPFREEZE_STATE_CANCELED; + } +} + +bool AppfreezeManager::IsValidFreezeFilter(int32_t pid, const std::string& bundleName) +{ + std::lock_guard lock(freezeFilterMutex_); + if (appfreezeFilterMap_.find(bundleName) != appfreezeFilterMap_.end()) { + return false; + } + return true; +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/appdfr/src/application_anr_listener.cpp b/services/appdfr/src/application_anr_listener.cpp index 0f8d8c2303..1c9cf3019b 100644 --- a/services/appdfr/src/application_anr_listener.cpp +++ b/services/appdfr/src/application_anr_listener.cpp @@ -21,7 +21,6 @@ #include "app_mgr_client.h" #include "fault_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { @@ -29,7 +28,7 @@ ApplicationAnrListener::ApplicationAnrListener() {} ApplicationAnrListener::~ApplicationAnrListener() {} -void ApplicationAnrListener::OnAnr(int32_t pid) const +void ApplicationAnrListener::OnAnr(int32_t pid, int32_t eventId) const { AppExecFwk::AppFaultDataBySA faultData; faultData.faultType = AppExecFwk::FaultDataType::APP_FREEZE; @@ -40,7 +39,8 @@ void ApplicationAnrListener::OnAnr(int32_t pid) const faultData.waitSaveState = false; faultData.notifyApp = false; faultData.forceExit = false; + faultData.eventId = eventId; DelayedSingleton::GetInstance()->NotifyAppFaultBySA(faultData); } } // namespace AAFwk -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/appmgr/BUILD.gn b/services/appmgr/BUILD.gn index 844e5ce311..397b7a04dd 100644 --- a/services/appmgr/BUILD.gn +++ b/services/appmgr/BUILD.gn @@ -129,7 +129,6 @@ ohos_shared_library("libappms") { "ipc:ipc_core", "json:nlohmann_json_static", "kv_store:distributeddata_inner", - "kv_store:distributeddata_mgr", "memmgr:memmgrclient", "memory_utils:libmeminfo", "os_account:libaccountkits", @@ -152,7 +151,7 @@ ohos_shared_library("libappms") { deps += [] external_deps += [ "i18n:intl_util", - "window_manager:libwm_lite", + "window_manager:libwm", "window_manager:libwsutils", ] } diff --git a/services/appmgr/include/ams_mgr_scheduler.h b/services/appmgr/include/ams_mgr_scheduler.h index 38aaeca589..74dd5b6a32 100644 --- a/services/appmgr/include/ams_mgr_scheduler.h +++ b/services/appmgr/include/ams_mgr_scheduler.h @@ -153,6 +153,17 @@ public: */ virtual int32_t KillApplication(const std::string &bundleName, const bool clearPageStack = true) override; + /** + * ForceKillApplication, force kill the application. + * + * @param bundleName, bundle name in Application record. + * @param userId, userId. + * @param appIndex, appIndex. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t ForceKillApplication(const std::string &bundleName, const int userId = -1, + const int appIndex = 0) override; + /** * KillApplicationByUid, call KillApplicationByUid() through proxy object, kill the application. * @@ -170,7 +181,7 @@ public: virtual void AbilityAttachTimeOut(const sptr &token) override; - virtual void PrepareTerminate(const sptr &token) override; + virtual void PrepareTerminate(const sptr &token, bool clearMissionFlag = false) override; virtual void GetRunningProcessInfoByToken( const sptr &token, AppExecFwk::RunningProcessInfo &info) override; @@ -296,6 +307,16 @@ public: */ void AttachedToStatusBar(const sptr &token) override; + virtual void BlockProcessCacheByPids(const std::vector &pids) override; + + /** + * whether killed for upgrade web. + * + * @param bundleName the bundle name is killed for upgrade web. + * @return Returns true is killed for upgrade web, others return false. + */ + virtual bool IsKilledForUpgradeWeb(const std::string &bundleName) override; + private: /** * @brief Judge whether the application service is ready. diff --git a/services/appmgr/include/app_lifecycle_deal.h b/services/appmgr/include/app_lifecycle_deal.h index 83440ae306..ce65133609 100644 --- a/services/appmgr/include/app_lifecycle_deal.h +++ b/services/appmgr/include/app_lifecycle_deal.h @@ -231,8 +231,6 @@ public: int DumpIpcStat(std::string& result); - int DumpFfrt(std::string& result); - /** * Notifies the application of process caching. * @@ -241,6 +239,8 @@ public: */ void ScheduleCacheProcess(); + 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 b4bdd7eae5..f49d37c5b1 100644 --- a/services/appmgr/include/app_mgr_service.h +++ b/services/appmgr/include/app_mgr_service.h @@ -405,6 +405,14 @@ public: */ int32_t NotifyAppFaultBySA(const AppFaultDataBySA &faultData) override; + /** + * Set Appfreeze Detect Filter + * + * @param pid the process pid. + * @return Returns true on success, others on failure. + */ + bool SetAppFreezeFilter(int32_t pid) override; + /** * get memorySize by pid. * @@ -482,12 +490,11 @@ public: /** * Start child process, called by ChildProcessManager. * - * @param srcEntry Child process source file entrance path to be started. * @param childPid Created child process pid. + * @param request Child process start request params. * @return Returns ERR_OK on success, others on failure. */ - int32_t StartChildProcess(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCoun, - bool isStartWithDebug) override; + int32_t StartChildProcess(pid_t &childPid, const ChildProcessRequest &request) override; /** * Get child process record for self. @@ -524,18 +531,9 @@ 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; + + int32_t SetSupportedProcessCacheSelf(bool isSupport) override; virtual void SaveBrowserChannel(sptr browser) override; @@ -546,6 +544,21 @@ public: * @return Returns ERR_OK is test ability, others is not test ability. */ int32_t CheckCallingIsUserTestMode(const pid_t pid, bool &isUserTest) 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 int32_t NotifyProcessDependedOnWeb() override; + + virtual void KillProcessDependedOnWeb() override; + + virtual void RestartResidentProcessDependedOnWeb() override; private: /** * Init, Initialize application services. diff --git a/services/appmgr/include/app_mgr_service_inner.h b/services/appmgr/include/app_mgr_service_inner.h index 796dd813c7..578d97eb65 100644 --- a/services/appmgr/include/app_mgr_service_inner.h +++ b/services/appmgr/include/app_mgr_service_inner.h @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -47,6 +48,7 @@ #include "bundle_info.h" #include "bundle_mgr_helper.h" #include "child_process_info.h" +#include "child_process_request.h" #include "cpp/mutex.h" #include "event_report.h" #include "fault_data.h" @@ -78,6 +80,7 @@ using OHOS::AAFwk::Want; class WindowFocusChangedListener; class WindowVisibilityChangedListener; using LoabAbilityTaskFunc = std::function; +constexpr int32_t BASE_USER_RANGE = 200000; class AppMgrServiceInner : public std::enable_shared_from_this { public: @@ -259,6 +262,17 @@ public: */ virtual int32_t KillApplication(const std::string &bundleName, const bool clearPageStack = true); + /** + * ForceKillApplication, force kill the application. + * + * @param bundleName, bundle name in Application record. + * @param userId, userId. + * @param appIndex, appIndex. + * @return ERR_OK, return back success, others fail. + */ + virtual int32_t ForceKillApplication(const std::string &bundleName, const int userId = -1, + const int appIndex = 0); + /** * KillApplicationByUid, call KillApplicationByUid() through proxy object, kill the application. * @@ -592,7 +606,7 @@ public: void HandleAbilityAttachTimeOut(const sptr &token); - void PrepareTerminate(const sptr &token); + void PrepareTerminate(const sptr &token, bool clearMissionFlag = false); void OnAppStateChanged(const std::shared_ptr &appRecord, const ApplicationState state, bool needNotifyApp, bool isFromWindowFocusChanged); @@ -729,7 +743,7 @@ public: virtual int GetRenderProcessTerminationStatus(pid_t renderPid, int &status); - int VerifyProcessPermission(const sptr &token) const; + int VerifyKillProcessPermission(const sptr &token) const; int VerifyAccountPermission(const std::string &permissionName, const int userId) const; @@ -753,15 +767,7 @@ public: */ void NotifyAppStatus(const std::string &bundleName, const std::string &eventData); - /** - * KillProcessByPid, Kill process by PID. - * - * @param pid_t, the app record pid. - * @param reason, the reason why the process is killed, default to "foundation" - * - * @return ERR_OK, return back success,others fail. - */ - int32_t KillProcessByPid(const pid_t pid, const std::string& reason = "foundation"); + int32_t KillProcessByPid(const pid_t pid, const std::string& reason = "foundation", int32_t uid = -1); bool GetAppRunningStateByBundleName(const std::string &bundleName); @@ -819,6 +825,14 @@ public: */ int32_t NotifyAppFaultBySA(const AppFaultDataBySA &faultData); + /** + * Set Appfreeze Detect Filter + * + * @param pid the process pid. + * @return Returns true on success, others on failure. + */ + bool SetAppFreezeFilter(int32_t pid); + /** * get memorySize by pid. * @@ -997,12 +1011,11 @@ public: * Start child process, called by ChildProcessManager. * * @param hostPid Host process pid. - * @param srcEntry Child process source file entrance path to be started. * @param childPid Created child process pid. + * @param request Child process start request params. * @return Returns ERR_OK on success, others on failure. */ - virtual int32_t StartChildProcess(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid, - int32_t childProcessCount, bool isStartWithDebug); + virtual int32_t StartChildProcess(const pid_t hostPid, pid_t &childPid, const ChildProcessRequest &request); /** * Get child process record for self. @@ -1037,13 +1050,6 @@ public: 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. - * @return Returns true is final application process, others return false. - */ - bool IsFinalAppProcessByBundleName(const std::string &bundleName); - /** * To clear the process by ability token. * @@ -1051,6 +1057,13 @@ public: */ void ClearProcessByToken(sptr token); + /** + * Whether the current application process is the last surviving process. + * @param bundleName To query the bundle name of a process. + * @return Returns true is final application process, others return false. + */ + bool IsFinalAppProcessByBundleName(const std::string &bundleName); + /** * @brief Notify memory size state changed to sufficient or insufficent. * @param isMemorySizeSufficent Indicates the memory size state. @@ -1105,14 +1118,6 @@ public: bool IsAppProcessesAllCached(const std::string &bundleName, int32_t uid, const std::set> &cachedSet); - bool GetSceneBoardAttachFlag() const; - - void SetSceneBoardAttachFlag(bool flag); - - void CacheLoabAbilityTask(const LoabAbilityTaskFunc& func); - - void SubmitCacheLoabAbilityTask(); - /** * Check caller is test ability * @@ -1120,7 +1125,14 @@ public: * @return Returns ERR_OK is test ability, others is not test ability. */ int32_t CheckCallingIsUserTestModeInner(const pid_t pid, bool &isUserTest); + + bool GetSceneBoardAttachFlag() const; + void SetSceneBoardAttachFlag(bool flag); + + void CacheLoabAbilityTask(const LoabAbilityTaskFunc& func); + + void SubmitCacheLoabAbilityTask(); /** * Notifies that one ability is attached to status bar. * @@ -1128,7 +1140,20 @@ public: */ void AttachedToStatusBar(const sptr &token); void KillApplicationByRecord(const std::shared_ptr &appRecord); + + int32_t NotifyProcessDependedOnWeb(); + + void KillProcessDependedOnWeb(); + + void RestartResidentProcessDependedOnWeb(); + + void BlockProcessCacheByPids(const std::vector& pids); + + bool IsKilledForUpgradeWeb(const std::string &bundleName) const; + private: + int32_t ForceKillApplicationInner(const std::string &bundleName, const int userId = -1, + const int appIndex = 0); std::string FaultTypeToString(FaultDataType type); @@ -1197,7 +1222,9 @@ private: std::shared_ptr appRecord, const int uid, const BundleInfo &bundleInfo, const std::string &bundleName, const int32_t bundleIndex, bool appExistFlag = true, bool isPreload = false, const std::string &moduleName = "", const std::string &abilityName = "", - bool strictMode = false, int32_t maxChildProcess = 0); + bool strictMode = false, int32_t maxChildProcess = 0, sptr token = nullptr, + std::shared_ptr want = nullptr, + ExtensionAbilityType ExtensionAbilityType = ExtensionAbilityType::UNSPECIFIED); /** * PushAppFront, Adjust the latest application record to the top level. @@ -1277,7 +1304,7 @@ private: * * @return true, return back existed,others non-existent. */ - bool ProcessExist(pid_t pid); + bool ProcessExist(pid_t pid, int32_t uid = -1); /** * CheckAllProcessExist, Determine whether all processes exist . @@ -1339,9 +1366,9 @@ private: static void PointerDeviceEventCallback(const char *key, const char *value, void *context); - int VerifyProcessPermission() const; + int VerifyKillProcessPermission(const std::string &bundleName) const; - int VerifyProcessPermission(const std::string &bundleName) const; + int32_t VerifyKillProcessPermissionCommon() const; bool CheckCallerIsAppGallery(); @@ -1351,7 +1378,7 @@ private: int32_t StartChildProcessPreCheck(const pid_t callingPid); int32_t StartChildProcessImpl(const std::shared_ptr childProcessRecord, - const std::shared_ptr appRecord, pid_t &childPid); + const std::shared_ptr appRecord, pid_t &childPid, const ChildProcessArgs &args); int32_t GetChildProcessInfo(const std::shared_ptr childProcessRecord, const std::shared_ptr appRecord, ChildProcessInfo &info); @@ -1454,18 +1481,11 @@ private: std::string GetSpecifiedProcessFlag(std::shared_ptr abilityInfo, std::shared_ptr want); void LoadAbilityNoAppRecord(const std::shared_ptr appRecord, - sptr preToken, - std::shared_ptr appInfo, - std::shared_ptr abilityInfo, - const std::string &processName, - const std::string &specifiedProcessFlag, - const BundleInfo &bundleInfo, - const HapModuleInfo &hapModuleInfo, - std::shared_ptr want, - bool appExistFlag, - bool isPreload); - - int32_t CheckSetProcessCachePermission() const; + sptr preToken, std::shared_ptr appInfo, + std::shared_ptr abilityInfo, const std::string &processName, + const std::string &specifiedProcessFlag, const BundleInfo &bundleInfo, + const HapModuleInfo &hapModuleInfo, std::shared_ptr want, + bool appExistFlag, bool isPreload, sptr token = nullptr); int32_t CreatNewStartMsg(const Want &want, const AbilityInfo &abilityInfo, const std::shared_ptr &appInfo, const std::string &processName, @@ -1489,6 +1509,8 @@ private: bool CreateAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo); + AAFwk::EventInfo BuildEventInfo(std::shared_ptr appRecord) const; + private: /** * Notify application status. @@ -1511,9 +1533,9 @@ private: void HandleConfigurationChange(const Configuration &config); bool CheckAppFault(const std::shared_ptr &appRecord, const FaultData &faultData); int32_t KillFaultApp(int32_t pid, const std::string &bundleName, const FaultData &faultData); - void NotifyStartResidentProcess(std::vector &bundleInfos); void AddUIExtensionLauncherItem(std::shared_ptr want, std::shared_ptr appRecord, sptr token); + void NotifyStartResidentProcess(std::vector &bundleInfos); void RemoveUIExtensionLauncherItem(std::shared_ptr appRecord, sptr token); bool IsSceneBoardCall(); const std::string TASK_ON_CALLBACK_DIED = "OnCallbackDiedTask"; @@ -1551,13 +1573,15 @@ private: ffrt::mutex killpedProcessMapLock_; mutable std::map killedPorcessMap_; ffrt::mutex startChildProcessLock_; - std::shared_ptr appRunningStatusModule_; std::vector serviceExtensionWhiteList_; + std::shared_ptr appRunningStatusModule_; std::shared_ptr securityModeManager_; std::shared_ptr dfxTaskHandler_; std::shared_ptr otherTaskHandler_; std::shared_ptr appPreloader_; std::atomic sceneBoardAttachFlag_ = true; + + std::mutex loadTaskListMutex_; std::vector loadAbilityTaskFuncList_; }; } // namespace AppExecFwk diff --git a/services/appmgr/include/app_running_manager.h b/services/appmgr/include/app_running_manager.h index 305ca53f84..fd6f3ee049 100644 --- a/services/appmgr/include/app_running_manager.h +++ b/services/appmgr/include/app_running_manager.h @@ -23,17 +23,18 @@ #include "ability_info.h" #include "app_debug_listener_interface.h" +#include "app_jsheap_mem_info.h" #include "app_malloc_info.h" #include "app_mem_info.h" #include "app_running_record.h" #include "app_state_data.h" #include "application_info.h" #include "bundle_info.h" +#include "configuration.h" #include "iremote_object.h" #include "record_query_result.h" #include "refbase.h" #include "running_process_info.h" -#include "app_jsheap_mem_info.h" namespace OHOS { namespace Rosen { @@ -72,6 +73,18 @@ public: const std::string &processName, const int uid, const BundleInfo &bundleInfo, const std::string &specifiedProcessFlag = ""); +#ifdef APP_NO_RESPONSE_DIALOG + /** + * CheckAppRunningRecordIsExist, Check whether the process of the app exists by bundle name and process Name. + * + * @param bundleName, Indicates the bundle name of the bundle.. + * @param ablityName, ablity name. + * + * @return true if exist. + */ + bool CheckAppRunningRecordIsExist(const std::string &bundleName, const std::string &ablityName); +#endif + /** * CheckAppRunningRecordIsExistByBundleName, Check whether the process of the application exists. * @@ -81,6 +94,14 @@ public: */ bool CheckAppRunningRecordIsExistByBundleName(const std::string &bundleName); + /** + * CheckAppRunningRecordIsExistByUid, check app exist when concurrent. + * + * @param uid, the process uid. + * @return, Return true if exist. + */ + bool CheckAppRunningRecordIsExistByUid(int32_t uid); + /** * CheckAppRunningRecordIsExistByBundleName, Check whether the process of the application exists. * @@ -235,7 +256,7 @@ public: const std::string &bundleName, const int uid, std::list &pids, const bool clearPageStack = true); bool GetPidsByUserId(int32_t userId, std::list &pids); - void PrepareTerminate(const sptr &token); + void PrepareTerminate(const sptr &token, bool clearMissionFlag = false); std::shared_ptr GetTerminatingAppRunningRecord(const sptr &abilityToken); @@ -320,6 +341,11 @@ public: bool IsAppProcessesAllCached(const std::string &bundleName, int32_t uid, const std::set> &cachedSet); + int32_t UpdateConfigurationDelayed(const std::shared_ptr &appRecord); + + bool GetPidsByBundleNameUserIdAndAppIndex(const std::string &bundleName, + const int userId, const int appIndex, std::list &pids); + private: std::shared_ptr GetAbilityRunningRecord(const int64_t eventId); int32_t AssignRunningProcessInfoByAppRecord( @@ -332,6 +358,10 @@ private: std::mutex uiExtensionMapLock_; std::map> uiExtensionLauncherMap_; + + std::shared_ptr configuration_; + std::mutex updateConfigurationDelayedLock_; + std::map updateConfigurationDelayedMap_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/include/app_running_record.h b/services/appmgr/include/app_running_record.h index 7e8c361d76..eda223f3ab 100644 --- a/services/appmgr/include/app_running_record.h +++ b/services/appmgr/include/app_running_record.h @@ -541,7 +541,7 @@ public: bool IsLastPageAbilityRecord(const sptr &token); - bool ExtensionAbilityRecordExists(const sptr &token); + bool ExtensionAbilityRecordExists(); void SetTerminating(); @@ -557,10 +557,10 @@ public: void SetKeepAliveEnableState(bool isKeepAliveEnable); - void SetSingleton(bool isSingleton); - void SetMainProcess(bool isMainProcess); + void SetSingleton(bool isSingleton); + void SetStageModelState(bool isStageBasedModel); std::list> GetAllModuleRecord() const; @@ -615,11 +615,14 @@ public: void SetDebugApp(bool isDebugApp); bool IsDebugApp(); bool IsDebugging() const; + void SetErrorInfoEnhance(const bool errorInfoEnhance); void SetNativeDebug(bool isNativeDebug); void SetPerfCmd(const std::string &perfCmd); void SetMultiThread(const bool multiThread); void AddRenderRecord(const std::shared_ptr &record); void RemoveRenderRecord(const std::shared_ptr &record); + void RemoveRenderPid(pid_t pid); + bool ConstainsRenderPid(pid_t renderPid); std::shared_ptr GetRenderRecordByPid(const pid_t pid); std::map> GetRenderRecordMap(); void SetStartMsg(const AppSpawnStartMsg &msg); @@ -675,10 +678,6 @@ public: ProcessChangeReason GetProcessChangeReason() const; - bool IsUpdateStateFromService(); - - void SetUpdateStateFromService(bool isUpdateStateFromService); - ExtensionAbilityType GetExtensionType() const; ProcessType GetProcessType() const; @@ -796,14 +795,14 @@ public: void SetAttachedToStatusBar(bool isAttached); bool IsAttachedToStatusBar(); + void ScheduleCacheProcess(); + void SetBrowserHost(sptr browser); sptr GetBrowserHost(); void SetIsGPU(bool gpu); bool GetIsGPU(); void SetGPUPid(pid_t gpuPid); pid_t GetGPUPid(); - - void ScheduleCacheProcess(); inline void SetStrictMode(bool strictMode) { @@ -814,15 +813,20 @@ public: { return isStrictMode_; } -private: - /** - * SearchTheModuleInfoNeedToUpdated, Get an uninitialized abilityStage data. - * - * @return If an uninitialized data is found return true,Otherwise return false. - */ - bool GetTheModuleInfoNeedToUpdated(const std::string bundleName, HapModuleInfo &info); - // drive application state changes when ability state changes. + inline void SetIsDependedOnArkWeb(bool isDepend) + { + isDependedOnArkWeb_ = isDepend; + } + + inline bool IsDependedOnArkWeb() + { + return isDependedOnArkWeb_; + } + + void SetProcessCacheBlocked(bool isBlocked); + bool GetProcessCacheBlocked(); + /** * ScheduleForegroundRunning, Notify application to switch to foreground. * @@ -837,6 +841,14 @@ private: */ void ScheduleBackgroundRunning(); +private: + /** + * SearchTheModuleInfoNeedToUpdated, Get an uninitialized abilityStage data. + * + * @return If an uninitialized data is found return true,Otherwise return false. + */ + bool GetTheModuleInfoNeedToUpdated(const std::string bundleName, HapModuleInfo &info); + /** * AbilityForeground, Handling the ability process when switching to the foreground. * @@ -947,13 +959,14 @@ private: // render record std::map> renderRecordMap_; ffrt::mutex renderRecordMapLock_; + std::set renderPidSet_; // Contains all render pid added, whether died or not + ffrt::mutex renderPidSetLock_; AppSpawnStartMsg startMsg_; int32_t appIndex_ = 0; bool securityFlag_ = false; int32_t requestProcCode_ = 0; ProcessChangeReason processChangeReason_ = ProcessChangeReason::REASON_NONE; - bool isUpdateStateFromService_ = false; int32_t callerPid_ = -1; int32_t callerUid_ = -1; int32_t callerTokenId_ = -1; @@ -967,14 +980,17 @@ private: bool isRestartApp_ = false; // Only app calling RestartApp can be set to true bool isAssertPause_ = false; + bool isErrorInfoEnhance_ = false; bool isNativeStart_ = false; bool isMultiThread_ = false; SupportProcessCacheState procCacheSupportState_ = SupportProcessCacheState::UNSPECIFIED; + bool processCacheBlocked = false; // temporarily block process cache feature sptr browserHost_; bool isGPU_ = false; pid_t gpuPid_ = 0; bool isStrictMode_ = false; bool isAttachedToStatusBar = false; + bool isDependedOnArkWeb_ = false; }; } // namespace AppExecFwk diff --git a/services/appmgr/include/app_spawn_client.h b/services/appmgr/include/app_spawn_client.h index 94c1c259a3..7e0018a11d 100644 --- a/services/appmgr/include/app_spawn_client.h +++ b/services/appmgr/include/app_spawn_client.h @@ -26,6 +26,7 @@ #include "appexecfwk_errors.h" #include "appspawn.h" +#include "child_process_info.h" #include "data_group_info.h" #include "nocopyable.h" #include "shared/base_shared_bundle_info.h" @@ -73,6 +74,8 @@ struct AppSpawnStartMsg { bool strictMode = false; // whether is strict mode std::string processType = ""; int32_t maxChildProcess = 0; + int32_t childProcessType = CHILD_PROCESS_TYPE_NOT_CHILD; + std::map fds; }; constexpr auto LEN_PID = sizeof(pid_t); @@ -220,6 +223,10 @@ private: std::string serviceName_ = APPSPAWN_SERVER_NAME; AppSpawnClientHandle handle_ = nullptr; SpawnConnectionState state_ = SpawnConnectionState::STATE_NOT_CONNECT; + + int32_t SetChildProcessTypeStartFlag(const AppSpawnReqMsgHandle &reqHandle, int32_t childProcessType); + + int32_t SetExtMsgFds(const AppSpawnReqMsgHandle &reqHandle, const std::map &fds); }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/include/cache_process_manager.h b/services/appmgr/include/cache_process_manager.h index 482215f285..d7c2828297 100644 --- a/services/appmgr/include/cache_process_manager.h +++ b/services/appmgr/include/cache_process_manager.h @@ -20,6 +20,7 @@ #include #include #include +#include #include "singleton.h" #include "app_running_record.h" #include "cpp/mutex.h" @@ -41,9 +42,7 @@ public: bool IsAppShouldCache(const std::shared_ptr &appRecord); void RefreshCacheNum(); std::string PrintCacheQueue(); - void UpdateTypeByToken(const sptr &token, const std::shared_ptr &appRecord); - void UpdateTypeByAbility(const std::shared_ptr &abilityRecord, - const std::shared_ptr &appRecord); + void PrepareActivateCache(const std::shared_ptr &appRecord); private: bool IsAppAbilitiesEmpty(const std::shared_ptr &appRecord); int GetCurrentCachedProcNum(); @@ -53,15 +52,21 @@ private: void AddToApplicationSet(const std::shared_ptr &appRecord); void RemoveFromApplicationSet(const std::shared_ptr &appRecord); bool CheckAndNotifyCachedState(const std::shared_ptr &appRecord); + bool IsAppContainsSrvExt(const std::shared_ptr &appRecord); + bool IsAppSupportProcessCacheInnerFirst(const std::shared_ptr &appRecord); int32_t maxProcCacheNum_ = 0; std::deque> cachedAppRecordQueue_; ffrt::recursive_mutex cacheQueueMtx; std::weak_ptr appMgr_; bool shouldCheckApi = true; + // whether the feature should check setSupportedProcessCache value or not + bool shouldCheckSupport = true; // bundleName->uid->record std::map>>> sameAppSet; // stores records that are servcie extension std::set> srvExtRecords; + // stores records that has been checked service extension + std::unordered_set> srvExtCheckedFlag; }; } // namespace OHOS } // namespace AppExecFwk diff --git a/services/appmgr/include/child_process_record.h b/services/appmgr/include/child_process_record.h index dd3690b9e2..6d3ceb14ee 100644 --- a/services/appmgr/include/child_process_record.h +++ b/services/appmgr/include/child_process_record.h @@ -23,6 +23,7 @@ #include "app_death_recipient.h" #include "child_scheduler_interface.h" #include "child_process_info.h" +#include "child_process_request.h" namespace OHOS { namespace AppExecFwk { @@ -30,14 +31,14 @@ class AppRunningRecord; 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 ChildProcessRequest &request, + const std::shared_ptr hostRecord); 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 CreateChildProcessRecord(pid_t hostPid, + const ChildProcessRequest &request, const std::shared_ptr hostRecord); 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); @@ -57,9 +58,12 @@ public: void RemoveDeathRecipient(); void ScheduleExitProcessSafely(); bool isStartWithDebug(); - int32_t GetProcessType() const; + int32_t GetChildProcessType() const; sptr GetMainProcessCallback() const; void ClearMainProcessCallback(); + void SetEntryParams(const std::string &entryParams); + std::string GetEntryParams() const; + private: void MakeProcessName(const std::shared_ptr hostRecord); @@ -75,6 +79,7 @@ private: sptr deathRecipient_ = nullptr; sptr mainProcessCb_ = nullptr; bool isStartWithDebug_; + std::string entryParams_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/include/exit_resident_process_manager.h b/services/appmgr/include/exit_resident_process_manager.h index 570f5938cd..557cf28ea3 100644 --- a/services/appmgr/include/exit_resident_process_manager.h +++ b/services/appmgr/include/exit_resident_process_manager.h @@ -38,16 +38,21 @@ public: ~ExitResidentProcessManager(); bool IsMemorySizeSufficent() const; bool RecordExitResidentBundleName(const std::string &bundleName); + void RecordExitResidentBundleDependedOnWeb(const std::string &bundleName); int32_t HandleMemorySizeInSufficent(); int32_t HandleMemorySizeSufficent(std::vector& bundleNames); + void HandleExitResidentBundleDependedOnWeb(std::vector& bundleNames); void QueryExitBundleInfos(const std::vector& exitBundleNames, std::vector& exitBundleInfos); + bool IsKilledForUpgradeWeb(const std::string &bundleName) const; private: ExitResidentProcessManager(); MemorySizeState currentMemorySizeState_ = MemorySizeState::MEMORY_SIZE_SUFFICENT; std::vector exitResidentBundleNames_; + std::vector exitResidentBundlesDependedOnWeb_; mutable ffrt::mutex mutexLock_; + mutable ffrt::mutex webMutexLock_; DISALLOW_COPY_AND_MOVE(ExitResidentProcessManager); }; } // namespace AppExecFwk diff --git a/services/appmgr/include/modal_system_app_freeze_uiextension.h b/services/appmgr/include/modal_system_app_freeze_uiextension.h index e9067cdcc8..9d1841af56 100644 --- a/services/appmgr/include/modal_system_app_freeze_uiextension.h +++ b/services/appmgr/include/modal_system_app_freeze_uiextension.h @@ -20,10 +20,12 @@ #include #include +#include #include "ability_connect_callback_stub.h" #include "ability_manager_client.h" #include "ability_state.h" +#include "fault_data.h" #include "iremote_stub.h" #include "task_handler_wrap.h" #include "want.h" @@ -31,15 +33,20 @@ namespace OHOS { namespace AppExecFwk { +constexpr const char* APP_NO_RESPONSE_BUNDLENAME = "com.ohos.taskmanager"; +constexpr const char* APP_NO_RESPONSE_ABILITY = "AppAbnormalAbility"; + class ModalSystemAppFreezeUIExtension { public: static ModalSystemAppFreezeUIExtension &GetInstance(); ModalSystemAppFreezeUIExtension() = default; virtual ~ModalSystemAppFreezeUIExtension(); - bool CreateModalUIExtension(std::string pid, std::string bundleName); + void ProcessAppFreeze(bool focusFlag, const FaultData &faultData, std::string pid, std::string bundleName, + std::function callback, bool isDialogExist); private: + bool CreateModalUIExtension(std::string pid, std::string bundleName); AAFwk::Want CreateSystemDialogWant(std::string pid, std::string bundleName); private: @@ -62,6 +69,7 @@ private: std::mutex appFreezeResultMutex_; std::mutex dialogConnectionMutex_; + std::string lastFreezePid; sptr dialogConnectionCallback_; }; } // namespace AppExecFwk diff --git a/services/appmgr/include/window_focus_changed_listener.h b/services/appmgr/include/window_focus_changed_listener.h index 42ed5fa7c9..003e596b24 100644 --- a/services/appmgr/include/window_focus_changed_listener.h +++ b/services/appmgr/include/window_focus_changed_listener.h @@ -17,7 +17,7 @@ #define OHOS_ABILITY_RUNTIME_WINDOW_FOCUS_CHANGE_LISTENER_H #ifdef SUPPORT_SCREEN -#include "window_manager_lite.h" +#include "window_manager.h" #endif // SUPPORT_SCREEN #include "task_handler_wrap.h" diff --git a/services/appmgr/include/window_visibility_changed_listener.h b/services/appmgr/include/window_visibility_changed_listener.h index c4f6b53d8a..765b30b554 100644 --- a/services/appmgr/include/window_visibility_changed_listener.h +++ b/services/appmgr/include/window_visibility_changed_listener.h @@ -18,7 +18,7 @@ #include "task_handler_wrap.h" #ifdef SUPPORT_SCREEN -#include "window_manager_lite.h" +#include "window_manager.h" #endif // SUPPORT_SCREEN namespace OHOS { namespace AppExecFwk { diff --git a/services/appmgr/src/ams_mgr_scheduler.cpp b/services/appmgr/src/ams_mgr_scheduler.cpp index 709bfa1f4c..ec7455f1d9 100644 --- a/services/appmgr/src/ams_mgr_scheduler.cpp +++ b/services/appmgr/src/ams_mgr_scheduler.cpp @@ -48,6 +48,7 @@ constexpr const char* SCENE_BOARD_BUNDLE_NAME = "com.ohos.sceneboard"; constexpr const char* SCENEBOARD_ABILITY_NAME = "com.ohos.sceneboard.MainAbility"; constexpr const char* TASK_SCENE_BOARD_ATTACH_TIMEOUT = "sceneBoardAttachTimeoutTask"; constexpr const char* TASK_ATTACHED_TO_STATUS_BAR = "AttachedToStatusBar"; +constexpr const char* TASK_BLOCK_PROCESS_CACHE_BY_PIDS = "BlockProcessCacheByPids"; constexpr int32_t SCENE_BOARD_ATTACH_TIMEOUT_TASK_TIME = 1000; }; // namespace @@ -167,6 +168,10 @@ void AmsMgrScheduler::TerminateAbility(const sptr &token, bool cl void AmsMgrScheduler::RegisterAppStateCallback(const sptr &callback) { + if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) { + TAG_LOGE(AAFwkTag::APPMGR, "caller is not SA"); + return; + } if (!IsReady()) { return; } @@ -201,7 +206,7 @@ void AmsMgrScheduler::KillProcessByAbilityToken(const sptr &token return; } - if (amsMgrServiceInner_->VerifyProcessPermission(token) != ERR_OK) { + if (amsMgrServiceInner_->VerifyKillProcessPermission(token) != ERR_OK) { TAG_LOGE(AAFwkTag::APPMGR, "%{public}s: Permission verification failed", __func__); return; } @@ -251,7 +256,7 @@ void AmsMgrScheduler::KillProcessesByPids(std::vector &pids) return; } - std::function killProcessesByPidsFunc = [amsMgrServiceInner = amsMgrServiceInner_, &pids]() { + std::function killProcessesByPidsFunc = [amsMgrServiceInner = amsMgrServiceInner_, pids]() mutable { amsMgrServiceInner->KillProcessesByPids(pids); }; amsHandler_->SubmitTask(killProcessesByPidsFunc, TASK_KILL_PROCESSES_BY_PIDS); @@ -304,7 +309,7 @@ void AmsMgrScheduler::AbilityAttachTimeOut(const sptr &token) amsHandler_->SubmitTask(task); } -void AmsMgrScheduler::PrepareTerminate(const sptr &token) +void AmsMgrScheduler::PrepareTerminate(const sptr &token, bool clearMissionFlag) { TAG_LOGD(AAFwkTag::APPMGR, "Notify AppMgrService to prepare to terminate the ability."); if (!IsReady()) { @@ -315,7 +320,7 @@ void AmsMgrScheduler::PrepareTerminate(const sptr &token) TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed."); return; } - auto task = [=]() { amsMgrServiceInner_->PrepareTerminate(token); }; + auto task = [=]() { amsMgrServiceInner_->PrepareTerminate(token, clearMissionFlag); }; amsHandler_->SubmitTask(task, AAFwk::TaskQoS::USER_INTERACTIVE); } @@ -339,6 +344,18 @@ int32_t AmsMgrScheduler::KillApplication(const std::string &bundleName, const bo return amsMgrServiceInner_->KillApplication(bundleName, clearPageStack); } +int32_t AmsMgrScheduler::ForceKillApplication(const std::string &bundleName, + const int userId, const int appIndex) +{ + TAG_LOGI(AAFwkTag::APPMGR, "bundleName=%{public}s,userId=%{public}d,apIndex=%{public}d", + bundleName.c_str(), userId, appIndex); + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + + return amsMgrServiceInner_->ForceKillApplication(bundleName, userId, appIndex); +} + int32_t AmsMgrScheduler::KillApplicationByUid(const std::string &bundleName, const int uid) { TAG_LOGI(AAFwkTag::APPMGR, "bundleName = %{public}s, uid = %{public}d", bundleName.c_str(), uid); @@ -420,6 +437,10 @@ void AmsMgrScheduler::StartSpecifiedProcess(const AAFwk::Want &want, const AppEx void AmsMgrScheduler::RegisterStartSpecifiedAbilityResponse(const sptr &response) { + if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) { + TAG_LOGE(AAFwkTag::APPMGR, "caller is not SA"); + return; + } if (!IsReady()) { return; } @@ -617,5 +638,33 @@ void AmsMgrScheduler::AttachedToStatusBar(const sptr &token) std::bind(&AppMgrServiceInner::AttachedToStatusBar, amsMgrServiceInner_, token); amsHandler_->SubmitTask(attachedToStatusBarFunc, TASK_ATTACHED_TO_STATUS_BAR); } + +void AmsMgrScheduler::BlockProcessCacheByPids(const std::vector &pids) +{ + if (!IsReady()) { + return; + } + + pid_t callingPid = IPCSkeleton::GetCallingPid(); + pid_t pid = getprocpid(); + if (callingPid != pid) { + TAG_LOGE(AAFwkTag::APPMGR, "Not allow other process to call."); + return; + } + + std::function blockProcCacheFunc = [amsMgrServiceInner = amsMgrServiceInner_, pids]() mutable { + amsMgrServiceInner->BlockProcessCacheByPids(pids); + }; + amsHandler_->SubmitTask(blockProcCacheFunc, TASK_BLOCK_PROCESS_CACHE_BY_PIDS); +} + +bool AmsMgrScheduler::IsKilledForUpgradeWeb(const std::string &bundleName) +{ + if (!IsReady()) { + TAG_LOGE(AAFwkTag::APPMGR, "AmsMgrService is not ready."); + return false; + } + return amsMgrServiceInner_->IsKilledForUpgradeWeb(bundleName); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_config_data_manager.cpp b/services/appmgr/src/app_config_data_manager.cpp index 48da642b3b..b99b136753 100644 --- a/services/appmgr/src/app_config_data_manager.cpp +++ b/services/appmgr/src/app_config_data_manager.cpp @@ -19,7 +19,6 @@ #include "errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AbilityRuntime { @@ -113,7 +112,7 @@ int32_t AppConfigDataManager::SetAppWaitingDebugInfo(const std::string &bundleNa int32_t AppConfigDataManager::ClearAppWaitingDebugInfo() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); { std::lock_guard lock(kvStorePtrMutex_); if (!CheckKvStore()) { @@ -138,7 +137,7 @@ int32_t AppConfigDataManager::ClearAppWaitingDebugInfo() int32_t AppConfigDataManager::GetAppWaitingDebugList(std::vector &bundleNameList) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); { std::lock_guard lock(kvStorePtrMutex_); if (!CheckKvStore()) { diff --git a/services/appmgr/src/app_debug_manager.cpp b/services/appmgr/src/app_debug_manager.cpp index 8d0ea1c4b1..cba80effbf 100644 --- a/services/appmgr/src/app_debug_manager.cpp +++ b/services/appmgr/src/app_debug_manager.cpp @@ -22,7 +22,7 @@ namespace OHOS { namespace AppExecFwk { int32_t AppDebugManager::RegisterAppDebugListener(const sptr &listener) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (listener == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Listener is nullptr."); return ERR_INVALID_DATA; @@ -48,7 +48,7 @@ int32_t AppDebugManager::RegisterAppDebugListener(const sptr int32_t AppDebugManager::UnregisterAppDebugListener(const sptr &listener) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (listener == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Listener is nullptr."); return ERR_INVALID_DATA; @@ -70,7 +70,7 @@ int32_t AppDebugManager::UnregisterAppDebugListener(const sptr &infos) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::lock_guard lock(mutex_); std::vector incrementInfos; GetIncrementAppDebugInfos(infos, incrementInfos); @@ -88,7 +88,7 @@ void AppDebugManager::StartDebug(const std::vector &infos) void AppDebugManager::StopDebug(const std::vector &infos) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::lock_guard lock(mutex_); std::vector debugInfos; for (auto &it : infos) { @@ -148,7 +148,7 @@ void AppDebugManager::GetIncrementAppDebugInfos( void AppDebugManager::RemoveAppDebugInfo(const AppDebugInfo &info) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::lock_guard lock(mutex_); auto isExist = [this, info](const AppDebugInfo &debugInfo) { return (debugInfo.bundleName == info.bundleName && debugInfo.pid == info.pid && diff --git a/services/appmgr/src/app_lifecycle_deal.cpp b/services/appmgr/src/app_lifecycle_deal.cpp index c46c9495c8..79fa3a4c84 100644 --- a/services/appmgr/src/app_lifecycle_deal.cpp +++ b/services/appmgr/src/app_lifecycle_deal.cpp @@ -318,7 +318,7 @@ int32_t AppLifeCycleDeal::ChangeAppGcState(int32_t state) int32_t AppLifeCycleDeal::AttachAppDebug() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto appThread = GetApplicationClient(); if (appThread == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "appThread is nullptr."); @@ -330,7 +330,7 @@ int32_t AppLifeCycleDeal::AttachAppDebug() int32_t AppLifeCycleDeal::DetachAppDebug() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto appThread = GetApplicationClient(); if (appThread == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "appThread is nullptr."); @@ -342,7 +342,7 @@ int32_t AppLifeCycleDeal::DetachAppDebug() int AppLifeCycleDeal::DumpIpcStart(std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto appThread = GetApplicationClient(); if (appThread == nullptr) { result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT)) @@ -356,7 +356,7 @@ int AppLifeCycleDeal::DumpIpcStart(std::string& result) int AppLifeCycleDeal::DumpIpcStop(std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto appThread = GetApplicationClient(); if (appThread == nullptr) { result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT)) @@ -370,7 +370,7 @@ int AppLifeCycleDeal::DumpIpcStop(std::string& result) int AppLifeCycleDeal::DumpIpcStat(std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto appThread = GetApplicationClient(); if (appThread == nullptr) { result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT)) @@ -382,19 +382,6 @@ int AppLifeCycleDeal::DumpIpcStat(std::string& result) 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); -} - void AppLifeCycleDeal::ScheduleCacheProcess() { auto appThread = GetApplicationClient(); @@ -405,5 +392,18 @@ void AppLifeCycleDeal::ScheduleCacheProcess() appThread->ScheduleCacheProcess(); } + +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 1153dcc654..3994aecb66 100644 --- a/services/appmgr/src/app_mgr_service.cpp +++ b/services/appmgr/src/app_mgr_service.cpp @@ -21,6 +21,7 @@ #include #include +#include "ability_manager_errors.h" #include "app_death_recipient.h" #include "app_mgr_constants.h" #include "datetime_ex.h" @@ -317,6 +318,10 @@ sptr AppMgrService::GetAmsMgr() int32_t AppMgrService::ClearUpApplicationData(const std::string &bundleName, int32_t appCloneIndex, int32_t userId) { + if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { + TAG_LOGE(AAFwkTag::APPMGR, "The caller is not system-app, can not use system-api"); + return AAFwk::ERR_NOT_SYSTEM_APP; + } if (!IsReady()) { return ERR_INVALID_OPERATION; } @@ -342,7 +347,7 @@ int32_t AppMgrService::ClearUpApplicationData(const std::string &bundleName, int AAFwk::PermissionConstants::PERMISSION_CLEAN_APPLICATION_DATA); if (!isCallingPerm) { TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed"); - return ERR_PERMISSION_DENIED; + return AAFwk::CHECK_PERMISSION_FAILED; } } pid_t pid = IPCSkeleton::GetCallingPid(); @@ -411,6 +416,12 @@ int32_t AppMgrService::JudgeSandboxByPid(pid_t pid, bool &isSandbox) TAG_LOGE(AAFwkTag::APPMGR, "AppMgrService is not ready."); return ERR_INVALID_OPERATION; } + bool isCallingPermission = + AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS); + if (!isCallingPermission) { + TAG_LOGE(AAFwkTag::APPMGR, "VerificationAllToken failed."); + return ERR_PERMISSION_DENIED; + } auto appRunningRecord = appMgrServiceInner_->GetAppRunningRecordByPid(pid); if (appRunningRecord && appRunningRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) { isSandbox = true; @@ -522,7 +533,7 @@ int32_t AppMgrService::UnregisterApplicationStateObserver(const sptr &observer) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!IsReady()) { TAG_LOGE(AAFwkTag::APPMGR, "Not ready."); return ERR_INVALID_OPERATION; @@ -532,7 +543,7 @@ int32_t AppMgrService::RegisterAbilityForegroundStateObserver(const sptr &observer) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!IsReady()) { TAG_LOGE(AAFwkTag::APPMGR, "Not ready."); return ERR_INVALID_OPERATION; @@ -609,7 +620,7 @@ int AppMgrService::FinishUserTest(const std::string &msg, const int64_t &resultC int AppMgrService::Dump(int fd, const std::vector& args) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!IsReady()) { TAG_LOGE(AAFwkTag::APPMGR, "not ready."); return ERR_APPEXECFWK_HIDUMP_ERROR; @@ -627,7 +638,7 @@ int AppMgrService::Dump(int fd, const std::vector& args) int AppMgrService::Dump(const std::vector& args, std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto size = args.size(); if (size == 0) { return ShowHelp(args, result); @@ -661,7 +672,7 @@ int AppMgrService::ShowHelp(const std::vector& args, std::string int AppMgrService::DumpIpcAllInner(const AppMgrService::DumpIpcKey key, std::string& result) { - TAG_LOGI(AAFwkTag::APPMGR, "Called."); + TAG_LOGI(AAFwkTag::APPMGR, "called"); switch (key) { case KEY_DUMP_IPC_START: return DumpIpcAllStart(result); @@ -681,7 +692,7 @@ int AppMgrService::DumpIpcAllInner(const AppMgrService::DumpIpcKey key, std::str int AppMgrService::DumpIpcWithPidInner(const AppMgrService::DumpIpcKey key, const std::string& optionPid, std::string& result) { - TAG_LOGI(AAFwkTag::APPMGR, "Called."); + TAG_LOGI(AAFwkTag::APPMGR, "called"); int32_t pid = -1; char* end = nullptr; pid = static_cast(std::strtol(optionPid.c_str(), &end, BASE_TEN)); @@ -829,37 +840,37 @@ int AppMgrService::DumpFfrt(const std::vector& args, std::string int AppMgrService::DumpIpcAllStart(std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); return appMgrServiceInner_->DumpIpcAllStart(result); } int AppMgrService::DumpIpcAllStop(std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); return appMgrServiceInner_->DumpIpcAllStop(result); } int AppMgrService::DumpIpcAllStat(std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); return appMgrServiceInner_->DumpIpcAllStat(result); } int AppMgrService::DumpIpcStart(const int32_t pid, std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); return appMgrServiceInner_->DumpIpcStart(pid, result); } int AppMgrService::DumpIpcStop(const int32_t pid, std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); return appMgrServiceInner_->DumpIpcStop(pid, result); } int AppMgrService::DumpIpcStat(const int32_t pid, std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); return appMgrServiceInner_->DumpIpcStat(pid, result); } @@ -1065,6 +1076,10 @@ int32_t AppMgrService::NotifyHotReloadPage(const std::string &bundleName, const #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE int32_t AppMgrService::SetContinuousTaskProcess(int32_t pid, bool isContinuousTask) { + if (!AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is not foundation."); + return ERR_INVALID_OPERATION; + } if (!IsReady()) { TAG_LOGE(AAFwkTag::APPMGR, "AppMgrService is not ready."); return ERR_INVALID_OPERATION; @@ -1171,6 +1186,20 @@ int32_t AppMgrService::NotifyAppFaultBySA(const AppFaultDataBySA &faultData) return ret; } +bool AppMgrService::SetAppFreezeFilter(int32_t pid) +{ + if (!IsReady()) { + TAG_LOGE(AAFwkTag::APPMGR, "AppMgrService is not ready."); + return ERR_INVALID_OPERATION; + } + + auto ret = appMgrServiceInner_->SetAppFreezeFilter(pid); + if (!ret) { + TAG_LOGE(AAFwkTag::APPMGR, "SetAppFreezeFilter fail."); + } + return ret; +} + int32_t AppMgrService::GetProcessMemoryByPid(const int32_t pid, int32_t &memorySize) { if (!IsReady()) { @@ -1265,7 +1294,7 @@ int32_t AppMgrService::NotifyPageHide(const sptr &token, const Pa int32_t AppMgrService::RegisterAppRunningStatusListener(const sptr &listener) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!IsReady()) { TAG_LOGE(AAFwkTag::APPMGR, "Not ready"); return ERR_INVALID_OPERATION; @@ -1275,7 +1304,7 @@ int32_t AppMgrService::RegisterAppRunningStatusListener(const sptr &listener) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!IsReady()) { TAG_LOGE(AAFwkTag::APPMGR, "Not ready."); return ERR_INVALID_OPERATION; @@ -1285,7 +1314,7 @@ int32_t AppMgrService::UnregisterAppRunningStatusListener(const sptr &observer) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!IsReady()) { TAG_LOGE(AAFwkTag::APPMGR, "Not ready."); return ERR_INVALID_OPERATION; @@ -1295,7 +1324,7 @@ int32_t AppMgrService::RegisterAppForegroundStateObserver(const sptr &observer) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!IsReady()) { TAG_LOGE(AAFwkTag::APPMGR, "Not ready."); return ERR_INVALID_OPERATION; @@ -1319,16 +1348,14 @@ int32_t AppMgrService::IsAppRunning(const std::string &bundleName, int32_t appCl return appMgrServiceInner_->IsAppRunning(bundleName, appCloneIndex, isRunning); } -int32_t AppMgrService::StartChildProcess(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount, - bool isStartWithDebug) +int32_t AppMgrService::StartChildProcess(pid_t &childPid, const ChildProcessRequest &request) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!IsReady()) { TAG_LOGE(AAFwkTag::APPMGR, "StartChildProcess failed, AppMgrService not ready."); return ERR_INVALID_OPERATION; } - return appMgrServiceInner_->StartChildProcess(IPCSkeleton::GetCallingPid(), srcEntry, childPid, - childProcessCount, isStartWithDebug); + return appMgrServiceInner_->StartChildProcess(IPCSkeleton::GetCallingPid(), childPid, request); } int32_t AppMgrService::GetChildProcessInfoForSelf(ChildProcessInfo &info) @@ -1529,5 +1556,40 @@ int32_t AppMgrService::CheckCallingIsUserTestMode(const pid_t pid, bool &isUserT return appMgrServiceInner_->CheckCallingIsUserTestModeInner(pid, isUserTest); } +int32_t AppMgrService::NotifyProcessDependedOnWeb() +{ + TAG_LOGD(AAFwkTag::APPMGR, "called."); + if (!appMgrServiceInner_) { + TAG_LOGE(AAFwkTag::APPMGR, "Not ready."); + return ERR_INVALID_VALUE; + } + return appMgrServiceInner_->NotifyProcessDependedOnWeb(); +} + +void AppMgrService::KillProcessDependedOnWeb() +{ + TAG_LOGD(AAFwkTag::APPMGR, "called."); + if (!AAFwk::PermissionVerification::GetInstance()->VerifyKillProcessDependedOnWebPermission()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "caller have not permission."); + return; + } + if (!appMgrServiceInner_) { + return; + } + appMgrServiceInner_->KillProcessDependedOnWeb(); +} + +void AppMgrService::RestartResidentProcessDependedOnWeb() +{ + TAG_LOGD(AAFwkTag::APPMGR, "called."); + if (!AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is not foundation."); + return; + } + if (!appMgrServiceInner_) { + return; + } + appMgrServiceInner_->RestartResidentProcessDependedOnWeb(); +} } // 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 7a1ae95894..bf9bc56566 100644 --- a/services/appmgr/src/app_mgr_service_inner.cpp +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -46,7 +47,6 @@ #include "freeze_util.h" #include "global_constant.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "in_process_call_wrapper.h" #include "ipc_skeleton.h" @@ -81,9 +81,9 @@ #include "meminfo.h" #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" +#include "cache_process_manager.h" #ifdef APP_NO_RESPONSE_DIALOG #include "fault_data.h" #include "modal_system_app_freeze_uiextension.h" @@ -139,6 +139,7 @@ constexpr const char* FUNC_NAME = "main"; constexpr const char* RENDER_PARAM = "invalidparam"; constexpr const char* COLD_START = "coldStart"; constexpr const char* PERF_CMD = "perfCmd"; +constexpr const char* ERROR_INFO_ENHANCE = "errorInfoEnhance"; constexpr const char* MULTI_THREAD = "multiThread"; constexpr const char* DEBUG_CMD = "debugCmd"; constexpr const char* ENTER_SANDBOX = "sandboxApp"; @@ -155,9 +156,9 @@ constexpr const char* SERVICE_EXTENSION = ":ServiceExtension"; constexpr const char* KEEP_ALIVE = ":KeepAlive"; constexpr const char* PARAM_SPECIFIED_PROCESS_FLAG = "ohoSpecifiedProcessFlag"; constexpr const char* TSAN_FLAG_NAME = "tsanEnabled"; -constexpr const char* MEMMGR_PROC_NAME = "memmgrservice"; constexpr const char* UIEXTENSION_ABILITY_ID = "ability.want.params.uiExtensionAbilityId"; constexpr const char* UIEXTENSION_ROOT_HOST_PID = "ability.want.params.uiExtensionRootHostPid"; +constexpr const char* MEMMGR_PROC_NAME = "memmgrservice"; constexpr const char* STRICT_MODE = "strictMode"; constexpr const char* RENDER_PROCESS_NAME = ":render"; constexpr const char* RENDER_PROCESS_TYPE = "render"; @@ -171,8 +172,6 @@ constexpr int32_t USER_SCALE = 200000; #define APP_ACCESS_BUNDLE_DIR 0x20 #define APP_OVERLAY_FLAG 0x100 -constexpr int32_t BASE_USER_RANGE = 200000; - constexpr int32_t MAX_RESTART_COUNT = 3; constexpr int32_t RESTART_INTERVAL_TIME = 120000; constexpr int32_t FIRST_FRAME_NOTIFY_TASK_DELAY = 5; //ms @@ -192,8 +191,6 @@ constexpr const char* EVENT_KEY_MESSAGE = "MSG"; constexpr const char* DEVELOPER_MODE_STATE = "const.security.developermode.state"; constexpr const char* PRODUCT_ASSERT_FAULT_DIALOG_ENABLED = "persisit.sys.abilityms.support_assert_fault_dialog"; -constexpr char BUNDLE_NAME_SAMPLE_MANAGEMENT[] = "com.huawei.hmsapp.samplemanagement"; - // Msg length is less than 48 characters constexpr const char* EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT = "Terminate Ability TimeOut!"; constexpr const char* EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT = "Terminate Application TimeOut!"; @@ -218,6 +215,7 @@ constexpr int32_t FOUNDATION_UID = 5523; constexpr int32_t QUICKFIX_UID = 5524; constexpr int32_t DEFAULT_USER_ID = 0; constexpr int32_t CURRENT_USER_ID = -1; +constexpr int32_t RESOURCE_MANAGER_UID = 1096; constexpr int32_t BLUETOOTH_GROUPID = 1002; @@ -426,7 +424,8 @@ void AppMgrServiceInner::HandlePreloadApplication(const PreloadRequest &request) return; } bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(bundleInfo.name); - if (!appExistFlag) { + bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(bundleInfo.uid); + if (!appMultiUserExistFlag) { NotifyAppRunningStatusEvent( bundleInfo.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START); } @@ -442,7 +441,8 @@ void AppMgrServiceInner::LoadAbility(sptr token, sptr want, int32_t abilityRecordId) { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); - TAG_LOGI(AAFwkTag::APPMGR, "name:%{public}s.", abilityInfo->name.c_str()); + TAG_LOGI(AAFwkTag::APPMGR, "name:%{public}s-%{public}s.", + abilityInfo->bundleName.c_str(), abilityInfo->name.c_str()); if (!CheckLoadAbilityConditions(token, abilityInfo, appInfo)) { TAG_LOGE(AAFwkTag::APPMGR, "CheckLoadAbilityConditions failed"); return; @@ -469,7 +469,6 @@ void AppMgrServiceInner::LoadAbility(sptr token, sptr token, sptrCheckAppRunningRecordIsExistByBundleName(bundleInfo.name); - if (!appExistFlag) { + bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(bundleInfo.uid); + if (!appMultiUserExistFlag) { NotifyAppRunningStatusEvent( bundleInfo.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START); } appRecord = CreateAppRunningRecord(token, preToken, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo, want, abilityRecordId); LoadAbilityNoAppRecord(appRecord, preToken, appInfo, abilityInfo, processName, specifiedProcessFlag, - bundleInfo, hapModuleInfo, want, appExistFlag, false); + bundleInfo, hapModuleInfo, want, appExistFlag, false, token); } else { TAG_LOGI(AAFwkTag::APPMGR, "have apprecord"); SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::MULTI_INSTANCE); @@ -503,11 +503,18 @@ void AppMgrServiceInner::LoadAbility(sptr token, sptr::GetInstance()->OnProcessReused(appRecord); } StartAbility(token, preToken, abilityInfo, appRecord, hapModuleInfo, want, abilityRecordId); + if (AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType)) { + AddUIExtensionLauncherItem(want, appRecord, token); + } } if (AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType) && - appRunningManager_ != nullptr && appRunningManager_->GetAppRunningRecordByAbilityToken(token)) { - AddUIExtensionLauncherItem(want, appRecord, token); + appRecord != nullptr && want != nullptr) { + auto abilityRunningRecord = appRecord->GetAbilityRunningRecordByToken(token); + auto uiExtensionAbilityId = want->GetIntParam(UIEXTENSION_ABILITY_ID, -1); + if (abilityRunningRecord != nullptr) { + abilityRunningRecord->SetUIExtensionAbilityId(uiExtensionAbilityId); + } } PerfProfile::GetInstance().SetAbilityLoadEndTime(GetTickCount()); @@ -535,17 +542,12 @@ void AppMgrServiceInner::AddUIExtensionLauncherItem(std::shared_ptr return; } - TAG_LOGD(AAFwkTag::APPMGR, "Add uiextension launcher info, uiExtensionAbilityId: %{public}d, hostPid: %{public}d, " + TAG_LOGI(AAFwkTag::APPMGR, "Add uiextension launcher info, uiExtensionAbilityId: %{public}d, hostPid: %{public}d, " "providerPid: %{public}d.", uiExtensionAbilityId, hostPid, providerPid); appRunningManager_->AddUIExtensionLauncherItem(uiExtensionAbilityId, hostPid, providerPid); want->RemoveParam(UIEXTENSION_ABILITY_ID); want->RemoveParam(UIEXTENSION_ROOT_HOST_PID); - - auto abilityRunningRecord = appRecord->GetAbilityRunningRecordByToken(token); - if (abilityRunningRecord != nullptr) { - abilityRunningRecord->SetUIExtensionAbilityId(uiExtensionAbilityId); - } } void AppMgrServiceInner::RemoveUIExtensionLauncherItem(std::shared_ptr appRecord, @@ -681,7 +683,7 @@ void AppMgrServiceInner::LoadAbilityNoAppRecord(const std::shared_ptr preToken, std::shared_ptr appInfo, std::shared_ptr abilityInfo, const std::string &processName, const std::string &specifiedProcessFlag, const BundleInfo &bundleInfo, const HapModuleInfo &hapModuleInfo, - std::shared_ptr want, bool appExistFlag, bool isPreload) + std::shared_ptr want, bool appExistFlag, bool isPreload, sptr token) { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::APPMGR, "LoadAbilityNoAppRecord, processName:%{public}s, isPreload:%{public}d", @@ -724,7 +726,7 @@ void AppMgrServiceInner::LoadAbilityNoAppRecord(const std::shared_ptrapplicationName, processName, startFlags, appRecord, appInfo->uid, bundleInfo, appInfo->bundleName, bundleIndex, appExistFlag, isPreload, abilityInfo->moduleName, - abilityInfo->name, strictMode, maxChildProcess); + abilityInfo->name, strictMode, maxChildProcess, token, want, abilityInfo->extensionAbilityType); std::string perfCmd = (want == nullptr) ? "" : want->GetStringParam(PERF_CMD); bool isSandboxApp = (want == nullptr) ? false : want->GetBoolParam(ENTER_SANDBOX, false); (void)StartPerfProcess(appRecord, perfCmd, "", isSandboxApp); @@ -815,6 +817,7 @@ bool AppMgrServiceInner::GetBundleAndHapInfo(const AbilityInfo &abilityInfo, bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetSandboxBundleInfo(appInfo->bundleName, appIndex, userId, bundleInfo)); } + if (bundleMgrResult != ERR_OK) { TAG_LOGE(AAFwkTag::APPMGR, "GetBundleInfo is fail."); return false; @@ -944,13 +947,15 @@ void AppMgrServiceInner::ApplicationForegrounded(const int32_t recordId) { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); auto appRecord = GetAppRunningRecordByAppRecordId(recordId); - if (!appRecord || (!appRecord->IsUpdateStateFromService() - && appRecord->GetApplicationPendingState() != ApplicationPendingState::FOREGROUNDING)) { + if (!appRecord) { TAG_LOGE(AAFwkTag::APPMGR, "get app record failed"); return; } ApplicationState appState = appRecord->GetState(); if (appState == ApplicationState::APP_STATE_READY || appState == ApplicationState::APP_STATE_BACKGROUND) { + if (appState == ApplicationState::APP_STATE_BACKGROUND) { + appRunningManager_->UpdateConfigurationDelayed(appRecord); + } appRecord->SetState(ApplicationState::APP_STATE_FOREGROUND); bool needNotifyApp = appRunningManager_->IsApplicationFirstForeground(*appRecord); OnAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND, needNotifyApp, false); @@ -959,28 +964,18 @@ void AppMgrServiceInner::ApplicationForegrounded(const int32_t recordId) TAG_LOGW(AAFwkTag::APPMGR, "app name(%{public}s), app state(%{public}d)!", appRecord->GetName().c_str(), static_cast(appState)); } - appRecord->SetUpdateStateFromService(false); - appRecord->SetApplicationPendingState(ApplicationPendingState::READY); appRecord->PopForegroundingAbilityTokens(); // push the foregrounded app front of RecentAppList. PushAppFront(recordId); - TAG_LOGD(AAFwkTag::APPMGR, "application is foregrounded"); - AAFwk::EventInfo eventInfo; - auto applicationInfo = appRecord->GetApplicationInfo(); - if (!applicationInfo) { - TAG_LOGE(AAFwkTag::APPMGR, "applicationInfo is nullptr, can not get app informations"); - } else { - eventInfo.bundleName = applicationInfo->name; - eventInfo.versionName = applicationInfo->versionName; - eventInfo.versionCode = applicationInfo->versionCode; - eventInfo.bundleType = static_cast(applicationInfo->bundleType); + TAG_LOGI(AAFwkTag::APPMGR, "application is foregrounded"); + if (appRecord->GetApplicationPendingState() == ApplicationPendingState::BACKGROUNDING) { + appRecord->ScheduleBackgroundRunning(); + } else if (appRecord->GetApplicationPendingState() == ApplicationPendingState::FOREGROUNDING) { + appRecord->SetApplicationPendingState(ApplicationPendingState::READY); } - eventInfo.pid = appRecord->GetPriorityObject()->GetPid(); - eventInfo.processName = appRecord->GetProcessName(); - eventInfo.processType = static_cast(appRecord->GetProcessType()); - int32_t callerPid = appRecord->GetCallerPid() == -1 ? - IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid(); + auto eventInfo = BuildEventInfo(appRecord); + int32_t callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid(); auto callerRecord = GetAppRunningRecordByPid(callerPid); if (callerRecord != nullptr) { eventInfo.callerBundleName = callerRecord->GetBundleName(); @@ -994,7 +989,7 @@ void AppMgrServiceInner::ApplicationBackgrounded(const int32_t recordId) { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); auto appRecord = GetAppRunningRecordByAppRecordId(recordId); - if (!appRecord || !appRecord->IsUpdateStateFromService()) { + if (!appRecord) { TAG_LOGE(AAFwkTag::APPMGR, "get app record failed"); return; } @@ -1009,26 +1004,39 @@ void AppMgrServiceInner::ApplicationBackgrounded(const int32_t recordId) TAG_LOGW(AAFwkTag::APPMGR, "app name(%{public}s), app state(%{public}d)!", appRecord->GetName().c_str(), static_cast(appRecord->GetState())); } - appRecord->SetUpdateStateFromService(false); - if (appRecord->GetApplicationPendingState() == ApplicationPendingState::BACKGROUNDING) { + if (appRecord->GetApplicationPendingState() == ApplicationPendingState::FOREGROUNDING) { + appRecord->ScheduleForegroundRunning(); + } else if (appRecord->GetApplicationPendingState() == ApplicationPendingState::BACKGROUNDING) { appRecord->SetApplicationPendingState(ApplicationPendingState::READY); } - TAG_LOGD(AAFwkTag::APPMGR, "application is backgrounded"); + TAG_LOGI(AAFwkTag::APPMGR, "application is backgrounded"); + auto eventInfo = BuildEventInfo(appRecord); + AAFwk::EventReport::SendAppBackgroundEvent(AAFwk::EventName::APP_BACKGROUND, eventInfo); +} + +AAFwk::EventInfo AppMgrServiceInner::BuildEventInfo(std::shared_ptr appRecord) const +{ AAFwk::EventInfo eventInfo; + if (appRecord == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "appRecord is nullptr."); + return eventInfo; + } auto applicationInfo = appRecord->GetApplicationInfo(); if (!applicationInfo) { - TAG_LOGE(AAFwkTag::APPMGR, "applicationInfo is nullptr, can not get app informations"); + TAG_LOGW(AAFwkTag::APPMGR, "applicationInfo is nullptr, can not get app informations"); } else { eventInfo.bundleName = applicationInfo->name; eventInfo.versionName = applicationInfo->versionName; eventInfo.versionCode = applicationInfo->versionCode; eventInfo.bundleType = static_cast(applicationInfo->bundleType); } - eventInfo.pid = appRecord->GetPriorityObject()->GetPid(); + if (appRecord->GetPriorityObject() != nullptr) { + eventInfo.pid = appRecord->GetPriorityObject()->GetPid(); + } eventInfo.processName = appRecord->GetProcessName(); eventInfo.processType = static_cast(appRecord->GetProcessType()); - AAFwk::EventReport::SendAppBackgroundEvent(AAFwk::EventName::APP_BACKGROUND, eventInfo); + return eventInfo; } void AppMgrServiceInner::ApplicationTerminated(const int32_t recordId) @@ -1132,7 +1140,7 @@ int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName, const return KillApplicationByBundleName(bundleName, clearPageStack); } - auto result = VerifyProcessPermission(bundleName); + auto result = VerifyKillProcessPermission(bundleName); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed."); return result; @@ -1141,6 +1149,49 @@ int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName, const return KillApplicationByBundleName(bundleName, clearPageStack); } +int32_t AppMgrServiceInner::ForceKillApplication(const std::string &bundleName, + const int userId, const int appIndex) +{ + TAG_LOGI(AAFwkTag::APPMGR, "Called."); + if (!IsSceneBoardCall()) { + TAG_LOGE(AAFwkTag::APPMGR, "this is not called by SceneBoard."); + return AAFwk::CHECK_PERMISSION_FAILED; + } + + return ForceKillApplicationInner(bundleName, userId, appIndex); +} + +int32_t AppMgrServiceInner::ForceKillApplicationInner(const std::string &bundleName, + const int userId, const int appIndex) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called."); + if (!appRunningManager_) { + TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr"); + return ERR_NO_INIT; + } + + std::list pids; + int32_t newUserId = userId; + if (userId == DEFAULT_INVAL_VALUE) { + newUserId = GetUserIdByUid(IPCSkeleton::GetCallingUid()); + } + int32_t result = ERR_OK; + if (!appRunningManager_->GetPidsByBundleNameUserIdAndAppIndex(bundleName, newUserId, appIndex, pids)) { + TAG_LOGI(AAFwkTag::APPMGR, "not start"); + return result; + } + for (auto iter = pids.begin(); iter != pids.end(); ++iter) { + result = KillProcessByPid(*iter, "ForceKillApplicationByBundleName"); + if (result < 0) { + TAG_LOGE(AAFwkTag::APPMGR, + "ForceKillApplicationByBundleName failed for bundleName:%{public}s pid:%{public}d", + bundleName.c_str(), *iter); + return result; + } + } + return result; +} + int32_t AppMgrServiceInner::KillApplicationByUid(const std::string &bundleName, const int uid) { if (!appRunningManager_) { @@ -1150,7 +1201,7 @@ int32_t AppMgrServiceInner::KillApplicationByUid(const std::string &bundleName, int32_t result = ERR_OK; if (!CheckCallerIsAppGallery()) { - result = VerifyProcessPermission(bundleName); + result = VerifyKillProcessPermission(bundleName); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed."); return result; @@ -1432,9 +1483,6 @@ int32_t AppMgrServiceInner::GetAllRunningProcesses(std::vectorGetSpawned()) { continue; } - if (GetUserIdByUid(appRecord->GetUid()) != currentUserId_) { - continue; - } if (isPerm) { GetRunningProcesses(appRecord, info); } else { @@ -1758,9 +1806,9 @@ void AppMgrServiceInner::GetRenderProcesses(const std::shared_ptr &pids) return (pids.empty() ? false : true); } -bool AppMgrServiceInner::ProcessExist(pid_t pid) +bool AppMgrServiceInner::ProcessExist(pid_t pid, int32_t uid) { char pid_path[128] = {0}; struct stat stat_buf; @@ -1843,7 +1891,14 @@ bool AppMgrServiceInner::ProcessExist(pid_t pid) if (snprintf_s(pid_path, sizeof(pid_path), sizeof(pid_path) - 1, "/proc/%d/status", pid) < 0) { return false; } - if (stat(pid_path, &stat_buf) == 0) { + if (stat(pid_path, &stat_buf) != 0) { + return false; + } + TAG_LOGI(AAFwkTag::APPMGR, "uid: %{public}d, input uid: %{public}d", stat_buf.st_uid, uid); + if (uid == -1 || stat_buf.st_uid == 0) { + return true; + } + if (stat_buf.st_uid == static_cast(uid)) { return true; } return false; @@ -1912,6 +1967,7 @@ std::shared_ptr AppMgrServiceInner::CreateAppRunningRecord(spt appRecord->SetDebugApp(true); } appRecord->SetPerfCmd(want->GetStringParam(PERF_CMD)); + appRecord->SetErrorInfoEnhance(want->GetBoolParam(ERROR_INFO_ENHANCE, false)); appRecord->SetMultiThread(want->GetBoolParam(MULTI_THREAD, false)); int32_t appIndex = 0; (void)AbilityRuntime::StartupUtil::GetAppIndex(*want, appIndex); @@ -2000,7 +2056,6 @@ void AppMgrServiceInner::UpdateAbilityState(const sptr &token, co return; } - appRecord->SetUpdateStateFromService(true); appRecord->UpdateAbilityState(token, state); } @@ -2094,12 +2149,6 @@ void AppMgrServiceInner::SetBundleManagerHelper(const std::shared_ptr &callback) { - pid_t callingPid = IPCSkeleton::GetCallingPid(); - pid_t pid = getprocpid(); - if (callingPid != pid) { - TAG_LOGE(AAFwkTag::APPMGR, "%{public}s: Not abilityMgr call.", __func__); - return; - } HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); if (callback != nullptr) { std::lock_guard lock(appStateCallbacksLock_); @@ -2241,7 +2290,8 @@ void AppMgrServiceInner::StartAbility(sptr token, sptr want, int32_t abilityRecordId) { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::APPMGR, "start ability"); + TAG_LOGI(AAFwkTag::APPMGR, "start ability, ability %{public}s-%{public}s", + abilityInfo->bundleName.c_str(), abilityInfo->name.c_str()); if (!appRecord) { TAG_LOGE(AAFwkTag::APPMGR, "appRecord is null"); return; @@ -2471,6 +2521,7 @@ int32_t AppMgrServiceInner::StartPerfProcessByStartMsg(AppSpawnStartMsg &startMs TAG_LOGD(AAFwkTag::APPMGR, "perfCmd is empty"); return ERR_INVALID_OPERATION; } + startMsg.code = static_cast(MSG_SPAWN_NATIVE_PROCESS); if (!isSandboxApp) { TAG_LOGD(AAFwkTag::APPMGR, "debuggablePipe sandbox: false."); @@ -2739,14 +2790,22 @@ int32_t AppMgrServiceInner::CreateStartMsg(const std::string &processName, uint3 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::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::QueryExtensionSandBox(const std::string &moduleName, const std::string &abilityName, const BundleInfo &bundleInfo, AppSpawnStartMsg &startMsg, DataGroupInfoList& dataGroupInfoList, bool strictMode) { @@ -2755,15 +2814,15 @@ void AppMgrServiceInner::QueryExtensionSandBox(const std::string &moduleName, co 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; + startMsg.strictMode = strictMode; + auto infoExisted = [&moduleName, &abilityName, &strictMode](const ExtensionAbilityInfo& info) { + return info.moduleName == moduleName && info.name == abilityName && info.needCreateSandbox && strictMode; }; auto infoIter = std::find_if(extensionInfos.begin(), extensionInfos.end(), infoExisted); DataGroupInfoList extensionDataGroupInfoList; if (infoIter != extensionInfos.end()) { - startMsg.isolatedExtension = infoIter->needCreateSandbox; + startMsg.isolatedExtension = true; startMsg.extensionSandboxPath = infoIter->moduleName + "-" + infoIter->name; - startMsg.strictMode = strictMode; for (auto dataGroupInfo : dataGroupInfoList) { auto groupIdExisted = [&dataGroupInfo](const std::string &dataGroupId) { return dataGroupInfo.dataGroupId == dataGroupId; @@ -2779,22 +2838,11 @@ void AppMgrServiceInner::QueryExtensionSandBox(const std::string &moduleName, co } } -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) + const std::string &moduleName, const std::string &abilityName, bool strictMode, int32_t maxChildProcess, + sptr token, std::shared_ptr want, ExtensionAbilityType ExtensionAbilityType) { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "bundleName: %{public}s, isPreload: %{public}d", bundleName.c_str(), isPreload); @@ -2850,6 +2898,10 @@ void AppMgrServiceInner::StartProcess(const std::string &appName, const std::str appRecord->SetStartMsg(startMsg); appRecord->SetAppMgrServiceInner(weak_from_this()); appRecord->SetSpawned(); + if (AAFwk::UIExtensionUtils::IsUIExtension(ExtensionAbilityType)) { + TAG_LOGD(AAFwkTag::APPMGR, "Add UIExtension LauncherItem."); + AddUIExtensionLauncherItem(want, appRecord, token); + } OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE, false, false); AddAppToRecentList(appName, appRecord->GetProcessName(), pid, appRecord->GetRecordId()); DelayedSingleton::GetInstance()->OnProcessCreated(appRecord); @@ -2898,7 +2950,7 @@ AppDebugInfo AppMgrServiceInner::MakeAppDebugInfo( void AppMgrServiceInner::ProcessAppDebug(const std::shared_ptr &appRecord, const bool &isDebugStart) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (appRecord == nullptr || appDebugManager_ == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "appRecord or appDebugManager_ is nullptr."); return; @@ -2960,7 +3012,7 @@ bool AppMgrServiceInner::SendProcessStartEvent(const std::shared_ptr lock(killpedProcessMapLock_); int64_t restartTime = std::chrono::duration_cast(std::chrono:: system_clock::now().time_since_epoch()).count(); @@ -3091,7 +3143,7 @@ void AppMgrServiceInner::OnRemoteDied(const wptr &remote, bool is TAG_LOGI(AAFwkTag::APPMGR, "app record is not exist."); return; } - + AppExecFwk::AppfreezeManager::GetInstance()->RemoveDeathProcess(appRecord->GetBundleName()); std::vector> abilityTokens; for (const auto &token : appRecord->GetAbilities()) { abilityTokens.emplace_back(token.first); @@ -3224,14 +3276,14 @@ void AppMgrServiceInner::HandleAbilityAttachTimeOut(const sptr &t appRunningManager_->HandleAbilityAttachTimeOut(token); } -void AppMgrServiceInner::PrepareTerminate(const sptr &token) +void AppMgrServiceInner::PrepareTerminate(const sptr &token, bool clearMissionFlag) { TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!appRunningManager_) { TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr"); return; } - appRunningManager_->PrepareTerminate(token); + appRunningManager_->PrepareTerminate(token, clearMissionFlag); } void AppMgrServiceInner::HandleTerminateApplicationTimeOut(const int64_t eventId) @@ -3256,10 +3308,11 @@ void AppMgrServiceInner::TerminateApplication(const std::shared_ptrSetProcessChangeReason(ProcessChangeReason::REASON_APP_TERMINATED_TIMEOUT); OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED, false, false); pid_t pid = appRecord->GetPriorityObject()->GetPid(); + int32_t uid = appRecord->GetUid(); if (pid > 0) { - auto timeoutTask = [appRecord, pid, innerService = shared_from_this()]() { - TAG_LOGI(AAFwkTag::APPMGR, "KillProcessByPid %{public}d", pid); - int32_t result = innerService->KillProcessByPid(pid, "TerminateApplication"); + auto timeoutTask = [appRecord, pid, uid, innerService = shared_from_this()]() { + TAG_LOGI(AAFwkTag::APPMGR, "KillProcessByPid %{public}d, uid: %{public}d", pid, uid); + int32_t result = innerService->KillProcessByPid(pid, "TerminateApplication", uid); innerService->SendProcessExitEvent(appRecord); if (result < 0) { TAG_LOGE(AAFwkTag::APPMGR, "KillProcessByPid kill process is fail"); @@ -3289,7 +3342,6 @@ void AppMgrServiceInner::TerminateApplication(const std::shared_ptrGetUid(); NotifyAppRunningStatusEvent(appRecord->GetBundleName(), uid, AbilityRuntime::RunningStatus::APP_RUNNING_STOP); } @@ -3421,9 +3473,10 @@ void AppMgrServiceInner::StartEmptyResidentProcess( } bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(info.name); + bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(info.uid); auto appInfo = std::make_shared(info.applicationInfo); - if (!appExistFlag) { + if (!appMultiUserExistFlag) { NotifyAppRunningStatusEvent(info.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START); } @@ -3705,8 +3758,9 @@ int AppMgrServiceInner::StartEmptyProcess(const AAFwk::Want &want, const sptrCheckAppRunningRecordIsExistByBundleName(info.name); + bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(info.uid); auto appInfo = std::make_shared(info.applicationInfo); - if (!appExistFlag) { + if (!appMultiUserExistFlag) { NotifyAppRunningStatusEvent(info.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START); } auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info); @@ -3842,7 +3896,8 @@ void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const Ap appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo); if (!appRecord) { bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(bundleInfo.name); - if (!appExistFlag) { + bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(bundleInfo.uid); + if (!appMultiUserExistFlag) { NotifyAppRunningStatusEvent( bundleInfo.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START); } @@ -3871,6 +3926,7 @@ void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const Ap appRecord->SetDebugApp(true); } appRecord->SetPerfCmd(wantPtr->GetStringParam(PERF_CMD)); + appRecord->SetErrorInfoEnhance(wantPtr->GetBoolParam(ERROR_INFO_ENHANCE, false)); appRecord->SetMultiThread(wantPtr->GetBoolParam(MULTI_THREAD, false)); } appRecord->SetProcessAndExtensionType(abilityInfoPtr); @@ -3910,14 +3966,6 @@ void AppMgrServiceInner::RegisterStartSpecifiedAbilityResponse(const sptrUpdateConfigurationByBundleName(config, name); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::APPMGR, "update error, not notify"); @@ -4081,6 +4128,10 @@ void AppMgrServiceInner::HandleConfigurationChange(const Configuration &config) int32_t AppMgrServiceInner::RegisterConfigurationObserver(const sptr& observer) { TAG_LOGD(AAFwkTag::APPMGR, "called"); + if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) { + TAG_LOGE(AAFwkTag::APPMGR, "caller is not SA"); + return ERR_INVALID_VALUE; + } if (observer == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "AppMgrServiceInner::Register error: observer is null"); @@ -4102,6 +4153,10 @@ int32_t AppMgrServiceInner::RegisterConfigurationObserver(const sptr& observer) { TAG_LOGI(AAFwkTag::APPMGR, "called"); + if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) { + TAG_LOGE(AAFwkTag::APPMGR, "caller is not SA"); + return ERR_INVALID_VALUE; + } if (observer == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "AppMgrServiceInner::Register error: observer is null"); return ERR_INVALID_VALUE; @@ -4324,33 +4379,13 @@ int32_t AppMgrServiceInner::NotifyAppMgrRecordExitReason(int32_t pid, int32_t re return ERR_OK; } -int AppMgrServiceInner::VerifyProcessPermission() const +int AppMgrServiceInner::VerifyKillProcessPermission(const std::string &bundleName) const { - auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); - if (isSaCall) { - return ERR_OK; - } - - if (VerifyAPL()) { - return ERR_OK; - } - - auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission( - AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES); - return isCallingPerm ? ERR_OK : ERR_PERMISSION_DENIED; -} - -int AppMgrServiceInner::VerifyProcessPermission(const std::string &bundleName) const -{ - CHECK_CALLER_IS_SYSTEM_APP; - auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); - auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall(); - if (isSaCall || isShellCall) { - return ERR_OK; - } - - if (VerifyAPL()) { - return ERR_OK; + TAG_LOGI(AAFwkTag::APPMGR, "Check Kill permission, callerUid:%{public}d, callerPid:%{public}d", + IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid()); + int32_t ret = VerifyKillProcessPermissionCommon(); + if (ret != ERR_PERMISSION_DENIED) { + return ret; } auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission( @@ -4370,16 +4405,13 @@ int AppMgrServiceInner::VerifyProcessPermission(const std::string &bundleName) c return ERR_OK; } -int AppMgrServiceInner::VerifyProcessPermission(const sptr &token) const +int AppMgrServiceInner::VerifyKillProcessPermission(const sptr &token) const { - CHECK_CALLER_IS_SYSTEM_APP; - auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); - if (isSaCall) { - return ERR_OK; - } - - if (VerifyAPL()) { - return ERR_OK; + TAG_LOGI(AAFwkTag::APPMGR, "Check Kill permission, callerUid:%{public}d, callerPid:%{public}d", + IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid()); + int32_t ret = VerifyKillProcessPermissionCommon(); + if (ret != ERR_PERMISSION_DENIED) { + return ret; } auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission( @@ -4399,6 +4431,29 @@ int AppMgrServiceInner::VerifyProcessPermission(const sptr &token return ERR_OK; } +int32_t AppMgrServiceInner::VerifyKillProcessPermissionCommon() const +{ + CHECK_CALLER_IS_SYSTEM_APP; + auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission( + AAFwk::PermissionConstants::PERMISSION_KILL_APP_PROCESSES); + if (isCallingPerm) { + return ERR_OK; + } + + // VerifyAPL and ohos.permission.CLEAN_BACKGROUND_PROCESSES will be removed on API18 + auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); + auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall(); + if (isSaCall || isShellCall) { + return ERR_OK; + } + + if (VerifyAPL()) { + return ERR_OK; + } + + return ERR_PERMISSION_DENIED; +} + bool AppMgrServiceInner::CheckCallerIsAppGallery() { TAG_LOGD(AAFwkTag::APPMGR, "called"); @@ -4734,6 +4789,24 @@ int AppMgrServiceInner::StartRenderProcessImpl(const std::shared_ptrGetAppRunningRecordByPid(callingPid); + if (!hostRecord) { + TAG_LOGE(AAFwkTag::APPMGR, "hostRecord is nullptr."); + return ERR_INVALID_VALUE; + } + if (!hostRecord->ConstainsRenderPid(renderPid)) { + TAG_LOGE(AAFwkTag::APPMGR, + "Permission denied, caller is not renderPid host, callingPid:%{public}d, renderPid:%{public}d.", + callingPid, renderPid); + return ERR_PERMISSION_DENIED; + } if (remoteClientManager_ == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ is null"); return ERR_INVALID_VALUE; @@ -4754,6 +4827,8 @@ int AppMgrServiceInner::GetRenderProcessTerminationStatus(pid_t renderPid, int & } TAG_LOGD(AAFwkTag::APPMGR, "Get render process termination status success, renderPid:%{public}d, status:%{public}d", renderPid, status); + hostRecord->RemoveRenderPid(renderPid); + return 0; } @@ -4814,7 +4889,7 @@ void AppMgrServiceInner::RegisterFocusListener() TAG_LOGE(AAFwkTag::APPMGR, "no focusListener_"); return; } - WindowManagerLite::GetInstance().RegisterFocusChangedListener(focusListener_); + WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_); #endif // SUPPORT_SCREEN TAG_LOGI(AAFwkTag::APPMGR, "RegisterFocusListener end"); } @@ -4827,7 +4902,7 @@ void AppMgrServiceInner::FreeFocusListener() TAG_LOGE(AAFwkTag::APPMGR, "no focusListener_"); return; } - WindowManagerLite::GetInstance().UnregisterFocusChangedListener(focusListener_); + WindowManager::GetInstance().UnregisterFocusChangedListener(focusListener_); focusListener_ = nullptr; #endif // SUPPORT_SCREEN TAG_LOGI(AAFwkTag::APPMGR, "FreeFocusListener end"); @@ -4916,7 +4991,7 @@ void AppMgrServiceInner::InitWindowVisibilityChangedListener() TAG_LOGE(AAFwkTag::APPMGR, "Window visibility changed listener is nullptr."); return; } - WindowManagerLite::GetInstance().RegisterVisibilityChangedListener(inner->windowVisibilityChangedListener_); + WindowManager::GetInstance().RegisterVisibilityChangedListener(inner->windowVisibilityChangedListener_); }; if (taskHandler_ == nullptr) { @@ -4929,18 +5004,19 @@ void AppMgrServiceInner::InitWindowVisibilityChangedListener() void AppMgrServiceInner::FreeWindowVisibilityChangedListener() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (windowVisibilityChangedListener_ == nullptr) { TAG_LOGW(AAFwkTag::APPMGR, "Visibility listener has been freed."); return; } - WindowManagerLite::GetInstance().UnregisterVisibilityChangedListener(windowVisibilityChangedListener_); + WindowManager::GetInstance().UnregisterVisibilityChangedListener(windowVisibilityChangedListener_); } void AppMgrServiceInner::HandleWindowVisibilityChanged( const std::vector> &windowVisibilityInfos) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (windowVisibilityInfos.empty()) { TAG_LOGW(AAFwkTag::APPMGR, "Window visibility info is empty."); return; @@ -5043,12 +5119,6 @@ int32_t AppMgrServiceInner::NotifyHotReloadPage(const std::string &bundleName, c #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE int32_t AppMgrServiceInner::SetContinuousTaskProcess(int32_t pid, bool isContinuousTask) { - auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); - if (!isSaCall) { - TAG_LOGE(AAFwkTag::APPMGR, "callerToken not SA %{public}s", __func__); - return ERR_INVALID_VALUE; - } - if (!appRunningManager_) { TAG_LOGE(AAFwkTag::APPMGR, "app running manager is nullptr."); return ERR_INVALID_OPERATION; @@ -5057,7 +5127,7 @@ int32_t AppMgrServiceInner::SetContinuousTaskProcess(int32_t pid, bool isContinu auto appRecord = appRunningManager_->GetAppRunningRecordByPid(pid); if (!appRecord) { TAG_LOGE(AAFwkTag::APPMGR, "Get app running record by pid failed. pid: %{public}d", pid); - return false; + return ERR_INVALID_VALUE; } appRecord->SetContinuousTaskAppState(isContinuousTask); DelayedSingleton::GetInstance()->OnProcessStateChanged(appRecord); @@ -5195,11 +5265,11 @@ int32_t AppMgrServiceInner::NotifyAppFault(const FaultData &faultData) #ifdef APP_NO_RESPONSE_DIALOG // A dialog box is displayed when the PC appfreeze - if (appRecord->GetFocusFlag() && (faultData.errorObject.name == AppFreezeType::THREAD_BLOCK_6S || - faultData.errorObject.name == AppFreezeType::APP_INPUT_BLOCK)) { - auto &connection = ModalSystemAppFreezeUIExtension::GetInstance(); - connection.CreateModalUIExtension(std::to_string(pid), bundleName); - } + bool isDialogExist = appRunningManager_ ? + appRunningManager_->CheckAppRunningRecordIsExist(APP_NO_RESPONSE_BUNDLENAME, APP_NO_RESPONSE_ABILITY) : false; + auto killFaultApp = std::bind(&AppMgrServiceInner::KillFaultApp, this, pid, bundleName, faultData); + ModalSystemAppFreezeUIExtension::GetInstance().ProcessAppFreeze(appRecord->GetFocusFlag(), faultData, + std::to_string(pid), bundleName, killFaultApp, isDialogExist); #else KillFaultApp(pid, bundleName, faultData); #endif @@ -5298,14 +5368,35 @@ int32_t AppMgrServiceInner::NotifyAppFaultBySA(const AppFaultDataBySA &faultData } record->NotifyAppFault(transformedFaultData); TAG_LOGW(AAFwkTag::APPMGR, "FaultDataBySA is: name: %{public}s, faultType: %{public}s, uid: %{public}d," - "pid: %{public}d, bundleName: %{public}s", faultData.errorObject.name.c_str(), - FaultTypeToString(faultData.faultType).c_str(), uid, pid, bundleName.c_str()); + "pid: %{public}d, bundleName: %{public}s, eventId: %{public}d", faultData.errorObject.name.c_str(), + FaultTypeToString(faultData.faultType).c_str(), uid, pid, bundleName.c_str(), faultData.eventId); return ERR_OK; } TAG_LOGD(AAFwkTag::APPMGR, "this is not called by SA."); return AAFwk::CHECK_PERMISSION_FAILED; } +bool AppMgrServiceInner::SetAppFreezeFilter(int32_t pid) +{ + int32_t callingPid = IPCSkeleton::GetCallingPid(); + auto callerRecord = GetAppRunningRecordByPid(pid); + if (callerRecord == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "SetAppFreezeFilter callerRecord is nullptr, can not get callerBundleName."); + return false; + } + std::string bundleName = callerRecord->GetBundleName(); + if (callingPid == pid && AppExecFwk::AppfreezeManager::GetInstance()->IsValidFreezeFilter(pid, bundleName)) { + bool cancelResult = AppExecFwk::AppfreezeManager::GetInstance()->CancelAppFreezeDetect(pid, bundleName); + auto resetAppfreezeTask = [pid, bundleName, innerService = shared_from_this()]() { + AppExecFwk::AppfreezeManager::GetInstance()->ResetAppfreezeState(pid, bundleName); + }; + constexpr int32_t waitTime = 120000; // wait 2min + taskHandler_->SubmitTask(resetAppfreezeTask, "resetAppfreezeTask", waitTime); + return cancelResult; + } + return false; +} + FaultData AppMgrServiceInner::ConvertDataTypes(const AppFaultDataBySA &faultData) { FaultData newfaultData; @@ -5321,6 +5412,7 @@ FaultData AppMgrServiceInner::ConvertDataTypes(const AppFaultDataBySA &faultData newfaultData.forceExit = faultData.forceExit; newfaultData.token = faultData.token; newfaultData.state = faultData.state; + newfaultData.eventId = faultData.eventId; return newfaultData; } @@ -5554,7 +5646,7 @@ void AppMgrServiceInner::SetCurrentUserId(const int32_t userId) int32_t AppMgrServiceInner::GetBundleNameByPid(const int32_t pid, std::string &bundleName, int32_t &uid) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) { TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed."); return ERR_PERMISSION_DENIED; @@ -5645,7 +5737,7 @@ int32_t AppMgrServiceInner::ChangeAppGcState(pid_t pid, int32_t state) { auto callerUid = IPCSkeleton::GetCallingUid(); TAG_LOGD(AAFwkTag::APPMGR, "called, pid:%{public}d, state:%{public}d, uid:%{public}d.", pid, state, callerUid); - if (callerUid != ROOT_UID) { // The current UID for resource management is 0 + if (callerUid != RESOURCE_MANAGER_UID) { // The current UID for resource management is 1096 TAG_LOGE(AAFwkTag::APPMGR, "The caller is not a resource manager."); return ERR_INVALID_VALUE; } @@ -5659,7 +5751,7 @@ int32_t AppMgrServiceInner::ChangeAppGcState(pid_t pid, int32_t state) int32_t AppMgrServiceInner::RegisterAppDebugListener(const sptr &listener) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) { TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed."); return ERR_PERMISSION_DENIED; @@ -5674,7 +5766,7 @@ int32_t AppMgrServiceInner::RegisterAppDebugListener(const sptr &listener) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) { TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed."); return ERR_PERMISSION_DENIED; @@ -5689,7 +5781,7 @@ int32_t AppMgrServiceInner::UnregisterAppDebugListener(const sptrIsSACall() && !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) { TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed."); @@ -5746,6 +5838,11 @@ int32_t AppMgrServiceInner::SetAppWaitingDebug(const std::string &bundleName, bo { TAG_LOGD(AAFwkTag::APPMGR, "Called, bundle name is %{public}s, persist flag is %{public}d.", bundleName.c_str(), isPersist); + if (!AAFwk::PermissionVerification::GetInstance()->IsShellCall()) { + TAG_LOGE(AAFwkTag::APPMGR, "Not shell call."); + return ERR_PERMISSION_DENIED; + } + if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) { TAG_LOGE(AAFwkTag::APPMGR, "Developer mode is false."); return AAFwk::ERR_NOT_DEVELOPER_MODE; @@ -5783,7 +5880,12 @@ int32_t AppMgrServiceInner::SetAppWaitingDebug(const std::string &bundleName, bo int32_t AppMgrServiceInner::CancelAppWaitingDebug() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); + if (!AAFwk::PermissionVerification::GetInstance()->IsShellCall()) { + TAG_LOGE(AAFwkTag::APPMGR, "Not shell call."); + return ERR_PERMISSION_DENIED; + } + if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) { TAG_LOGE(AAFwkTag::APPMGR, "Developer mode is false."); return AAFwk::ERR_NOT_DEVELOPER_MODE; @@ -5798,7 +5900,12 @@ int32_t AppMgrServiceInner::CancelAppWaitingDebug() int32_t AppMgrServiceInner::GetWaitingDebugApp(std::vector &debugInfoList) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); + if (!AAFwk::PermissionVerification::GetInstance()->IsShellCall()) { + TAG_LOGE(AAFwkTag::APPMGR, "Not shell call."); + return ERR_PERMISSION_DENIED; + } + if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) { TAG_LOGE(AAFwkTag::APPMGR, "Developer mode is false."); return AAFwk::ERR_NOT_DEVELOPER_MODE; @@ -5823,7 +5930,7 @@ int32_t AppMgrServiceInner::GetWaitingDebugApp(std::vector &debugIn void AppMgrServiceInner::InitAppWaitingDebugList() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); { std::lock_guard lock(waitingDebugLock_); if (isInitAppWaitingDebugListExecuted_) { @@ -5845,7 +5952,7 @@ void AppMgrServiceInner::InitAppWaitingDebugList() bool AppMgrServiceInner::IsWaitingDebugApp(const std::string &bundleName) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) { TAG_LOGE(AAFwkTag::APPMGR, "Not foundation call."); @@ -5856,7 +5963,7 @@ bool AppMgrServiceInner::IsWaitingDebugApp(const std::string &bundleName) std::lock_guard lock(waitingDebugLock_); if (waitingDebugBundleList_.empty()) { - TAG_LOGD(AAFwkTag::APPMGR, "The waiting debug bundle list is empty."); + TAG_LOGD(AAFwkTag::APPMGR, "The waiting debug bundles list is empty."); return false; } @@ -5870,7 +5977,7 @@ bool AppMgrServiceInner::IsWaitingDebugApp(const std::string &bundleName) void AppMgrServiceInner::ClearNonPersistWaitingDebugFlag() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) { TAG_LOGE(AAFwkTag::APPMGR, "Not foundation call."); @@ -5950,7 +6057,7 @@ int32_t AppMgrServiceInner::NotifyAbilitysAssertDebugChange( bool AppMgrServiceInner::IsAttachDebug(const std::string &bundleName) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); if (!isSaCall) { TAG_LOGE(AAFwkTag::APPMGR, "Caller token is not SA."); @@ -6003,7 +6110,11 @@ void AppMgrServiceInner::ClearAppRunningDataForKeepAlive(const std::shared_ptrIsKeepAliveApp()) { - if (appRecord->GetBundleName() != BUNDLE_NAME_SAMPLE_MANAGEMENT && + if (ExitResidentProcessManager::GetInstance().IsKilledForUpgradeWeb(appRecord->GetBundleName())) { + TAG_LOGI(AAFwkTag::APPMGR, "Is killed for upgrade web"); + return; + } + if (!AAFwk::AppUtils::GetInstance().IsAllowResidentInExtremeMemory(appRecord->GetBundleName()) && ExitResidentProcessManager::GetInstance().RecordExitResidentBundleName(appRecord->GetBundleName())) { TAG_LOGI(AAFwkTag::APPMGR, "memory size is insufficent, record exit resident process info"); return; @@ -6103,14 +6214,14 @@ int32_t AppMgrServiceInner::UnregisterAppRunningStatusListener(const sptrUnregisterListener(appRunningStatusListener); } -int32_t AppMgrServiceInner::StartChildProcess(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid, - int32_t childProcessCount, bool isStartWithDebug) +int32_t AppMgrServiceInner::StartChildProcess(const pid_t hostPid, pid_t &childPid, const ChildProcessRequest &request) { TAG_LOGI(AAFwkTag::APPMGR, "StarChildProcess, hostPid:%{public}d", hostPid); auto errCode = StartChildProcessPreCheck(hostPid); if (errCode != ERR_OK) { return errCode; } + auto &srcEntry = request.srcEntry; if (hostPid <= 0 || srcEntry.empty()) { TAG_LOGE(AAFwkTag::APPMGR, "Invalid param: hostPid:%{public}d srcEntry:%{private}s", hostPid, srcEntry.c_str()); return ERR_INVALID_VALUE; @@ -6120,9 +6231,17 @@ int32_t AppMgrServiceInner::StartChildProcess(const pid_t hostPid, const std::st return ERR_NO_INIT; } auto appRecord = GetAppRunningRecordByPid(hostPid); - auto childProcessRecord = ChildProcessRecord::CreateChildProcessRecord(hostPid, srcEntry, appRecord, - childProcessCount, isStartWithDebug); - return StartChildProcessImpl(childProcessRecord, appRecord, childPid); + auto childProcessRecord = ChildProcessRecord::CreateChildProcessRecord(hostPid, request, appRecord); + if (!childProcessRecord) { + TAG_LOGE(AAFwkTag::APPMGR, "CreateChildProcessRecord failed, childProcessRecord is nullptr"); + return ERR_NULL_OBJECT; + } + auto &args = request.args; + childProcessRecord->SetEntryParams(args.entryParams); + TAG_LOGI(AAFwkTag::APPMGR, "StartChildProcess, srcEntry:%{private}s, args.entryParams:%{public}s," + " args.fds size:%{public}zu, options.isolationMode:%{public}d", request.srcEntry.c_str(), + args.entryParams.c_str(), args.fds.size(), request.options.isolationMode); + return StartChildProcessImpl(childProcessRecord, appRecord, childPid, args); } int32_t AppMgrServiceInner::StartChildProcessPreCheck(const pid_t callingPid) @@ -6140,9 +6259,9 @@ int32_t AppMgrServiceInner::StartChildProcessPreCheck(const pid_t callingPid) } int32_t AppMgrServiceInner::StartChildProcessImpl(const std::shared_ptr childProcessRecord, - const std::shared_ptr appRecord, pid_t &childPid) + const std::shared_ptr appRecord, pid_t &childPid, const ChildProcessArgs &args) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!appRecord) { TAG_LOGE(AAFwkTag::APPMGR, "No such appRecord, childPid:%{public}d.", childPid); return ERR_NAME_NOT_FOUND; @@ -6156,9 +6275,14 @@ int32_t AppMgrServiceInner::StartChildProcessImpl(const std::shared_ptrGetStartMsg(); startMsg.procName = childProcessRecord->GetProcessName(); + startMsg.childProcessType = childProcessRecord->GetChildProcessType(); + startMsg.fds = args.fds; pid_t pid = 0; { std::lock_guard lock(startChildProcessLock_); @@ -6180,7 +6304,7 @@ int32_t AppMgrServiceInner::StartChildProcessImpl(const std::shared_ptr childProcessRecord, const std::shared_ptr appRecord, ChildProcessInfo &info) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!childProcessRecord) { TAG_LOGE(AAFwkTag::APPMGR, "No such child process record."); return ERR_NAME_NOT_FOUND; @@ -6220,10 +6344,11 @@ int32_t AppMgrServiceInner::GetChildProcessInfo(const std::shared_ptrGetPid(); info.hostPid = childProcessRecord->GetHostPid(); info.uid = childProcessRecord->GetUid(); - info.processType = childProcessRecord->GetProcessType(); + info.childProcessType = childProcessRecord->GetChildProcessType(); info.bundleName = appRecord->GetBundleName(); info.processName = childProcessRecord->GetProcessName(); info.srcEntry = childProcessRecord->GetSrcEntry(); + info.entryParams = childProcessRecord->GetEntryParams(); info.jitEnabled = appRecord->IsJITEnabled(); info.isStartWithDebug = childProcessRecord->isStartWithDebug(); auto applicationInfo = appRecord->GetApplicationInfo(); @@ -6269,7 +6394,7 @@ void AppMgrServiceInner::AttachChildProcess(const pid_t pid, const sptrSetDeathRecipient(appDeathRecipient); childRecord->RegisterDeathRecipient(); - if (childRecord->GetProcessType() != CHILD_PROCESS_TYPE_NATIVE) { + if (childRecord->GetChildProcessType() != CHILD_PROCESS_TYPE_NATIVE) { childScheduler->ScheduleLoadJs(); } else { childScheduler->ScheduleRunNativeProc(childRecord->GetMainProcessCallback()); @@ -6376,7 +6501,7 @@ void AppMgrServiceInner::KillAttachedChildProcess(const std::shared_ptr& pids, std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + 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)); @@ -6603,7 +6728,7 @@ int32_t AppMgrServiceInner::UnregisterRenderStateObserver(const sptrGetAppRunningRecordMap()) { - const auto &appRecord = item.second; - if (appRecord != nullptr && appRecord->GetBundleName() == bundleName) { - TAG_LOGD(AAFwkTag::APPMGR, "%{public}s update state: %{public}d", - bundleName.c_str(), static_cast(enable)); - appRecord->SetKeepAliveEnableState(enable); - } - } -} - bool AppMgrServiceInner::IsMemorySizeSufficent() { return ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent(); @@ -6810,19 +6912,43 @@ void AppMgrServiceInner::NotifyStartResidentProcess(std::vectorGetAppRunningRecordMap()) { + const auto &appRecord = item.second; + if (appRecord != nullptr && appRecord->GetBundleName() == bundleName) { + TAG_LOGD(AAFwkTag::APPMGR, "%{public}s update state: %{public}d", + bundleName.c_str(), static_cast(enable)); + appRecord->SetKeepAliveEnableState(enable); + } + } +} + int32_t AppMgrServiceInner::SetSupportedProcessCacheSelf(bool isSupport) { - TAG_LOGI(AAFwkTag::APPMGR, "Called."); + TAG_LOGI(AAFwkTag::APPMGR, "called"); HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); if (!appRunningManager_) { TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr"); return ERR_NO_INIT; } - auto result = CheckSetProcessCachePermission(); - if (result != ERR_OK) { - TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed."); - return result; - } auto callerPid = IPCSkeleton::GetCallingPid(); auto appRecord = GetAppRunningRecordByPid(callerPid); @@ -6830,21 +6956,61 @@ int32_t AppMgrServiceInner::SetSupportedProcessCacheSelf(bool isSupport) TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord, callerPid:%{public}d", callerPid); return ERR_INVALID_VALUE; } - if (!appRecord->SetSupportedProcessCache(isSupport)) { - TAG_LOGE(AAFwkTag::APPMGR, "SetSupportedProcessCache more than once"); - return AAFwk::ERR_SET_SUPPORTED_PROCESS_CACHE_AGAIN; + + if (!DelayedSingleton::GetInstance()->QueryEnableProcessCache()) { + TAG_LOGE(AAFwkTag::APPMGR, "process cache feature is disabled."); + return AAFwk::ERR_CAPABILITY_NOT_SUPPORT; } + appRecord->SetSupportedProcessCache(isSupport); return ERR_OK; } -int32_t AppMgrServiceInner::CheckSetProcessCachePermission() const +bool AppMgrServiceInner::IsAppProcessesAllCached(const std::string &bundleName, int32_t uid, + const std::set> &cachedSet) { - TAG_LOGI(AAFwkTag::APPMGR, "Called."); - HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); - CHECK_CALLER_IS_SYSTEM_APP; - auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifySetProcessCachePermission(); - TAG_LOGI(AAFwkTag::APPMGR, "ProcessCache permission: %{public}d", isCallingPerm); - return isCallingPerm ? ERR_OK : AAFwk::CHECK_PERMISSION_FAILED; + if (!appRunningManager_) { + TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr"); + return false; + } + return appRunningManager_->IsAppProcessesAllCached(bundleName, uid, cachedSet); +} + +int32_t AppMgrServiceInner::CheckCallingIsUserTestModeInner(const pid_t pid, bool &isUserTest) +{ + if (!IsSceneBoardCall()) { + TAG_LOGE(AAFwkTag::APPMGR, "this is not called by SceneBoard."); + return AAFwk::CHECK_PERMISSION_FAILED; + } + if (pid <= 0) { + TAG_LOGE(AAFwkTag::APPMGR, "hht-invalid pid:%{public}d", pid); + return ERR_INVALID_VALUE; + } + auto appRecord = GetAppRunningRecordByPid(pid); + if (!appRecord) { + TAG_LOGE(AAFwkTag::APPMGR, "hht-no such appRecord"); + return ERR_INVALID_VALUE; + } + if (appRecord->GetUserTestInfo() == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "hht-no such user test info."); + return ERR_INVALID_VALUE; + } + isUserTest = true; + return ERR_OK; +} + +bool AppMgrServiceInner::IsSceneBoardCall() { + if (remoteClientManager_ == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "The remoteClientManager_ is nullptr."); + return false; + } + auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper(); + if (bundleMgrHelper != nullptr) { + int32_t callingUid = IPCSkeleton::GetCallingUid(); + std::string callerBundleName; + IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callingUid, callerBundleName)); + return callerBundleName == SCENE_BOARD_BUNDLE_NAME; + } + return false; } void AppMgrServiceInner::OnAppCacheStateChanged(const std::shared_ptr &appRecord, @@ -6895,7 +7061,7 @@ int32_t AppMgrServiceInner::StartNativeChildProcess(const pid_t hostPid, const s auto childRecordMap = appRecord->GetChildProcessRecordMap(); auto itNativeChildInfo = find_if(childRecordMap.begin(), childRecordMap.end(), [] (const auto &pair) -> bool { - return pair.second->GetProcessType() == CHILD_PROCESS_TYPE_NATIVE; + return pair.second->GetChildProcessType() == CHILD_PROCESS_TYPE_NATIVE; }); if (itNativeChildInfo != childRecordMap.end()) { @@ -6907,26 +7073,19 @@ int32_t AppMgrServiceInner::StartNativeChildProcess(const pid_t hostPid, const s pid_t dummyChildPid = 0; auto nativeChildRecord = ChildProcessRecord::CreateNativeChildProcessRecord( hostPid, libName, appRecord, callback, childProcessCount, false); - return StartChildProcessImpl(nativeChildRecord, appRecord, dummyChildPid); -} - -bool AppMgrServiceInner::IsAppProcessesAllCached(const std::string &bundleName, int32_t uid, - const std::set> &cachedSet) -{ - if (!appRunningManager_) { - TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr"); - return false; - } - return appRunningManager_->IsAppProcessesAllCached(bundleName, uid, cachedSet); + ChildProcessArgs args; + return StartChildProcessImpl(nativeChildRecord, appRecord, dummyChildPid, args); } void AppMgrServiceInner::CacheLoabAbilityTask(const LoabAbilityTaskFunc& func) { + std::lock_guard lock(loadTaskListMutex_); loadAbilityTaskFuncList_.emplace_back(func); } void AppMgrServiceInner::SubmitCacheLoabAbilityTask() { + std::lock_guard lock(loadTaskListMutex_); std::weak_ptr taskHandler = taskHandler_; for_each(loadAbilityTaskFuncList_.begin(), loadAbilityTaskFuncList_.end(), [taskHandler](LoabAbilityTaskFunc loadAbilityFunc) { @@ -6948,44 +7107,6 @@ void AppMgrServiceInner::SetSceneBoardAttachFlag(bool flag) sceneBoardAttachFlag_ = flag; } -int32_t AppMgrServiceInner::CheckCallingIsUserTestModeInner(const pid_t pid, bool &isUserTest) -{ - if (!IsSceneBoardCall()) { - TAG_LOGE(AAFwkTag::APPMGR, "this is not called by SceneBoard."); - return AAFwk::CHECK_PERMISSION_FAILED; - } - if (pid <= 0) { - TAG_LOGE(AAFwkTag::APPMGR, "hht-invalid pid:%{public}d", pid); - return ERR_INVALID_VALUE; - } - auto appRecord = GetAppRunningRecordByPid(pid); - if (!appRecord) { - TAG_LOGE(AAFwkTag::APPMGR, "hht-no such appRecord"); - return ERR_INVALID_VALUE; - } - if (appRecord->GetUserTestInfo() == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "hht-no such user test info."); - return ERR_INVALID_VALUE; - } - isUserTest = true; - return ERR_OK; -} - -bool AppMgrServiceInner::IsSceneBoardCall() { - if (remoteClientManager_ == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "The remoteClientManager_ is nullptr."); - return false; - } - auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper(); - if (bundleMgrHelper != nullptr) { - int32_t callingUid = IPCSkeleton::GetCallingUid(); - std::string callerBundleName; - IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callingUid, callerBundleName)); - return callerBundleName == SCENE_BOARD_BUNDLE_NAME; - } - return false; -} - void AppMgrServiceInner::AttachedToStatusBar(const sptr &token) { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); @@ -6996,5 +7117,81 @@ void AppMgrServiceInner::AttachedToStatusBar(const sptr &token) } appRecord->SetAttachedToStatusBar(true); } + +int32_t AppMgrServiceInner::NotifyProcessDependedOnWeb() +{ + int32_t pid = IPCSkeleton::GetCallingPid(); + auto appRecord = GetAppRunningRecordByPid(pid); + if (appRecord == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord"); + return ERR_INVALID_VALUE; + } + TAG_LOGD(AAFwkTag::APPMGR, "call"); + appRecord->SetIsDependedOnArkWeb(true); + return ERR_OK; +} + +void AppMgrServiceInner::KillProcessDependedOnWeb() +{ + TAG_LOGD(AAFwkTag::APPMGR, "call"); + CHECK_POINTER_AND_RETURN_LOG(appRunningManager_, "appRunningManager_ is nullptr"); + for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) { + const auto &appRecord = item.second; + if (!appRecord || !appRecord->GetSpawned() || + !appRecord->GetPriorityObject() || !appRecord->IsDependedOnArkWeb()) { + continue; + } + + std::string bundleName = appRecord->GetBundleName(); + pid_t pid = appRecord->GetPriorityObject()->GetPid(); + if (appRecord->IsKeepAliveApp()) { + ExitResidentProcessManager::GetInstance().RecordExitResidentBundleDependedOnWeb(bundleName); + } + KillProcessByPid(pid, "KillProcessDependedOnWeb"); + } +} + +void AppMgrServiceInner::RestartResidentProcessDependedOnWeb() +{ + TAG_LOGD(AAFwkTag::APPMGR, "call"); + std::vector bundleNames; + ExitResidentProcessManager::GetInstance().HandleExitResidentBundleDependedOnWeb(bundleNames); + if (bundleNames.empty()) { + TAG_LOGE(AAFwkTag::APPMGR, "exit resident bundle names is empty"); + return; + } + + auto RestartResidentProcessDependedOnWebTask = [bundleNames, innerServicerWeak = weak_from_this()]() { + auto innerServicer = innerServicerWeak.lock(); + CHECK_POINTER_AND_RETURN_LOG(innerServicer, "get AppMgrServiceInner failed"); + std::vector exitBundleInfos; + ExitResidentProcessManager::GetInstance().QueryExitBundleInfos(bundleNames, exitBundleInfos); + + innerServicer->NotifyStartResidentProcess(exitBundleInfos); + }; + taskHandler_->SubmitTask(RestartResidentProcessDependedOnWebTask, "RestartResidentProcessDependedOnWeb"); +} + +void AppMgrServiceInner::BlockProcessCacheByPids(const std::vector& pids) +{ + for (const auto& pid : pids) { + auto appRecord = GetAppRunningRecordByPid(pid); + if (appRecord == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "appRecord is nullptr.."); + continue; + } + appRecord->SetProcessCacheBlocked(true); + } +} + +bool AppMgrServiceInner::IsKilledForUpgradeWeb(const std::string &bundleName) const +{ + auto callerUid = IPCSkeleton::GetCallingUid(); + if (callerUid != FOUNDATION_UID) { + TAG_LOGE(AAFwkTag::APPMGR, "Not foundation call."); + return false; + } + return ExitResidentProcessManager::GetInstance().IsKilledForUpgradeWeb(bundleName); +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/appmgr/src/app_process_manager.cpp b/services/appmgr/src/app_process_manager.cpp index 58cacc6bfc..13f7b4d896 100644 --- a/services/appmgr/src/app_process_manager.cpp +++ b/services/appmgr/src/app_process_manager.cpp @@ -16,7 +16,6 @@ #include "app_process_manager.h" #include -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/services/appmgr/src/app_running_manager.cpp b/services/appmgr/src/app_running_manager.cpp index b11ee0a2bc..a41de40dd5 100644 --- a/services/appmgr/src/app_running_manager.cpp +++ b/services/appmgr/src/app_running_manager.cpp @@ -39,7 +39,6 @@ #include "res_sched_util.h" #include "ui_extension_utils.h" - namespace OHOS { namespace AppExecFwk { namespace { @@ -50,6 +49,7 @@ namespace { using EventFwk::CommonEventSupport; AppRunningManager::AppRunningManager() + : configuration_(std::make_shared()) {} AppRunningManager::~AppRunningManager() {} @@ -85,8 +85,14 @@ std::shared_ptr AppRunningManager::CreateAppRunningRecord( appRecord->SetSingleton(bundleInfo.singleton); appRecord->SetSignCode(signCode); appRecord->SetJointUserId(bundleInfo.jointUserId); - std::lock_guard guard(runningRecordMapMutex_); - appRunningRecordMap_.emplace(recordId, appRecord); + { + std::lock_guard guard(runningRecordMapMutex_); + appRunningRecordMap_.emplace(recordId, appRecord); + } + { + std::lock_guard guard(updateConfigurationDelayedLock_); + updateConfigurationDelayedMap_.emplace(recordId, false); + } return appRecord; } @@ -144,6 +150,33 @@ std::shared_ptr AppRunningManager::CheckAppRunningRecordIsExis return nullptr; } +#ifdef APP_NO_RESPONSE_DIALOG +bool AppRunningManager::CheckAppRunningRecordIsExist(const std::string &bundleName, const std::string &ablityName) +{ + std::lock_guard guard(runningRecordMapMutex_); + if (appRunningRecordMap_.empty()) { + return false; + } + for (const auto &item : appRunningRecordMap_) { + const auto &appRecord = item.second; + if (!appRecord) { + continue; + } + if (appRecord->GetBundleName() != bundleName) { + continue; + } + const auto &abilityRunningRecordMap = appRecord->GetAbilities(); + for (const auto &abilityItem : abilityRunningRecordMap) { + const auto &abilityRunning = abilityItem.second; + if (abilityRunning && abilityRunning->GetName() == ablityName) { + return true; + } + } + } + return false; +} +#endif + bool AppRunningManager::CheckAppRunningRecordIsExistByBundleName(const std::string &bundleName) { std::lock_guard guard(runningRecordMapMutex_); @@ -159,6 +192,21 @@ bool AppRunningManager::CheckAppRunningRecordIsExistByBundleName(const std::stri return false; } +bool AppRunningManager::CheckAppRunningRecordIsExistByUid(int32_t uid) +{ + std::lock_guard guard(runningRecordMapMutex_); + if (appRunningRecordMap_.empty()) { + return false; + } + for (const auto &item : appRunningRecordMap_) { + const auto &appRecord = item.second; + if (appRecord && appRecord->GetUid() == uid && !(appRecord->GetRestartAppFlag())) { + return true; + } + } + return false; +} + int32_t AppRunningManager::CheckAppCloneRunningRecordIsExistByBundleName(const std::string &bundleName, int32_t appCloneIndex, bool &isRunning) { @@ -200,8 +248,8 @@ std::shared_ptr AppRunningManager::GetAppRunningRecordByPid(co std::shared_ptr AppRunningManager::GetAppRunningRecordByAbilityToken( const sptr &abilityToken) { - HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard guard(runningRecordMapMutex_); + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (appRecord && appRecord->GetAbilityRunningRecordByToken(abilityToken)) { @@ -311,6 +359,32 @@ bool AppRunningManager::ProcessExitByBundleNameAndUid( return (pids.empty() ? false : true); } +bool AppRunningManager::GetPidsByBundleNameUserIdAndAppIndex(const std::string &bundleName, + const int userId, const int appIndex, std::list &pids) +{ + auto appRunningMap = GetAppRunningRecordMap(); + for (const auto &item : appRunningMap) { + const auto &appRecord = item.second; + if (appRecord == nullptr) { + continue; + } + auto appInfoList = appRecord->GetAppInfoList(); + auto isExist = [&bundleName, &userId, &appIndex](const std::shared_ptr &appInfo) { + return appInfo->bundleName == bundleName && appInfo->uid / BASE_USER_RANGE == userId && + appInfo->appIndex == appIndex; + }; + auto iter = std::find_if(appInfoList.begin(), appInfoList.end(), isExist); + pid_t pid = appRecord->GetPriorityObject()->GetPid(); + if (iter == appInfoList.end() || pid <= 0) { + continue; + } + pids.push_back(pid); + appRecord->SetKilling(); + } + + return (!pids.empty()); +} + bool AppRunningManager::ProcessExitByPid(pid_t pid) { auto appRecord = GetAppRunningRecordByPid(pid); @@ -354,6 +428,10 @@ std::shared_ptr AppRunningManager::OnRemoteDied(const wptrGetRecordId()); + } appRecord->RemoveAppDeathRecipient(); appRecord->SetApplicationClient(nullptr); TAG_LOGI(AAFwkTag::APPMGR, "processName: %{public}s.", appRecord->GetProcessName().c_str()); @@ -389,6 +467,10 @@ void AppRunningManager::RemoveAppRunningRecordById(const int32_t recordId) appRunningRecordMap_.erase(it); } } + { + std::lock_guard guard(updateConfigurationDelayedLock_); + updateConfigurationDelayedMap_.erase(recordId); + } if (appRecord != nullptr && appRecord->GetPriorityObject() != nullptr) { RemoveUIExtensionLauncherItem(appRecord->GetPriorityObject()->GetPid()); @@ -488,7 +570,7 @@ void AppRunningManager::HandleAbilityAttachTimeOut(const sptr &to appRecord->PostTask("DELAY_KILL_ABILITY", AMSEventHandler::KILL_PROCESS_TIMEOUT, timeoutTask); } -void AppRunningManager::PrepareTerminate(const sptr &token) +void AppRunningManager::PrepareTerminate(const sptr &token, bool clearMissionFlag) { if (token == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "token is nullptr."); @@ -506,10 +588,12 @@ void AppRunningManager::PrepareTerminate(const sptr &token) abilityRecord->SetTerminating(); } - if (appRecord->IsLastAbilityRecord(token) && (!appRecord->IsKeepAliveApp() || + // set app record terminating when close last page ability + auto isLastAbility = + clearMissionFlag ? appRecord->IsLastPageAbilityRecord(token) : appRecord->IsLastAbilityRecord(token); + if (isLastAbility && (!appRecord->IsKeepAliveApp() || !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent())) { auto cacheProcMgr = DelayedSingleton::GetInstance(); - cacheProcMgr->UpdateTypeByAbility(abilityRecord, appRecord); if (cacheProcMgr != nullptr && cacheProcMgr->IsAppShouldCache(appRecord)) { cacheProcMgr->PenddingCacheProcess(appRecord); TAG_LOGI(AAFwkTag::APPMGR, "App %{public}s supports process cache, not terminate record.", @@ -572,7 +656,6 @@ void AppRunningManager::TerminateAbility(const sptr &token, bool if (isLastAbility && (!appRecord->IsKeepAliveApp() || !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent()) && !isLauncherApp) { auto cacheProcMgr = DelayedSingleton::GetInstance(); - cacheProcMgr->UpdateTypeByToken(token, appRecord); if (cacheProcMgr != nullptr && cacheProcMgr->IsAppShouldCache(appRecord)) { TAG_LOGI(AAFwkTag::APPMGR, "App %{public}s is cached, not terminate app.", appRecord->GetBundleName().c_str()); @@ -581,7 +664,7 @@ void AppRunningManager::TerminateAbility(const sptr &token, bool TAG_LOGD(AAFwkTag::APPMGR, "The ability is the last in the app:%{public}s.", appRecord->GetName().c_str()); appRecord->SetTerminating(); if (clearMissionFlag && appMgrServiceInner != nullptr) { - auto delayTime = appRecord->ExtensionAbilityRecordExists(token) ? + auto delayTime = appRecord->ExtensionAbilityRecordExists() ? AMSEventHandler::DELAY_KILL_EXTENSION_PROCESS_TIMEOUT : AMSEventHandler::DELAY_KILL_PROCESS_TIMEOUT; appRecord->PostTask("DELAY_KILL_PROCESS", delayTime, killProcess); } @@ -726,6 +809,12 @@ void AppRunningManager::HandleStartSpecifiedAbilityTimeOut(const int64_t eventId int32_t AppRunningManager::UpdateConfiguration(const Configuration &config) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + std::vector changeKeyV; + configuration_->CompareDifferent(changeKeyV, config); + if (!changeKeyV.empty()) { + configuration_->Merge(changeKeyV, config); + } + auto appRunningMap = GetAppRunningRecordMap(); TAG_LOGD(AAFwkTag::APPMGR, "current app size %{public}zu", appRunningMap.size()); int32_t result = ERR_OK; @@ -737,7 +826,13 @@ int32_t AppRunningManager::UpdateConfiguration(const Configuration &config) } if (appRecord && !isCollaboratorReserveType(appRecord)) { TAG_LOGD(AAFwkTag::APPMGR, "Notification app [%{public}s]", appRecord->GetName().c_str()); - result = appRecord->UpdateConfiguration(config); + std::lock_guard guard(updateConfigurationDelayedLock_); + if (appRecord->GetState() != ApplicationState::APP_STATE_BACKGROUND) { + updateConfigurationDelayedMap_[appRecord->GetRecordId()] = false; + result = appRecord->UpdateConfiguration(config); + } else { + updateConfigurationDelayedMap_[appRecord->GetRecordId()] = true; + } } } return result; @@ -1094,7 +1189,7 @@ bool AppRunningManager::IsApplicationBackground(const std::string &bundleName) void AppRunningManager::OnWindowVisibilityChanged( const std::vector> &windowVisibilityInfos) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::set pids; for (const auto &info : windowVisibilityInfos) { if (info == nullptr) { @@ -1146,7 +1241,7 @@ bool AppRunningManager::IsApplicationUnfocused(const std::string &bundleName) void AppRunningManager::SetAttachAppDebug(const std::string &bundleName, const bool &isAttachDebug) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto appRunningMap = GetAppRunningRecordMap(); for (const auto &item : appRunningMap) { const auto &appRecord = item.second; @@ -1163,7 +1258,7 @@ void AppRunningManager::SetAttachAppDebug(const std::string &bundleName, const b std::vector AppRunningManager::GetAppDebugInfosByBundleName( const std::string &bundleName, const bool &isDetachDebug) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::lock_guard guard(runningRecordMapMutex_); std::vector debugInfos; for (const auto &item : appRunningRecordMap_) { @@ -1189,7 +1284,7 @@ std::vector AppRunningManager::GetAppDebugInfosByBundleName( void AppRunningManager::GetAbilityTokensByBundleName( const std::string &bundleName, std::vector> &abilityTokens) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; @@ -1263,7 +1358,7 @@ std::shared_ptr AppRunningManager::OnChildProcessRemoteDied( int32_t AppRunningManager::SignRestartAppFlag(const std::string &bundleName) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::lock_guard guard(runningRecordMapMutex_); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; @@ -1280,7 +1375,7 @@ int32_t AppRunningManager::SignRestartAppFlag(const std::string &bundleName) int32_t AppRunningManager::GetAppRunningUniqueIdByPid(pid_t pid, std::string &appRunningUniqueId) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto appRecord = GetAppRunningRecordByPid(pid); if (appRecord == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "appRecord is nullptr."); @@ -1293,6 +1388,7 @@ int32_t AppRunningManager::GetAppRunningUniqueIdByPid(pid_t pid, std::string &ap int32_t AppRunningManager::GetAllUIExtensionRootHostPid(pid_t pid, std::vector &hostPids) { + TAG_LOGD(AAFwkTag::APPMGR, "called"); std::lock_guard guard(uiExtensionMapLock_); for (auto &item: uiExtensionLauncherMap_) { auto temp = item.second.second; @@ -1300,7 +1396,12 @@ int32_t AppRunningManager::GetAllUIExtensionRootHostPid(pid_t pid, std::vector

& pids, std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); int errCode = DumpErrorCode::ERR_OK; size_t count = 0; for (const auto& pid : pids) { @@ -1503,5 +1604,17 @@ bool AppRunningManager::IsAppProcessesAllCached(const std::string &bundleName, i } return true; } + +int32_t AppRunningManager::UpdateConfigurationDelayed(const std::shared_ptr &appRecord) +{ + std::lock_guard guard(updateConfigurationDelayedLock_); + int32_t result = ERR_OK; + auto it = updateConfigurationDelayedMap_.find(appRecord->GetRecordId()); + if (it != updateConfigurationDelayedMap_.end()) { + result = appRecord->UpdateConfiguration(*configuration_); + it->second = false; + } + return result; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_running_record.cpp b/services/appmgr/src/app_running_record.cpp index 723744509f..a5ca86a294 100644 --- a/services/appmgr/src/app_running_record.cpp +++ b/services/appmgr/src/app_running_record.cpp @@ -453,6 +453,7 @@ void AppRunningRecord::LaunchApplication(const Configuration &config) launchData.SetAppIndex(appIndex_); launchData.SetDebugApp(isDebugApp_); launchData.SetPerfCmd(perfCmd_); + launchData.SetErrorInfoEnhance(isErrorInfoEnhance_); launchData.SetMultiThread(isMultiThread_); launchData.SetJITEnabled(jitEnabled_); launchData.SetNativeStart(isNativeStart_); @@ -658,6 +659,8 @@ void AppRunningRecord::ScheduleBackgroundRunning() void AppRunningRecord::ScheduleProcessSecurityExit() { if (appLifeCycleDeal_) { + auto appRecord = shared_from_this(); + DelayedSingleton::GetInstance()->PrepareActivateCache(appRecord); appLifeCycleDeal_->ScheduleProcessSecurityExit(); } } @@ -784,25 +787,27 @@ std::shared_ptr AppRunningRecord::GetModuleRecordByModuleNa return nullptr; } -void AppRunningRecord::StateChangedNotifyObserver( - const std::shared_ptr &ability, - const int32_t state, - bool isAbility, - bool isFromWindowFocusChanged) +void AppRunningRecord::StateChangedNotifyObserver(const std::shared_ptr &ability, + int32_t state, bool isAbility, bool isFromWindowFocusChanged) { - if (!ability || ability->GetAbilityInfo() == nullptr) { + if (ability == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "ability is null"); return; } + auto abilityInfo = ability->GetAbilityInfo(); + if (abilityInfo == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo is nullptr"); + return; + } AbilityStateData abilityStateData; - abilityStateData.bundleName = ability->GetAbilityInfo()->applicationInfo.bundleName; - abilityStateData.moduleName = ability->GetAbilityInfo()->moduleName; + abilityStateData.bundleName = abilityInfo->applicationInfo.bundleName; + abilityStateData.moduleName = abilityInfo->moduleName; abilityStateData.abilityName = ability->GetName(); abilityStateData.pid = GetPriorityObject()->GetPid(); abilityStateData.abilityState = state; - abilityStateData.uid = ability->GetAbilityInfo()->applicationInfo.uid; + abilityStateData.uid = abilityInfo->applicationInfo.uid; abilityStateData.token = ability->GetToken(); - abilityStateData.abilityType = static_cast(ability->GetAbilityInfo()->type); + abilityStateData.abilityType = static_cast(abilityInfo->type); abilityStateData.isFocused = ability->GetFocusFlag(); abilityStateData.abilityRecordId = ability->GetAbilityRecordId(); auto applicationInfo = GetApplicationInfo(); @@ -817,9 +822,11 @@ void AppRunningRecord::StateChangedNotifyObserver( if (applicationInfo && applicationInfo->bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE) { abilityStateData.isAtomicService = true; } - - if (isAbility && ability->GetAbilityInfo()->type == AbilityType::EXTENSION) { - TAG_LOGD(AAFwkTag::APPMGR, "extension type, not notify any more."); + TAG_LOGI(AAFwkTag::APPMGR, "The ability(bundle:%{public}s, ability:%{public}s) state will change.", + abilityStateData.bundleName.c_str(), abilityStateData.abilityName.c_str()); + if (isAbility && abilityInfo->type == AbilityType::EXTENSION && + abilityInfo->extensionAbilityType != ExtensionAbilityType::UI) { + TAG_LOGW(AAFwkTag::APPMGR, "extensionType:%{public}d, not notify any more.", abilityInfo->extensionAbilityType); return; } auto serviceInner = appMgrServiceInner_.lock(); @@ -967,9 +974,10 @@ void AppRunningRecord::AbilityForeground(const std::shared_ptrGetToken()); @@ -1021,8 +1029,11 @@ void AppRunningRecord::AbilityBackground(const std::shared_ptr &token) auto appRecord = shared_from_this(); auto cacheProcMgr = DelayedSingleton::GetInstance(); bool needCache = false; - cacheProcMgr->UpdateTypeByAbility(abilityRecord, appRecord); if (cacheProcMgr != nullptr && cacheProcMgr->IsAppShouldCache(appRecord)) { cacheProcMgr->CheckAndCacheProcess(appRecord); TAG_LOGI(AAFwkTag::APPMGR, "App %{public}s should cache, not remove module and terminate app.", @@ -1354,19 +1364,15 @@ bool AppRunningRecord::IsLastAbilityRecord(const sptr &token) return false; } -bool AppRunningRecord::ExtensionAbilityRecordExists(const sptr &token) +bool AppRunningRecord::ExtensionAbilityRecordExists() { - auto moduleRecord = GetModuleRunningRecordByToken(token); - if (!moduleRecord) { - TAG_LOGE(AAFwkTag::APPMGR, "can not find module record"); - return false; - } auto moduleRecordList = GetAllModuleRecord(); for (auto moduleRecord : moduleRecordList) { if (moduleRecord && moduleRecord->ExtensionAbilityRecordExists()) { return true; + } } - } + TAG_LOGD(AAFwkTag::APPMGR, "can not find extension record"); return false; } @@ -1694,6 +1700,10 @@ void AppRunningRecord::AddRenderRecord(const std::shared_ptr &reco TAG_LOGD(AAFwkTag::APPMGR, "AddRenderRecord: record is null"); return; } + { + std::lock_guard renderPidSetLock(renderPidSetLock_); + renderPidSet_.insert(record->GetPid()); + } std::lock_guard renderRecordMapLock(renderRecordMapLock_); renderRecordMap_.emplace(record->GetUid(), record); } @@ -1708,6 +1718,18 @@ void AppRunningRecord::RemoveRenderRecord(const std::shared_ptr &r renderRecordMap_.erase(record->GetUid()); } +void AppRunningRecord::RemoveRenderPid(pid_t renderPid) +{ + std::lock_guard renderPidSetLock(renderPidSetLock_); + renderPidSet_.erase(renderPid); +} + +bool AppRunningRecord::ConstainsRenderPid(pid_t renderPid) +{ + std::lock_guard renderPidSetLock(renderPidSetLock_); + return renderPidSet_.find(renderPid) != renderPidSet_.end(); +} + std::shared_ptr AppRunningRecord::GetRenderRecordByPid(const pid_t pid) { std::lock_guard renderRecordMapLock(renderRecordMapLock_); @@ -1761,6 +1783,11 @@ void AppRunningRecord::SetPerfCmd(const std::string &perfCmd) perfCmd_ = perfCmd; } +void AppRunningRecord::SetErrorInfoEnhance(bool errorInfoEnhance) +{ + isErrorInfoEnhance_ = errorInfoEnhance; +} + void AppRunningRecord::SetMultiThread(bool multiThread) { isMultiThread_ = multiThread; @@ -1898,7 +1925,8 @@ bool AppRunningRecord::IsAbilitytiesBackground() void AppRunningRecord::OnWindowVisibilityChanged( const std::vector> &windowVisibilityInfos) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + TAG_LOGI(AAFwkTag::APPMGR, "called"); if (windowVisibilityInfos.empty()) { TAG_LOGW(AAFwkTag::APPMGR, "Window visibility info is empty."); return; @@ -1924,24 +1952,24 @@ void AppRunningRecord::OnWindowVisibilityChanged( } } - bool isScheduleForeground = (!windowIds_.empty() && curState_ != ApplicationState::APP_STATE_FOREGROUND) || - (!windowIds_.empty() && curState_ == ApplicationState::APP_STATE_FOREGROUND && - pendingState_ == ApplicationPendingState::BACKGROUNDING); - if (isScheduleForeground) { - SetApplicationPendingState(ApplicationPendingState::FOREGROUNDING); - SetUpdateStateFromService(true); - ScheduleForegroundRunning(); - return; - } - - bool isScheduleBackground = (windowIds_.empty() && IsAbilitytiesBackground() && - curState_ == ApplicationState::APP_STATE_FOREGROUND) || - (windowIds_.empty() && IsAbilitytiesBackground() && curState_ == ApplicationState::APP_STATE_BACKGROUND && - pendingState_ == ApplicationPendingState::FOREGROUNDING); - if (isScheduleBackground) { - SetApplicationPendingState(ApplicationPendingState::BACKGROUNDING); - SetUpdateStateFromService(true); - ScheduleBackgroundRunning(); + if (pendingState_ == ApplicationPendingState::READY) { + TAG_LOGD(AAFwkTag::APPMGR, "pending state is READY."); + if (!windowIds_.empty() && curState_ != ApplicationState::APP_STATE_FOREGROUND) { + SetApplicationPendingState(ApplicationPendingState::FOREGROUNDING); + ScheduleForegroundRunning(); + } + if (windowIds_.empty() && IsAbilitytiesBackground() && curState_ == ApplicationState::APP_STATE_FOREGROUND) { + SetApplicationPendingState(ApplicationPendingState::BACKGROUNDING); + ScheduleBackgroundRunning(); + } + } else { + TAG_LOGI(AAFwkTag::APPMGR, "pending state is not READY."); + if (!windowIds_.empty()) { + SetApplicationPendingState(ApplicationPendingState::FOREGROUNDING); + } + if (windowIds_.empty() && IsAbilitytiesBackground()) { + SetApplicationPendingState(ApplicationPendingState::BACKGROUNDING); + } } } #endif //SUPPORT_SCREEN @@ -1986,16 +2014,6 @@ ProcessChangeReason AppRunningRecord::GetProcessChangeReason() const return processChangeReason_; } -bool AppRunningRecord::IsUpdateStateFromService() -{ - return isUpdateStateFromService_; -} - -void AppRunningRecord::SetUpdateStateFromService(bool isUpdateStateFromService) -{ - isUpdateStateFromService_ = isUpdateStateFromService; -} - ExtensionAbilityType AppRunningRecord::GetExtensionType() const { return extensionType_; @@ -2048,7 +2066,7 @@ int32_t AppRunningRecord::ChangeAppGcState(const int32_t state) void AppRunningRecord::SetAttachDebug(const bool &isAttachDebug) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); isAttachDebug_ = isAttachDebug; if (appLifeCycleDeal_ == nullptr) { @@ -2211,7 +2229,7 @@ std::string AppRunningRecord::GetExitMsg() const int AppRunningRecord::DumpIpcStart(std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (appLifeCycleDeal_ == nullptr) { result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT)) .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) @@ -2224,7 +2242,7 @@ int AppRunningRecord::DumpIpcStart(std::string& result) int AppRunningRecord::DumpIpcStop(std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (appLifeCycleDeal_ == nullptr) { result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT)) .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) @@ -2237,7 +2255,7 @@ int AppRunningRecord::DumpIpcStop(std::string& result) int AppRunningRecord::DumpIpcStat(std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (appLifeCycleDeal_ == nullptr) { result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT)) .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL)) @@ -2250,7 +2268,7 @@ int AppRunningRecord::DumpIpcStat(std::string& result) int AppRunningRecord::DumpFfrt(std::string& result) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + 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)); @@ -2263,10 +2281,6 @@ int AppRunningRecord::DumpFfrt(std::string& result) bool AppRunningRecord::SetSupportedProcessCache(bool isSupport) { TAG_LOGI(AAFwkTag::APPMGR, "Called"); - if (procCacheSupportState_ != SupportProcessCacheState::UNSPECIFIED) { - TAG_LOGI(AAFwkTag::APPMGR, "Process cache not support set more than once."); - return false; - } procCacheSupportState_ = isSupport ? SupportProcessCacheState::SUPPORT : SupportProcessCacheState::NOT_SUPPORT; return true; } @@ -2276,6 +2290,24 @@ SupportProcessCacheState AppRunningRecord::GetSupportProcessCacheState() return procCacheSupportState_; } +void AppRunningRecord::ScheduleCacheProcess() +{ + if (appLifeCycleDeal_ == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ is null"); + return; + } + appLifeCycleDeal_->ScheduleCacheProcess(); +} + +bool AppRunningRecord::CancelTask(std::string msg) +{ + if (!taskHandler_) { + TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ is nullptr"); + return false; + } + return taskHandler_->CancelTask(msg); +} + void AppRunningRecord::SetBrowserHost(sptr browser) { browserHost_ = browser; @@ -2308,24 +2340,6 @@ pid_t AppRunningRecord::GetGPUPid() return gpuPid_; } -void AppRunningRecord::ScheduleCacheProcess() -{ - if (appLifeCycleDeal_ == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ is null"); - return; - } - appLifeCycleDeal_->ScheduleCacheProcess(); -} - -bool AppRunningRecord::CancelTask(std::string msg) -{ - if (!taskHandler_) { - TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ is nullptr"); - return false; - } - return taskHandler_->CancelTask(msg); -} - void AppRunningRecord::SetAttachedToStatusBar(bool isAttached) { isAttachedToStatusBar = isAttached; @@ -2335,5 +2349,15 @@ bool AppRunningRecord::IsAttachedToStatusBar() { return isAttachedToStatusBar; } + +void AppRunningRecord::SetProcessCacheBlocked(bool isBlocked) +{ + processCacheBlocked = isBlocked; +} + +bool AppRunningRecord::GetProcessCacheBlocked() +{ + return processCacheBlocked; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_running_status_module.cpp b/services/appmgr/src/app_running_status_module.cpp index 18cfa42db1..3e15f5a9c9 100644 --- a/services/appmgr/src/app_running_status_module.cpp +++ b/services/appmgr/src/app_running_status_module.cpp @@ -25,7 +25,7 @@ namespace OHOS { namespace AbilityRuntime { int32_t AppRunningStatusModule::RegisterListener(const sptr &listener) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (listener == nullptr || listener->AsObject() == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Listener is null."); return ERR_INVALID_OPERATION; @@ -56,7 +56,7 @@ int32_t AppRunningStatusModule::RegisterListener(const sptr &listener) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (listener == nullptr || listener->AsObject() == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Input param invalid."); return ERR_INVALID_VALUE; @@ -68,7 +68,7 @@ int32_t AppRunningStatusModule::UnregisterListener(const sptr lock(listenerMutex_); for (const auto &item : listeners_) { if (item.first == nullptr) { @@ -87,7 +87,7 @@ AppRunningStatusModule::ClientDeathRecipient::ClientDeathRecipient(const std::we void AppRunningStatusModule::ClientDeathRecipient::OnRemoteDied(const wptr &remote) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto appRunningStatus = weakPtr_.lock(); if (appRunningStatus == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "appRunningStatus is nullptr."); @@ -98,7 +98,7 @@ void AppRunningStatusModule::ClientDeathRecipient::OnRemoteDied(const wptr &remote) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); auto listener = remote.promote(); if (listener == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Remote object is nullptr."); diff --git a/services/appmgr/src/app_spawn_client.cpp b/services/appmgr/src/app_spawn_client.cpp index 5452ce4ece..ea3ec9d155 100644 --- a/services/appmgr/src/app_spawn_client.cpp +++ b/services/appmgr/src/app_spawn_client.cpp @@ -18,7 +18,6 @@ #include "hitrace_meter.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "nlohmann/json.hpp" #include "securec.h" @@ -50,7 +49,7 @@ AppSpawnClient::AppSpawnClient(bool isNWebSpawn) AppSpawnClient::AppSpawnClient(const char* serviceName) { - HILOG_DEBUG("AppspawnCreateClient"); + TAG_LOGD(AAFwkTag::APPMGR, "AppspawnCreateClient"); std::string serviceName__ = serviceName; if (serviceName__ == APPSPAWN_SERVER_NAME) { serviceName_ = APPSPAWN_SERVER_NAME; @@ -59,7 +58,7 @@ AppSpawnClient::AppSpawnClient(const char* serviceName) } else if (serviceName__ == NWEBSPAWN_SERVER_NAME) { serviceName_ = NWEBSPAWN_SERVER_NAME; } else { - HILOG_ERROR("unknown service name"); + TAG_LOGE(AAFwkTag::APPMGR, "unknown service name"); serviceName_ = NWEBSPAWN_SERVER_NAME; } state_ = SpawnConnectionState::STATE_NOT_CONNECT; @@ -235,7 +234,11 @@ int32_t AppSpawnClient::SetStartFlags(const AppSpawnStartMsg &startMsg, AppSpawn return ret; } } - + ret = SetChildProcessTypeStartFlag(reqHandle, startMsg.childProcessType); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::APPMGR, "Set childProcessType flag failed, ret: %{public}d", ret); + return ret; + } return ret; } @@ -333,6 +336,14 @@ int32_t AppSpawnClient::AppspawnSetExtMsgMore(const AppSpawnStartMsg &startMsg, } TAG_LOGI(AAFwkTag::APPMGR, "Send maxChildProcess %{public}s success.", maxChildProcessStr.c_str()); + if (!startMsg.fds.empty()) { + ret = SetExtMsgFds(reqHandle, startMsg.fds); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::APPMGR, "SetExtMsgFds failed, ret: %{public}d", ret); + return ret; + } + } + return ret; } @@ -442,7 +453,6 @@ bool AppSpawnClient::VerifyMsg(const AppSpawnStartMsg &startMsg) return true; } -// 预启动 int32_t AppSpawnClient::PreStartNWebSpawnProcess() { TAG_LOGI(AAFwkTag::APPMGR, "PreStartNWebSpawnProcess"); @@ -454,7 +464,7 @@ int32_t AppSpawnClient::StartProcess(const AppSpawnStartMsg &startMsg, pid_t &pi TAG_LOGI(AAFwkTag::APPMGR, "StartProcess"); HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); if (!VerifyMsg(startMsg)) { - return ERR_INVALID_VALUE; // 入参非法 + return ERR_INVALID_VALUE; } int32_t ret = 0; @@ -499,9 +509,9 @@ int32_t AppSpawnClient::GetRenderProcessTerminationStatus(const AppSpawnStartMsg int32_t ret = 0; AppSpawnReqMsgHandle reqHandle = nullptr; - // 入参校验 + // check parameters if (!VerifyMsg(startMsg)) { - return ERR_INVALID_VALUE; // 入参非法 + return ERR_INVALID_VALUE; } ret = OpenConnection(); @@ -528,5 +538,30 @@ int32_t AppSpawnClient::GetRenderProcessTerminationStatus(const AppSpawnStartMsg return ret; } +int32_t AppSpawnClient::SetChildProcessTypeStartFlag(const AppSpawnReqMsgHandle &reqHandle, + int32_t childProcessType) +{ + TAG_LOGD(AAFwkTag::APPMGR, "SetChildProcessTypeStartFlag, type:%{public}d", childProcessType); + if (childProcessType != CHILD_PROCESS_TYPE_NOT_CHILD) { + return AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_CHILDPROCESS); + } + return ERR_OK; +} + +int32_t AppSpawnClient::SetExtMsgFds(const AppSpawnReqMsgHandle &reqHandle, + const std::map &fds) +{ + TAG_LOGI(AAFwkTag::APPMGR, "SetExtMsgFds, fds size:%{public}zu", fds.size()); + int32_t ret = ERR_OK; + for (const auto &item : fds) { + ret = AppSpawnReqMsgAddFd(reqHandle, item.first.c_str(), item.second); + if (ret != ERR_OK) { + TAG_LOGE(AAFwkTag::APPMGR, "AppSpawnReqMsgAddFd failed, key:%{public}s, fd:%{public}d, ret:%{public}d", + item.first.c_str(), item.second, ret); + return ret; + } + } + return ERR_OK; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/app_state_observer_manager.cpp b/services/appmgr/src/app_state_observer_manager.cpp index 507b1d9570..7e3e18b8f8 100644 --- a/services/appmgr/src/app_state_observer_manager.cpp +++ b/services/appmgr/src/app_state_observer_manager.cpp @@ -104,7 +104,7 @@ int32_t AppStateObserverManager::UnregisterApplicationStateObserver(const sptr &observer) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (observer == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "The param observer is nullptr."); return ERR_INVALID_VALUE; @@ -127,7 +127,7 @@ int32_t AppStateObserverManager::RegisterAppForegroundStateObserver(const sptr &observer) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (observer == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Observer nullptr."); return ERR_INVALID_VALUE; @@ -151,7 +151,7 @@ int32_t AppStateObserverManager::RegisterAbilityForegroundStateObserver( const sptr &observer) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (observer == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "The param observer is nullptr."); return ERR_INVALID_VALUE; @@ -175,7 +175,7 @@ int32_t AppStateObserverManager::UnregisterAbilityForegroundStateObserver( const sptr &observer) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (observer == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Observer nullptr."); return ERR_INVALID_VALUE; @@ -385,7 +385,7 @@ void AppStateObserverManager::StateChangedNotifyObserver( TAG_LOGE(AAFwkTag::APPMGR, "self is nullptr, StateChangedNotifyObserver failed."); return; } - TAG_LOGD(AAFwkTag::APPMGR, "StateChangedNotifyObserver come."); + TAG_LOGI(AAFwkTag::APPMGR, "StateChangedNotifyObserver come."); self->HandleStateChangedNotifyObserver(abilityStateData, isAbility, isFromWindowFocusChanged); }; handler_->SubmitTask(task); diff --git a/services/appmgr/src/cache_process_manager.cpp b/services/appmgr/src/cache_process_manager.cpp index 49b1a73ca9..21a873694b 100644 --- a/services/appmgr/src/cache_process_manager.cpp +++ b/services/appmgr/src/cache_process_manager.cpp @@ -25,6 +25,7 @@ namespace { const std::string MAX_PROC_CACHE_NUM = "persist.sys.abilityms.maxProcessCacheNum"; const std::string PROCESS_CACHE_API_CHECK_CONFIG = "persist.sys.abilityms.processCacheApiCheck"; +const std::string PROCESS_CACHE_SET_SUPPORT_CHECK_CONFIG = "persist.sys.abilityms.processCacheSetSupportCheck"; const std::string SHELL_ASSISTANT_BUNDLENAME = "com.huawei.shell_assistant"; constexpr int32_t API12 = 12; constexpr int32_t API_VERSION_MOD = 100; @@ -37,6 +38,7 @@ CacheProcessManager::CacheProcessManager() { maxProcCacheNum_ = OHOS::system::GetIntParameter(MAX_PROC_CACHE_NUM, 0); shouldCheckApi = OHOS::system::GetBoolParameter(PROCESS_CACHE_API_CHECK_CONFIG, true); + shouldCheckSupport = OHOS::system::GetBoolParameter(PROCESS_CACHE_SET_SUPPORT_CHECK_CONFIG, true); TAG_LOGW(AAFwkTag::APPMGR, "maxProcCacheNum is =%{public}d", maxProcCacheNum_); } @@ -183,6 +185,7 @@ void CacheProcessManager::OnProcessKilled(const std::shared_ptr queueLock(cacheQueueMtx); srvExtRecords.erase(appRecord); + srvExtCheckedFlag.erase(appRecord); } if (!IsCachedProcess(appRecord)) { return; @@ -233,7 +236,7 @@ bool CacheProcessManager::IsAppSupportProcessCache(const std::shared_ptrGetName().c_str(), actualVer); return false; } - if (srvExtRecords.find(appRecord) != srvExtRecords.end()) { + if (IsAppContainsSrvExt(appRecord)) { TAG_LOGD(AAFwkTag::APPMGR, "%{public}s of %{public}s is service, not support cache", appRecord->GetProcessName().c_str(), appRecord->GetBundleName().c_str()); return false; @@ -251,20 +254,39 @@ bool CacheProcessManager::IsAppSupportProcessCache(const std::shared_ptr &appRecord) +{ + if (appRecord == nullptr) { + TAG_LOGI(AAFwkTag::APPMGR, "appRecord nullptr precheck failed"); + return false; + } if (appRecord->GetBundleName() == SHELL_ASSISTANT_BUNDLENAME) { TAG_LOGD(AAFwkTag::APPMGR, "shell assistant, not support."); return false; } + if (appRecord->GetProcessCacheBlocked()) { + TAG_LOGD(AAFwkTag::APPMGR, "%{public}s of %{public}s 's process cache temporarily blocked.", + appRecord->GetProcessName().c_str(), appRecord->GetBundleName().c_str()); + return false; + } auto supportState = appRecord->GetSupportProcessCacheState(); switch (supportState) { case SupportProcessCacheState::UNSPECIFIED: - return true; + TAG_LOGD(AAFwkTag::APPMGR, "App %{public}s has not defined support state.", + appRecord->GetBundleName().c_str()); + return shouldCheckSupport ? false : true; case SupportProcessCacheState::SUPPORT: return true; case SupportProcessCacheState::NOT_SUPPORT: + TAG_LOGD(AAFwkTag::APPMGR, "App %{public}s defines not support.", + appRecord->GetBundleName().c_str()); return false; default: - return true; + TAG_LOGD(AAFwkTag::APPMGR, "Invalid support state."); + return false; } } @@ -359,6 +381,8 @@ bool CacheProcessManager::KillProcessByRecord(const std::shared_ptrOnAppCacheStateChanged(appRecord, ApplicationState::APP_STATE_READY); // this uses ScheduleProcessSecurityExit appMgrSptr->KillApplicationByRecord(appRecord); return true; @@ -427,47 +451,62 @@ void CacheProcessManager::RemoveFromApplicationSet(const std::shared_ptr &token, - const std::shared_ptr &appRecord) +void CacheProcessManager::PrepareActivateCache(const std::shared_ptr &appRecord) { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); if (!QueryEnableProcessCache()) { return; } - if (token == nullptr || appRecord == nullptr) { + if (appRecord == nullptr) { return; } - auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token); - if (abilityRecord == nullptr) { + if (!IsCachedProcess(appRecord)) { return; } - UpdateTypeByAbility(abilityRecord, appRecord); + TAG_LOGD(AAFwkTag::APPMGR, "%{public}s needs activate.", appRecord->GetBundleName().c_str()); + auto appMgrSptr = appMgr_.lock(); + if (appMgrSptr == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "appMgr is nullptr"); + return; + } + appMgrSptr->OnAppCacheStateChanged(appRecord, ApplicationState::APP_STATE_READY); } -void CacheProcessManager::UpdateTypeByAbility(const std::shared_ptr &abilityRecord, - const std::shared_ptr &appRecord) +bool CacheProcessManager::IsAppContainsSrvExt(const std::shared_ptr &appRecord) { HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); - if (!QueryEnableProcessCache()) { - return; + std::lock_guard queueLock(cacheQueueMtx); + if (appRecord == nullptr) { + return false; } - if (abilityRecord == nullptr || appRecord == nullptr) { - return; + if (srvExtCheckedFlag.find(appRecord) != srvExtCheckedFlag.end()) { + return srvExtRecords.find(appRecord) != srvExtRecords.end() ? true : false; } - auto abilityInfo = abilityRecord->GetAbilityInfo(); - if (abilityInfo == nullptr) { - return; - } - auto type = abilityInfo->type; - if (type == AppExecFwk::AbilityType::EXTENSION && - abilityInfo->extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) { - std::lock_guard queueLock(cacheQueueMtx); - srvExtRecords.insert(appRecord); - // incase service record is in cache queue due to delay - RemoveCacheRecord(appRecord); - TAG_LOGD(AAFwkTag::APPMGR, "%{public}s is service, will not cache, service records size: %{public}zu.", - appRecord->GetBundleName().c_str(), srvExtRecords.size()); + auto allModuleRecord = appRecord->GetAllModuleRecord(); + for (auto moduleRecord : allModuleRecord) { + if (moduleRecord == nullptr) { + continue; + } + HapModuleInfo hapModuleInfo; + moduleRecord->GetHapModuleInfo(hapModuleInfo); + for (auto abilityInfo : hapModuleInfo.abilityInfos) { + if (abilityInfo.type == AppExecFwk::AbilityType::EXTENSION && + abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) { + srvExtRecords.insert(appRecord); + TAG_LOGD(AAFwkTag::APPMGR, "%{public}s of %{public}s is service, will not cache", + abilityInfo.name.c_str(), appRecord->GetBundleName().c_str()); + } + } + for (auto extAbilityInfo : hapModuleInfo.extensionInfos) { + if (extAbilityInfo.type == AppExecFwk::ExtensionAbilityType::SERVICE) { + srvExtRecords.insert(appRecord); + TAG_LOGD(AAFwkTag::APPMGR, "%{public}s of %{public}s is service, will not cache", + extAbilityInfo.name.c_str(), appRecord->GetBundleName().c_str()); + } + } } + srvExtCheckedFlag.insert(appRecord); + return srvExtRecords.find(appRecord) != srvExtRecords.end() ? true : false; } } // namespace OHOS } // namespace AppExecFwk \ No newline at end of file diff --git a/services/appmgr/src/child_process_record.cpp b/services/appmgr/src/child_process_record.cpp index a5a3b9d828..f286176cfc 100644 --- a/services/appmgr/src/child_process_record.cpp +++ b/services/appmgr/src/child_process_record.cpp @@ -21,10 +21,10 @@ namespace OHOS { namespace AppExecFwk { -ChildProcessRecord::ChildProcessRecord(pid_t hostPid, const std::string &srcEntry, - const std::shared_ptr hostRecord, int32_t childProcessCount, bool isStartWithDebug) - : hostPid_(hostPid), childProcessCount_(childProcessCount), srcEntry_(srcEntry), hostRecord_(hostRecord), - isStartWithDebug_(isStartWithDebug) +ChildProcessRecord::ChildProcessRecord(pid_t hostPid, const ChildProcessRequest &request, + const std::shared_ptr hostRecord) + : hostPid_(hostPid), childProcessCount_(request.childProcessCount), childProcessType_(request.childProcessType), + srcEntry_(request.srcEntry), hostRecord_(hostRecord), isStartWithDebug_(request.isStartWithDebug) { MakeProcessName(hostRecord); } @@ -40,19 +40,18 @@ ChildProcessRecord::ChildProcessRecord(pid_t hostPid, const std::string &libName ChildProcessRecord::~ChildProcessRecord() { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); } std::shared_ptr ChildProcessRecord::CreateChildProcessRecord(pid_t hostPid, - const std::string &srcEntry, const std::shared_ptr hostRecord, int32_t childProcessCount, - bool isStartWithDebug) + const ChildProcessRequest &request, const std::shared_ptr hostRecord) { - TAG_LOGD(AAFwkTag::APPMGR, "hostPid: %{public}d, srcEntry: %{public}s", hostPid, srcEntry.c_str()); - if (hostPid <= 0 || srcEntry.empty() || !hostRecord) { + TAG_LOGD(AAFwkTag::APPMGR, "hostPid: %{public}d, srcEntry: %{priavte}s,", hostPid, request.srcEntry.c_str()); + if (hostPid <= 0 || request.srcEntry.empty() || !hostRecord) { TAG_LOGE(AAFwkTag::APPMGR, "Invalid parameter."); return nullptr; } - return std::make_shared(hostPid, srcEntry, hostRecord, childProcessCount, isStartWithDebug); + return std::make_shared(hostPid, request, hostRecord); } std::shared_ptr ChildProcessRecord::CreateNativeChildProcessRecord( @@ -185,7 +184,7 @@ bool ChildProcessRecord::isStartWithDebug() return isStartWithDebug_; } -int32_t ChildProcessRecord::GetProcessType() const +int32_t ChildProcessRecord::GetChildProcessType() const { return childProcessType_; } @@ -200,5 +199,14 @@ void ChildProcessRecord::ClearMainProcessCallback() mainProcessCb_.clear(); } +void ChildProcessRecord::SetEntryParams(const std::string &entryParams) +{ + entryParams_ = entryParams; +} + +std::string ChildProcessRecord::GetEntryParams() const +{ + return entryParams_; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/exit_resident_process_manager.cpp b/services/appmgr/src/exit_resident_process_manager.cpp index d7a68f8b8b..d5f3a5cada 100644 --- a/services/appmgr/src/exit_resident_process_manager.cpp +++ b/services/appmgr/src/exit_resident_process_manager.cpp @@ -18,7 +18,6 @@ #include "ability_manager_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "in_process_call_wrapper.h" #include "remote_client_manager.h" @@ -53,6 +52,13 @@ bool ExitResidentProcessManager::RecordExitResidentBundleName(const std::string return true; } +void ExitResidentProcessManager::RecordExitResidentBundleDependedOnWeb(const std::string &bundleName) +{ + std::lock_guard lock(webMutexLock_); + TAG_LOGE(AAFwkTag::APPMGR, "call"); + exitResidentBundlesDependedOnWeb_.emplace_back(bundleName); +} + int32_t ExitResidentProcessManager::HandleMemorySizeInSufficent() { std::lock_guard lock(mutexLock_); @@ -77,6 +83,14 @@ int32_t ExitResidentProcessManager::HandleMemorySizeSufficent(std::vector& bundleNames) +{ + std::lock_guard lock(webMutexLock_); + TAG_LOGE(AAFwkTag::APPMGR, "call"); + bundleNames = exitResidentBundlesDependedOnWeb_; + exitResidentBundlesDependedOnWeb_.clear(); +} + void ExitResidentProcessManager::QueryExitBundleInfos(const std::vector& exitBundleNames, std::vector& exitBundleInfos) { @@ -104,5 +118,23 @@ void ExitResidentProcessManager::QueryExitBundleInfos(const std::vector bundleNames; + { + std::lock_guard lock(webMutexLock_); + bundleNames = exitResidentBundlesDependedOnWeb_; + } + for (const auto &innerBundleName : bundleNames) { + if (innerBundleName == bundleName) { + TAG_LOGD(AAFwkTag::APPMGR, "Is killed for upgrade web."); + return true; + } + } + TAG_LOGD(AAFwkTag::APPMGR, "Not killed for upgrade web."); + return false; +} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/modal_system_app_freeze_uiextension.cpp b/services/appmgr/src/modal_system_app_freeze_uiextension.cpp index c87ce0122f..e3ece0177f 100644 --- a/services/appmgr/src/modal_system_app_freeze_uiextension.cpp +++ b/services/appmgr/src/modal_system_app_freeze_uiextension.cpp @@ -19,8 +19,8 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" +#include "in_process_call_wrapper.h" #include "scene_board_judgement.h" namespace OHOS { @@ -56,9 +56,30 @@ sptr ModalSystemAppF return dialogConnectionCallback_; } +void ModalSystemAppFreezeUIExtension::ProcessAppFreeze(bool focusFlag, const FaultData &faultData, std::string pid, + std::string bundleName, std::function callback, bool isDialogExist) +{ + const std::string SCENE_BAOARD_NAME = "com.ohos.sceneboard"; + if (bundleName == SCENE_BAOARD_NAME && callback) { + callback(); + return; + } + FaultDataType faultType = faultData.faultType; + std::string name = faultData.errorObject.name; + bool isAppFreezeDialog = name == AppFreezeType::THREAD_BLOCK_6S || name == AppFreezeType::APP_INPUT_BLOCK || + name == AppFreezeType::LIFECYCLE_TIMEOUT; + isAppFreezeDialog = isAppFreezeDialog && (!isDialogExist || (isDialogExist && pid != lastFreezePid)); + TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s is %{public}s", bundleName.c_str(), focusFlag ? " focus" : " not focus"); + if (focusFlag && isAppFreezeDialog) { + CreateModalUIExtension(pid, bundleName); + } else if (callback && faultType != FaultDataType::APP_FREEZE) { + callback(); + } +} + bool ModalSystemAppFreezeUIExtension::CreateModalUIExtension(std::string pid, std::string bundleName) { - TAG_LOGI(AAFwkTag::ABILITYMGR, "CreateModalUIExtension Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); AAFwk::Want want = CreateSystemDialogWant(pid, bundleName); std::unique_lock lockAssertResult(appFreezeResultMutex_); auto callback = GetConnection(); @@ -78,24 +99,23 @@ bool ModalSystemAppFreezeUIExtension::CreateModalUIExtension(std::string pid, st } else { systemUIWant.SetElementName("com.ohos.systemui", "com.ohos.systemui.dialog"); } - auto result = abilityManagerClient->ConnectAbility(systemUIWant, callback, INVALID_USERID); + IN_PROCESS_CALL_WITHOUT_RET(abilityManagerClient->DisconnectAbility(callback)); + auto result = IN_PROCESS_CALL(abilityManagerClient->ConnectAbility(systemUIWant, callback, INVALID_USERID)); if (result != ERR_OK) { TAG_LOGE(AAFwkTag::ABILITYMGR, "CreateModalUIExtension ConnectSystemUi ConnectAbility dialog failed, result = %{public}d", result); return false; } - TAG_LOGE(AAFwkTag::ABILITYMGR, + lastFreezePid = pid; + TAG_LOGI(AAFwkTag::ABILITYMGR, "CreateModalUIExtension ConnectSystemUi ConnectAbility dialog success, result = %{public}d", result); return true; } AAFwk::Want ModalSystemAppFreezeUIExtension::CreateSystemDialogWant(std::string pid, std::string bundleName) { - std::string startAbilityName = "AppAbnormalAbility"; - std::string startBundleName = - Rosen::SceneBoardJudgement::IsSceneBoardEnabled() ? "com.ohos.sceneboard" : "com.ohos.systemui"; AAFwk::Want want; - want.SetElementName(startBundleName, startAbilityName); + want.SetElementName(APP_NO_RESPONSE_BUNDLENAME, APP_NO_RESPONSE_ABILITY); want.SetParam(UIEXTENSION_TYPE_KEY, UIEXTENSION_SYS_COMMON_UI); want.SetParam(APP_FREEZE_PID, pid); want.SetParam(START_BUNDLE_NAME, bundleName); @@ -110,7 +130,7 @@ void ModalSystemAppFreezeUIExtension::AppFreezeDialogConnection::SetReqeustAppFr void ModalSystemAppFreezeUIExtension::AppFreezeDialogConnection::OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remote, int resultCode) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); if (remote == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Input remote object is nullptr."); return; @@ -145,7 +165,7 @@ void ModalSystemAppFreezeUIExtension::AppFreezeDialogConnection::OnAbilityConnec void ModalSystemAppFreezeUIExtension::AppFreezeDialogConnection::OnAbilityDisconnectDone( const AppExecFwk::ElementName &element, int resultCode) { - TAG_LOGI(AAFwkTag::ABILITYMGR, "Called."); + TAG_LOGI(AAFwkTag::ABILITYMGR, "called"); } } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/module_running_record.cpp b/services/appmgr/src/module_running_record.cpp index 8e5c76f7a0..41d4b1a44a 100644 --- a/services/appmgr/src/module_running_record.cpp +++ b/services/appmgr/src/module_running_record.cpp @@ -319,7 +319,7 @@ bool ModuleRunningRecord::RemoveTerminateAbilityTimeoutTask(const sptr lock(abilitiesMutex_); for (const auto &iter : abilities_) { const auto &ability = iter.second; diff --git a/services/appmgr/src/remote_client_manager.cpp b/services/appmgr/src/remote_client_manager.cpp index 1a8f293210..edb5cafe12 100644 --- a/services/appmgr/src/remote_client_manager.cpp +++ b/services/appmgr/src/remote_client_manager.cpp @@ -15,7 +15,6 @@ #include "remote_client_manager.h" -#include "hilog_wrapper.h" #include "iservice_registry.h" #include "singleton.h" #include "system_ability_definition.h" diff --git a/services/appmgr/src/window_visibility_changed_listener.cpp b/services/appmgr/src/window_visibility_changed_listener.cpp index a59398f069..4de7ad1d8d 100644 --- a/services/appmgr/src/window_visibility_changed_listener.cpp +++ b/services/appmgr/src/window_visibility_changed_listener.cpp @@ -30,7 +30,7 @@ WindowVisibilityChangedListener::WindowVisibilityChangedListener( void WindowVisibilityChangedListener::OnWindowVisibilityChanged( const std::vector> &windowVisibilityInfos) { - TAG_LOGD(AAFwkTag::APPMGR, "Called."); + TAG_LOGD(AAFwkTag::APPMGR, "called"); if (windowVisibilityInfos.empty()) { TAG_LOGW(AAFwkTag::APPMGR, "Window visibility info is empty."); return; diff --git a/services/common/BUILD.gn b/services/common/BUILD.gn index eb41a6095a..d5aca12037 100644 --- a/services/common/BUILD.gn +++ b/services/common/BUILD.gn @@ -118,12 +118,15 @@ ohos_shared_library("app_util") { sources = [ "src/ability_manager_radar.cpp", "src/app_utils.cpp", + "src/json_utils.cpp", ] external_deps = [ + "config_policy:configpolicy_util", "hilog:libhilog", "hisysevent:libhisysevent", "init:libbegetutil", + "json:nlohmann_json_static", ] if (ability_runtime_graphics) { diff --git a/services/common/include/app_utils.h b/services/common/include/app_utils.h index df40d7733f..4531361c2a 100644 --- a/services/common/include/app_utils.h +++ b/services/common/include/app_utils.h @@ -34,6 +34,7 @@ public: class AppUtils { public: static AppUtils &GetInstance(); + ~AppUtils(); bool IsLauncher(const std::string &bundleName) const; bool IsLauncherAbility(const std::string &abilityName) const; bool IsInheritWindowSplitScreenMode(); @@ -50,13 +51,16 @@ public: bool EnableMoveUIAbilityToBackgroundApi(); bool IsLaunchEmbededUIAbility(); bool IsSupportNativeChildProcess(); + bool IsAllowResidentInExtremeMemory(const std::string& bundleName, const std::string& abilityName = ""); int32_t GetLimitMaximumExtensionsPerProc(); int32_t GetLimitMaximumExtensionsPerDevice(); std::string GetCacheExtensionTypeList(); + bool IsAllowStartAbilityWithoutCallerToken(const std::string& bundleName, const std::string& abilityName); private: + void LoadResidentProcessInExtremeMemory(); + void LoadStartAbilityWithoutCallerToken(); AppUtils(); - ~AppUtils(); volatile bool isSceneBoard_ = false; volatile DeviceConfiguration isInheritWindowSplitScreenMode_ = {false, true}; volatile DeviceConfiguration isSupportAncoApp_ = {false, false}; @@ -72,8 +76,12 @@ private: volatile DeviceConfiguration enableMoveUIAbilityToBackgroundApi_ = {false, true}; volatile DeviceConfiguration isLaunchEmbededUIAbility_ = {false, false}; volatile DeviceConfiguration isSupportNativeChildProcess_ = {false, false}; + DeviceConfiguration>> + residentProcessInExtremeMemory_ = {false, {}}; volatile DeviceConfiguration limitMaximumExtensionsPerProc_ = {false, DEFAULT_MAX_EXT_PER_PROC}; volatile DeviceConfiguration limitMaximumExtensionsPerDevice_ = {false, DEFAULT_MAX_EXT_PER_DEV}; + DeviceConfiguration>> + startAbilityWithoutCallerToken_ = {false, {}}; DISALLOW_COPY_AND_MOVE(AppUtils); }; } // namespace AAFwk diff --git a/services/common/include/cache_extension_utils.h b/services/common/include/cache_extension_utils.h index c8300224cd..bb4d44344b 100755 --- a/services/common/include/cache_extension_utils.h +++ b/services/common/include/cache_extension_utils.h @@ -24,6 +24,8 @@ namespace OHOS { namespace AAFwk { namespace CacheExtensionUtils { +constexpr const int32_t BASE_TEN = 10; + // cache extension type list std::unordered_set GetCacheExtensionTypeList() { @@ -35,7 +37,8 @@ std::unordered_set GetCacheExtensionTypeList() std::vector cacheExtTypeListVec; SplitStr(cacheExtTypeListStr, ";", cacheExtTypeListVec); for (auto it = cacheExtTypeListVec.begin(); it != cacheExtTypeListVec.end(); it++) { - cacheExtTypeList.insert(static_cast(std::stoi(*it))); + cacheExtTypeList.insert( + static_cast(std::strtol((*it).c_str(), nullptr, BASE_TEN))); } return cacheExtTypeList; } diff --git a/services/common/include/event_report.h b/services/common/include/event_report.h index 086fe9c840..5b32a1a4fa 100644 --- a/services/common/include/event_report.h +++ b/services/common/include/event_report.h @@ -125,6 +125,13 @@ public: private: static std::string ConvertEventName(const EventName &eventName); + static void LogErrorEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo); + static void LogStartAbilityEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo); + static void LogTerminateAbilityEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo); + static void LogAbilityOnForegroundEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo); + static void LogAbilityOnBackgroundEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo); + static void LogAbilityOnActiveEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo); + static void LogStartStandardEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo); }; } // namespace AAFWK } // namespace OHOS diff --git a/services/common/include/hilog_tag_wrapper.h b/services/common/include/hilog_tag_wrapper.h index f6102af751..d58e5a1b60 100644 --- a/services/common/include/hilog_tag_wrapper.h +++ b/services/common/include/hilog_tag_wrapper.h @@ -56,6 +56,7 @@ enum class AAFwkLogTag : uint32_t { FA, INTENT, JSNAPI, + CJRUNTIME, DELEGATOR = DEFAULT + 0x30, // 0xD001330 CONTEXT, @@ -63,7 +64,6 @@ enum class AAFwkLogTag : uint32_t { WANT, MISSION, CONNECTION, - ATOMIC_SERVICE, ABILITYMGR, ECOLOGICAL_RULE, DATA_ABILITY, @@ -76,6 +76,7 @@ enum class AAFwkLogTag : uint32_t { UI_EXT, ACTION_EXT, EMBEDDED_EXT, + UISERVC_EXT, WANTAGENT = DEFAULT + 0x50, // 0xD001350 AUTOFILLMGR, @@ -133,7 +134,7 @@ inline const char* GetDomainName2(AAFwkLogTag tag) inline const char* GetDomainName3(AAFwkLogTag tag) { const char* tagNames[] = { "AAFwkDelegator", "AAFwkContext", "AAFwkUIAbility", "AAFwkWant", "AAFwkMission", - "AAFwkConnection", "AAFwkAtomicService", "AAFwkAbilityMgr", "AAFwkEcologicalRule", "AAFwkDataAbility" }; + "AAFwkConnection", "AAFwkAbilityMgr", "AAFwkEcologicalRule", "AAFwkDataAbility" }; uint32_t offset = GetOffset(tag, AAFwkLogTag::DELEGATOR); if (offset >= sizeof(tagNames) / sizeof(const char*)) { return "AAFwkUN"; @@ -144,7 +145,7 @@ inline const char* GetDomainName3(AAFwkLogTag tag) inline const char* GetDomainName4(AAFwkLogTag tag) { const char* tagNames[] = { "AAFwkExt", "AAFwkAutoFillExt", "AAFwkServiceExt", "AAFwkFormExt", "AAFwkShareExt", - "AAFwkUIExt", "AAFwkActionExt", "AAFwkEmbeddedExt" }; + "AAFwkUIExt", "AAFwkActionExt", "AAFwkEmbeddedExt", "AAFwkUIServiceExt" }; uint32_t offset = GetOffset(tag, AAFwkLogTag::EXT); if (offset >= sizeof(tagNames) / sizeof(const char*)) { return "AAFwkUN"; diff --git a/services/common/include/json_utils.h b/services/common/include/json_utils.h new file mode 100644 index 0000000000..67c0c6c280 --- /dev/null +++ b/services/common/include/json_utils.h @@ -0,0 +1,45 @@ +/* + * 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_JSON_UTILS_H +#define OHOS_ABILITY_RUNTIME_JSON_UTILS_H + +#include +#include + +#include "nlohmann/json.hpp" +#include "singleton.h" + +namespace OHOS { +namespace AAFwk { +class JsonUtils { +public: + static JsonUtils &GetInstance() + { + static JsonUtils instance; + return instance; + } + ~JsonUtils() = default; + bool LoadConfiguration(const std::string& path, nlohmann::json& jsonBuf, const std::string& defaultPath = ""); + +private: + std::string GetConfigPath(const std::string& path, const std::string& defaultPath); + bool ReadFileInfoJson(const std::string &filePath, nlohmann::json &jsonBuf); + JsonUtils() = default; + DISALLOW_COPY_AND_MOVE(JsonUtils); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_JSON_UTILS_H \ No newline at end of file diff --git a/services/common/include/permission_constants.h b/services/common/include/permission_constants.h index 25f5d28bc4..17535d45a7 100644 --- a/services/common/include/permission_constants.h +++ b/services/common/include/permission_constants.h @@ -42,20 +42,26 @@ constexpr const char* PERMISSION_WRITE_IMAGEVIDEO = "ohos.permission.WRITE_IMAGE constexpr const char* PERMISSION_READ_IMAGEVIDEO = "ohos.permission.READ_IMAGEVIDEO"; constexpr const char* PERMISSION_WRITE_AUDIO = "ohos.permission.WRITE_AUDIO"; constexpr const char* PERMISSION_READ_AUDIO = "ohos.permission.READ_AUDIO"; +constexpr const char* PERMISSION_READ_WRITE_DOWNLOAD = "ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY"; +constexpr const char* PERMISSION_READ_WRITE_DESKTON = "ohos.permission.READ_WRITE_DESKTOP_DIRECTORY"; +constexpr const char* PERMISSION_READ_WRITE_DOCUMENTS = "ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"; constexpr const char* PERMISSION_GRANT_URI_PERMISSION_PRIVILEGED = "ohos.permission.GRANT_URI_PERMISSION_PRIVILEGED"; constexpr const char* PERMISSION_EXEMPT_AS_CALLER = "ohos.permission.EXEMPT_AS_CALLER"; constexpr const char* PERMISSION_EXEMPT_AS_TARGET = "ohos.permission.EXEMPT_AS_TARGET"; constexpr const char* PERMISSION_PREPARE_TERMINATE = "ohos.permission.PREPARE_APP_TERMINATE"; +constexpr const char* PERMISSION_START_RECENT_ABILITY = "ohos.permission.START_RECENT_ABILITY"; constexpr const char* PERMISSION_MANAGE_APP_BOOT = "ohos.permission.MANAGE_APP_BOOT"; constexpr const char* PERMISSION_START_ABILITY_WITH_ANIMATION = "ohos.permission.START_ABILITY_WITH_ANIMATION"; constexpr const char* PERMISSION_MANAGE_APP_BOOT_INTERNAL = "ohos.permission.MANAGE_APP_BOOT_INTERNAL"; constexpr const char* PERMISSION_CONNECT_UI_EXTENSION_ABILITY = "ohos.permission.CONNECT_UI_EXTENSION_ABILITY"; -constexpr const char* PERMISSION_START_RECENT_ABILITY = "ohos.permission.START_RECENT_ABILITY"; constexpr const char* PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT = "ohos.permission.NOTIFY_DEBUG_ASSERT_RESULT"; constexpr const char* PERMISSION_START_SHORTCUT = "ohos.permission.START_SHORTCUT"; constexpr const char* PERMISSION_PRELOAD_APPLICATION = "ohos.permission.PRELOAD_APPLICATION"; constexpr const char* PERMISSION_SET_PROCESS_CACHE_STATE = "ohos.permission.SET_PROCESS_CACHE_STATE"; constexpr const char* PERMISSION_PRELOAD_UI_EXTENSION_ABILITY = "ohos.permission.PRELOAD_UI_EXTENSION_ABILITY"; +constexpr const char* PERMISSION_PRE_START_ATOMIC_SERVICE = "ohos.permission.PRE_START_ATOMIC_SERVICE"; +constexpr const char* PERMISSION_KILL_APP_PROCESSES = "ohos.permission.KILL_APP_PROCESSES"; +constexpr const char* PERMISSION_KILL_PROCESS_DEPENDED_ON_WEB = "ohos.permission.KILL_PROCESS_DEPENDED_ON_ARKWEB"; } // namespace PermissionConstants } // namespace AAFwk } // namespace OHOS diff --git a/services/common/include/permission_verification.h b/services/common/include/permission_verification.h index c45ab2a48a..02f09653e4 100644 --- a/services/common/include/permission_verification.h +++ b/services/common/include/permission_verification.h @@ -75,7 +75,7 @@ struct VerificationInfo { int CheckCallServiceAbilityPermission(const VerificationInfo &verificationInfo) const; - int CheckCallAbilityPermission(const VerificationInfo &verificationInfo) const; + int CheckCallAbilityPermission(const VerificationInfo &verificationInfo, bool isCallByShortcut = false) const; /** * Check if Caller is allowed to start ServiceExtension(Stage) or DataShareExtension(Stage) @@ -99,7 +99,9 @@ struct VerificationInfo { bool VerifyPreloadApplicationPermission() const; - bool VerifySetProcessCachePermission() const; + bool VerifyPreStartAtomicServicePermission() const; + + bool VerifyKillProcessDependedOnWebPermission() const; private: DISALLOW_COPY_AND_MOVE(PermissionVerification); @@ -115,7 +117,7 @@ private: bool JudgeAssociatedWakeUp(const uint32_t accessTokenId, const bool associatedWakeUp) const; - int JudgeInvisibleAndBackground(const VerificationInfo &verificationInfo) const; + int JudgeInvisibleAndBackground(const VerificationInfo &verificationInfo, bool isCallByShortcut = false) const; inline bool IsCallFromSameAccessToken(const uint32_t accessTokenId) const { diff --git a/services/common/include/res_sched_util.h b/services/common/include/res_sched_util.h index 918a10f65d..8639366731 100644 --- a/services/common/include/res_sched_util.h +++ b/services/common/include/res_sched_util.h @@ -35,7 +35,8 @@ public: void ReportAbilitStartInfoToRSS(const AbilityInfo &abilityInfo, int32_t pid, bool isColdStart); void ReportAbilitAssociatedStartInfoToRSS( const AbilityInfo &abilityInfo, int64_t resSchedType, int32_t callerUid, int32_t callerPid); - void ReportEventToRSS(int32_t uid, std::string bundleName, std::string name); + void ReportEventToRSS(const int32_t uid, const std::string &bundleName, const std::string &reason, + const int32_t callerPid = -1); void GetAllFrozenPidsFromRSS(std::unordered_set &frozenPids); private: ResSchedUtil() = default; diff --git a/services/common/include/support_system_ability_permission.h b/services/common/include/support_system_ability_permission.h index bdfd79bb77..e59289d219 100755 --- a/services/common/include/support_system_ability_permission.h +++ b/services/common/include/support_system_ability_permission.h @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parameters.h" namespace OHOS { diff --git a/services/common/include/ui_extension_utils.h b/services/common/include/ui_extension_utils.h index 074aee322e..9873fd01b4 100755 --- a/services/common/include/ui_extension_utils.h +++ b/services/common/include/ui_extension_utils.h @@ -63,7 +63,8 @@ inline std::unordered_set GetUiExtensionSet() AppExecFwk::ExtensionAbilityType::LIVEVIEW_LOCKSCREEN, AppExecFwk::ExtensionAbilityType::SYSPICKER_PHOTOEDITOR, AppExecFwk::ExtensionAbilityType::PHOTO_EDITOR, - AppExecFwk::ExtensionAbilityType::SYSPICKER_AUDIOPICKER + AppExecFwk::ExtensionAbilityType::SYSPICKER_AUDIOPICKER, + AppExecFwk::ExtensionAbilityType::SYS_VISUAL }; } @@ -99,7 +100,8 @@ inline bool IsSystemUIExtension(const AppExecFwk::ExtensionAbilityType type) AppExecFwk::ExtensionAbilityType::AUTO_FILL_SMART, AppExecFwk::ExtensionAbilityType::SYSPICKER_FILEPICKER, AppExecFwk::ExtensionAbilityType::SYSDIALOG_USERAUTH, - AppExecFwk::ExtensionAbilityType::HMS_ACCOUNT + AppExecFwk::ExtensionAbilityType::HMS_ACCOUNT, + AppExecFwk::ExtensionAbilityType::SYS_VISUAL }; return systemUiExtensionSet.find(type) != systemUiExtensionSet.end(); } @@ -120,14 +122,26 @@ inline bool IsSystemCallerNeeded(const AppExecFwk::ExtensionAbilityType type) } // In this collection, extension can be embedded by public app, which requires vertical businesses to ensure security. -inline bool IsPublicCallerForNonModal(const AppExecFwk::ExtensionAbilityType type) +inline bool IsPublicForEmbedded(const AppExecFwk::ExtensionAbilityType type) { - const std::unordered_set callerPublicForNonModalSet = { + const std::unordered_set publicForEmbeddedSet = { AppExecFwk::ExtensionAbilityType::EMBEDDED_UI, // EMBEDDED_UI usage within the app AppExecFwk::ExtensionAbilityType::ADS, + AppExecFwk::ExtensionAbilityType::SYSPICKER_PHOTOPICKER, + AppExecFwk::ExtensionAbilityType::SYSPICKER_MEDIACONTROL, + AppExecFwk::ExtensionAbilityType::SYS_VISUAL, + AppExecFwk::ExtensionAbilityType::AUTO_FILL_SMART + }; + return publicForEmbeddedSet.find(type) != publicForEmbeddedSet.end(); +} + +// In this collection, extension can be embedded by public app, which some UX effects are constrained +inline bool IsPublicForConstrainedEmbedded(const AppExecFwk::ExtensionAbilityType type) +{ + const std::unordered_set publicForConstrainedEmbeddedSet = { AppExecFwk::ExtensionAbilityType::SYSPICKER_PHOTOPICKER }; - return callerPublicForNonModalSet.find(type) != callerPublicForNonModalSet.end(); + return publicForConstrainedEmbeddedSet.find(type) != publicForConstrainedEmbeddedSet.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 2b017c1401..04b4c06309 100644 --- a/services/common/src/ability_manager_radar.cpp +++ b/services/common/src/ability_manager_radar.cpp @@ -18,7 +18,6 @@ #include "ability_manager_errors.h" #include "hisysevent.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFWK { diff --git a/services/common/src/app_utils.cpp b/services/common/src/app_utils.cpp index 696e70f2df..6ba762f91c 100644 --- a/services/common/src/app_utils.cpp +++ b/services/common/src/app_utils.cpp @@ -14,9 +14,9 @@ */ #include "app_utils.h" - +#include "json_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" +#include "nlohmann/json.hpp" #include "parameters.h" #ifdef SUPPORT_GRAPHICS #include "scene_board_judgement.h" @@ -26,30 +26,38 @@ namespace OHOS { namespace AAFwk { namespace { -const std::string BUNDLE_NAME_LAUNCHER = "com.ohos.launcher"; -const std::string BUNDLE_NAME_SCENEBOARD = "com.ohos.sceneboard"; -const std::string LAUNCHER_ABILITY_NAME = "com.ohos.launcher.MainAbility"; -const std::string SCENEBOARD_ABILITY_NAME = "com.ohos.sceneboard.MainAbility"; -const std::string INHERIT_WINDOW_SPLIT_SCREEN_MODE = "persist.sys.abilityms.inherit_window_split_screen_mode"; -const std::string SUPPORT_ANCO_APP = "persist.sys.abilityms.support_anco_app"; -const std::string TIMEOUT_UNIT_TIME_RATIO = "persist.sys.abilityms.timeout_unit_time_ratio"; -const std::string SELECTOR_DIALOG_POSSION = "persist.sys.abilityms.selector_dialog_possion"; -const std::string START_SPECIFIED_PROCESS = "persist.sys.abilityms.start_specified_process"; -const std::string USE_MULTI_RENDER_PROCESS = "persist.sys.abilityms.use_multi_render_process"; -const std::string LIMIT_MAXIMUM_OF_RENDER_PROCESS = "persist.sys.abilityms.limit_maximum_of_render_process"; -const std::string GRANT_PERSIST_URI_PERMISSION = "persist.sys.abilityms.grant_persist_uri_permission"; -const std::string START_OPTIONS_WITH_ANIMATION = "persist.sys.abilityms.start_options_with_animation"; -const std::string MULTI_PROCESS_MODEL = "persist.sys.abilityms.multi_process_model"; -const std::string START_OPTIONS_WITH_PROCESS_OPTION = "persist.sys.abilityms.start_options_with_process_option"; -const std::string MOVE_UI_ABILITY_TO_BACKGROUND_API_ENABLE = +constexpr const char* BUNDLE_NAME_LAUNCHER = "com.ohos.launcher"; +constexpr const char* BUNDLE_NAME_SCENEBOARD = "com.ohos.sceneboard"; +constexpr const char* LAUNCHER_ABILITY_NAME = "com.ohos.launcher.MainAbility"; +constexpr const char* SCENEBOARD_ABILITY_NAME = "com.ohos.sceneboard.MainAbility"; +constexpr const char* INHERIT_WINDOW_SPLIT_SCREEN_MODE = "persist.sys.abilityms.inherit_window_split_screen_mode"; +constexpr const char* SUPPORT_ANCO_APP = "persist.sys.abilityms.support_anco_app"; +constexpr const char* TIMEOUT_UNIT_TIME_RATIO = "persist.sys.abilityms.timeout_unit_time_ratio"; +constexpr const char* SELECTOR_DIALOG_POSSION = "persist.sys.abilityms.selector_dialog_possion"; +constexpr const char* START_SPECIFIED_PROCESS = "persist.sys.abilityms.start_specified_process"; +constexpr const char* USE_MULTI_RENDER_PROCESS = "persist.sys.abilityms.use_multi_render_process"; +constexpr const char* LIMIT_MAXIMUM_OF_RENDER_PROCESS = "persist.sys.abilityms.limit_maximum_of_render_process"; +constexpr const char* GRANT_PERSIST_URI_PERMISSION = "persist.sys.abilityms.grant_persist_uri_permission"; +constexpr const char* START_OPTIONS_WITH_ANIMATION = "persist.sys.abilityms.start_options_with_animation"; +constexpr const char* MULTI_PROCESS_MODEL = "persist.sys.abilityms.multi_process_model"; +constexpr const char* START_OPTIONS_WITH_PROCESS_OPTION = "persist.sys.abilityms.start_options_with_process_option"; +constexpr const char* 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"; +constexpr const char* CONFIG_PATH = "/etc/ability_runtime/resident_process_in_extreme_memory.json"; +constexpr const char* RESIDENT_PROCESS_IN_EXTREME_MEMORY = "residentProcessInExtremeMemory"; +constexpr const char* BUNDLE_NAME = "bundleName"; +constexpr const char* ABILITY_NAME = "abilityName"; +constexpr const char* LAUNCH_EMBEDED_UI_ABILITY = "const.abilityms.launch_embeded_ui_ability"; const std::string SUPPROT_NATIVE_CHILD_PROCESS = "persist.sys.abilityms.start_native_child_process"; const std::string LIMIT_MAXIMUM_EXTENSIONS_OF_PER_PROCESS = - "persist.sys.abilityms.limit_maximum_extensions_of_per_process"; + "const.sys.abilityms.limit_maximum_extensions_of_per_process"; const std::string LIMIT_MAXIMUM_EXTENSIONS_OF_PER_DEVICE = - "persist.sys.abilityms.limit_maximum_extensions_of_per_device"; -const std::string CACHE_EXTENSION_TYPES = "persist.sys.abilityms.cache_extension"; + "const.sys.abilityms.limit_maximum_extensions_of_per_device"; +const std::string CACHE_EXTENSION_TYPES = "const.sys.abilityms.cache_extension"; +constexpr const char* START_ABILITY_WITHOUT_CALLERTOKEN = "/system/etc/start_ability_without_caller_token.json"; +constexpr const char* START_ABILITY_WITHOUT_CALLERTOKEN_PATH = + "/etc/ability_runtime/start_ability_without_caller_token.json"; +constexpr const char* START_ABILITY_WITHOUT_CALLERTOKEN_TITLE = "startAbilityWithoutCallerToken"; } AppUtils::~AppUtils() {} @@ -103,7 +111,7 @@ bool AppUtils::IsSupportAncoApp() isSupportAncoApp_.value = system::GetBoolParameter(SUPPORT_ANCO_APP, false); isSupportAncoApp_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, "isSupportAncoApp is %{public}d", isSupportAncoApp_.value); + TAG_LOGD(AAFwkTag::DEFAULT, "isSupportAncoApp is %{public}d", isSupportAncoApp_.value); return isSupportAncoApp_.value; } @@ -123,7 +131,7 @@ bool AppUtils::IsSelectorDialogDefaultPossion() isSelectorDialogDefaultPossion_.value = system::GetBoolParameter(SELECTOR_DIALOG_POSSION, true); isSelectorDialogDefaultPossion_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, "isSelectorDialogDefaultPossion is %{public}d", isSelectorDialogDefaultPossion_.value); + TAG_LOGD(AAFwkTag::DEFAULT, "isSelectorDialogDefaultPossion is %{public}d", isSelectorDialogDefaultPossion_.value); return isSelectorDialogDefaultPossion_.value; } @@ -133,7 +141,7 @@ bool AppUtils::IsStartSpecifiedProcess() isStartSpecifiedProcess_.value = system::GetBoolParameter(START_SPECIFIED_PROCESS, false); isStartSpecifiedProcess_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, "isStartSpecifiedProcess is %{public}d", isStartSpecifiedProcess_.value); + TAG_LOGD(AAFwkTag::DEFAULT, "isStartSpecifiedProcess is %{public}d", isStartSpecifiedProcess_.value); return isStartSpecifiedProcess_.value; } @@ -143,7 +151,7 @@ bool AppUtils::IsUseMultiRenderProcess() isUseMultiRenderProcess_.value = system::GetBoolParameter(USE_MULTI_RENDER_PROCESS, true); isUseMultiRenderProcess_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, "isUseMultiRenderProcess is %{public}d", isUseMultiRenderProcess_.value); + TAG_LOGD(AAFwkTag::DEFAULT, "isUseMultiRenderProcess is %{public}d", isUseMultiRenderProcess_.value); return isUseMultiRenderProcess_.value; } @@ -153,7 +161,7 @@ bool AppUtils::IsLimitMaximumOfRenderProcess() isLimitMaximumOfRenderProcess_.value = system::GetBoolParameter(LIMIT_MAXIMUM_OF_RENDER_PROCESS, true); isLimitMaximumOfRenderProcess_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, "isLimitMaximumOfRenderProcess_ is %{public}d", isLimitMaximumOfRenderProcess_.value); + TAG_LOGD(AAFwkTag::DEFAULT, "isLimitMaximumOfRenderProcess_ is %{public}d", isLimitMaximumOfRenderProcess_.value); return isLimitMaximumOfRenderProcess_.value; } @@ -163,7 +171,7 @@ bool AppUtils::IsGrantPersistUriPermission() isGrantPersistUriPermission_.value = system::GetBoolParameter(GRANT_PERSIST_URI_PERMISSION, false); isGrantPersistUriPermission_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, "isGrantPersistUriPermission_ is %{public}d", isGrantPersistUriPermission_.value); + TAG_LOGD(AAFwkTag::DEFAULT, "isGrantPersistUriPermission_ is %{public}d", isGrantPersistUriPermission_.value); return isGrantPersistUriPermission_.value; } @@ -173,7 +181,7 @@ bool AppUtils::IsStartOptionsWithAnimation() isStartOptionsWithAnimation_.value = system::GetBoolParameter(START_OPTIONS_WITH_ANIMATION, false); isStartOptionsWithAnimation_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, "isStartOptionsWithAnimation_ is %{public}d", isStartOptionsWithAnimation_.value); + TAG_LOGD(AAFwkTag::DEFAULT, "isStartOptionsWithAnimation_ is %{public}d", isStartOptionsWithAnimation_.value); return isStartOptionsWithAnimation_.value; } @@ -193,7 +201,7 @@ bool AppUtils::IsStartOptionsWithProcessOptions() isStartOptionsWithProcessOptions_.value = system::GetBoolParameter(START_OPTIONS_WITH_PROCESS_OPTION, false); isStartOptionsWithProcessOptions_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, + TAG_LOGD(AAFwkTag::DEFAULT, "isStartOptionsWithProcessOptions_ is %{public}d", isStartOptionsWithProcessOptions_.value); return isStartOptionsWithProcessOptions_.value; } @@ -205,7 +213,7 @@ bool AppUtils::EnableMoveUIAbilityToBackgroundApi() system::GetBoolParameter(MOVE_UI_ABILITY_TO_BACKGROUND_API_ENABLE, true); enableMoveUIAbilityToBackgroundApi_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, + TAG_LOGD(AAFwkTag::DEFAULT, "enableMoveUIAbilityToBackgroundApi_ is %{public}d", enableMoveUIAbilityToBackgroundApi_.value); return enableMoveUIAbilityToBackgroundApi_.value; } @@ -216,7 +224,7 @@ bool AppUtils::IsLaunchEmbededUIAbility() isLaunchEmbededUIAbility_.value = system::GetBoolParameter(LAUNCH_EMBEDED_UI_ABILITY, false); isLaunchEmbededUIAbility_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, "isLaunchEmbededUIAbility_ is %{public}d", isLaunchEmbededUIAbility_.value); + TAG_LOGD(AAFwkTag::DEFAULT, "isLaunchEmbededUIAbility_ is %{public}d", isLaunchEmbededUIAbility_.value); return isLaunchEmbededUIAbility_.value; } @@ -226,10 +234,54 @@ bool AppUtils::IsSupportNativeChildProcess() isSupportNativeChildProcess_.value = system::GetBoolParameter(SUPPROT_NATIVE_CHILD_PROCESS, false); isSupportNativeChildProcess_.isLoaded = true; } - TAG_LOGI(AAFwkTag::DEFAULT, "isSupportNativeChildProcess_ is %{public}d", isSupportNativeChildProcess_.value); + TAG_LOGD(AAFwkTag::DEFAULT, "isSupportNativeChildProcess_ is %{public}d", isSupportNativeChildProcess_.value); return isSupportNativeChildProcess_.value; } +bool AppUtils::IsAllowResidentInExtremeMemory(const std::string& bundleName, const std::string& abilityName) +{ + if (!residentProcessInExtremeMemory_.isLoaded) { + LoadResidentProcessInExtremeMemory(); + residentProcessInExtremeMemory_.isLoaded = true; + } + TAG_LOGD(AAFwkTag::DEFAULT, "isSupportNativeChildProcess_ is %{public}d", isSupportNativeChildProcess_.value); + for (auto &element : residentProcessInExtremeMemory_.value) { + if (bundleName == element.first && + (abilityName == "" || abilityName == element.second)) { + return true; + } + } + return false; +} + +void AppUtils::LoadResidentProcessInExtremeMemory() +{ + nlohmann::json object; + if (!JsonUtils::GetInstance().LoadConfiguration(CONFIG_PATH, object)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "load resident process in extreme memory failed."); + return; + } + if (!object.contains(RESIDENT_PROCESS_IN_EXTREME_MEMORY)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "resident process in extreme memory config not existed."); + return; + } + + for (auto &item : object.at(RESIDENT_PROCESS_IN_EXTREME_MEMORY).items()) { + const nlohmann::json& jsonObject = item.value(); + if (!jsonObject.contains(BUNDLE_NAME) || !jsonObject.at(BUNDLE_NAME).is_string()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to load bundleName."); + return; + } + if (!jsonObject.contains(ABILITY_NAME) || !jsonObject.at(ABILITY_NAME).is_string()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to load abilityName."); + return; + } + std::string bundleName = jsonObject.at(BUNDLE_NAME).get(); + std::string abilityName = jsonObject.at(ABILITY_NAME).get(); + residentProcessInExtremeMemory_.value.emplace_back(std::make_pair(bundleName, abilityName)); + } +} + int32_t AppUtils::GetLimitMaximumExtensionsPerProc() { if (!limitMaximumExtensionsPerProc_.isLoaded) { @@ -255,9 +307,54 @@ int32_t AppUtils::GetLimitMaximumExtensionsPerDevice() std::string AppUtils::GetCacheExtensionTypeList() { - std::string cacheExtAbilityTypeList = system::GetParameter(CACHE_EXTENSION_TYPES, "3;5;17"); + std::string cacheExtAbilityTypeList = system::GetParameter(CACHE_EXTENSION_TYPES, "260"); TAG_LOGD(AAFwkTag::DEFAULT, "cacheExtAbilityTypeList is %{public}s", cacheExtAbilityTypeList.c_str()); return cacheExtAbilityTypeList; } + +bool AppUtils::IsAllowStartAbilityWithoutCallerToken(const std::string& bundleName, const std::string& abilityName) +{ + if (!startAbilityWithoutCallerToken_.isLoaded) { + LoadStartAbilityWithoutCallerToken(); + startAbilityWithoutCallerToken_.isLoaded = true; + } + TAG_LOGD(AAFwkTag::DEFAULT, "isLoaded: %{public}d", startAbilityWithoutCallerToken_.isLoaded); + for (auto &element : startAbilityWithoutCallerToken_.value) { + if (bundleName == element.first && abilityName == element.second) { + TAG_LOGI(AAFwkTag::DEFAULT, "call"); + return true; + } + } + return false; +} + +void AppUtils::LoadStartAbilityWithoutCallerToken() +{ + nlohmann::json object; + if (!JsonUtils::GetInstance().LoadConfiguration( + START_ABILITY_WITHOUT_CALLERTOKEN_PATH, object, START_ABILITY_WITHOUT_CALLERTOKEN)) { + TAG_LOGE(AAFwkTag::DEFAULT, "load start ability without caller token list failed."); + return; + } + if (!object.contains(START_ABILITY_WITHOUT_CALLERTOKEN_TITLE)) { + TAG_LOGE(AAFwkTag::DEFAULT, "start ability without caller token config not existed."); + return; + } + + for (auto &item : object.at(START_ABILITY_WITHOUT_CALLERTOKEN_TITLE).items()) { + const nlohmann::json& jsonObject = item.value(); + if (!jsonObject.contains(BUNDLE_NAME) || !jsonObject.at(BUNDLE_NAME).is_string()) { + TAG_LOGE(AAFwkTag::DEFAULT, "failed to load bundleName."); + return; + } + if (!jsonObject.contains(ABILITY_NAME) || !jsonObject.at(ABILITY_NAME).is_string()) { + TAG_LOGE(AAFwkTag::DEFAULT, "failed to load abilityName."); + return; + } + std::string bundleName = jsonObject.at(BUNDLE_NAME).get(); + std::string abilityName = jsonObject.at(ABILITY_NAME).get(); + startAbilityWithoutCallerToken_.value.emplace_back(std::make_pair(bundleName, abilityName)); + } +} } // namespace AAFwk } // namespace OHOS diff --git a/services/common/src/event_report.cpp b/services/common/src/event_report.cpp index b1e17b3616..872b82eded 100644 --- a/services/common/src/event_report.cpp +++ b/services/common/src/event_report.cpp @@ -15,7 +15,6 @@ #include "event_report.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" namespace OHOS { @@ -106,6 +105,96 @@ void EventReport::SendAppEvent(const EventName &eventName, HiSysEventType type, } } +void EventReport::LogErrorEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo) +{ + HiSysEventWrite( + HiSysEvent::Domain::AAFWK, + name, + type, + EVENT_KEY_USERID, eventInfo.userId, + EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, + EVENT_KEY_MODULE_NAME, eventInfo.moduleName, + EVENT_KEY_ABILITY_NAME, eventInfo.abilityName, + EVENT_KEY_ERROR_CODE, eventInfo.errCode); +} + +void EventReport::LogStartAbilityEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo) +{ + HiSysEventWrite( + HiSysEvent::Domain::AAFWK, + name, + type, + EVENT_KEY_USERID, eventInfo.userId, + EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, + EVENT_KEY_MODULE_NAME, eventInfo.moduleName, + EVENT_KEY_ABILITY_NAME, eventInfo.abilityName); +} + +void EventReport::LogTerminateAbilityEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo) +{ + HiSysEventWrite( + HiSysEvent::Domain::AAFWK, + name, + type, + EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, + EVENT_KEY_ABILITY_NAME, eventInfo.abilityName); +} + +void EventReport::LogAbilityOnForegroundEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo) +{ + HiSysEventWrite( + HiSysEvent::Domain::AAFWK, + name, + type, + EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, + EVENT_KEY_MODULE_NAME, eventInfo.moduleName, + EVENT_KEY_ABILITY_NAME, eventInfo.abilityName, + EVENT_KEY_BUNDLE_TYPE, eventInfo.bundleType, + EVENT_KEY_CALLER_BUNDLE_NAME, eventInfo.callerBundleName); +} + +void EventReport::LogAbilityOnBackgroundEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo) +{ + HiSysEventWrite( + HiSysEvent::Domain::AAFWK, + name, + type, + EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, + EVENT_KEY_MODULE_NAME, eventInfo.moduleName, + EVENT_KEY_ABILITY_NAME, eventInfo.abilityName, + EVENT_KEY_BUNDLE_TYPE, eventInfo.bundleType); +} + +void EventReport::LogAbilityOnActiveEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo) +{ + HiSysEventWrite( + HiSysEvent::Domain::AAFWK, + name, + type, + EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, + EVENT_KEY_MODULE_NAME, eventInfo.moduleName, + EVENT_KEY_ABILITY_NAME, eventInfo.abilityName, + EVENT_KEY_ABILITY_TYPE, eventInfo.abilityType, + EVENT_KEY_BUNDLE_TYPE, eventInfo.bundleType, + EVENT_KEY_CALLER_BUNDLE_NAME, eventInfo.callerBundleName); +} + +void EventReport::LogStartStandardEvent(const std::string &name, HiSysEventType type, const EventInfo &eventInfo) +{ + TAG_LOGD(AAFwkTag::DEFAULT, "EventInfo is [%{public}d, %{public}s, %{public}s, %{public}s]", + eventInfo.userId, eventInfo.bundleName.c_str(), eventInfo.moduleName.c_str(), + eventInfo.abilityName.c_str()); + HiSysEventWrite( + HiSysEvent::Domain::AAFWK, + name, + type, + EVENT_KEY_USERID, eventInfo.userId, + EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, + EVENT_KEY_MODULE_NAME, eventInfo.moduleName, + EVENT_KEY_ABILITY_NAME, eventInfo.abilityName, + EVENT_KEY_ABILITY_NUMBER, eventInfo.abilityNumber); +} + void EventReport::SendAbilityEvent(const EventName &eventName, HiSysEventType type, const EventInfo &eventInfo) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); @@ -114,85 +203,30 @@ void EventReport::SendAbilityEvent(const EventName &eventName, HiSysEventType ty TAG_LOGE(AAFwkTag::DEFAULT, "invalid eventName"); return; } - HILOG_DEBUG("EventName is %{public}s", name.c_str()); switch (eventName) { case EventName::START_ABILITY_ERROR: case EventName::TERMINATE_ABILITY_ERROR: - HiSysEventWrite( - HiSysEvent::Domain::AAFWK, - name, - type, - EVENT_KEY_USERID, eventInfo.userId, - EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, - EVENT_KEY_MODULE_NAME, eventInfo.moduleName, - EVENT_KEY_ABILITY_NAME, eventInfo.abilityName, - EVENT_KEY_ERROR_CODE, eventInfo.errCode); + LogErrorEvent(name, type, eventInfo); break; case EventName::START_ABILITY: - HiSysEventWrite( - HiSysEvent::Domain::AAFWK, - name, - type, - EVENT_KEY_USERID, eventInfo.userId, - EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, - EVENT_KEY_MODULE_NAME, eventInfo.moduleName, - EVENT_KEY_ABILITY_NAME, eventInfo.abilityName); + LogStartAbilityEvent(name, type, eventInfo); break; case EventName::TERMINATE_ABILITY: case EventName::CLOSE_ABILITY: - HiSysEventWrite( - HiSysEvent::Domain::AAFWK, - name, - type, - EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, - EVENT_KEY_ABILITY_NAME, eventInfo.abilityName); + LogTerminateAbilityEvent(name, type, eventInfo); break; case EventName::ABILITY_ONFOREGROUND: - HiSysEventWrite( - HiSysEvent::Domain::AAFWK, - name, - type, - EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, - EVENT_KEY_MODULE_NAME, eventInfo.moduleName, - EVENT_KEY_ABILITY_NAME, eventInfo.abilityName, - EVENT_KEY_BUNDLE_TYPE, eventInfo.bundleType, - EVENT_KEY_CALLER_BUNDLE_NAME, eventInfo.callerBundleName); + LogAbilityOnForegroundEvent(name, type, eventInfo); break; case EventName::ABILITY_ONBACKGROUND: case EventName::ABILITY_ONINACTIVE: - HiSysEventWrite( - HiSysEvent::Domain::AAFWK, - name, - type, - EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, - EVENT_KEY_MODULE_NAME, eventInfo.moduleName, - EVENT_KEY_ABILITY_NAME, eventInfo.abilityName, - EVENT_KEY_BUNDLE_TYPE, eventInfo.bundleType); + LogAbilityOnBackgroundEvent(name, type, eventInfo); break; case EventName::ABILITY_ONACTIVE: - HiSysEventWrite( - HiSysEvent::Domain::AAFWK, - name, - type, - EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, - EVENT_KEY_MODULE_NAME, eventInfo.moduleName, - EVENT_KEY_ABILITY_NAME, eventInfo.abilityName, - EVENT_KEY_ABILITY_TYPE, eventInfo.abilityType, - EVENT_KEY_BUNDLE_TYPE, eventInfo.bundleType, - EVENT_KEY_CALLER_BUNDLE_NAME, eventInfo.callerBundleName); + LogAbilityOnActiveEvent(name, type, eventInfo); break; case EventName::START_STANDARD_ABILITIES: - HILOG_DEBUG("EventInfo is [%{public}d, %{public}s, %{public}s, %{public}s]", eventInfo.userId, - eventInfo.bundleName.c_str(), eventInfo.moduleName.c_str(), eventInfo.abilityName.c_str()); - HiSysEventWrite( - HiSysEvent::Domain::AAFWK, - name, - type, - EVENT_KEY_USERID, eventInfo.userId, - EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName, - EVENT_KEY_MODULE_NAME, eventInfo.moduleName, - EVENT_KEY_ABILITY_NAME, eventInfo.abilityName, - EVENT_KEY_ABILITY_NUMBER, eventInfo.abilityNumber); + LogStartStandardEvent(name, type, eventInfo); break; default: break; diff --git a/services/common/src/ffrt_task_handler_wrap.cpp b/services/common/src/ffrt_task_handler_wrap.cpp index 51e5d522af..cd512176e7 100644 --- a/services/common/src/ffrt_task_handler_wrap.cpp +++ b/services/common/src/ffrt_task_handler_wrap.cpp @@ -14,7 +14,6 @@ */ #include "ffrt_task_handler_wrap.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/common/src/json_utils.cpp b/services/common/src/json_utils.cpp new file mode 100644 index 0000000000..78c2192a85 --- /dev/null +++ b/services/common/src/json_utils.cpp @@ -0,0 +1,95 @@ +/* + * 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 "json_utils.h" +#include +#include +#include +#include + +#include "config_policy_utils.h" +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace AAFwk { +bool JsonUtils::LoadConfiguration(const std::string& path, nlohmann::json& jsonBuf, + const std::string& defaultPath) +{ + std::string configPath = GetConfigPath(path, defaultPath); + TAG_LOGD(AAFwkTag::ABILITYMGR, "config path is: %{public}s", configPath.c_str()); + if (!ReadFileInfoJson(configPath, jsonBuf)) { + return false; + } + return true; +} + +std::string JsonUtils::GetConfigPath(const std::string& path, const std::string& defaultPath) +{ + char buf[MAX_PATH_LEN] = { 0 }; + char *configPath = GetOneCfgFile(path.c_str(), buf, MAX_PATH_LEN); + if (configPath == nullptr || configPath[0] == '\0' || strlen(configPath) > MAX_PATH_LEN) { + return defaultPath; + } + return configPath; +} + +bool JsonUtils::ReadFileInfoJson(const std::string &filePath, nlohmann::json &jsonBuf) +{ + if (access(filePath.c_str(), F_OK) != 0) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Deeplink reserve config not exist."); + return false; + } + + if (filePath.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "File path is empty."); + return false; + } + + char path[PATH_MAX] = {0}; + if (realpath(filePath.c_str(), path) == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "realpath error, errno is %{public}d.", errno); + return false; + } + + std::fstream in; + char errBuf[256]; + errBuf[0] = '\0'; + in.open(path, std::ios_base::in); + if (!in.is_open()) { + strerror_r(errno, errBuf, sizeof(errBuf)); + TAG_LOGE(AAFwkTag::ABILITYMGR, "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::ABILITYMGR, "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::ABILITYMGR, "bad profile file"); + return false; + } + + return true; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/common/src/permission_verification.cpp b/services/common/src/permission_verification.cpp index c851f29542..2f3e1bbe28 100644 --- a/services/common/src/permission_verification.cpp +++ b/services/common/src/permission_verification.cpp @@ -18,12 +18,11 @@ #include "ability_manager_errors.h" #include "accesstoken_kit.h" #include "hilog_tag_wrapper.h" -#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 "hitrace_meter.h" #include "hilog_tag_wrapper.h" namespace OHOS { @@ -55,8 +54,6 @@ bool PermissionVerification::VerifyCallingPermission( const std::string &permissionName, const uint32_t specifyTokenId) const { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::DEFAULT, "VerifyCallingPermission permission %{public}s, specifyTokenId is %{public}u", - permissionName.c_str(), specifyTokenId); auto callerToken = specifyTokenId == 0 ? GetCallingTokenID() : specifyTokenId; TAG_LOGD(AAFwkTag::DEFAULT, "callerToken is %{public}u", callerToken); int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permissionName, false); @@ -209,10 +206,12 @@ int32_t PermissionVerification::VerifyUpdateConfigurationPerm() const int32_t PermissionVerification::VerifyUpdateAPPConfigurationPerm() const { if (VerifyCallingPermission(PermissionConstants::PERMISSION_UPDATE_APP_CONFIGURATION)) { - HILOG_INFO("Verify permission %{public}s succeed.", PermissionConstants::PERMISSION_UPDATE_APP_CONFIGURATION); + TAG_LOGI(AAFwkTag::DEFAULT, + "Verify permission %{public}s succeed.", PermissionConstants::PERMISSION_UPDATE_APP_CONFIGURATION); return ERR_OK; } - HILOG_ERROR("Verify permission %{public}s failed.", PermissionConstants::PERMISSION_UPDATE_APP_CONFIGURATION); + TAG_LOGE(AAFwkTag::DEFAULT, + "Verify permission %{public}s failed.", PermissionConstants::PERMISSION_UPDATE_APP_CONFIGURATION); return ERR_PERMISSION_DENIED; } @@ -297,9 +296,10 @@ int PermissionVerification::CheckCallServiceAbilityPermission(const Verification return ERR_OK; } -int PermissionVerification::CheckCallAbilityPermission(const VerificationInfo &verificationInfo) const +int PermissionVerification::CheckCallAbilityPermission(const VerificationInfo &verificationInfo, + bool isCallByShortcut) const { - return JudgeInvisibleAndBackground(verificationInfo); + return JudgeInvisibleAndBackground(verificationInfo, isCallByShortcut); } int PermissionVerification::CheckCallServiceExtensionPermission(const VerificationInfo &verificationInfo) const @@ -397,16 +397,19 @@ bool PermissionVerification::JudgeAssociatedWakeUp(const uint32_t accessTokenId, return false; } -int PermissionVerification::JudgeInvisibleAndBackground(const VerificationInfo &verificationInfo) const +int PermissionVerification::JudgeInvisibleAndBackground(const VerificationInfo &verificationInfo, + bool isCallByShortcut) const { uint32_t specifyTokenId = verificationInfo.specifyTokenId; - TAG_LOGD(AAFwkTag::DEFAULT, "specifyTokenId = %{public}u", specifyTokenId); + TAG_LOGD(AAFwkTag::DEFAULT, "specifyTokenId = %{public}u, isCallByShortcut %{public}d", + specifyTokenId, isCallByShortcut); if (specifyTokenId == 0 && IPCSkeleton::GetCallingUid() != BROKER_UID && SupportSystemAbilityPermission::IsSupportSaCallPermission() && IsSACall()) { TAG_LOGD(AAFwkTag::DEFAULT, "Support SA call"); return ERR_OK; } - if (!JudgeStartInvisibleAbility(verificationInfo.accessTokenId, verificationInfo.visible, + if (!isCallByShortcut && + !JudgeStartInvisibleAbility(verificationInfo.accessTokenId, verificationInfo.visible, specifyTokenId)) { return ABILITY_VISIBLE_FALSE_DENY_REQUEST; } @@ -466,16 +469,30 @@ bool PermissionVerification::VerifyShellStartExtensionType(int32_t type) const bool PermissionVerification::VerifyPreloadApplicationPermission() const { if (VerifyCallingPermission(PermissionConstants::PERMISSION_PRELOAD_APPLICATION)) { - HILOG_DEBUG("Verify permission %{public}s succeed.", PermissionConstants::PERMISSION_PRELOAD_APPLICATION); + TAG_LOGD(AAFwkTag::DEFAULT, "Verify permission %{public}s succeed.", + PermissionConstants::PERMISSION_PRELOAD_APPLICATION); return true; } - HILOG_ERROR("Verify permission %{public}s failed.", PermissionConstants::PERMISSION_PRELOAD_APPLICATION); + TAG_LOGE(AAFwkTag::DEFAULT, "Verify permission %{public}s failed.", + PermissionConstants::PERMISSION_PRELOAD_APPLICATION); return false; } -bool PermissionVerification::VerifySetProcessCachePermission() const +bool PermissionVerification::VerifyPreStartAtomicServicePermission() const { - if (VerifyCallingPermission(PermissionConstants::PERMISSION_SET_PROCESS_CACHE_STATE)) { + if (VerifyCallingPermission(PermissionConstants::PERMISSION_PRE_START_ATOMIC_SERVICE)) { + TAG_LOGD(AAFwkTag::APPMGR, "verify permission %{public}s succeeded.", + PermissionConstants::PERMISSION_PRE_START_ATOMIC_SERVICE); + return true; + } + TAG_LOGW(AAFwkTag::APPMGR, "verify permission %{public}s failed.", + PermissionConstants::PERMISSION_PRE_START_ATOMIC_SERVICE); + return false; +} + +bool PermissionVerification::VerifyKillProcessDependedOnWebPermission() const +{ + if (IsSACall() && VerifyCallingPermission(PermissionConstants::PERMISSION_KILL_PROCESS_DEPENDED_ON_WEB)) { TAG_LOGD(AAFwkTag::APPMGR, "Permission verification succeeded."); return true; } diff --git a/services/common/src/queue_task_handler_wrap.cpp b/services/common/src/queue_task_handler_wrap.cpp index 4448212154..efd8de7f68 100644 --- a/services/common/src/queue_task_handler_wrap.cpp +++ b/services/common/src/queue_task_handler_wrap.cpp @@ -15,7 +15,6 @@ #include "queue_task_handler_wrap.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/services/common/src/res_sched_util.cpp b/services/common/src/res_sched_util.cpp index 861b90b403..fed66fc3e7 100644 --- a/services/common/src/res_sched_util.cpp +++ b/services/common/src/res_sched_util.cpp @@ -19,7 +19,6 @@ #include "ability_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #ifdef RESOURCE_SCHEDULE_SERVICE_ENABLE #include "res_sched_client.h" #include "res_type.h" @@ -83,7 +82,8 @@ void ResSchedUtil::ReportAbilitAssociatedStartInfoToRSS( #endif } -void ResSchedUtil::ReportEventToRSS(int32_t uid, std::string bundleName, std::string reason) +void ResSchedUtil::ReportEventToRSS(const int32_t uid, const std::string &bundleName, const std::string &reason, + const int32_t callerPid) { #ifdef RESOURCE_SCHEDULE_SERVICE_ENABLE uint32_t resType = ResourceSchedule::ResType::SYNC_RES_TYPE_THAW_ONE_APP; @@ -92,6 +92,7 @@ void ResSchedUtil::ReportEventToRSS(int32_t uid, std::string bundleName, std::st payload.emplace("pid", -1); payload.emplace("bundleName", bundleName); payload.emplace("reason", reason); + payload.emplace("callerPid", callerPid); nlohmann::json reply; TAG_LOGD(AAFwkTag::DEFAULT, "call"); ResourceSchedule::ResSchedClient::GetInstance().ReportSyncEvent(resType, 0, payload, reply); diff --git a/services/common/src/task_handler_wrap.cpp b/services/common/src/task_handler_wrap.cpp index 48cc9072a6..58550bf4d1 100644 --- a/services/common/src/task_handler_wrap.cpp +++ b/services/common/src/task_handler_wrap.cpp @@ -18,7 +18,6 @@ #include #include "cpp/mutex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ffrt_task_utils_wrap.h" #include "queue_task_handler_wrap.h" #include "ffrt_task_handler_wrap.h" diff --git a/services/dataobsmgr/include/concurrent_map.h b/services/dataobsmgr/include/concurrent_map.h index cc603d37c0..c8ee212047 100644 --- a/services/dataobsmgr/include/concurrent_map.h +++ b/services/dataobsmgr/include/concurrent_map.h @@ -181,12 +181,6 @@ public: return count; } - mapped_type &operator[](const key_type &key) noexcept - { - std::lock_guard lock(mutex_); - return entries_[key]; - } - void ForEach(const std::function &action) { if (action == nullptr) { diff --git a/services/dataobsmgr/include/dataobs_mgr_service.h b/services/dataobsmgr/include/dataobs_mgr_service.h index 824e5e8914..78b71d300f 100644 --- a/services/dataobsmgr/include/dataobs_mgr_service.h +++ b/services/dataobsmgr/include/dataobs_mgr_service.h @@ -26,7 +26,6 @@ #include "dataobs_mgr_inner_ext.h" #include "dataobs_mgr_inner_pref.h" #include "dataobs_mgr_stub.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "system_ability.h" #include "task_handler_wrap.h" diff --git a/services/dataobsmgr/include/dataobs_mgr_stub.h b/services/dataobsmgr/include/dataobs_mgr_stub.h index 1cf92c38b7..3addf258b5 100644 --- a/services/dataobsmgr/include/dataobs_mgr_stub.h +++ b/services/dataobsmgr/include/dataobs_mgr_stub.h @@ -22,7 +22,6 @@ #include #include -#include "hilog_wrapper.h" #include "dataobs_mgr_errors.h" namespace OHOS { diff --git a/services/dataobsmgr/src/data_ability_observer_proxy.cpp b/services/dataobsmgr/src/data_ability_observer_proxy.cpp index 403dc21b10..5b752e755b 100644 --- a/services/dataobsmgr/src/data_ability_observer_proxy.cpp +++ b/services/dataobsmgr/src/data_ability_observer_proxy.cpp @@ -15,7 +15,6 @@ #include "data_ability_observer_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "message_parcel.h" namespace OHOS { diff --git a/services/dataobsmgr/src/data_ability_observer_stub.cpp b/services/dataobsmgr/src/data_ability_observer_stub.cpp index 89cd01da1b..c50b71608b 100644 --- a/services/dataobsmgr/src/data_ability_observer_stub.cpp +++ b/services/dataobsmgr/src/data_ability_observer_stub.cpp @@ -16,7 +16,6 @@ #include "data_ability_observer_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "common_utils.h" #include "string_ex.h" diff --git a/services/dataobsmgr/src/dataobs_mgr_client.cpp b/services/dataobsmgr/src/dataobs_mgr_client.cpp index 45332c3593..25403e4f17 100644 --- a/services/dataobsmgr/src/dataobs_mgr_client.cpp +++ b/services/dataobsmgr/src/dataobs_mgr_client.cpp @@ -17,7 +17,6 @@ #include "dataobs_mgr_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "system_ability_definition.h" @@ -80,10 +79,11 @@ DataObsMgrClient::~DataObsMgrClient() */ ErrCode DataObsMgrClient::RegisterObserver(const Uri &uri, sptr dataObserver) { - if (Connect() != SUCCESS) { + auto [errCode, dataObsManger] = GetObsMgr(); + if (errCode != SUCCESS) { return DATAOBS_SERVICE_NOT_CONNECTED; } - auto status = dataObsManger_->RegisterObserver(uri, dataObserver); + auto status = dataObsManger->RegisterObserver(uri, dataObserver); if (status != NO_ERROR) { return status; } @@ -104,10 +104,11 @@ ErrCode DataObsMgrClient::RegisterObserver(const Uri &uri, sptr dataObserver) { - if (Connect() != SUCCESS) { + auto [errCode, dataObsManger] = GetObsMgr(); + if (errCode != SUCCESS) { return DATAOBS_SERVICE_NOT_CONNECTED; } - auto status = dataObsManger_->UnregisterObserver(uri, dataObserver); + auto status = dataObsManger->UnregisterObserver(uri, dataObserver); if (status != NO_ERROR) { return status; } @@ -129,10 +130,11 @@ ErrCode DataObsMgrClient::UnregisterObserver(const Uri &uri, sptrNotifyChange(uri); + return dataObsManger->NotifyChange(uri); } /** @@ -140,43 +142,44 @@ ErrCode DataObsMgrClient::NotifyChange(const Uri &uri) * * @return Returns SUCCESS on success, others on failure. */ -Status DataObsMgrClient::Connect() +std::pair> DataObsMgrClient::GetObsMgr() { std::lock_guard lock(mutex_); if (dataObsManger_ != nullptr) { - return SUCCESS; + return std::make_pair(SUCCESS, dataObsManger_); } sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (systemManager == nullptr) { TAG_LOGE(AAFwkTag::DBOBSMGR, "fail to get Registry"); - return GET_DATAOBS_SERVICE_FAILED; + return std::make_pair(GET_DATAOBS_SERVICE_FAILED, nullptr); } auto remoteObject = systemManager->CheckSystemAbility(DATAOBS_MGR_SERVICE_SA_ID); if (remoteObject == nullptr) { TAG_LOGE(AAFwkTag::DBOBSMGR, "fail to get systemAbility"); - return GET_DATAOBS_SERVICE_FAILED; + return std::make_pair(GET_DATAOBS_SERVICE_FAILED, nullptr); } dataObsManger_ = iface_cast(remoteObject); if (dataObsManger_ == nullptr) { TAG_LOGE(AAFwkTag::DBOBSMGR, "fail to get IDataObsMgr"); - return GET_DATAOBS_SERVICE_FAILED; + return std::make_pair(GET_DATAOBS_SERVICE_FAILED, nullptr); } sptr serviceDeathRecipient(new (std::nothrow) ServiceDeathRecipient(GetInstance())); dataObsManger_->AsObject()->AddDeathRecipient(serviceDeathRecipient); - return SUCCESS; + return std::make_pair(SUCCESS, dataObsManger_); } Status DataObsMgrClient::RegisterObserverExt(const Uri &uri, sptr dataObserver, bool isDescendants) { - if (Connect() != SUCCESS) { + auto [errCode, dataObsManger] = GetObsMgr(); + if (errCode != SUCCESS) { return DATAOBS_SERVICE_NOT_CONNECTED; } - auto status = dataObsManger_->RegisterObserverExt(uri, dataObserver, isDescendants); + auto status = dataObsManger->RegisterObserverExt(uri, dataObserver, isDescendants); if (status != SUCCESS) { return status; } @@ -189,10 +192,11 @@ Status DataObsMgrClient::RegisterObserverExt(const Uri &uri, sptr dataObserver) { - if (Connect() != SUCCESS) { + auto [errCode, dataObsManger] = GetObsMgr(); + if (errCode != SUCCESS) { return DATAOBS_SERVICE_NOT_CONNECTED; } - auto status = dataObsManger_->UnregisterObserverExt(uri, dataObserver); + auto status = dataObsManger->UnregisterObserverExt(uri, dataObserver); if (status != SUCCESS) { return status; } @@ -207,10 +211,11 @@ Status DataObsMgrClient::UnregisterObserverExt(const Uri &uri, sptr dataObserver) { - if (Connect() != SUCCESS) { + auto [errCode, dataObsManger] = GetObsMgr(); + if (errCode != SUCCESS) { return DATAOBS_SERVICE_NOT_CONNECTED; } - auto status = dataObsManger_->UnregisterObserverExt(dataObserver); + auto status = dataObsManger->UnregisterObserverExt(dataObserver); if (status != SUCCESS) { return status; } @@ -220,10 +225,11 @@ Status DataObsMgrClient::UnregisterObserverExt(sptr dataOb Status DataObsMgrClient::NotifyChangeExt(const ChangeInfo &changeInfo) { - if (Connect() != SUCCESS) { + auto [errCode, dataObsManger] = GetObsMgr(); + if (errCode != SUCCESS) { return DATAOBS_SERVICE_NOT_CONNECTED; } - return dataObsManger_->NotifyChangeExt(changeInfo); + return dataObsManger->NotifyChangeExt(changeInfo); } void DataObsMgrClient::ResetService() @@ -236,7 +242,8 @@ void DataObsMgrClient::OnRemoteDied() { std::this_thread::sleep_for(std::chrono::seconds(RESUB_INTERVAL)); ResetService(); - if (Connect() != SUCCESS) { + auto [errCode, dataObsManger] = GetObsMgr(); + if (errCode != SUCCESS) { sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (systemManager == nullptr) { TAG_LOGE(AAFwkTag::DBOBSMGR, "System mgr is nullptr"); diff --git a/services/dataobsmgr/src/dataobs_mgr_inner.cpp b/services/dataobsmgr/src/dataobs_mgr_inner.cpp index ac8e005c76..dc2d0115c3 100644 --- a/services/dataobsmgr/src/dataobs_mgr_inner.cpp +++ b/services/dataobsmgr/src/dataobs_mgr_inner.cpp @@ -17,7 +17,6 @@ #include "data_ability_observer_stub.h" #include "dataobs_mgr_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "common_utils.h" namespace OHOS { diff --git a/services/dataobsmgr/src/dataobs_mgr_inner_ext.cpp b/services/dataobsmgr/src/dataobs_mgr_inner_ext.cpp index c9ee6f9191..1d506a8fb5 100644 --- a/services/dataobsmgr/src/dataobs_mgr_inner_ext.cpp +++ b/services/dataobsmgr/src/dataobs_mgr_inner_ext.cpp @@ -17,7 +17,6 @@ #include "data_ability_observer_stub.h" #include "dataobs_mgr_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "common_utils.h" namespace OHOS { diff --git a/services/dataobsmgr/src/dataobs_mgr_inner_pref.cpp b/services/dataobsmgr/src/dataobs_mgr_inner_pref.cpp index 13a68b0643..90bb8a9d9d 100644 --- a/services/dataobsmgr/src/dataobs_mgr_inner_pref.cpp +++ b/services/dataobsmgr/src/dataobs_mgr_inner_pref.cpp @@ -17,7 +17,6 @@ #include "data_ability_observer_stub.h" #include "dataobs_mgr_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "common_utils.h" namespace OHOS { diff --git a/services/dataobsmgr/src/dataobs_mgr_proxy.cpp b/services/dataobsmgr/src/dataobs_mgr_proxy.cpp index e1c29d1b60..001224ef06 100644 --- a/services/dataobsmgr/src/dataobs_mgr_proxy.cpp +++ b/services/dataobsmgr/src/dataobs_mgr_proxy.cpp @@ -17,7 +17,6 @@ #include "errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "dataobs_mgr_errors.h" #include "common_utils.h" diff --git a/services/dataobsmgr/src/dataobs_mgr_service.cpp b/services/dataobsmgr/src/dataobs_mgr_service.cpp index e060d62bf9..4fdcaf28a2 100644 --- a/services/dataobsmgr/src/dataobs_mgr_service.cpp +++ b/services/dataobsmgr/src/dataobs_mgr_service.cpp @@ -23,7 +23,6 @@ #include "dataobs_mgr_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "system_ability_definition.h" diff --git a/services/dialog_ui/ams_system_dialog/AppScope/app.json b/services/dialog_ui/ams_system_dialog/AppScope/app.json index eb0725a887..7f0ce6c35f 100644 --- a/services/dialog_ui/ams_system_dialog/AppScope/app.json +++ b/services/dialog_ui/ams_system_dialog/AppScope/app.json @@ -2,8 +2,8 @@ "app": { "bundleName": "com.ohos.amsdialog", "vendor": "example", - "versionCode": 1000005, - "versionName": "1.2.0", + "versionCode": 1000007, + "versionName": "1.4.0", "icon": "$media:app_icon", "label": "$string:app_name", "distributedNotificationEnabled": true, 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 c08a6464ab..b663ac45aa 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 @@ -48,7 +48,7 @@ export default class SelectorServiceExtensionAbility extends extension { let phoneShowHapList = []; let jsonIconMap: Map = new Map(); for (let i = 1; i <= globalThis.params.hapList.length; i++) { - console.info(TAG, 'hapList[' + (i - 1).toString() + ']: ' + JSON.stringify(globalThis.params.hapList[i])); + console.info(TAG, 'hapList[' + (i - 1).toString() + ']: ' + JSON.stringify(globalThis.params.hapList[i - 1])); await this.getHapResource(globalThis.params.hapList[i - 1], showHapList, jsonIconMap); if (i % lineNums === 0) { phoneShowHapList.push(showHapList); @@ -65,7 +65,7 @@ export default class SelectorServiceExtensionAbility extends extension { let signalRowShowHapList = []; let signalRowPhoneShowHapList = []; for (let i = 1; i <= globalThis.params.hapList.length; i++) { - console.info(TAG, 'hapList[' + (i - 1).toString() + ']: ' + JSON.stringify(globalThis.params.hapList[i])); + console.info(TAG, 'hapList[' + (i - 1).toString() + ']: ' + JSON.stringify(globalThis.params.hapList[i - 1])); await this.getHapResource(globalThis.params.hapList[i - 1], signalRowShowHapList, jsonIconMap); if (i % signalRowlineNums === 0) { signalRowPhoneShowHapList.push(signalRowShowHapList); @@ -99,19 +99,30 @@ export default class SelectorServiceExtensionAbility extends extension { let appIcon = ''; let type = ''; let userId = Number('0'); + let appIndex = Number(hap.appIndex); if (!globalThis.params.isDefaultSelector) { type = hap.type; userId = Number(hap.userId); } let lableId = Number(hap.label); + if (lableId === 0) { + lableId = Number(hap.bundleLabel); + } let moduleContext = globalThis.selectExtensionContext.createModuleContext(bundleName, moduleName); await moduleContext.resourceManager.getString(lableId).then(value => { - appName = value; + if (appIndex === 0) { + appName = value; + } else { + appName = value + hap.appIndex; + } }).catch(error => { console.error(TAG, 'getString error:' + JSON.stringify(error)); }); let iconId = Number(hap.icon); + if (iconId === 0) { + iconId = Number(hap.bundleIcon); + } await moduleContext.resourceManager.getMediaBase64(iconId).then(value => { appIcon = value; if (appIcon.indexOf('image/json') > -1) { @@ -123,7 +134,8 @@ export default class SelectorServiceExtensionAbility extends extension { imageDescriptor; let foregroundDescriptor: drawableDescriptor.DrawableDescriptor = layeredDrawableDescriptor.getForeground(); if (foregroundDescriptor !== null && foregroundDescriptor !== undefined) { - jsonIconMap.set(bundleName + ':' + moduleName + ':' + abilityName, foregroundDescriptor.getPixelMap()); + jsonIconMap.set(bundleName + ':' + moduleName + ':' + abilityName + ':' + hap.appIndex, + foregroundDescriptor.getPixelMap()); } else { console.error(TAG, 'get foregroundDescriptor is null'); } @@ -136,7 +148,7 @@ export default class SelectorServiceExtensionAbility extends extension { console.error(TAG, 'getMediaBase64 error:' + JSON.stringify(error)); }); showHapList.push(bundleName + '#' + abilityName + '#' + appName + - '#' + appIcon + '#' + moduleName + '#' + type + '#' + userId); + '#' + appIcon + '#' + moduleName + '#' + type + '#' + userId + '#' + appIndex); } async onRequest(want, startId) { diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPcDialog.ets b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPcDialog.ets index 1b99992ab0..f6cebc23be 100644 --- a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPcDialog.ets +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPcDialog.ets @@ -79,6 +79,7 @@ struct SelectorPcDialog { globalThis.abilityWant.bundleName = item.split('#')[0]; globalThis.abilityWant.abilityName = item.split('#')[1]; globalThis.abilityWant.moduleName = item.split('#')[4]; + globalThis.abilityWant.parameters['ohos.extra.param.key.appCloneIndex'] = Number(item.split('#')[7]); globalThis.selectExtensionContext.startAbilityAsCaller(globalThis.abilityWant, (data, error) => { if (error) { console.error(this.TAG + ' startAbility finish, error: ' + JSON.stringify(error)); @@ -148,7 +149,7 @@ struct SelectorPcDialog { let foregroundDescriptor: drawableDescriptor.DrawableDescriptor = layeredDrawableDescriptor.getForeground(); if (foregroundDescriptor !== null && foregroundDescriptor !== undefined) { - globalThis.jsonIconMap.set(bundleName + ':' + moduleName + ':' + abilityName, + globalThis.jsonIconMap.set(bundleName + ':' + moduleName + ':' + abilityName + ':' + hap.appIndex, foregroundDescriptor.getPixelMap()); } else { console.error(this.TAG, 'get foregroundDescriptor is null'); @@ -276,7 +277,7 @@ struct SelectorPcDialog { if (item.split('#')[3] != '') { if (item.split('#')[3].indexOf('image/json') > -1) { Image(globalThis.jsonIconMap.get(item.split('#')[0] + ':' + item.split('#')[4] + - ':' + item.split('#')[1])) + ':' + item.split('#')[1] + ':' + item.split('#')[7])) .height(48) .width(48) .alignSelf(ItemAlign.Center) @@ -372,7 +373,7 @@ struct SelectorPcDialog { if (item.split('#')[3] != '') { if (item.split('#')[3].indexOf('image/json') > -1) { Image(globalThis.jsonIconMap.get(item.split('#')[0] + ':' + item.split('#')[4] + - ':' + item.split('#')[1])) + ':' + item.split('#')[1] + ':' + item.split('#')[7])) .height(48) .width(48) .alignSelf(ItemAlign.Center) diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPhoneDialog.ets b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPhoneDialog.ets index 3a6cab6471..577e3de206 100644 --- a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPhoneDialog.ets +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPhoneDialog.ets @@ -83,6 +83,29 @@ struct SelectorPhoneDialog { @State private hapList: HapInfo[] = []; private TAG = 'SelectorDialog_Phone_Page'; + @Builder + elementIconCombine(iconSrc: string, appIndex: string) { + RelativeContainer() { + Image(iconSrc) + .id('iconLab') + .height(60) + .width(60) + .alignSelf(ItemAlign.Center); + if (appIndex !== '0') { + Image($r('app.media.app_icon_clone_index_' + appIndex)) + .height(18) + .width(18) + .alignRules({ + end: { anchor: 'iconLab', align: HorizontalAlign.End }, + bottom: { anchor: 'iconLab', align: VerticalAlign.Bottom } + }) + } + } + .height(60) + .width(60) + .alignSelf(ItemAlign.Center); + } + aboutToAppear(): void { console.log(this.TAG, 'dialog page appears'); this.hapList = globalThis.params.hapList; @@ -99,6 +122,7 @@ struct SelectorPhoneDialog { globalThis.abilityWant.bundleName = item.split('#')[0]; globalThis.abilityWant.abilityName = item.split('#')[1]; globalThis.abilityWant.moduleName = item.split('#')[4]; + globalThis.abilityWant.parameters['ohos.extra.param.key.appCloneIndex'] = Number(item.split('#')[7]); globalThis.selectExtensionContext.startAbilityAsCaller(globalThis.abilityWant, (data, error) => { if (error) { console.error(this.TAG + ' startAbility finish, error: ' + JSON.stringify(error)); @@ -139,8 +163,8 @@ struct SelectorPhoneDialog { } build() { - Flex({ direction: FlexDirection.Column }) { - Flex({ direction: FlexDirection.Column }) { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) { Text($r('app.string.message_title_selector')) .fontSize(22) .fontWeight(FontWeight.Medium) @@ -158,16 +182,11 @@ struct SelectorPhoneDialog { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) { if (item.split('#')[3] != '') { if (item.split('#')[3].indexOf('image/json') > -1) { - Image(globalThis.jsonIconMap.get(item.split('#')[0] + ':' + item.split('#')[4] + - ':' + item.split('#')[1])) - .height(60) - .width(60) - .alignSelf(ItemAlign.Center); + this.elementIconCombine(globalThis.jsonIconMap.get(item.split('#')[0] + ':' + + item.split('#')[4] + ':' + item.split('#')[1] + ':' + item.split('#')[7]), + item.split('#')[7]); } else { - Image(item.split('#')[3]) - .height(60) - .width(60) - .alignSelf(ItemAlign.Center); + this.elementIconCombine(item.split('#')[3], item.split('#')[7]); } } else { Image($r('app.media.app_icon')) @@ -199,14 +218,15 @@ struct SelectorPhoneDialog { }) } .margin({ top: 10 }) + .align(Alignment.Center) }, item => item) } .columnsTemplate(this.selector.swiper.gridColumns) .rowsTemplate(this.selector.swiper.gridRows) .columnsGap(12) .rowsGap(12) - .margin({ top: 30 }) - .height(210) + .margin({ top: 10 }) + .height(300) }, item => item) } .indicatorStyle({ color: '#bebdc0', selectedColor: '#ff326Ce9', size: 4 }) @@ -232,6 +252,7 @@ struct SelectorPhoneDialog { } .borderRadius(24) .borderWidth(1) + .align(Alignment.Center) .borderColor('#e9e9e9') .backgroundColor('#ffffff') .width('100%') diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/module.json b/services/dialog_ui/ams_system_dialog/entry/src/main/module.json index 1ad3c1f2ea..39f640741f 100644 --- a/services/dialog_ui/ams_system_dialog/entry/src/main/module.json +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/module.json @@ -60,14 +60,14 @@ "label": "$string:SelectorExtAbility_label", "type": "sys/commonUI", "visible": false, - "exported": true + "exported": false }, { "name": "AssertFaultDialog", "icon": "$media:icon", "description": "$string:AssertFaultShareExtAbility_desc", "type": "sys/commonUI", - "visible": true, + "visible": false, "srcEntry": "./ets/ShareExtAbility/AssertFaultShareExtAbility.ts" } ], diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_1.svg b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_1.svg new file mode 100644 index 0000000000..9ffedee3d2 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_1.svg @@ -0,0 +1,10 @@ + + + 画板 + + + + + + + \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_2.svg b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_2.svg new file mode 100644 index 0000000000..ed4b17f123 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_2.svg @@ -0,0 +1,10 @@ + + + 画板备份 6 + + + + + + + \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_3.svg b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_3.svg new file mode 100644 index 0000000000..39852e4570 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_3.svg @@ -0,0 +1,10 @@ + + + 画板备份 7 + + + + + + + \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_4.svg b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_4.svg new file mode 100644 index 0000000000..fbce202557 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_4.svg @@ -0,0 +1,10 @@ + + + 画板备份 8 + + + + + + + \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_5.svg b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_5.svg new file mode 100644 index 0000000000..91c4473567 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/app_icon_clone_index_5.svg @@ -0,0 +1,10 @@ + + + 画板备份 9 + + + + + + + \ No newline at end of file diff --git a/services/quickfixmgr/include/quick_fix_manager_apply_task.h b/services/quickfixmgr/include/quick_fix_manager_apply_task.h index 299f427bcb..0c3a535df9 100644 --- a/services/quickfixmgr/include/quick_fix_manager_apply_task.h +++ b/services/quickfixmgr/include/quick_fix_manager_apply_task.h @@ -44,6 +44,7 @@ public: void HandlePatchDeleted(); bool SetQuickFixInfo(const std::shared_ptr &result); + bool ExtractQuickFixDataFromJson(nlohmann::json& resultJson); bool GetRunningState(); void RemoveTimeoutTask(); diff --git a/services/quickfixmgr/src/quick_fix_manager_apply_task.cpp b/services/quickfixmgr/src/quick_fix_manager_apply_task.cpp index 731651b910..b9e707d890 100644 --- a/services/quickfixmgr/src/quick_fix_manager_apply_task.cpp +++ b/services/quickfixmgr/src/quick_fix_manager_apply_task.cpp @@ -20,7 +20,6 @@ #include "common_event_manager.h" #include "common_event_support.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "quick_fix_callback_stub.h" #include "quick_fix_error_utils.h" @@ -50,7 +49,7 @@ constexpr const char *PATCH_VERSION = "patchVersion"; // timeout task constexpr const char *TIMEOUT_TASK_NAME = "timeoutTask"; -constexpr int64_t TIMEOUT_TASK_DELAY_TIME = 5000; +constexpr int64_t TIMEOUT_TASK_DELAY_TIME = 3 * 60 * 1000; } // namespace class QuickFixManagerStatusCallback : public AppExecFwk::QuickFixStatusCallbackHost { @@ -535,13 +534,8 @@ void QuickFixManagerApplyTask::RemoveTimeoutTask() eventHandler_->RemoveTask(TIMEOUT_TASK_NAME); } -bool QuickFixManagerApplyTask::SetQuickFixInfo(const std::shared_ptr &result) +bool QuickFixManagerApplyTask::ExtractQuickFixDataFromJson(nlohmann::json& resultJson) { - auto resultJson = nlohmann::json::parse(result->ToString(), nullptr, false); - if (resultJson.is_discarded()) { - TAG_LOGE(AAFwkTag::QUICKFIX, "failed to parse json sting."); - return false; - } if (!resultJson.contains(QUICK_FIX_BUNDLE_NAME) || !resultJson.at(QUICK_FIX_BUNDLE_NAME).is_string()) { TAG_LOGE(AAFwkTag::QUICKFIX, "Invalid bundleName."); return false; @@ -573,6 +567,19 @@ bool QuickFixManagerApplyTask::SetQuickFixInfo(const std::shared_ptr(resultJson.at(QUICK_FIX_TYPE).get()); + return true; +} + +bool QuickFixManagerApplyTask::SetQuickFixInfo(const std::shared_ptr &result) +{ + auto resultJson = nlohmann::json::parse(result->ToString(), nullptr, false); + if (resultJson.is_discarded()) { + TAG_LOGE(AAFwkTag::QUICKFIX, "failed to parse json sting."); + return false; + } + if (ExtractQuickFixDataFromJson(resultJson) != true) { + return false; + } if (type_ != AppExecFwk::QuickFixType::PATCH && type_ != AppExecFwk::QuickFixType::HOT_RELOAD) { TAG_LOGE(AAFwkTag::QUICKFIX, "Quick fix type is invalid."); return false; diff --git a/services/quickfixmgr/src/quick_fix_manager_service.cpp b/services/quickfixmgr/src/quick_fix_manager_service.cpp index ab79154d7f..c2fab8196a 100644 --- a/services/quickfixmgr/src/quick_fix_manager_service.cpp +++ b/services/quickfixmgr/src/quick_fix_manager_service.cpp @@ -17,7 +17,6 @@ #include "bundle_mgr_helper.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "hitrace_meter.h" #include "permission_verification.h" #include "quick_fix_error_utils.h" @@ -124,7 +123,7 @@ int32_t QuickFixManagerService::GetApplyedQuickFixInfo(const std::string &bundle int32_t QuickFixManagerService::RevokeQuickFix(const std::string &bundleName) { - TAG_LOGD(AAFwkTag::QUICKFIX, "Called."); + TAG_LOGD(AAFwkTag::QUICKFIX, "called"); if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { TAG_LOGE(AAFwkTag::QUICKFIX, "The caller is not system-app, can not use system-api"); return QUICK_FIX_NOT_SYSTEM_APP; diff --git a/services/quickfixmgr/src/quick_fix_manager_service_ability.cpp b/services/quickfixmgr/src/quick_fix_manager_service_ability.cpp index 5a8dca5bb9..4ddebdbebc 100644 --- a/services/quickfixmgr/src/quick_fix_manager_service_ability.cpp +++ b/services/quickfixmgr/src/quick_fix_manager_service_ability.cpp @@ -16,7 +16,6 @@ #include "quick_fix_manager_service_ability.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "system_ability_definition.h" namespace OHOS { diff --git a/services/uripermmgr/BUILD.gn b/services/uripermmgr/BUILD.gn index 785746ebaf..6a8c50b3ea 100644 --- a/services/uripermmgr/BUILD.gn +++ b/services/uripermmgr/BUILD.gn @@ -28,6 +28,7 @@ config("upms_config") { } libupms_sources = [ + "src/file_permission_manager.cpp", "src/tokenid_permission.cpp", "src/uri_permission_manager_service.cpp", "src/uri_permission_manager_stub_impl.cpp", @@ -69,10 +70,12 @@ ohos_shared_library("libupms") { "ability_base:zuri", "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", + "app_file_service:fileuri_native", "background_task_mgr:bgtaskmgr_innerkits", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", + "common_event_service:cesfwk_core", "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", "graphic_2d:color_manager", @@ -88,6 +91,9 @@ ohos_shared_library("libupms") { "samgr:samgr_proxy", "storage_service:storage_manager_sa_proxy", ] + if (ability_runtime_feature_sandboxmanager) { + external_deps += [ "sandbox_manager:libsandbox_manager_sdk" ] + } if (ability_runtime_graphics) { external_deps += [ "i18n:intl_util" ] } @@ -98,6 +104,13 @@ ohos_shared_library("libupms") { # Note: Just for test ohos_static_library("libupms_static") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../test/cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" configs = [ "${ability_runtime_innerkits_path}/app_manager:appmgr_sdk_config", "${ability_runtime_services_path}/common:common_config", @@ -120,9 +133,11 @@ ohos_static_library("libupms_static") { "ability_base:zuri", "ability_runtime:ability_deps_wrapper", "access_token:libaccesstoken_sdk", + "app_file_service:fileuri_native", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", + "common_event_service:cesfwk_core", "common_event_service:cesfwk_innerkits", "hilog:libhilog", "init:libbeget_proxy", @@ -133,6 +148,10 @@ ohos_static_library("libupms_static") { "storage_service:storage_manager_sa_proxy", ] + if (ability_runtime_feature_sandboxmanager) { + external_deps += [ "sandbox_manager:libsandbox_manager_sdk" ] + } + subsystem_name = "ability" part_name = "ability_runtime" } diff --git a/services/uripermmgr/include/file_permission_manager.h b/services/uripermmgr/include/file_permission_manager.h new file mode 100644 index 0000000000..922b478243 --- /dev/null +++ b/services/uripermmgr/include/file_permission_manager.h @@ -0,0 +1,49 @@ +/* + * 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_AAFWK_FILE_PERMISSION_MANAGER +#define OHOS_AAFWK_FILE_PERMISSION_MANAGER + +#include +#include +#include +#include "uri.h" +#include "sandbox_manager_kit.h" + +namespace OHOS { +namespace AAFwk { +using namespace AccessControl::SandboxManager; +typedef enum OperationMode { + READ_MODE = 1 << 0, + WRITE_MODE = 1 << 1, +} OperationMode; + +struct PathPolicyInfo { + std::string path = ""; + uint32_t mode = OperationMode::READ_MODE; +}; + +class FilePermissionManager { +public: + static std::vector + CheckUriPersistentPermission(std::vector &uriVec, + uint32_t callerTokenId, uint32_t flag, + std::vector &pathPolicies); + + static PolicyInfo GetPathPolicyInfoFromUri(Uri &uri, uint32_t flag, const std::string &bundleName = ""); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_AAFWK_FILE_PERMISSION_MANAGER diff --git a/services/uripermmgr/include/uri_permission_manager_stub_impl.h b/services/uripermmgr/include/uri_permission_manager_stub_impl.h index 561b5b7aa2..e4b337f189 100644 --- a/services/uripermmgr/include/uri_permission_manager_stub_impl.h +++ b/services/uripermmgr/include/uri_permission_manager_stub_impl.h @@ -143,6 +143,10 @@ private: void RemoveUriRecord(std::vector &uriList, const TokenId tokenId, int32_t abilityId); + bool VerifySubDirUriPermission(const std::string &uriStr, uint32_t newFlag, uint32_t tokenId); + + bool IsDistributedSubDirUri(const std::string &inputUri, const std::string &cachedUri); + class ProxyDeathRecipient : public IRemoteObject::DeathRecipient { public: explicit ProxyDeathRecipient(ClearProxyCallback&& proxy) : proxy_(proxy) {} diff --git a/services/uripermmgr/src/file_permission_manager.cpp b/services/uripermmgr/src/file_permission_manager.cpp new file mode 100644 index 0000000000..8cfada8603 --- /dev/null +++ b/services/uripermmgr/src/file_permission_manager.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 "file_permission_manager.h" + +#include "accesstoken_kit.h" +#include "file_uri.h" +#include "hilog_tag_wrapper.h" +#include "ipc_skeleton.h" +#include "permission_constants.h" +#include "permission_verification.h" +#include "tokenid_kit.h" +#include "uri.h" + +namespace OHOS { +namespace AAFwk { +constexpr const uint32_t SANDBOX_MANAGER_OK = 0; +const std::string FILE_MANAGER_AUTHORITY = "docs"; +const std::string DOWNLOAD_PATH = "/storage/Users/currentUser/Download"; +const std::string DESKTOP_PATH = "/storage/Users/currentUser/Desktop"; +const std::string DOCUMENTS_PATH = "/storage/Users/currentUser/Documents"; +const std::string CURRENTUSER = "currentUser"; + +static bool CheckPermission(uint64_t tokenCaller, const std::string &permission) +{ + return PermissionVerification::GetInstance()->VerifyPermissionByTokenId(tokenCaller, permission); +} + +static bool CheckFileManagerUriPermission(uint64_t providerTokenId, std::string &path) +{ + if (path.find(DOWNLOAD_PATH) == 0) { + return CheckPermission(providerTokenId, PermissionConstants::PERMISSION_READ_WRITE_DOWNLOAD); + } + if (path.find(DESKTOP_PATH) == 0) { + return CheckPermission(providerTokenId, PermissionConstants::PERMISSION_READ_WRITE_DESKTON); + } + if (path.find(DOCUMENTS_PATH) == 0) { + return CheckPermission(providerTokenId, PermissionConstants::PERMISSION_READ_WRITE_DOCUMENTS); + } + return false; +} + +PolicyInfo FilePermissionManager::GetPathPolicyInfoFromUri(Uri &uri, uint32_t flag, const std::string &bundleName) +{ + AppFileService::ModuleFileUri::FileUri fileUri(uri.ToString()); + std::string path = fileUri.GetRealPathBySA(bundleName); + PolicyInfo policyInfo; + policyInfo.path = path; + policyInfo.mode = (flag & (OperationMode::READ_MODE | OperationMode::WRITE_MODE)); + return policyInfo; +} + +std::vector FilePermissionManager::CheckUriPersistentPermission(std::vector &uriVec, + uint32_t callerTokenId, uint32_t flag, std::vector &pathPolicies) +{ + TAG_LOGI(AAFwkTag::URIPERMMGR, + "CheckUriPersistentPermission called, size of uri is %{public}zu", uriVec.size()); + std::vector resultCodes(uriVec.size(), false); + pathPolicies.clear(); + if (CheckPermission(callerTokenId, PermissionConstants::PERMISSION_FILE_ACCESS_MANAGER)) { + for (size_t i = 0; i < uriVec.size(); i++) { + resultCodes[i] = true; + PolicyInfo policyInfo = GetPathPolicyInfoFromUri(uriVec[i], flag); + pathPolicies.emplace_back(policyInfo); + } + return resultCodes; + } + std::vector resultIndex; + std::vector persistPolicys; + for (size_t i = 0; i < uriVec.size(); i++) { + PolicyInfo policyInfo = GetPathPolicyInfoFromUri(uriVec[i], flag); + pathPolicies.emplace_back(policyInfo); + if (uriVec[i].GetAuthority() == FILE_MANAGER_AUTHORITY && + CheckFileManagerUriPermission(callerTokenId, policyInfo.path)) { + resultCodes[i] = true; + continue; + } + resultIndex.emplace_back(i); + persistPolicys.emplace_back(policyInfo); + } + + std::vector persistResultCodes; + int32_t ret = SandboxManagerKit::CheckPersistPolicy(callerTokenId, persistPolicys, persistResultCodes); + if (ret == SANDBOX_MANAGER_OK && persistResultCodes.size() == resultIndex.size()) { + for (size_t i = 0; i < persistResultCodes.size(); i++) { + auto index = resultIndex[i]; + resultCodes[index] = persistResultCodes[i]; + } + } + return resultCodes; +} +} +} diff --git a/services/uripermmgr/src/uri_permission_manager_service.cpp b/services/uripermmgr/src/uri_permission_manager_service.cpp index 38355abed9..504b406a2e 100644 --- a/services/uripermmgr/src/uri_permission_manager_service.cpp +++ b/services/uripermmgr/src/uri_permission_manager_service.cpp @@ -16,7 +16,6 @@ #include "uri_permission_manager_service.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" diff --git a/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp b/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp index 9e99f4892b..ea62066ae0 100644 --- a/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp +++ b/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp @@ -21,7 +21,6 @@ #include "accesstoken_kit.h" #include "app_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "in_process_call_wrapper.h" #include "ipc_skeleton.h" @@ -76,11 +75,51 @@ bool UriPermissionManagerStubImpl::VerifyUriPermission(const Uri &uri, uint32_t return true; } } + TAG_LOGI(AAFwkTag::URIPERMMGR, "Uri permission not exists."); + return false; + } + return VerifySubDirUriPermission(uriStr, newFlag, tokenId); +} + +bool UriPermissionManagerStubImpl::VerifySubDirUriPermission(const std::string &uriStr, + uint32_t newFlag, uint32_t tokenId) +{ + auto iPos = uriStr.find(CLOUND_DOCS_URI_MARK); + if (iPos == std::string::npos) { + TAG_LOGI(AAFwkTag::URIPERMMGR, "Local uri not support to verify sub directory uri permission."); + return false; + } + + for (auto search = uriMap_.rbegin(); search != uriMap_.rend(); ++search) { + if (!IsDistributedSubDirUri(uriStr, search->first)) { + continue; + } + auto& list = search->second; + for (auto it = list.begin(); it != list.end(); it++) { + if ((it->targetTokenId == tokenId) && ((it->flag | FLAG_READ_URI) & newFlag) != 0) { + TAG_LOGD(AAFwkTag::URIPERMMGR, "have uri permission."); + return true; + } + } + break; } TAG_LOGI(AAFwkTag::URIPERMMGR, "Uri permission not exists."); return false; } +bool UriPermissionManagerStubImpl::IsDistributedSubDirUri(const std::string &inputUri, const std::string &cachedUri) +{ + auto iPos = inputUri.find(CLOUND_DOCS_URI_MARK); + auto cPos = cachedUri.find(CLOUND_DOCS_URI_MARK); + if ((iPos == std::string::npos) || (cPos == std::string::npos)) { + TAG_LOGI(AAFwkTag::URIPERMMGR, "The uri is not distributed file uri."); + return false; + } + std::string iTempUri = inputUri.substr(0, iPos); + std::string cTempUri = cachedUri.substr(0, cPos); + return iTempUri.find(cTempUri + "/") == 0; +} + int UriPermissionManagerStubImpl::GrantUriPermission(const Uri &uri, unsigned int flag, const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId, int32_t abilityId) { @@ -156,7 +195,7 @@ int32_t UriPermissionManagerStubImpl::GrantUriPermissionPrivileged(const std::ve int UriPermissionManagerStubImpl::GrantUriPermissionInner(const std::vector &uriVec, unsigned int flag, const std::string targetBundleName, int32_t appIndex, uint32_t initiatorTokenId, int32_t abilityId) { - TAG_LOGD(AAFwkTag::URIPERMMGR, "Called."); + TAG_LOGD(AAFwkTag::URIPERMMGR, "called"); flag &= FLAG_READ_WRITE_URI; uint32_t targetTokenId = 0; auto ret = UPMSUtils::GetTokenIdByBundleName(targetBundleName, appIndex, targetTokenId); @@ -171,8 +210,6 @@ int UriPermissionManagerStubImpl::GrantUriPermissionInner(const std::vector recordId = abilityId; appTokenId = initiatorTokenId; auto callerName = UPMSUtils::GetCallerNameByTokenId(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, recordId); @@ -214,7 +251,7 @@ int32_t UriPermissionManagerStubImpl::CheckCalledBySandBox() } auto callerPid = IPCSkeleton::GetCallingPid(); bool isSandbox = false; - if (appMgr_->JudgeSandboxByPid(callerPid, isSandbox) != ERR_OK) { + if (IN_PROCESS_CALL(appMgr_->JudgeSandboxByPid(callerPid, isSandbox)) != ERR_OK) { TAG_LOGE(AAFwkTag::URIPERMMGR, "JudgeSandboxByPid failed."); return INNER_ERR; } diff --git a/test/fuzztest/BUILD.gn b/test/fuzztest/BUILD.gn index c3b6b2de52..9ba018af56 100644 --- a/test/fuzztest/BUILD.gn +++ b/test/fuzztest/BUILD.gn @@ -17,9 +17,36 @@ group("fuzztest") { testonly = true deps = [ + "abilityappdfrapplicationanrlistener_fuzzer:fuzztest", + "abilityappmgrapprunningmanager_fuzzer:fuzztest", + "abilityappmgrpagestatedata_fuzzer:fuzztest", + "abilityappmgrrenderstatedata_fuzzer:fuzztest", + "abilityappmgrrenderstateobservermanager_fuzzer:fuzztest", + "abilityappmgrrunningmultiinfo_fuzzer:fuzztest", "abilityattachtimeout_fuzzer:fuzztest", + "abilityautostartupdatamanagera_fuzzer:fuzztest", + "abilityautostartupdatamanagerb_fuzzer:fuzztest", + "abilityautostartupservicea_fuzzer:fuzztest", + "abilityautostartupserviceb_fuzzer:fuzztest", + "abilitybackgroundconnection_fuzzer:fuzztest", + "abilitycachemanagera_fuzzer:fuzztest", + "abilitychildprocessinfo_fuzzer:fuzztest", + "abilitychildprocessrecord_fuzzer:fuzztest", "abilityconnectionstub_fuzzer:fuzztest", "abilitycontext_fuzzer:fuzztest", + "abilitydebugdeal_fuzzer:fuzztest", + "abilitydebugresponseproxy_fuzzer:fuzztest", + "abilityeventutil_fuzzer:fuzztest", + "abilityfirstframestateobservermanager_fuzzer:fuzztest", + "abilityforegroundstateobserverproxy_fuzzer:fuzztest", + "abilityframeworksnativejsworker_fuzzer:fuzztest", + "abilityframeworksnativeohosjsenvlogger_fuzzer:fuzztest", + "abilityinterfacesappmanageramsmgrstub_fuzzer:fuzztest", + "abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer:fuzztest", + "abilityinterfacesappmgrappdebuglistenerproxy_fuzzer:fuzztest", + "abilityinterfacesappmgrchildschedulerproxy_fuzzer:fuzztest", + "abilityinterfacesappmgrnativechildnotifyproxy_fuzzer:fuzztest", + "abilitymanagereventsubscriber_fuzzer:fuzztest", "abilitymanagerserviceb_fuzzer:fuzztest", "abilitymanagerservicec_fuzzer:fuzztest", "abilitymanagerserviced_fuzzer:fuzztest", @@ -33,7 +60,23 @@ group("fuzztest") { "abilitymanagerservicesecond_fuzzer:fuzztest", "abilitymanagerservicesixth_fuzzer:fuzztest", "abilitymanagerservicethird_fuzzer:fuzztest", + "abilitymgrabilitymanagerstub_fuzzer:fuzztest", + "abilitymgrappexitreasonhelper_fuzzer:fuzztest", + "abilitymgrcontrolinterceptor_fuzzer:fuzztest", + "abilitymgrdisposedruleinterceptor_fuzzer:fuzztest", + "abilitymgrecologicalruleinterceptor_fuzzer:fuzztest", + "abilitymgrecologicalrulemgrserviceparam_fuzzer:fuzztest", + "abilitymgrextensionrecord_fuzzer:fuzztest", + "abilitymgrinsightintentexecutemanager_fuzzer:fuzztest", + "abilitymgrinsightintentexecuteresult_fuzzer:fuzztest", + "abilitymgrinsightintentutils_fuzzer:fuzztest", + "abilitymgrinterceptorexecuter_fuzzer:fuzztest", + "abilitymgrjumpinterceptor_fuzzer:fuzztest", + "abilitymgrrdbparserutil_fuzzer:fuzztest", "abilitymgrrest_fuzzer:fuzztest", + "abilitymgrrestartappmanager_fuzzer:fuzztest", + "abilitymgruiextensionrecord_fuzzer:fuzztest", + "abilitymgruiextensionsessioninfo_fuzzer:fuzztest", "abilityrunningrecord_fuzzer:fuzztest", "abilitystubabilityrecovery_fuzzer:fuzztest", "abilitystubabilityrecoveryenable_fuzzer:fuzztest", @@ -93,6 +136,7 @@ group("fuzztest") { "abilitystubgettopabilitytoken_fuzzer:fuzztest", "abilitystubgetwantsender_fuzzer:fuzztest", "abilitystubgetwantsendinfo_fuzzer:fuzztest", + "abilitystubinterface_fuzzer:fuzztest", "abilitystubisramconstraineddevice_fuzzer:fuzztest", "abilitystubisrunninginstabilitytest_fuzzer:fuzztest", "abilitystubkillprocess_fuzzer:fuzztest", @@ -167,16 +211,23 @@ group("fuzztest") { "addabilitystagedone_fuzzer:fuzztest", "amsmanager_fuzzer:fuzztest", "amsmgrscheduler_fuzzer:fuzztest", + "appforegroundstateobserverproxy_fuzzer:fuzztest", "applifecycledeal_fuzzer:fuzztest", "appmanager_fuzzer:fuzztest", "appmgrclientrest_fuzzer:fuzztest", "appmgrrest_fuzzer:fuzztest", + "appmgrstub_fuzzer:fuzztest", + "apprunningstatusproxy_fuzzer:fuzztest", "appstateobservermanager_fuzzer:fuzztest", + "assertfaultcallbackdeathmgr_fuzzer:fuzztest", "attachabilitythread_fuzzer:fuzztest", "attachrenderprocess_fuzzer:fuzztest", "blockability_fuzzer:fuzztest", "blockamsservice_fuzzer:fuzztest", "blockappservice_fuzzer:fuzztest", + "bundlemgrhelper_fuzzer:fuzztest", + "cacheprocessmanagera_fuzzer:fuzztest", + "cacheprocessmanagerb_fuzzer:fuzztest", "cancelwantsender_fuzzer:fuzztest", "cleanallmissions_fuzzer:fuzztest", "cleanmission_fuzzer:fuzztest", @@ -189,6 +240,7 @@ group("fuzztest") { "connectionstatemanager_fuzzer:fuzztest", "continueability_fuzzer:fuzztest", "continuemission_fuzzer:fuzztest", + "crowdtestinterceptor_fuzzer:fuzztest", "dataabilitymanager_fuzzer:fuzztest", "delegatordoabilityforeground_fuzzer:fuzztest", "doabilitybackground_fuzzer:fuzztest", @@ -196,6 +248,9 @@ group("fuzztest") { "dumpabilityinfodone_fuzzer:fuzztest", "dumpstate_fuzzer:fuzztest", "dumpsysstate_fuzzer:fuzztest", + "extensioncontrolinterceptor_fuzzer:fuzztest", + "extensionrecordmanagera_fuzzer:fuzztest", + "faultdata_fuzzer:fuzztest", "forcetimeoutfortest_fuzzer:fuzztest", "freeinstallabilityfromremote_fuzzer:fuzztest", "getabilityrunninginfos_fuzzer:fuzztest", @@ -210,6 +265,8 @@ group("fuzztest") { "getwantsender_fuzzer:fuzztest", "handledlpapp_fuzzer:fuzztest", "isramconstraineddevice_fuzzer:fuzztest", + "jsabilityautostartupmanager_fuzzer:fuzztest", + "jsabilityautostartupmanager_fuzzer:fuzztest", "killapplication_fuzzer:fuzztest", "killapplicationself_fuzzer:fuzztest", "killprocessbyabilitytoken_fuzzer:fuzztest", @@ -226,6 +283,7 @@ group("fuzztest") { "missionlistmanagersecond_fuzzer:fuzztest", "missionlistmanagerthird_fuzzer:fuzztest", "modulerunningrecord_fuzzer:fuzztest", + "napicommonwant_fuzzer:fuzztest", "notifycompletecontinuation_fuzzer:fuzztest", "notifycontinuationresult_fuzzer:fuzztest", "notifymemorylevel_fuzzer:fuzztest", @@ -239,10 +297,12 @@ group("fuzztest") { "registermissionlistener_fuzzer:fuzztest", "releasedataability_fuzzer:fuzztest", "remotemissionlistenerstub_fuzzer:fuzztest", + "renderstateobserverproxy_fuzzer:fuzztest", "scheduleacceptwantdone_fuzzer:fuzztest", "schedulecommandabilitydone_fuzzer:fuzztest", "scheduleconnectabilitydone_fuzzer:fuzztest", "scheduledisconnectabilitydone_fuzzer:fuzztest", + "screenunlockinterceptor_fuzzer:fuzztest", "sendresulttoability_fuzzer:fuzztest", "setabilitycontroller_fuzzer:fuzztest", "setmissioncontinuestate_fuzzer:fuzztest", @@ -250,7 +310,9 @@ group("fuzztest") { "setmissionlabel_fuzzer:fuzztest", "startability_fuzzer:fuzztest", "startabilitybycall_fuzzer:fuzztest", + "startabilityutils_fuzzer:fuzztest", "startcontinuation_fuzzer:fuzztest", + "startotherappinterceptor_fuzzer:fuzztest", "startrenderprocess_fuzzer:fuzztest", "startserviceextensionability_fuzzer:fuzztest", "startspecifiedability_fuzzer:fuzztest", @@ -264,6 +326,8 @@ group("fuzztest") { "stopuser_fuzzer:fuzztest", "systemabilitytokencallbackstub_fuzzer:fuzztest", "terminateability_fuzzer:fuzztest", + "uiabilitylifecyclemanagera_fuzzer:fuzztest", + "uiabilitylifecyclemanagerb_fuzzer:fuzztest", "unlockmissionforcleanup_fuzzer:fuzztest", "unregisterabilitylifecyclecallback_fuzzer:fuzztest", "unregisterapplicationstateobserver_fuzzer:fuzztest", diff --git a/test/fuzztest/abilityappdebuginfo_fuzzer/BUILD.gn b/test/fuzztest/abilityappdebuginfo_fuzzer/BUILD.gn new file mode 100644 index 0000000000..97372cb7e6 --- /dev/null +++ b/test/fuzztest/abilityappdebuginfo_fuzzer/BUILD.gn @@ -0,0 +1,63 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +##############################fuzztest########################################## +module_output_path = "ability_runtime/appmgrservice" +ohos_fuzztest("AbilityAppDebugInfoFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilityappdebuginfo_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityappdebuginfo_fuzzer.cpp" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:want", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "samgr:samgr_proxy", + "window_manager:libwm", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAppDebugInfoFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityappdebuginfo_fuzzer/abilityappdebuginfo_fuzzer.cpp b/test/fuzztest/abilityappdebuginfo_fuzzer/abilityappdebuginfo_fuzzer.cpp new file mode 100644 index 0000000000..fac8dc9818 --- /dev/null +++ b/test/fuzztest/abilityappdebuginfo_fuzzer/abilityappdebuginfo_fuzzer.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "abilityappdebuginfo_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "app_debug_info.h" +#undef protected +#undef private +#include "parcel.h" +#include +#include "securec.h" +#include "configuration.h" + +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptrappDebugInfo = std::make_shared(); + if (appDebugInfo == nullptr) { + return false; + } + Parcel parcel; + appDebugInfo->ReadFromParcel(parcel); + appDebugInfo->Marshalling(parcel); + AppDebugInfo::Unmarshalling(parcel); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityappdebuginfo_fuzzer/abilityappdebuginfo_fuzzer.h b/test/fuzztest/abilityappdebuginfo_fuzzer/abilityappdebuginfo_fuzzer.h new file mode 100644 index 0000000000..18473e4c09 --- /dev/null +++ b/test/fuzztest/abilityappdebuginfo_fuzzer/abilityappdebuginfo_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPDEBUGINFO_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPDEBUGINFO_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityappdebuginfo_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMANAGERSERVICEA_FUZZER_H diff --git a/test/fuzztest/abilityappdebuginfo_fuzzer/corpus/init b/test/fuzztest/abilityappdebuginfo_fuzzer/corpus/init new file mode 100644 index 0000000000..8eb5a7d6eb --- /dev/null +++ b/test/fuzztest/abilityappdebuginfo_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityappdebuginfo_fuzzer/project.xml b/test/fuzztest/abilityappdebuginfo_fuzzer/project.xml new file mode 100644 index 0000000000..6e8ad2cfde --- /dev/null +++ b/test/fuzztest/abilityappdebuginfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityappdebugmanager_fuzzer/BUILD.gn b/test/fuzztest/abilityappdebugmanager_fuzzer/BUILD.gn new file mode 100644 index 0000000000..ed4f64e3b8 --- /dev/null +++ b/test/fuzztest/abilityappdebugmanager_fuzzer/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. + +#####################hydra-fuzz################### +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +##############################fuzztest########################################## +module_output_path = "ability_runtime/appmgrservice" +ohos_fuzztest("AbilityAppDebugManagerFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilityappdebugmanager_fuzzer" + + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/appmgr/src/app_debug_manager.cpp", + "abilityappdebugmanager_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAppDebugManagerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityappdebugmanager_fuzzer/abilityappdebugmanager_fuzzer.cpp b/test/fuzztest/abilityappdebugmanager_fuzzer/abilityappdebugmanager_fuzzer.cpp new file mode 100644 index 0000000000..3819193eeb --- /dev/null +++ b/test/fuzztest/abilityappdebugmanager_fuzzer/abilityappdebugmanager_fuzzer.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "abilityappdebugmanager_fuzzer.h" + +#define private public +#include "app_debug_manager.h" +#include "app_debug_listener_proxy.h" +#undef private + +#include +#include "securec.h" +#include "configuration.h" + +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr manager=std::make_shared(); + if (!manager) { + return false; + } + sptr listener; + manager->RegisterAppDebugListener(listener); + manager->UnregisterAppDebugListener(listener); + std::vector infos; + manager->StartDebug(infos); + manager->StopDebug(infos); + std::string stringParam(data, size); + manager->IsAttachDebug(stringParam); + AppDebugInfo info; + manager->RemoveAppDebugInfo(info); + std::vector incrementInfos; + manager->GetIncrementAppDebugInfos(infos,incrementInfos); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityappdebugmanager_fuzzer/abilityappdebugmanager_fuzzer.h b/test/fuzztest/abilityappdebugmanager_fuzzer/abilityappdebugmanager_fuzzer.h new file mode 100644 index 0000000000..88900bed7f --- /dev/null +++ b/test/fuzztest/abilityappdebugmanager_fuzzer/abilityappdebugmanager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPDEBUGMANAGER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPDEBUGMANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityappdebugmanager_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYATTACHTIMEOUT_FUZZER_H diff --git a/test/fuzztest/abilityappdebugmanager_fuzzer/corpus/init b/test/fuzztest/abilityappdebugmanager_fuzzer/corpus/init new file mode 100644 index 0000000000..8eb5a7d6eb --- /dev/null +++ b/test/fuzztest/abilityappdebugmanager_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityappdebugmanager_fuzzer/project.xml b/test/fuzztest/abilityappdebugmanager_fuzzer/project.xml new file mode 100644 index 0000000000..6e8ad2cfde --- /dev/null +++ b/test/fuzztest/abilityappdebugmanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/BUILD.gn b/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/BUILD.gn new file mode 100644 index 0000000000..d9dfb2bb12 --- /dev/null +++ b/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityAppdfrApplicationAnrListenerFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityappdfrapplicationanrlistener_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${bgtaskmgr_interfaces_path}/innerkits/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityappdfrapplicationanrlistener_fuzzer.cpp" ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "background_task_mgr:bgtaskmgr_innerkits", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAppdfrApplicationAnrListenerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/abilityappdfrapplicationanrlistener_fuzzer.cpp b/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/abilityappdfrapplicationanrlistener_fuzzer.cpp new file mode 100644 index 0000000000..14e956ff97 --- /dev/null +++ b/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/abilityappdfrapplicationanrlistener_fuzzer.cpp @@ -0,0 +1,91 @@ +/* + * 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 "abilityappdfrapplicationanrlistener_fuzzer.h" + +#include +#include + +#include "application_anr_listener.h" + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + // fuzz for ApplicationAnrListener + int32_t intParam = static_cast(GetU32Data(data)); + int32_t int32Param = static_cast(GetU32Data(data)); + auto applicationAnrListener = std::make_shared(); + applicationAnrListener->OnAnr(int32Param, intParam); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/abilityappdfrapplicationanrlistener_fuzzer.h b/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/abilityappdfrapplicationanrlistener_fuzzer.h new file mode 100644 index 0000000000..f54e17124a --- /dev/null +++ b/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/abilityappdfrapplicationanrlistener_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPDFRAPPLICATIONANRLISTENER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPDFRAPPLICATIONANRLISTENER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityappdfrapplicationanrlistener_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_APPLICATIONANRLISTENER_FUZZER_H diff --git a/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/corpus/init b/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/project.xml b/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityappdfrapplicationanrlistener_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityappjsheapmeminfo_fuzzer/BUILD.gn b/test/fuzztest/abilityappjsheapmeminfo_fuzzer/BUILD.gn new file mode 100644 index 0000000000..8e613c4e73 --- /dev/null +++ b/test/fuzztest/abilityappjsheapmeminfo_fuzzer/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. + +#####################hydra-fuzz################### +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +##############################fuzztest########################################## +module_output_path = "ability_runtime/appmgrservice" +ohos_fuzztest("AbilityAppJsHeapMemInfoFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilityappjsheapmeminfo_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_jsheap_mem_info.cpp", + "abilityappjsheapmeminfo_fuzzer.cpp", + ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:want", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "samgr:samgr_proxy", + "window_manager:libwm", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAppJsHeapMemInfoFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityappjsheapmeminfo_fuzzer/abilityappjsheapmeminfo_fuzzer.cpp b/test/fuzztest/abilityappjsheapmeminfo_fuzzer/abilityappjsheapmeminfo_fuzzer.cpp new file mode 100644 index 0000000000..177223104a --- /dev/null +++ b/test/fuzztest/abilityappjsheapmeminfo_fuzzer/abilityappjsheapmeminfo_fuzzer.cpp @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "abilityappjsheapmeminfo_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "app_jsheap_mem_info.h" +#undef protected +#undef private +#include "parcel.h" +#include +#include "securec.h" +#include "configuration.h" + +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + + + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + JsHeapDumpInfo js; + Parcel parcel; + js.Marshalling(parcel); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityappjsheapmeminfo_fuzzer/abilityappjsheapmeminfo_fuzzer.h b/test/fuzztest/abilityappjsheapmeminfo_fuzzer/abilityappjsheapmeminfo_fuzzer.h new file mode 100644 index 0000000000..32793d8f30 --- /dev/null +++ b/test/fuzztest/abilityappjsheapmeminfo_fuzzer/abilityappjsheapmeminfo_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPJSHEAPMEMINFO_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPJSHEAPMEMINFO_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityappjsheapmeminfo_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMANAGERSERVICEA_FUZZER_H diff --git a/test/fuzztest/abilityappjsheapmeminfo_fuzzer/corpus/init b/test/fuzztest/abilityappjsheapmeminfo_fuzzer/corpus/init new file mode 100644 index 0000000000..8eb5a7d6eb --- /dev/null +++ b/test/fuzztest/abilityappjsheapmeminfo_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityappjsheapmeminfo_fuzzer/project.xml b/test/fuzztest/abilityappjsheapmeminfo_fuzzer/project.xml new file mode 100644 index 0000000000..6e8ad2cfde --- /dev/null +++ b/test/fuzztest/abilityappjsheapmeminfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/BUILD.gn b/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/BUILD.gn new file mode 100644 index 0000000000..2c58b843d6 --- /dev/null +++ b/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/BUILD.gn @@ -0,0 +1,119 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/appmgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityAppMgrAppRunningManagerFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityappmgrapprunningmanager_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_services_path}/appmgr/include", + "${ability_runtime_services_path}/common/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityappmgrapprunningmanager_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/appmgr:appmgr_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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}/uri_permission:uri_permission_mgr", + "${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}/appmgr:libappms", + "${ability_runtime_services_path}/common:event_report", + "${ability_runtime_services_path}/common:perm_verification", + "${ability_runtime_services_path}/common:task_handler_wrap", + "${windowmanager_path}/utils:libwmutil_static", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "access_token:libaccesstoken_sdk", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hicollie:libhicollie", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbeget_proxy", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_mgr", + "memory_utils:libmeminfo", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ + "window_manager:libwm", + "window_manager:libwsutils", + ] + defines = [ "SUPPORT_SCREEN" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAppMgrAppRunningManagerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/abilityappmgrapprunningmanager_fuzzer.cpp b/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/abilityappmgrapprunningmanager_fuzzer.cpp new file mode 100644 index 0000000000..0e024569f8 --- /dev/null +++ b/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/abilityappmgrapprunningmanager_fuzzer.cpp @@ -0,0 +1,256 @@ +/* + * 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 "abilityappmgrapprunningmanager_fuzzer.h" +#include "ability_record.h" + +#include +#include + +#define private public +#include "app_running_manager.h" +#include "child_process_record.h" +#include "app_running_record.h" +#undef private +#include "securec.h" +#include "ability_record.h" + + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void DoSomethingInterestingWithMyAPIadda(const char* data, size_t size) +{ + std::shared_ptr manager = std::make_shared(); + pid_t pidApps = static_cast(GetU32Data(data)); + std::string jsonStr(data, size); + int uid = static_cast(GetU32Data(data)); + manager->SetAbilityForegroundingFlagToAppRecord(pidApps); + int64_t eventId = static_cast(GetU32Data(data)); + manager->HandleTerminateTimeOut(eventId); + sptr token = GetFuzzAbilityToken(); + manager->HandleAbilityAttachTimeOut(token); + manager->GetAppRunningRecord(eventId); + bool clearMissionFlag = *data % ENABLE; + std::shared_ptr appMgrServiceInner; + manager->TerminateAbility(token, clearMissionFlag, appMgrServiceInner); + ApplicationInfo appInfos; + manager->ProcessUpdateApplicationInfoInstalled(appInfos); + std::list pids; + bool clearPageStack = *data % ENABLE; + manager->ProcessExitByBundleNameAndUid(jsonStr, uid, pids, clearPageStack); + int32_t userId = static_cast(GetU32Data(data)); + manager->GetPidsByUserId(userId, pids); + manager->PrepareTerminate(token, clearMissionFlag); + sptr abilityToken = GetFuzzAbilityToken(); + manager->GetTerminatingAppRunningRecord(abilityToken); + AppExecFwk::RunningProcessInfo processInfo; + manager->GetRunningProcessInfoByToken(token, processInfo); + OHOS::AppExecFwk::RunningProcessInfo infoByPid; + manager->GetRunningProcessInfoByPid(pidApps, infoByPid); + std::regex re; + manager->ClipStringContent(re, jsonStr, jsonStr); + manager->HandleAddAbilityStageTimeOut(eventId); + manager->HandleStartSpecifiedAbilityTimeOut(eventId); + manager->GetAppRunningRecordByRenderPid(pidApps); + wptr remote; + manager->OnRemoteRenderDied(remote); + manager->ProcessExitByPid(pidApps); + manager->GetAppRunningStateByBundleName(jsonStr); + sptr callback; + manager->NotifyLoadRepairPatch(jsonStr, callback); + manager->NotifyHotReloadPage(jsonStr, callback); + manager->NotifyUnLoadRepairPatch(jsonStr, callback); + std::shared_ptr infoAPP; + int32_t recordId = static_cast(GetU32Data(data)); + OHOS::AppExecFwk::AppRunningRecord foregroundingRecord(infoAPP, recordId, jsonStr); +} + +void DoSomethingInterestingWithMyAPIaddb(const char* data, size_t size) +{ + std::shared_ptr manager = std::make_shared(); + std::string jsonStr(data, size); + int32_t recordId = static_cast(GetU32Data(data)); + std::shared_ptr infoAPP; + OHOS::AppExecFwk::AppRunningRecord foregroundingRecord(infoAPP, recordId, jsonStr); + manager->IsApplicationFirstForeground(foregroundingRecord); + manager->IsApplicationBackground(jsonStr); + manager->IsApplicationFirstFocused(foregroundingRecord); + manager->IsApplicationUnfocused(jsonStr); + bool isAttachDebug = *data % ENABLE; + manager->SetAttachAppDebug(jsonStr, isAttachDebug); + bool isDetachDebug = *data % ENABLE; + manager->GetAppDebugInfosByBundleName(jsonStr, isDetachDebug); + std::vector> abilityTokens; + manager->GetAbilityTokensByBundleName(jsonStr, abilityTokens); + pid_t pidApps = static_cast(GetU32Data(data)); + manager->GetAppRunningRecordByChildProcessPid(pidApps); + wptr remote; + manager->OnChildProcessRemoteDied(remote); + manager->GetAllAppRunningRecordCountByBundleName(jsonStr); + manager->SignRestartAppFlag(jsonStr); + manager->GetAppRunningUniqueIdByPid(pidApps, jsonStr); + std::vector hostPids; + manager->GetAllUIExtensionRootHostPid(pidApps, hostPids); + std::vector providerPids; + pid_t hostPid = static_cast(GetU32Data(data)); + manager->GetAllUIExtensionProviderPid(hostPid, providerPids); + int32_t uiExtensionAbilityId = static_cast(GetU32Data(data)); + pid_t providerPid = static_cast(GetU32Data(data)); + manager->AddUIExtensionLauncherItem(uiExtensionAbilityId, hostPid, providerPid); + manager->RemoveUIExtensionLauncherItem(pidApps); + manager->RemoveUIExtensionLauncherItemById(uiExtensionAbilityId); + manager->DumpIpcAllStart(jsonStr); + manager->DumpIpcAllStop(jsonStr); + manager->DumpIpcAllStat(jsonStr); +} + +void DoSomethingInterestingWithMyAPIaddc(const char* data, size_t size) +{ + std::shared_ptr manager = std::make_shared(); + std::string jsonStr(data, size); + int32_t pidDump = static_cast(GetU32Data(data)); + manager->DumpIpcStart(pidDump, jsonStr); + manager->DumpIpcStop(pidDump, jsonStr); + manager->DumpIpcStat(pidDump, jsonStr); + std::vector pidFrt; + manager->DumpFfrt(pidFrt, jsonStr); + int32_t uids = static_cast(GetU32Data(data)); + std::shared_ptr appInfosd = std::make_shared(); + std::set> cachedSet; + manager->IsAppProcessesAllCached(jsonStr, uids, cachedSet); + int64_t eventId = static_cast(GetU32Data(data)); + manager->GetAbilityRunningRecord(eventId); + std::shared_ptr appRecord; + AppExecFwk::RunningProcessInfo infoRecord; + manager->AssignRunningProcessInfoByAppRecord(appRecord, infoRecord); +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr manager = std::make_shared(); + std::shared_ptr appInfo = std::make_shared(); + std::string jsonStr(data, size); + BundleInfo bundleInfo; + manager->CreateAppRunningRecord(appInfo, jsonStr, bundleInfo); + int uid = static_cast(GetU32Data(data)); + manager->CheckAppRunningRecordIsExist(jsonStr, jsonStr, uid, bundleInfo, jsonStr); + manager->CheckAppRunningRecordIsExistByBundleName(jsonStr); + int32_t appCloneIndex = static_cast(GetU32Data(data)); + bool isRunning = *data % ENABLE; + manager->CheckAppCloneRunningRecordIsExistByBundleName(jsonStr, appCloneIndex, isRunning); + pid_t pidApps = static_cast(GetU32Data(data)); + manager->GetAppRunningRecordByPid(pidApps); + sptr abilityToken = GetFuzzAbilityToken(); + manager->GetAppRunningRecordByAbilityToken(abilityToken); + wptr remote; + std::shared_ptr appMgrServiceInner; + manager->OnRemoteDied(remote, appMgrServiceInner); + manager->GetAppRunningRecordMap(); + int32_t recordId = static_cast(GetU32Data(data)); + manager->RemoveAppRunningRecordById(recordId); + manager->ClearAppRunningRecordMap(); + std::list pids; + bool clearPageStack = *data % ENABLE; + manager->ProcessExitByBundleName(jsonStr, pids, clearPageStack); + std::vector list; + manager->GetForegroundApplications(list); + Configuration config; + manager->UpdateConfiguration(config); + manager->UpdateConfigurationByBundleName(config, jsonStr); + int32_t level = static_cast(GetU32Data(data)); + manager->NotifyMemoryLevel(level); + std::map procLevelMap; + manager->NotifyProcMemoryLevel(procLevelMap); + int32_t pidDump = static_cast(GetU32Data(data)); + OHOS::AppExecFwk::MallocInfo mallocInfo; + manager->DumpHeapMemory(pidDump, mallocInfo); + OHOS::AppExecFwk::JsHeapDumpInfo info; + manager->DumpJsHeapMemory(info); + DoSomethingInterestingWithMyAPIadda(data, size); + DoSomethingInterestingWithMyAPIaddb(data, size); + DoSomethingInterestingWithMyAPIaddc(data, size); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/abilityappmgrapprunningmanager_fuzzer.h b/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/abilityappmgrapprunningmanager_fuzzer.h new file mode 100644 index 0000000000..8c84bb5230 --- /dev/null +++ b/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/abilityappmgrapprunningmanager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRAPPRUNNINGMANAGER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRAPPRUNNINGMANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityappmgrapprunningmanager_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRAPPRUNNINGMANAGER_FUZZER_H diff --git a/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/corpus/init b/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/project.xml b/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityappmgrapprunningmanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityappmgrevent_fuzzer/BUILD.gn b/test/fuzztest/abilityappmgrevent_fuzzer/BUILD.gn new file mode 100644 index 0000000000..2d77f0c5f3 --- /dev/null +++ b/test/fuzztest/abilityappmgrevent_fuzzer/BUILD.gn @@ -0,0 +1,83 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +##############################fuzztest########################################## +module_output_path = "ability_runtime/appmgrservice" +ohos_fuzztest("AbilityAppMgrEventFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilityappmgrevent_fuzzer" + + include_dirs = + [ "${ability_runtime_innerkits_path}/app_manager/include/appmgr" ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/appmgr/src/app_mgr_event.cpp", + "${ability_runtime_services_path}/common/src/event_report.cpp", + "abilityappmgrevent_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/appmgr:appmgr_config" ] + + deps = [ "${ability_runtime_services_path}/appmgr:libappms" ] + + external_deps = [ + "ability_base:configuration", + "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", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbeget_proxy", + "init:libbegetutil", + "ipc:ipc_core", + ] + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } + + defines = [] + if (background_task_mgr_continuous_task_enable) { + defines += [ "BGTASKMGR_CONTINUOUS_TASK_ENABLE" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAppMgrEventFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityappmgrevent_fuzzer/abilityappmgrevent_fuzzer.cpp b/test/fuzztest/abilityappmgrevent_fuzzer/abilityappmgrevent_fuzzer.cpp new file mode 100644 index 0000000000..7041cc428e --- /dev/null +++ b/test/fuzztest/abilityappmgrevent_fuzzer/abilityappmgrevent_fuzzer.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "abilityappmgrevent_fuzzer.h" + +#define private public +#include "app_mgr_event.h" +#undef private + +#include +#include +#include +#include "securec.h" +#include "configuration.h" +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr callerAppRecord; + std::shared_ptr appRecord; + std::string stringParam(data, size); + AppMgrEventUtil::SendCreateAtomicServiceProcessEvent(callerAppRecord, appRecord, + stringParam, stringParam); + AAFwk::EventInfo eventInfo; + AppMgrEventUtil::SendProcessStartEvent(callerAppRecord,appRecord,eventInfo); + int32_t appUid = static_cast(GetU32Data(data)); + int64_t restartTime = static_cast(GetU32Data(data)); + AppMgrEventUtil::SendReStartProcessEvent(eventInfo, appUid, restartTime); + AppMgrEventUtil:: GetCallerPid(callerAppRecord); + std::shared_ptr abilityInfo; + int32_t abilityType = static_cast(GetU32Data(data)); + int32_t extensionType = static_cast(GetU32Data(data)); + AppMgrEventUtil:: UpdateStartupType(abilityInfo, abilityType,extensionType); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityappmgrevent_fuzzer/abilityappmgrevent_fuzzer.h b/test/fuzztest/abilityappmgrevent_fuzzer/abilityappmgrevent_fuzzer.h new file mode 100644 index 0000000000..a57a17fff4 --- /dev/null +++ b/test/fuzztest/abilityappmgrevent_fuzzer/abilityappmgrevent_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGREVENT_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGREVENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityappmgrevent_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYATTACHTIMEOUT_FUZZER_H diff --git a/test/fuzztest/abilityappmgrevent_fuzzer/corpus/init b/test/fuzztest/abilityappmgrevent_fuzzer/corpus/init new file mode 100644 index 0000000000..8eb5a7d6eb --- /dev/null +++ b/test/fuzztest/abilityappmgrevent_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityappmgrevent_fuzzer/project.xml b/test/fuzztest/abilityappmgrevent_fuzzer/project.xml new file mode 100644 index 0000000000..6e8ad2cfde --- /dev/null +++ b/test/fuzztest/abilityappmgrevent_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityappmgrpagestatedata_fuzzer/BUILD.gn b/test/fuzztest/abilityappmgrpagestatedata_fuzzer/BUILD.gn new file mode 100644 index 0000000000..732af2078d --- /dev/null +++ b/test/fuzztest/abilityappmgrpagestatedata_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +##############################fuzztest########################################## +module_output_path = "ability_runtime/appmgrservice" +ohos_fuzztest("AbilityAppMgrPageStateDataFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilityappmgrpagestatedata_fuzzer" + include_dirs = [ + "${ability_runtime_services_path}/appmgr/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityappmgrpagestatedata_fuzzer.cpp" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:configuration", + "ability_base:want", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "faultloggerd:libdfx_dumpcatcher", + "faultloggerd:libfaultloggerd", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "init:libbegetutil", + "ipc:ipc_core", + "samgr:samgr_proxy", + "window_manager:libwm", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAppMgrPageStateDataFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityappmgrpagestatedata_fuzzer/abilityappmgrpagestatedata_fuzzer.cpp b/test/fuzztest/abilityappmgrpagestatedata_fuzzer/abilityappmgrpagestatedata_fuzzer.cpp new file mode 100644 index 0000000000..0521edb5b5 --- /dev/null +++ b/test/fuzztest/abilityappmgrpagestatedata_fuzzer/abilityappmgrpagestatedata_fuzzer.cpp @@ -0,0 +1,108 @@ +/* + * 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 "abilityappmgrpagestatedata_fuzzer.h" + +#include +#include + +#define private public +#include "page_state_data.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + PageStateData info; + Parcel parcel; + info.ReadFromParcel(parcel); + info.Marshalling(parcel); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityappmgrpagestatedata_fuzzer/abilityappmgrpagestatedata_fuzzer.h b/test/fuzztest/abilityappmgrpagestatedata_fuzzer/abilityappmgrpagestatedata_fuzzer.h new file mode 100644 index 0000000000..c665724cd2 --- /dev/null +++ b/test/fuzztest/abilityappmgrpagestatedata_fuzzer/abilityappmgrpagestatedata_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRPAGESTATEDATA_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRPAGESTATEDATA_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityappmgrpagestatedata_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRPAGESTATEDATA_FUZZER_H diff --git a/test/fuzztest/abilityappmgrpagestatedata_fuzzer/corpus/init b/test/fuzztest/abilityappmgrpagestatedata_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityappmgrpagestatedata_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityappmgrpagestatedata_fuzzer/project.xml b/test/fuzztest/abilityappmgrpagestatedata_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityappmgrpagestatedata_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/BUILD.gn b/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/BUILD.gn new file mode 100644 index 0000000000..42f5e101e4 --- /dev/null +++ b/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +##############################fuzztest########################################## +module_output_path = "ability_runtime/appmgrservice" +ohos_fuzztest("AbilityAppMgrRenderStateDataFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityappmgrrenderstatedata_fuzzer" + include_dirs = [ + "${ability_runtime_services_path}/appmgr/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityappmgrrenderstatedata_fuzzer.cpp" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:configuration", + "ability_base:want", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "faultloggerd:libdfx_dumpcatcher", + "faultloggerd:libfaultloggerd", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "init:libbegetutil", + "ipc:ipc_core", + "samgr:samgr_proxy", + "window_manager:libwm", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAppMgrRenderStateDataFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/abilityappmgrrenderstatedata_fuzzer.cpp b/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/abilityappmgrrenderstatedata_fuzzer.cpp new file mode 100644 index 0000000000..ddef5cf942 --- /dev/null +++ b/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/abilityappmgrrenderstatedata_fuzzer.cpp @@ -0,0 +1,108 @@ +/* + * 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 "abilityappmgrrenderstatedata_fuzzer.h" + +#include +#include + +#define private public +#include "page_state_data.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + RunningMultiAppInfo info; + Parcel parcel; + info.Marshalling(parcel); + info.ReadFromParcel(parcel); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/abilityappmgrrenderstatedata_fuzzer.h b/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/abilityappmgrrenderstatedata_fuzzer.h new file mode 100644 index 0000000000..0e7c5e1986 --- /dev/null +++ b/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/abilityappmgrrenderstatedata_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRRENDERSTATEDATA_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRRENDERSTATEDATA_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityappmgrrenderstatedata_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRRENDERSTATEDATA_FUZZER_H diff --git a/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/corpus/init b/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/project.xml b/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityappmgrrenderstatedata_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/BUILD.gn b/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/BUILD.gn new file mode 100644 index 0000000000..44f816bf99 --- /dev/null +++ b/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityAppMgrRenderStateObserverManagerFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_services_path}/appmgr/include", + "${ability_runtime_services_path}/common/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/appmgr/src/render_state_observer_manager.cpp", + "abilityappmgrrenderstateobservermanager_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_path}/utils/server/startup:startup_util", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:perm_verification", + "${ability_runtime_services_path}/common:task_handler_wrap", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "appspawn:appspawn_client", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "window_manager:libwm", + "window_manager:libwsutils", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAppMgrRenderStateObserverManagerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/abilityappmgrrenderstateobservermanager_fuzzer.cpp b/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/abilityappmgrrenderstateobservermanager_fuzzer.cpp new file mode 100644 index 0000000000..afec600c2e --- /dev/null +++ b/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/abilityappmgrrenderstateobservermanager_fuzzer.cpp @@ -0,0 +1,120 @@ +/* + * 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 "abilityappmgrrenderstateobservermanager_fuzzer.h" +#include "ability_record.h" + +#include +#include + +#define private public +#include "render_state_observer_manager.h" +#include "hilog_tag_wrapper.h" +#include "iremote_object.h" +#undef private +#include "render_state_observer_proxy.h" +#include "render_state_observer_stub.h" + +#include "securec.h" + + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr manager = std::make_shared(); + manager->Init(); + sptr observer; + manager->RegisterRenderStateObserver(observer); + manager->Init(); + sptr observers; + manager->UnregisterRenderStateObserver(observers); + manager->Init(); + std::shared_ptr renderRecord; + int32_t state = static_cast(GetU32Data(data)); + manager->OnRenderStateChanged(renderRecord, state); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/abilityappmgrrenderstateobservermanager_fuzzer.h b/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/abilityappmgrrenderstateobservermanager_fuzzer.h new file mode 100644 index 0000000000..e389076ed5 --- /dev/null +++ b/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/abilityappmgrrenderstateobservermanager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRRENDERSTATEOBSERVERMANAGER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRRENDERSTATEOBSERVERMANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityappmgrrenderstateobservermanager_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRRENDERSTATEOBSERVERMANAGER_FUZZER_H diff --git a/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/corpus/init b/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/project.xml b/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityappmgrrenderstateobservermanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/BUILD.gn b/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/BUILD.gn new file mode 100644 index 0000000000..c83191a2ad --- /dev/null +++ b/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +##############################fuzztest########################################## +module_output_path = "ability_runtime/appmgrservice" +ohos_fuzztest("AbilityAppMgrRunningMultiInfoFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityappmgrrunningmultiinfo_fuzzer" + include_dirs = [ + "${ability_runtime_services_path}/appmgr/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityappmgrrunningmultiinfo_fuzzer.cpp" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:configuration", + "ability_base:want", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "faultloggerd:libdfx_dumpcatcher", + "faultloggerd:libfaultloggerd", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "init:libbegetutil", + "ipc:ipc_core", + "samgr:samgr_proxy", + "window_manager:libwm", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAppMgrRunningMultiInfoFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/abilityappmgrrunningmultiinfo_fuzzer.cpp b/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/abilityappmgrrunningmultiinfo_fuzzer.cpp new file mode 100644 index 0000000000..495bd2e3c6 --- /dev/null +++ b/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/abilityappmgrrunningmultiinfo_fuzzer.cpp @@ -0,0 +1,108 @@ +/* + * 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 "abilityappmgrrunningmultiinfo_fuzzer.h" + +#include +#include + +#define private public +#include "page_state_data.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + RenderStateData info; + Parcel parcel; + info.Marshalling(parcel); + info.ReadFromParcel(parcel); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/abilityappmgrrunningmultiinfo_fuzzer.h b/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/abilityappmgrrunningmultiinfo_fuzzer.h new file mode 100644 index 0000000000..eb351602c7 --- /dev/null +++ b/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/abilityappmgrrunningmultiinfo_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRRUNNINGMULTIINFO_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRRUNNINGMULTIINFO_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityappmgrrunningmultiinfo_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAPPMGRRUNNINGMULTIINFO_FUZZER_H diff --git a/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/corpus/init b/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/project.xml b/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityappmgrrunningmultiinfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityautostartupclient_fuzzer/BUILD.gn b/test/fuzztest/abilityautostartupclient_fuzzer/BUILD.gn new file mode 100644 index 0000000000..73fc4cad27 --- /dev/null +++ b/test/fuzztest/abilityautostartupclient_fuzzer/BUILD.gn @@ -0,0 +1,91 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityAutoStartupClientFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilityautostartupclient_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_client.cpp", + "${ability_runtime_services_path}/common/src/app_utils.cpp", + "${ability_runtime_services_path}/common/src/json_utils.cpp", + "abilityautostartupclient_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAutoStartupClientFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityautostartupclient_fuzzer/abilityautostartupclient_fuzzer.cpp b/test/fuzztest/abilityautostartupclient_fuzzer/abilityautostartupclient_fuzzer.cpp new file mode 100644 index 0000000000..90b52a035b --- /dev/null +++ b/test/fuzztest/abilityautostartupclient_fuzzer/abilityautostartupclient_fuzzer.cpp @@ -0,0 +1,106 @@ +/* + * 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 "abilityautostartupclient_fuzzer.h" + +#include +#include + +#define private public +#include "ability_auto_startup_client.h" +#undef private + +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr uint8_t ENABLE = 2; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + auto abilityAutoStartupClient = AbilityAutoStartupClient::GetInstance(); + abilityAutoStartupClient->Connect(); + AutoStartupInfo info; + bool boolParam = *data % ENABLE; + abilityAutoStartupClient->SetApplicationAutoStartupByEDM(info, boolParam); + abilityAutoStartupClient->CancelApplicationAutoStartupByEDM(info, boolParam); + std::vector infoList; + abilityAutoStartupClient->QueryAllAutoStartupApplications(infoList); + + auto abilityMgrDeathRecipient = + std::make_shared(); + wptr remote; + abilityMgrDeathRecipient->OnRemoteDied(remote); + + abilityAutoStartupClient->GetAbilityManager(); + abilityAutoStartupClient->ResetProxy(remote); + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityautostartupclient_fuzzer/abilityautostartupclient_fuzzer.h b/test/fuzztest/abilityautostartupclient_fuzzer/abilityautostartupclient_fuzzer.h new file mode 100644 index 0000000000..dabb987be5 --- /dev/null +++ b/test/fuzztest/abilityautostartupclient_fuzzer/abilityautostartupclient_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITY_AUTO_STARTUP_CLIENT_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITY_AUTO_STARTUP_CLIENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityautostartupclient_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITY_AUTO_STARTUP_CLIENT_FUZZER_H diff --git a/test/fuzztest/abilityautostartupclient_fuzzer/corpus/init b/test/fuzztest/abilityautostartupclient_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityautostartupclient_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityautostartupclient_fuzzer/project.xml b/test/fuzztest/abilityautostartupclient_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityautostartupclient_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityautostartupdatamanager_fuzzer/BUILD.gn b/test/fuzztest/abilityautostartupdatamanager_fuzzer/BUILD.gn new file mode 100644 index 0000000000..35de92d307 --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanager_fuzzer/BUILD.gn @@ -0,0 +1,91 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityAutoStartupDataManagerFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityautostartupdatamanager_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_innerkits_path}/deps_wrapper/src/os_account_manager_wrapper.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_data_manager.cpp", + "${ability_runtime_services_path}/common/src/app_utils.cpp", + "${ability_runtime_services_path}/common/src/json_utils.cpp", + "abilityautostartupdatamanager_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAutoStartupDataManagerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityautostartupdatamanager_fuzzer/abilityautostartupdatamanager_fuzzer.cpp b/test/fuzztest/abilityautostartupdatamanager_fuzzer/abilityautostartupdatamanager_fuzzer.cpp new file mode 100644 index 0000000000..cdbf00fb4f --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanager_fuzzer/abilityautostartupdatamanager_fuzzer.cpp @@ -0,0 +1,121 @@ +/* + * 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 "abilityautostartupdatamanager_fuzzer.h" + +#include +#include +#include + +#define private public +#include "ability_auto_startup_data_manager.h" +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr uint8_t ENABLE = 2; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + auto abilityAutoStartupDataManager = std::make_shared(); + AbilityRuntime::AutoStartupInfo info; + bool isAutoStartup = *data % ENABLE; + bool isEdmForce = *data % ENABLE; + abilityAutoStartupDataManager->InsertAutoStartupData(info, isAutoStartup, isEdmForce); + abilityAutoStartupDataManager->UpdateAutoStartupData(info, isAutoStartup, isEdmForce); + std::string strParam(data, size); + int32_t in32Param = static_cast(GetU32Data(data)); + abilityAutoStartupDataManager->QueryAutoStartupData(info); + std::vector infoList; + abilityAutoStartupDataManager->QueryAllAutoStartupApplications(infoList, in32Param); + abilityAutoStartupDataManager->GetCurrentAppAutoStartupData(strParam, infoList, strParam); + abilityAutoStartupDataManager->GetKvStore(); + abilityAutoStartupDataManager->CheckKvStore(); + DistributedKv::Value value; + DistributedKv::Key key; + abilityAutoStartupDataManager->ConvertAutoStartupStatusFromValue(value, isAutoStartup, isEdmForce); + abilityAutoStartupDataManager->ConvertAutoStartupDataToKey(info); + abilityAutoStartupDataManager->ConvertAutoStartupInfoFromKeyAndValue(key, value); + nlohmann::json jsonObject; + std::string keys(data, size); + std::string values(data, size); + bool checkEmpty = *data % ENABLE; + abilityAutoStartupDataManager->IsEqual(jsonObject, keys, values, checkEmpty); + abilityAutoStartupDataManager->IsEqual(jsonObject, keys, values); + abilityAutoStartupDataManager->IsEqual(key, info); + abilityAutoStartupDataManager->IsEqual(key, strParam); + abilityAutoStartupDataManager->IsEqual(key, in32Param); + abilityAutoStartupDataManager->DeleteAutoStartupData(info); + abilityAutoStartupDataManager->DeleteAutoStartupData(strParam, in32Param); + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityautostartupdatamanager_fuzzer/abilityautostartupdatamanager_fuzzer.h b/test/fuzztest/abilityautostartupdatamanager_fuzzer/abilityautostartupdatamanager_fuzzer.h new file mode 100644 index 0000000000..d3a0fc27f4 --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanager_fuzzer/abilityautostartupdatamanager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITY_AUTO_STARTUP_DATA_MANAGER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITY_AUTO_STARTUP_DATA_MANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityautostartupdatamanager_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITY_AUTOS_TARTUP_DATA_MANAGER_FUZZER_H diff --git a/test/fuzztest/abilityautostartupdatamanager_fuzzer/corpus/init b/test/fuzztest/abilityautostartupdatamanager_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanager_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityautostartupdatamanager_fuzzer/project.xml b/test/fuzztest/abilityautostartupdatamanager_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityautostartupdatamanagera_fuzzer/BUILD.gn b/test/fuzztest/abilityautostartupdatamanagera_fuzzer/BUILD.gn new file mode 100755 index 0000000000..7d31c46269 --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanagera_fuzzer/BUILD.gn @@ -0,0 +1,96 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityAutoStartupDataManageraFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityautostartupdatamanagera_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_data_manager.cpp", + "abilityautostartupdatamanagera_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAutoStartupDataManageraFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityautostartupdatamanagera_fuzzer/abilityautostartupdatamanagera_fuzzer.cpp b/test/fuzztest/abilityautostartupdatamanagera_fuzzer/abilityautostartupdatamanagera_fuzzer.cpp new file mode 100755 index 0000000000..19dfe7203e --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanagera_fuzzer/abilityautostartupdatamanagera_fuzzer.cpp @@ -0,0 +1,183 @@ +/* + * 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 "abilityautostartupdatamanagera_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "ability_auto_startup_data_manager.h" +#undef protected +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +const std::string jsonStr1 = "{\n\"isAutoStartup\": true, \n\"isEdmForce\": true\n}"; +const std::string jsonStr2 = "{\n\"isAutoStartup\": \"true\", \n\"isEdmForce\": \"true\"\n}"; +const std::string jsonStr3 = "{\n\"isAutoStartup2\": true, \n\"isEdmForce2\": true\n}"; +const std::string jsonStr4 = "{\n\"isAutoStartup2\": true, \n\"isEdmForce2\": true\n"; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void AbilityAutoStartupDataManagerFuzztest1(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr dataMgr = std::make_shared(); + dataMgr->CheckKvStore(); + AutoStartupInfo info1; + info1.userId = int32Param; + dataMgr->InsertAutoStartupData(info1, boolParam, boolParam); // branch info1.bundleName empty + info1.bundleName = "com.example.fuzzTest"; + dataMgr->InsertAutoStartupData(info1, boolParam, boolParam); // branch info1.abilityName empty + info1.abilityName = "MainAbility"; + dataMgr->InsertAutoStartupData(info1, boolParam, boolParam); // branch info1.accestoken empty + info1.accessTokenId = "AccessTokenId"; + dataMgr->InsertAutoStartupData(info1, boolParam, boolParam); // branch info1.accestoken empty + + AutoStartupInfo info2; + info2.userId = int32Param; + dataMgr->UpdateAutoStartupData(info2, boolParam, boolParam); // branch info2.bundleName empty + info2.bundleName = "com.example.fuzzTest"; + dataMgr->UpdateAutoStartupData(info2, boolParam, boolParam); // branch info2.abilityName empty + info2.abilityName = "MainAbility"; + dataMgr->UpdateAutoStartupData(info2, boolParam, boolParam); // branch info2.accestoken empty + info2.accessTokenId = "AccessTokenId"; + dataMgr->UpdateAutoStartupData(info2, boolParam, boolParam); // branch info2.accestoken empty + + AutoStartupInfo info3; + info3.userId = int32Param; + dataMgr->UpdateAutoStartupData(info3, boolParam, boolParam); // branch info3.bundleName empty + info3.bundleName = "com.example.fuzzTest"; + dataMgr->UpdateAutoStartupData(info3, boolParam, boolParam); // branch info3.abilityName empty + info3.abilityName = "MainAbility"; + dataMgr->UpdateAutoStartupData(info3, boolParam, boolParam); // branch info3.accestoken empty + info3.accessTokenId = "AccessTokenId"; + dataMgr->UpdateAutoStartupData(info3, boolParam, boolParam); // branch userid + + dataMgr->DeleteAutoStartupData(stringParam, int32Param); // called + + AutoStartupInfo info4; + info4.userId = int32Param; + dataMgr->QueryAutoStartupData(info4); // branch info3.bundleName empty + info4.bundleName = "com.example.fuzzTest"; + dataMgr->QueryAutoStartupData(info4); // branch info3.abilityName empty + info4.abilityName = "MainAbility"; + dataMgr->QueryAutoStartupData(info4); // branch info3.accestoken empty + info4.accessTokenId = "AccessTokenId"; + dataMgr->QueryAutoStartupData(info4); // branch userid + + std::vector vecs; + vecs.emplace_back(info1); + dataMgr->QueryAllAutoStartupApplications(vecs, int32Param); // called + dataMgr->GetCurrentAppAutoStartupData(stringParam, vecs, stringParam); //called +} + +void AbilityAutoStartupDataManagerFuzztest2(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr dataMgr = std::make_shared(); + AutoStartupInfo info1; + info1.userId = int32Param; + dataMgr->ConvertAutoStartupStatusToValue(boolParam, boolParam, info1.abilityName); + + DistributedKv::Value value1(jsonStr1); + dataMgr->ConvertAutoStartupStatusFromValue(value1, boolParam, boolParam); // branch json + DistributedKv::Value value2(jsonStr2); + dataMgr->ConvertAutoStartupStatusFromValue(value2, boolParam, boolParam); // branch json + DistributedKv::Value value3(jsonStr3); + dataMgr->ConvertAutoStartupStatusFromValue(value3, boolParam, boolParam); // branch json + DistributedKv::Value value4(jsonStr4); + dataMgr->ConvertAutoStartupStatusFromValue(value4, boolParam, boolParam); // branch discard jsonstr +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + AbilityAutoStartupDataManagerFuzztest1(boolParam, stringParam, int32Param); + AbilityAutoStartupDataManagerFuzztest2(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityautostartupdatamanagera_fuzzer/abilityautostartupdatamanagera_fuzzer.h b/test/fuzztest/abilityautostartupdatamanagera_fuzzer/abilityautostartupdatamanagera_fuzzer.h new file mode 100755 index 0000000000..1aa0d39990 --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanagera_fuzzer/abilityautostartupdatamanagera_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPDATAMANAGERA_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPDATAMANAGERA_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityautostartupdatamanagera_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPDATAMANAGERA_FUZZER_H diff --git a/test/fuzztest/abilityautostartupdatamanagera_fuzzer/corpus/init b/test/fuzztest/abilityautostartupdatamanagera_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanagera_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityautostartupdatamanagera_fuzzer/project.xml b/test/fuzztest/abilityautostartupdatamanagera_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanagera_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/BUILD.gn b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/BUILD.gn new file mode 100755 index 0000000000..bf4f2d2f73 --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/BUILD.gn @@ -0,0 +1,96 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityAutoStartupDataManagerbFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityautostartupdatamanagerb_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_data_manager.cpp", + "abilityautostartupdatamanagerb_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAutoStartupDataManagerbFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/abilityautostartupdatamanagerb_fuzzer.cpp b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/abilityautostartupdatamanagerb_fuzzer.cpp new file mode 100755 index 0000000000..be7c2e6d5c --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/abilityautostartupdatamanagerb_fuzzer.cpp @@ -0,0 +1,167 @@ +/* + * 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 "abilityautostartupdatamanagerb_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "ability_auto_startup_data_manager.h" +#undef protected +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; + +const std::string jsonKey1 = "{\n\"bundleName\": \"com.example.fuzzTest\", \n\"moduleName\": \"module\",\ + \n\"abilityName\": \"ability\", \n\"appCloneIndex\": -1, \n\"accessTokenId\": \"token\",\ + \n\"userId\": 100 }"; +const std::string jsonValue1 = "{\n\"abilityTypeName\": \"typeName\"}"; +const std::string jsonValue1Illegal = "{\n\"abilityTypeName\": \"typeName\""; + +const std::string jsonKey2 = "{\n\"bundleName2\": \"com.example.fuzzTest2\"}"; +const std::string jsonValue2 = "{\n\"abilityTypeName2\": \"typeName\"}"; +const std::string jsonValue3 = "{\n\"abilityTypeName\": 1 }"; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void AbilityAutoStartupDataManagerFuzztest1(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr dataMgr = std::make_shared(); + AutoStartupInfo info; + info.bundleName = "com.example.fuzzTest"; + info.moduleName = "stringParam"; + info.abilityName = "MainAbility"; + info.appCloneIndex = int32Param; + info.accessTokenId = "accessTokenId"; + info.userId = int32Param; + dataMgr->ConvertAutoStartupDataToKey(info); + + DistributedKv::Key key1(jsonKey1); + DistributedKv::Key key1Illegal(jsonValue1Illegal); + DistributedKv::Value value1(jsonValue1); + dataMgr->ConvertAutoStartupInfoFromKeyAndValue(key1, value1); + dataMgr->ConvertAutoStartupInfoFromKeyAndValue(key1Illegal, value1); + + DistributedKv::Key key2(jsonKey2); + DistributedKv::Value value2(jsonValue2); + DistributedKv::Value value2Illegal(jsonValue1Illegal); + DistributedKv::Value value3(jsonValue3); + dataMgr->ConvertAutoStartupInfoFromKeyAndValue(key2, value2); + dataMgr->ConvertAutoStartupInfoFromKeyAndValue(key2, value2Illegal); + dataMgr->ConvertAutoStartupInfoFromKeyAndValue(key2, value3); + + nlohmann::json jsonObject = nlohmann::json::parse(key1.ToString(), nullptr, false); + dataMgr->IsEqual(jsonObject, "abilityName", "ability", boolParam); // branch,return true + dataMgr->IsEqual(jsonObject, "abilityName", "NaN", boolParam); // branch,return true + dataMgr->IsEqual(jsonObject, "userId", "ability", boolParam); // branch + dataMgr->IsEqual(jsonObject, "NaN", "ability", boolParam); // branch + + dataMgr->IsEqual(jsonObject, "userId", 100); // 100 means userid,branch + dataMgr->IsEqual(jsonObject, "userId", int32Param); // branch + dataMgr->IsEqual(jsonObject, "NaN", int32Param); + dataMgr->IsEqual(key1, info); + dataMgr->IsEqual(key2, info); + dataMgr->IsEqual(key1Illegal, info); + + dataMgr->IsEqual(key1, "token"); + dataMgr->IsEqual(key1, "NaN"); + dataMgr->IsEqual(key1Illegal, "token"); + + dataMgr->IsEqual(key1, 100); // 100 means userid + dataMgr->IsEqual(key1, int32Param); + dataMgr->IsEqual(key1Illegal, 0); +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + AbilityAutoStartupDataManagerFuzztest1(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/abilityautostartupdatamanagerb_fuzzer.h b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/abilityautostartupdatamanagerb_fuzzer.h new file mode 100755 index 0000000000..986e2a5f57 --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/abilityautostartupdatamanagerb_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPDATAMANAGERB_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPDATAMANAGERB_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityautostartupdatamanagerb_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPDATAMANAGERB_FUZZER_H diff --git a/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/corpus/init b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/project.xml b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityautostartupdatamanagerb_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityautostartupservicea_fuzzer/BUILD.gn b/test/fuzztest/abilityautostartupservicea_fuzzer/BUILD.gn new file mode 100755 index 0000000000..be7e922906 --- /dev/null +++ b/test/fuzztest/abilityautostartupservicea_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityAutoStartupServiceaFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilityautostartupservicea_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_data_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_service.cpp", + "abilityautostartupservicea_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:auto_startup_callback", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:perm_verification", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:libappexecfwk_common", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAutoStartupServiceaFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityautostartupservicea_fuzzer/abilityautostartupservicea_fuzzer.cpp b/test/fuzztest/abilityautostartupservicea_fuzzer/abilityautostartupservicea_fuzzer.cpp new file mode 100755 index 0000000000..866f3417d4 --- /dev/null +++ b/test/fuzztest/abilityautostartupservicea_fuzzer/abilityautostartupservicea_fuzzer.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 "abilityautostartupservicea_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "ability_auto_startup_service.h" +#undef protected +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void AbilityStartupServiceFuzztest(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr service = std::make_shared(); + sptr token1 = GetFuzzAbilityToken(); + service->RegisterAutoStartupSystemCallback(token1); // branch + service->RegisterAutoStartupSystemCallback(token1); // branch duplicate regist + service->UnregisterAutoStartupSystemCallback(token1); // branch + sptr token2 = GetFuzzAbilityToken(); + service->UnregisterAutoStartupSystemCallback(token2); // branch unregister not exist. + + AutoStartupInfo info; + info.bundleName = "com.example.fuzzTest"; + info.moduleName = "stringParam"; + info.abilityName = "MainAbility"; + info.appCloneIndex = int32Param; + info.accessTokenId = "accessTokenId"; + info.userId = int32Param; + service->SetApplicationAutoStartup(info); + service->InnerSetApplicationAutoStartup(info); + service->CancelApplicationAutoStartup(info); + + std::vector vecs; + vecs.emplace_back(info); + service->QueryAllAutoStartupApplications(vecs, int32Param); + service->QueryAllAutoStartupApplicationsWithoutPermission(vecs, int32Param); + service->DeleteAutoStartupData(stringParam, int32Param); + service->CheckAutoStartupData(stringParam, int32Param); + service->ExecuteCallbacks(boolParam, info); +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + AbilityStartupServiceFuzztest(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityautostartupservicea_fuzzer/abilityautostartupservicea_fuzzer.h b/test/fuzztest/abilityautostartupservicea_fuzzer/abilityautostartupservicea_fuzzer.h new file mode 100755 index 0000000000..57edc0fab1 --- /dev/null +++ b/test/fuzztest/abilityautostartupservicea_fuzzer/abilityautostartupservicea_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPSERVICEA_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPSERVICEA_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityautostartupservicea_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPSERVICEA_FUZZER_H diff --git a/test/fuzztest/abilityautostartupservicea_fuzzer/corpus/init b/test/fuzztest/abilityautostartupservicea_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityautostartupservicea_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityautostartupservicea_fuzzer/project.xml b/test/fuzztest/abilityautostartupservicea_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityautostartupservicea_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityautostartupserviceb_fuzzer/BUILD.gn b/test/fuzztest/abilityautostartupserviceb_fuzzer/BUILD.gn new file mode 100755 index 0000000000..c2eccaf98d --- /dev/null +++ b/test/fuzztest/abilityautostartupserviceb_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityAutoStartupServicebFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilityautostartupserviceb_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_data_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_service.cpp", + "abilityautostartupserviceb_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:auto_startup_callback", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:perm_verification", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:libappexecfwk_common", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityAutoStartupServicebFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityautostartupserviceb_fuzzer/abilityautostartupserviceb_fuzzer.cpp b/test/fuzztest/abilityautostartupserviceb_fuzzer/abilityautostartupserviceb_fuzzer.cpp new file mode 100755 index 0000000000..a6282a3607 --- /dev/null +++ b/test/fuzztest/abilityautostartupserviceb_fuzzer/abilityautostartupserviceb_fuzzer.cpp @@ -0,0 +1,153 @@ +/* + * 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 "abilityautostartupserviceb_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "ability_auto_startup_service.h" +#undef protected +#undef private + +#include "ability_record.h" +#include "auto_startup_callback_proxy.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void AbilityStartupServiceFuzztest1(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr service = std::make_shared(); + service->SetDeathRecipient(nullptr, nullptr); + sptr token1 = GetFuzzAbilityToken(); + service->SetDeathRecipient(token1, nullptr); // add deathrecipient + sptr client = + new (std::nothrow) AbilityAutoStartupService::ClientDeathRecipient(std::weak_ptr(service)); + service->SetDeathRecipient(token1, client); // add deathrecipient + service->SetDeathRecipient(token1, client); // duplicate add deathrecipient + sptr token2 = GetFuzzAbilityToken(); + service->RegisterAutoStartupSystemCallback(token1); + service->CleanResource(nullptr); // branch nullptr token + service->CleanResource(token1); // branch clean exists token + service->CleanResource(token2); // branch clean not exists token + + client->OnRemoteDied(nullptr); // branch + client->OnRemoteDied(token1); // branch + + service->GetSelfApplicationBundleName(); + service->CheckSelfApplication(stringParam); + AppExecFwk::BundleInfo bundleInfo; + service->GetBundleInfo(stringParam, bundleInfo, int32Param, int32Param, int32Param); // branch + AutoStartupInfo info; + service->GetAbilityData(info, boolParam, stringParam, stringParam, int32Param); // branch + AppExecFwk::AbilityInfo abilityInfo; + service->GetAbilityTypeName(abilityInfo); // branch + abilityInfo.type == AppExecFwk::AbilityType::PAGE; + service->GetAbilityTypeName(abilityInfo); // branch + AppExecFwk::ExtensionAbilityInfo extensionInfo; + service->GetExtensionTypeName(extensionInfo); + extensionInfo.type == AppExecFwk::ExtensionAbilityType::SERVICE; + service->GetExtensionTypeName(extensionInfo); + service->GetBundleMgrClient(); + service->CheckPermissionForSystem(); + service->CheckPermissionForSelf(stringParam); + service->GetAbilityInfo(info, stringParam, stringParam, int32Param); + service->SetApplicationAutoStartupByEDM(info, boolParam); + service->CancelApplicationAutoStartupByEDM(info, boolParam); + service->InnerApplicationAutoStartupByEDM(info, boolParam, boolParam); + service->CheckPermissionForEDM(); +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + AbilityStartupServiceFuzztest1(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityautostartupserviceb_fuzzer/abilityautostartupserviceb_fuzzer.h b/test/fuzztest/abilityautostartupserviceb_fuzzer/abilityautostartupserviceb_fuzzer.h new file mode 100755 index 0000000000..480c54a9f3 --- /dev/null +++ b/test/fuzztest/abilityautostartupserviceb_fuzzer/abilityautostartupserviceb_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPSERVICEB_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPSERVICEB_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityautostartupserviceb_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPSERVICEB_FUZZER_H diff --git a/test/fuzztest/abilityautostartupserviceb_fuzzer/corpus/init b/test/fuzztest/abilityautostartupserviceb_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityautostartupserviceb_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityautostartupserviceb_fuzzer/project.xml b/test/fuzztest/abilityautostartupserviceb_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityautostartupserviceb_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitybackgroundconnection_fuzzer/BUILD.gn b/test/fuzztest/abilitybackgroundconnection_fuzzer/BUILD.gn new file mode 100644 index 0000000000..ba3aa4c52e --- /dev/null +++ b/test/fuzztest/abilitybackgroundconnection_fuzzer/BUILD.gn @@ -0,0 +1,81 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityBackgroundConnectionFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitybackgroundconnection_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ability_background_connection.cpp", + "abilitybackgroundconnection_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityBackgroundConnectionFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitybackgroundconnection_fuzzer/abilitybackgroundconnection_fuzzer.cpp b/test/fuzztest/abilitybackgroundconnection_fuzzer/abilitybackgroundconnection_fuzzer.cpp new file mode 100644 index 0000000000..89e1925e6d --- /dev/null +++ b/test/fuzztest/abilitybackgroundconnection_fuzzer/abilitybackgroundconnection_fuzzer.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 "abilitybackgroundconnection_fuzzer.h" + +#include +#include + +#include "ability_background_connection.h" + +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr uint8_t ENABLE = 2; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + AppExecFwk::ElementName element; + sptr remoteObject; + int intParam = static_cast(GetU32Data(data)); + auto abilityBackgroundConnection = std::make_shared(); + abilityBackgroundConnection->OnAbilityConnectDone(element, remoteObject, intParam); + abilityBackgroundConnection->OnAbilityDisconnectDone(element, intParam); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitybackgroundconnection_fuzzer/abilitybackgroundconnection_fuzzer.h b/test/fuzztest/abilitybackgroundconnection_fuzzer/abilitybackgroundconnection_fuzzer.h new file mode 100644 index 0000000000..f6bd29feef --- /dev/null +++ b/test/fuzztest/abilitybackgroundconnection_fuzzer/abilitybackgroundconnection_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYBACKGROUNDCONNECTION_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYBACKGROUNDCONNECTION_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitybackgroundconnection_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYBACKGROUNDCONNECTION_FUZZER_H diff --git a/test/fuzztest/abilitybackgroundconnection_fuzzer/corpus/init b/test/fuzztest/abilitybackgroundconnection_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitybackgroundconnection_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitybackgroundconnection_fuzzer/project.xml b/test/fuzztest/abilitybackgroundconnection_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitybackgroundconnection_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitycachemanagera_fuzzer/BUILD.gn b/test/fuzztest/abilitycachemanagera_fuzzer/BUILD.gn new file mode 100755 index 0000000000..d5957acdcc --- /dev/null +++ b/test/fuzztest/abilitycachemanagera_fuzzer/BUILD.gn @@ -0,0 +1,97 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityCacheManageraFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitycachemanagera_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ability_cache_manager.cpp", + "abilitycachemanagera_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityCacheManageraFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitycachemanagera_fuzzer/abilitycachemanagera_fuzzer.cpp b/test/fuzztest/abilitycachemanagera_fuzzer/abilitycachemanagera_fuzzer.cpp new file mode 100755 index 0000000000..91a4914272 --- /dev/null +++ b/test/fuzztest/abilitycachemanagera_fuzzer/abilitycachemanagera_fuzzer.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 "abilitycachemanagera_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "ability_cache_manager.h" +#undef protected +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +Want& SetElement(Want &want) +{ + return want.SetElementName("deviceId", "bundleName", "ability", "moduleName"); +} + +void AbilityCacheManagerFuzztest1(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + AbilityCacheManager& mgr = AbilityCacheManager::GetInstance(); + mgr.Init(int32Param, int32Param); + std::shared_ptr abilityRecord1; + Want want; + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + std::shared_ptr abilityRecord2 = std::make_shared(want, abilityInfo, applicationInfo); + abilityRecord2->recordId_ = 2; // 2 means recordId + std::shared_ptr abilityRecord3 = std::make_shared(want, abilityInfo, applicationInfo); + abilityRecord3->recordId_ = 3; // 3 means recordId + mgr.AddToProcLru(abilityRecord2); + mgr.AddToDevLru(abilityRecord2, abilityRecord2); + mgr.AddToProcLru(abilityRecord3); + mgr.AddToDevLru(abilityRecord3, abilityRecord3); + mgr.Put(abilityRecord1); + mgr.Remove(abilityRecord1); + mgr.Put(abilityRecord2); + mgr.Remove(abilityRecord2); + AbilityRequest abilityRequest; + SetElement(abilityRequest.want); + bool ret = mgr.IsRecInfoSame(abilityRequest, abilityRecord2); + abilityInfo.moduleName = "moduleName"; + abilityRequest.abilityInfo.moduleName = abilityInfo.moduleName; + SetElement(want); + std::shared_ptr abilityRecord4 = std::make_shared(want, abilityInfo, applicationInfo); + ret = mgr.IsRecInfoSame(abilityRequest, abilityRecord4); + abilityInfo.moduleName = "moduleName1"; + mgr.IsRecInfoSame(abilityRequest, abilityRecord4); + mgr.AddToProcLru(abilityRecord4); + mgr.GetAbilityRecInProcList(abilityRequest); + abilityRequest.appInfo.accessTokenId = applicationInfo.accessTokenId; + mgr.GetAbilityRecInProcList(abilityRequest); + mgr.Get(abilityRequest); + mgr.FindRecordByToken(nullptr); + sptr token = GetFuzzAbilityToken(); + mgr.FindRecordByToken(token); + mgr.GetAbilityList(); + mgr.FindRecordBySessionId(stringParam); + mgr.FindRecordByServiceKey(stringParam); + mgr.RemoveLauncherDeathRecipient(); + mgr.SignRestartAppFlag(stringParam); + mgr.DeleteInvalidServiceRecord(stringParam); +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + AbilityCacheManagerFuzztest1(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitycachemanagera_fuzzer/abilitycachemanagera_fuzzer.h b/test/fuzztest/abilitycachemanagera_fuzzer/abilitycachemanagera_fuzzer.h new file mode 100755 index 0000000000..1180410d1c --- /dev/null +++ b/test/fuzztest/abilitycachemanagera_fuzzer/abilitycachemanagera_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYCACHEMANAGERA_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYCACHEMANAGERA_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitycachemanagera_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYCACHEMANAGERA_FUZZER_H diff --git a/test/fuzztest/abilitycachemanagera_fuzzer/corpus/init b/test/fuzztest/abilitycachemanagera_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitycachemanagera_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitycachemanagera_fuzzer/project.xml b/test/fuzztest/abilitycachemanagera_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitycachemanagera_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitychildprocessinfo_fuzzer/BUILD.gn b/test/fuzztest/abilitychildprocessinfo_fuzzer/BUILD.gn new file mode 100644 index 0000000000..0d4b6820da --- /dev/null +++ b/test/fuzztest/abilitychildprocessinfo_fuzzer/BUILD.gn @@ -0,0 +1,63 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +##############################fuzztest########################################## +module_output_path = "ability_runtime/appmgrservice" +ohos_fuzztest("AbilityChildProcessInfoFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitychildprocessinfo_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilitychildprocessinfo_fuzzer.cpp" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:want", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "samgr:samgr_proxy", + "window_manager:libwm", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityChildProcessInfoFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitychildprocessinfo_fuzzer/abilitychildprocessinfo_fuzzer.cpp b/test/fuzztest/abilitychildprocessinfo_fuzzer/abilitychildprocessinfo_fuzzer.cpp new file mode 100644 index 0000000000..3219216e52 --- /dev/null +++ b/test/fuzztest/abilitychildprocessinfo_fuzzer/abilitychildprocessinfo_fuzzer.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "abilitychildprocessinfo_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "child_process_info.h" +#undef protected +#undef private +#include "parcel.h" +#include +#include "securec.h" +#include "configuration.h" + +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptrchildProcessInfo = std::make_shared(); + if (childProcessInfo == nullptr) { + return false; + } + Parcel parcel; + childProcessInfo->ReadFromParcel(parcel); + childProcessInfo->Marshalling(parcel); + ChildProcessInfo::Unmarshalling(parcel); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitychildprocessinfo_fuzzer/abilitychildprocessinfo_fuzzer.h b/test/fuzztest/abilitychildprocessinfo_fuzzer/abilitychildprocessinfo_fuzzer.h new file mode 100644 index 0000000000..1e2acc5d6b --- /dev/null +++ b/test/fuzztest/abilitychildprocessinfo_fuzzer/abilitychildprocessinfo_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYCHILDPROCESSINFO_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYCHILDPROCESSINFO_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitychildprocessinfo_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMANAGERSERVICEA_FUZZER_H diff --git a/test/fuzztest/abilitychildprocessinfo_fuzzer/corpus/init b/test/fuzztest/abilitychildprocessinfo_fuzzer/corpus/init new file mode 100644 index 0000000000..8eb5a7d6eb --- /dev/null +++ b/test/fuzztest/abilitychildprocessinfo_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitychildprocessinfo_fuzzer/project.xml b/test/fuzztest/abilitychildprocessinfo_fuzzer/project.xml new file mode 100644 index 0000000000..6e8ad2cfde --- /dev/null +++ b/test/fuzztest/abilitychildprocessinfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitychildprocessrecord_fuzzer/BUILD.gn b/test/fuzztest/abilitychildprocessrecord_fuzzer/BUILD.gn new file mode 100644 index 0000000000..f6e966ebbe --- /dev/null +++ b/test/fuzztest/abilitychildprocessrecord_fuzzer/BUILD.gn @@ -0,0 +1,98 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +##############################fuzztest########################################## +module_output_path = "ability_runtime/appmgrservice" +ohos_fuzztest("AbilityChildProcessRecordFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitychildprocessrecord_fuzzer" + + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include/", + "${ability_runtime_services_path}/appmgr/include/", + "{ability_runtime_services_path}/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr/", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/child_process_args.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/child_process_options.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/child_process_request.cpp", + "${ability_runtime_services_path}/appmgr/src/child_process_record.cpp", + "abilitychildprocessrecord_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/appmgr:appmgr_config" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:event_report", + "${ability_runtime_services_path}/common:perm_verification", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:want", + "access_token:libaccesstoken_sdk", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hicollie:libhicollie", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbeget_proxy", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_mgr", + "memory_utils:libmeminfo", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libwm", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityChildProcessRecordFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitychildprocessrecord_fuzzer/abilitychildprocessrecord_fuzzer.cpp b/test/fuzztest/abilitychildprocessrecord_fuzzer/abilitychildprocessrecord_fuzzer.cpp new file mode 100644 index 0000000000..26dc9044b6 --- /dev/null +++ b/test/fuzztest/abilitychildprocessrecord_fuzzer/abilitychildprocessrecord_fuzzer.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "abilitychildprocessrecord_fuzzer.h" + +#define private public +#include "app_running_record.h" +#include "child_process_record.h" +#undef private +#include "child_process_request.h" +#include +#include +#include +#include "securec.h" +#include "configuration.h" +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +namespace OHOS { +namespace { +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +} + + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; +} + + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + int32_t hostPid = static_cast(GetU32Data(data)); + ChildProcessRequest request; + std::shared_ptr hostRecord; + ChildProcessRecord::CreateChildProcessRecord(hostPid,request,hostRecord); + std::string stringParam(data, size); + sptr mainProcessCb; + int32_t childProcessCount =static_cast(GetU32Data(data)); + bool isStartWithDebug = *data % ENABLE; + ChildProcessRecord::CreateNativeChildProcessRecord(hostPid,stringParam,hostRecord,mainProcessCb,childProcessCount,isStartWithDebug); + std::shared_ptr appInfo = std::make_shared(); + int32_t RECORD_ID = static_cast(GetU32Data(data)); + auto appRecord = std::make_shared(appInfo, RECORD_ID, stringParam); + auto childRecord = std::make_shared(hostPid, request, appRecord); + childRecord->SetPid(hostPid); + childRecord->GetPid(); + childRecord->GetHostPid(); + int32_t uid = static_cast(GetU32Data(data)); + childRecord->SetUid(uid); + childRecord->GetUid(); + childRecord->GetProcessName(); + childRecord->GetSrcEntry(); + childRecord->GetHostRecord(); + sptr scheduler; + childRecord->SetScheduler(scheduler); + sptr recipient; + childRecord->SetDeathRecipient(recipient); + childRecord->RegisterDeathRecipient(); + childRecord-> RemoveDeathRecipient(); + childRecord-> ScheduleExitProcessSafely(); + childRecord->isStartWithDebug(); + childRecord-> GetChildProcessType(); + childRecord->GetMainProcessCallback(); + childRecord->ClearMainProcessCallback(); + std::string entryParams(data, size); + childRecord->GetEntryParams(); + childRecord->MakeProcessName(hostRecord); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitychildprocessrecord_fuzzer/abilitychildprocessrecord_fuzzer.h b/test/fuzztest/abilitychildprocessrecord_fuzzer/abilitychildprocessrecord_fuzzer.h new file mode 100644 index 0000000000..1145c7ff2c --- /dev/null +++ b/test/fuzztest/abilitychildprocessrecord_fuzzer/abilitychildprocessrecord_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYCHILDPROCESSRECORD_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYCHILDPROCESSRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitychildprocessrecord_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYATTACHTIMEOUT_FUZZER_H diff --git a/test/fuzztest/abilitychildprocessrecord_fuzzer/corpus/init b/test/fuzztest/abilitychildprocessrecord_fuzzer/corpus/init new file mode 100644 index 0000000000..8eb5a7d6eb --- /dev/null +++ b/test/fuzztest/abilitychildprocessrecord_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitychildprocessrecord_fuzzer/project.xml b/test/fuzztest/abilitychildprocessrecord_fuzzer/project.xml new file mode 100644 index 0000000000..6e8ad2cfde --- /dev/null +++ b/test/fuzztest/abilitychildprocessrecord_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitycontext_fuzzer/abilitycontext_fuzzer.cpp b/test/fuzztest/abilitycontext_fuzzer/abilitycontext_fuzzer.cpp index 563b92e25e..80802fa45e 100644 --- a/test/fuzztest/abilitycontext_fuzzer/abilitycontext_fuzzer.cpp +++ b/test/fuzztest/abilitycontext_fuzzer/abilitycontext_fuzzer.cpp @@ -20,7 +20,7 @@ #include "ability_record.h" #define private public -#include "ability_context.h" +#include "fa_ability_context.h" #undef private #include "want.h" #include "parcel.h" diff --git a/test/fuzztest/abilitydebugdeal_fuzzer/BUILD.gn b/test/fuzztest/abilitydebugdeal_fuzzer/BUILD.gn new file mode 100644 index 0000000000..68a984c1d0 --- /dev/null +++ b/test/fuzztest/abilitydebugdeal_fuzzer/BUILD.gn @@ -0,0 +1,86 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityDebugDealFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitydebugdeal_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/ability_debug_response_stub.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_debug_deal.cpp", + "abilitydebugdeal_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + #deps file + ":AbilityDebugDealFuzzTest", + ] +} +############################################################################## # diff --git a/test/fuzztest/abilitydebugdeal_fuzzer/abilitydebugdeal_fuzzer.cpp b/test/fuzztest/abilitydebugdeal_fuzzer/abilitydebugdeal_fuzzer.cpp new file mode 100644 index 0000000000..3ec7aca18e --- /dev/null +++ b/test/fuzztest/abilitydebugdeal_fuzzer/abilitydebugdeal_fuzzer.cpp @@ -0,0 +1,129 @@ +/* + * 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 "abilitydebugdeal_fuzzer.h" + +#include +#include + +#define private public +#include "ability_debug_deal.h" +#undef private +#include "ability_record.h" +#include "ability_debug_response_stub.h" +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr uint8_t ENABLE = 2; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +std::shared_ptr GetFuzzAbilityRecord() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (!abilityRecord) { + return nullptr; + } + return abilityRecord; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + std::shared_ptr abilityRecord = GetFuzzAbilityRecord(); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + sptr token = GetFuzzAbilityToken(); + std::vector> tokens; + std::weak_ptr deal; + auto abilityDebugDeal = std::make_shared(); + abilityDebugDeal->OnAbilitysDebugStarted(tokens); + abilityDebugDeal->OnAbilitysDebugStoped(tokens); + abilityDebugDeal->OnAbilitysAssertDebugChange(tokens, boolParam); + abilityDebugDeal->RegisterAbilityDebugResponse(); + + auto abilityDebugResponse = std::make_shared(deal); + abilityDebugResponse->OnAbilitysDebugStarted(tokens); + abilityDebugResponse->OnAbilitysDebugStoped(tokens); + abilityDebugResponse->OnAbilitysAssertDebugChange(tokens, boolParam); + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitydebugdeal_fuzzer/abilitydebugdeal_fuzzer.h b/test/fuzztest/abilitydebugdeal_fuzzer/abilitydebugdeal_fuzzer.h new file mode 100644 index 0000000000..8280ee0c90 --- /dev/null +++ b/test/fuzztest/abilitydebugdeal_fuzzer/abilitydebugdeal_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYDEBUGDEAL_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYDEBUGDEAL_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitydebugdeal_fuzzer" + +#endif diff --git a/test/fuzztest/abilitydebugdeal_fuzzer/corpus/init b/test/fuzztest/abilitydebugdeal_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitydebugdeal_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitydebugdeal_fuzzer/project.xml b/test/fuzztest/abilitydebugdeal_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitydebugdeal_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitydebugresponseproxy_fuzzer/BUILD.gn b/test/fuzztest/abilitydebugresponseproxy_fuzzer/BUILD.gn new file mode 100755 index 0000000000..0a2de126a2 --- /dev/null +++ b/test/fuzztest/abilitydebugresponseproxy_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityDebugResponseProxyFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitydebugresponseproxy_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/ability_debug_response_proxy.cpp", + "abilitydebugresponseproxy_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:auto_startup_callback", + "${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", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:libappexecfwk_common", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityDebugResponseProxyFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitydebugresponseproxy_fuzzer/abilitydebugresponseproxy_fuzzer.cpp b/test/fuzztest/abilitydebugresponseproxy_fuzzer/abilitydebugresponseproxy_fuzzer.cpp new file mode 100755 index 0000000000..dd0b054718 --- /dev/null +++ b/test/fuzztest/abilitydebugresponseproxy_fuzzer/abilitydebugresponseproxy_fuzzer.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 "abilitydebugresponseproxy_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "ability_debug_response_proxy.h" +#undef protected +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void AbilityDebugResponseProxyFuzztest1(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr proxy = + std::make_shared(nullptr); // branch constructor + MessageParcel data; + proxy->WriteInterfaceToken(data); // branch + std::vector> tokens; + proxy->OnAbilitysDebugStarted(tokens); // branch + proxy->OnAbilitysDebugStoped(tokens); // branch + proxy->OnAbilitysAssertDebugChange(tokens, boolParam); // branch + sptr token = GetFuzzAbilityToken(); + tokens.emplace_back(token); + proxy->SendRequest(static_cast(int32Param), tokens); // branch tokens no empty. + tokens.clear(); + proxy->SendRequest(static_cast(int32Param), tokens); // branch tokens empty. +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + AbilityDebugResponseProxyFuzztest1(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitydebugresponseproxy_fuzzer/abilitydebugresponseproxy_fuzzer.h b/test/fuzztest/abilitydebugresponseproxy_fuzzer/abilitydebugresponseproxy_fuzzer.h new file mode 100755 index 0000000000..c7ef4e55ec --- /dev/null +++ b/test/fuzztest/abilitydebugresponseproxy_fuzzer/abilitydebugresponseproxy_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_ABILITYDEBUGRESPONSEPROXY_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_ABILITYDEBUGRESPONSEPROXY_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitydebugresponseproxy_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_ABILITYDEBUGRESPONSEPROXY_FUZZER_H diff --git a/test/fuzztest/abilitydebugresponseproxy_fuzzer/corpus/init b/test/fuzztest/abilitydebugresponseproxy_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitydebugresponseproxy_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitydebugresponseproxy_fuzzer/project.xml b/test/fuzztest/abilitydebugresponseproxy_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitydebugresponseproxy_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityeventutil_fuzzer/BUILD.gn b/test/fuzztest/abilityeventutil_fuzzer/BUILD.gn new file mode 100644 index 0000000000..8f25606141 --- /dev/null +++ b/test/fuzztest/abilityeventutil_fuzzer/BUILD.gn @@ -0,0 +1,82 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityEventUtilFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilityeventutil_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ability_event_util.cpp", + "abilityeventutil_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityEventUtilFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityeventutil_fuzzer/abilityeventutil_fuzzer.cpp b/test/fuzztest/abilityeventutil_fuzzer/abilityeventutil_fuzzer.cpp new file mode 100644 index 0000000000..fd6fe697e5 --- /dev/null +++ b/test/fuzztest/abilityeventutil_fuzzer/abilityeventutil_fuzzer.cpp @@ -0,0 +1,91 @@ +/* + * 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 "abilityeventutil_fuzzer.h" + +#include +#include +#include + +#include "ability_event_util.h" +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr uint8_t ENABLE = 2; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::string strParam(data, size); + int intParam = static_cast(GetU32Data(data)); + auto abilityEventUtil = std::make_shared(); + abilityEventUtil->HandleModuleInfoUpdated(strParam, intParam); + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityeventutil_fuzzer/abilityeventutil_fuzzer.h b/test/fuzztest/abilityeventutil_fuzzer/abilityeventutil_fuzzer.h new file mode 100644 index 0000000000..7ec29475ce --- /dev/null +++ b/test/fuzztest/abilityeventutil_fuzzer/abilityeventutil_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYEVENTTUTIL_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYEVENTTUTIL_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityeventutil_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYEVENTTUTIL_FUZZER_H diff --git a/test/fuzztest/abilityeventutil_fuzzer/corpus/init b/test/fuzztest/abilityeventutil_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityeventutil_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityeventutil_fuzzer/project.xml b/test/fuzztest/abilityeventutil_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityeventutil_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/BUILD.gn b/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/BUILD.gn new file mode 100644 index 0000000000..e004cbeea6 --- /dev/null +++ b/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/BUILD.gn @@ -0,0 +1,87 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityFirstFrameStateObserverManagerFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityfirstframestateobservermanager_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_services_path}/common/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ability_first_frame_state_observer_manager.cpp", + "${ability_runtime_services_path}/common/src/permission_verification.cpp", + "abilityfirstframestateobservermanager_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityFirstFrameStateObserverManagerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/abilityfirstframestateobservermanager_fuzzer.cpp b/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/abilityfirstframestateobservermanager_fuzzer.cpp new file mode 100644 index 0000000000..326ad66bf8 --- /dev/null +++ b/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/abilityfirstframestateobservermanager_fuzzer.cpp @@ -0,0 +1,102 @@ +/* + * 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 "abilityfirstframestateobservermanager_fuzzer.h" + +#include +#include + +#define protected public +#include "ability_first_frame_state_observer_manager.h" +#undef protected +#include "permission_verification.h" +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr uint8_t ENABLE = 2; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} // namespace +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | + (ptr[ENABLE] << OFFSET_TWO) | ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string strParam(data, size); + std::shared_ptr abilityRecord; + sptr observers; + sptr observer; + auto abilityFirstFrameStateObserverSet = + std::make_shared(boolParam); + abilityFirstFrameStateObserverSet->AddAbilityFirstFrameStateObserver( + observer, strParam); + abilityFirstFrameStateObserverSet->RemoveAbilityFirstFrameStateObserver(observer); + abilityFirstFrameStateObserverSet->OnAbilityFirstFrameState(abilityRecord); + abilityFirstFrameStateObserverSet->AddObserverDeathRecipient(observers); + abilityFirstFrameStateObserverSet->RemoveObserverDeathRecipient(observers); + AbilityFirstFrameStateObserverManager& instance = + AbilityFirstFrameStateObserverManager::GetInstance(); + instance.Init(); + instance.RegisterAbilityFirstFrameStateObserver(observer, strParam); + instance.UnregisterAbilityFirstFrameStateObserver(observer); + instance.HandleOnFirstFrameState(abilityRecord); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} diff --git a/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/abilityfirstframestateobservermanager_fuzzer.h b/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/abilityfirstframestateobservermanager_fuzzer.h new file mode 100644 index 0000000000..9165caba14 --- /dev/null +++ b/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/abilityfirstframestateobservermanager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFIRSTFRAMESTATEOBSERVERMANAGER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFIRSTFRAMESTATEOBSERVERMANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityfirstframestateobservermanager_fuzzer" + +#endif diff --git a/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/corpus/init b/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/project.xml b/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityfirstframestateobservermanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/BUILD.gn b/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/BUILD.gn new file mode 100644 index 0000000000..662b510795 --- /dev/null +++ b/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/BUILD.gn @@ -0,0 +1,75 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/appmgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityForegroundStateObserverProxyFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityforegroundstateobserverproxy_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityforegroundstateobserverproxy_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/appmgr:appmgr_config" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityForegroundStateObserverProxyFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/abilityforegroundstateobserverproxy_fuzzer.cpp b/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/abilityforegroundstateobserverproxy_fuzzer.cpp new file mode 100644 index 0000000000..0f50bf9882 --- /dev/null +++ b/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/abilityforegroundstateobserverproxy_fuzzer.cpp @@ -0,0 +1,99 @@ +/* + * 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 "abilityforegroundstateobserverproxy_fuzzer.h" + +#include +#include + +#define private public +#include "ability_foreground_state_observer_proxy.h" +#undef private + +#include "ability_record.h" +#include "parcel.h" +#include "securec.h" +#include "want.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +const std::u16string APPMGR_INTERFACE_TOKEN = u"ohos.aafwk.AppManager"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + sptr impl; + auto abilityForegroundStateObserverProxy = std::make_shared(impl); + AbilityStateData abilityStateData; + abilityForegroundStateObserverProxy->OnAbilityStateChanged(abilityStateData); + MessageParcel dataParcel; + abilityForegroundStateObserverProxy->WriteInterfaceToken(dataParcel); + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} diff --git a/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/abilityforegroundstateobserverproxy_fuzzer.h b/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/abilityforegroundstateobserverproxy_fuzzer.h new file mode 100644 index 0000000000..fa58d7e161 --- /dev/null +++ b/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/abilityforegroundstateobserverproxy_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFOREGROUNDSTATEOBSERVERPROXY_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFOREGROUNDSTATEOBSERVERPROXY_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityforegroundstateobserverproxy_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFOREGROUNDSTATEOBSERVERPROXY_FUZZER_H diff --git a/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/corpus/init b/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/project.xml b/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityforegroundstateobserverproxy_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityframeworkscjenvironment_fuzzer/BUILD.gn b/test/fuzztest/abilityframeworkscjenvironment_fuzzer/BUILD.gn new file mode 100644 index 0000000000..42de5ca11d --- /dev/null +++ b/test/fuzztest/abilityframeworkscjenvironment_fuzzer/BUILD.gn @@ -0,0 +1,119 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +import("//foundation/ability/ability_runtime/cj_environment/cj_environment.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityFrameworksCjEnvironmentFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityframeworkscjenvironment_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + "${ability_runtime_path}/cj_environment/frameworks/cj_environment/include", + "${ability_runtime_native_path}/runtime", + "${ability_runtime_native_path}/runtime/utils/include", + "${ability_base_kits_path}/extractortool/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//third_party/jsoncpp:jsoncpp", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_path}/cj_environment/frameworks/cj_environment/src/cj_environment.cpp", + "abilityframeworkscjenvironment_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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_innerkits_path}/uri_permission:uri_permission_mgr", + "${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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + defines = [ "WITH_EVENT_HANDLER" ] + external_deps = [ + "ability_base:extractortool", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "ability_runtime:js_environment", + "ability_runtime:runtime", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ets_runtime:libark_jsruntime", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityFrameworksCjEnvironmentFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityframeworkscjenvironment_fuzzer/abilityframeworkscjenvironment_fuzzer.cpp b/test/fuzztest/abilityframeworkscjenvironment_fuzzer/abilityframeworkscjenvironment_fuzzer.cpp new file mode 100644 index 0000000000..c09ee88c67 --- /dev/null +++ b/test/fuzztest/abilityframeworkscjenvironment_fuzzer/abilityframeworkscjenvironment_fuzzer.cpp @@ -0,0 +1,106 @@ +/* + * 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 "abilityframeworkscjenvironment_fuzzer.h" + +#include +#include + +#define private public +#include "cj_environment.h" +#undef private + +#include "ability_record.h" +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::string jsonStr(data, size); + IsCJAbility(jsonStr); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityframeworkscjenvironment_fuzzer/abilityframeworkscjenvironment_fuzzer.h b/test/fuzztest/abilityframeworkscjenvironment_fuzzer/abilityframeworkscjenvironment_fuzzer.h new file mode 100644 index 0000000000..97127ada29 --- /dev/null +++ b/test/fuzztest/abilityframeworkscjenvironment_fuzzer/abilityframeworkscjenvironment_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFRAMEWORKSCJENVIRONMENT_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFRAMEWORKSCJENVIRONMENT_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityframeworkscjenvironment_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFRAMEWORKSCJENVIRONMENT_FUZZER_H diff --git a/test/fuzztest/abilityframeworkscjenvironment_fuzzer/corpus/init b/test/fuzztest/abilityframeworkscjenvironment_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityframeworkscjenvironment_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityframeworkscjenvironment_fuzzer/project.xml b/test/fuzztest/abilityframeworkscjenvironment_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityframeworkscjenvironment_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityframeworksnativejsworker_fuzzer/BUILD.gn b/test/fuzztest/abilityframeworksnativejsworker_fuzzer/BUILD.gn new file mode 100644 index 0000000000..a0c9399bb4 --- /dev/null +++ b/test/fuzztest/abilityframeworksnativejsworker_fuzzer/BUILD.gn @@ -0,0 +1,112 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityFrameworksNativeJsWorkerFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityframeworksnativejsworker_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + "${ability_runtime_native_path}/runtime", + "${ability_runtime_native_path}/runtime/utils/include", + "${ability_base_kits_path}/extractortool/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//third_party/jsoncpp:jsoncpp", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityframeworksnativejsworker_fuzzer.cpp" ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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_innerkits_path}/uri_permission:uri_permission_mgr", + "${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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:extractortool", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "ability_runtime:js_environment", + "ability_runtime:runtime", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ets_runtime:libark_jsruntime", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityFrameworksNativeJsWorkerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityframeworksnativejsworker_fuzzer/abilityframeworksnativejsworker_fuzzer.cpp b/test/fuzztest/abilityframeworksnativejsworker_fuzzer/abilityframeworksnativejsworker_fuzzer.cpp new file mode 100644 index 0000000000..73a433b75b --- /dev/null +++ b/test/fuzztest/abilityframeworksnativejsworker_fuzzer/abilityframeworksnativejsworker_fuzzer.cpp @@ -0,0 +1,132 @@ +/* + * 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 "abilityframeworksnativejsworker_fuzzer.h" + +#include +#include + +#define private public +#include "js_worker.h" +#undef private + +#include "ability_record.h" +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr workerInfo = std::make_shared(); + workerInfo->codePath = "/data/test/codePath"; + workerInfo->packagePathStr = "/data/test/packagePath"; + workerInfo->hapPath = "/data/test/hapPath"; + workerInfo->moduleName = "moduleName"; + AbilityRuntime::AssetHelper helper = AbilityRuntime::AssetHelper(workerInfo); + std::string jsonStr(data, size); + uint8_t *buff = nullptr; + size_t buffSize; + helper.GetSafeData(jsonStr, &buff, &buffSize); + helper.NormalizedFileName(jsonStr); + bool useSecureMem = *data % ENABLE; + bool isRestricted = *data % ENABLE; + std::vector content; + helper.ReadAmiData(jsonStr, &buff, &buffSize, content, useSecureMem, isRestricted); + helper.ReadFilePathData(jsonStr, &buff, &buffSize, content, useSecureMem, isRestricted); + helper.GetAmi(jsonStr, jsonStr); + AbilityRuntime::GetContainerId(); + bool isDebugApp = *data % ENABLE; + bool isNativeStart = *data % ENABLE; + AbilityRuntime::StartDebuggerInWorkerModule(isDebugApp, isNativeStart); + NativeEngine *nativeEngine = nullptr; + AbilityRuntime::InitWorkerFunc(nativeEngine); + AbilityRuntime::OffWorkerFunc(nativeEngine); + int32_t id = static_cast(GetU32Data(data)); + AbilityRuntime::UpdateContainerScope(id); + AbilityRuntime::RestoreContainerScope(id); + AbilityRuntime::SetJsFramework(); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityframeworksnativejsworker_fuzzer/abilityframeworksnativejsworker_fuzzer.h b/test/fuzztest/abilityframeworksnativejsworker_fuzzer/abilityframeworksnativejsworker_fuzzer.h new file mode 100644 index 0000000000..0ac7d373cf --- /dev/null +++ b/test/fuzztest/abilityframeworksnativejsworker_fuzzer/abilityframeworksnativejsworker_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFRAMEWORKSNATIVEJSWORKER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFRAMEWORKSNATIVEJSWORKER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityframeworksnativejsworker_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFRAMEWORKSNATIVEJSWORKER_FUZZER_H diff --git a/test/fuzztest/abilityframeworksnativejsworker_fuzzer/corpus/init b/test/fuzztest/abilityframeworksnativejsworker_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityframeworksnativejsworker_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityframeworksnativejsworker_fuzzer/project.xml b/test/fuzztest/abilityframeworksnativejsworker_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityframeworksnativejsworker_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/BUILD.gn b/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/BUILD.gn new file mode 100644 index 0000000000..8c9733cf7c --- /dev/null +++ b/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/BUILD.gn @@ -0,0 +1,118 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +import("//foundation/ability/ability_runtime/js_environment/js_environment.gni") + +##############################fuzztest########################################## +ohos_fuzztest("AbilityFrameworksNativeOhosJsEnvLoggerFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + "${ability_runtime_native_path}/runtime", + "${ability_runtime_native_path}/runtime/utils/include", + "${ability_base_kits_path}/extractortool/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "//third_party/jsoncpp:jsoncpp", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/app_scheduler.cpp", + "${ability_runtime_services_path}/abilitymgr/src/start_ability_utils.cpp", + "abilityframeworksnativeohosjsenvlogger_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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_innerkits_path}/uri_permission:uri_permission_mgr", + "${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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:extractortool", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "ability_runtime:js_environment", + "ability_runtime:runtime", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ets_runtime:libark_jsruntime", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityFrameworksNativeOhosJsEnvLoggerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/abilityframeworksnativeohosjsenvlogger_fuzzer.cpp b/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/abilityframeworksnativeohosjsenvlogger_fuzzer.cpp new file mode 100644 index 0000000000..4b2fae8ecb --- /dev/null +++ b/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/abilityframeworksnativeohosjsenvlogger_fuzzer.cpp @@ -0,0 +1,90 @@ +/* + * 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 "abilityframeworksnativeohosjsenvlogger_fuzzer.h" + +#include +#include + +#define private public +#include "ohos_js_env_logger.h" +#undef private +#include "js_environment.h" +#include "securec.h" + +using namespace OHOS::JsEnv; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + AbilityRuntime::OHOSJsEnvLogger::RegisterJsEnvLogger(); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/abilityframeworksnativeohosjsenvlogger_fuzzer.h b/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/abilityframeworksnativeohosjsenvlogger_fuzzer.h new file mode 100644 index 0000000000..bfdf2c636c --- /dev/null +++ b/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/abilityframeworksnativeohosjsenvlogger_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFRAMEWORKSNATIVEOHOSJSENVLOGGER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYFRAMEWORKSNATIVEOHOSJSENVLOGGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityframeworksnativeohosjsenvlogger_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMANAGERSERVICEA_FUZZER_H diff --git a/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/corpus/init b/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/project.xml b/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityframeworksnativeohosjsenvlogger_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/BUILD.gn b/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/BUILD.gn new file mode 100644 index 0000000000..1500deea9f --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/BUILD.gn @@ -0,0 +1,82 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityInterfacesAppManagerAmsMgrStubFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityinterfacesappmanageramsmgrstub_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:perm_verification", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityInterfacesAppManagerAmsMgrStubFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/abilityinterfacesappmanageramsmgrstub_fuzzer.cpp b/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/abilityinterfacesappmanageramsmgrstub_fuzzer.cpp new file mode 100644 index 0000000000..689cb472c5 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/abilityinterfacesappmanageramsmgrstub_fuzzer.cpp @@ -0,0 +1,118 @@ +/* + * 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 "abilityinterfacesappmanageramsmgrstub_fuzzer.h" + +#include +#include + +#define private public +#include "ams_mgr_stub.h" +#include "ams_mgr_scheduler.h" +#undef private + +#include "securec.h" +#include "parcel.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +const std::u16string AMSMGR_INTERFACE_TOKEN = u"ohos.appexecfwk.IAmsMgr"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + uint32_t code = static_cast(IAmsMgr::Message::UPDATE_EXTENSION_STATE); + MessageParcel parcel; + parcel.WriteInterfaceToken(AMSMGR_INTERFACE_TOKEN); + parcel.WriteBuffer(data, size); + parcel.RewindRead(0); + MessageParcel reply; + MessageOption option; + std::shared_ptr MgrServiceInner; + std::shared_ptr Handler; + std::shared_ptr abms = std::make_shared(MgrServiceInner, Handler); + abms->OnRemoteRequest(code, parcel, reply, option); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/abilityinterfacesappmanageramsmgrstub_fuzzer.h b/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/abilityinterfacesappmanageramsmgrstub_fuzzer.h new file mode 100644 index 0000000000..ece7601ebb --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/abilityinterfacesappmanageramsmgrstub_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMANGERAMSMGRSTUB_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMANGERAMSMGRSTUB_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityinterfacesappmanageramsmgrstub_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMANGERAMSMGRSTUB_FUZZER_H diff --git a/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/corpus/init b/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/project.xml b/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmanageramsmgrstub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/BUILD.gn b/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/BUILD.gn new file mode 100644 index 0000000000..006c7c5a79 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/BUILD.gn @@ -0,0 +1,82 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityInterfacesAppMgrAbilityDebugResponseProxyFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:perm_verification", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityInterfacesAppMgrAbilityDebugResponseProxyFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer.cpp b/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer.cpp new file mode 100644 index 0000000000..2b68bca8be --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer.cpp @@ -0,0 +1,125 @@ +/* + * 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 "abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer.h" + +#include +#include + +#define private public +#include "ability_debug_response_proxy.h" +#include "ability_debug_response_interface.h" +#undef private + +#include "securec.h" +#include "parcel.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +const std::u16string AMSMGR_INTERFACE_TOKEN = u"ohos.appexecfwk.IAmsMgr"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + sptr impl; + std::shared_ptr infosProxy = std::make_shared(impl); + std::vector> tokens; + infosProxy->OnAbilitysDebugStarted(tokens); + infosProxy->OnAbilitysDebugStoped(tokens); + bool isAssertDebug = *data % ENABLE; + infosProxy->OnAbilitysAssertDebugChange(tokens, isAssertDebug); + MessageParcel parcels; + parcels.WriteInterfaceToken(AMSMGR_INTERFACE_TOKEN); + parcels.WriteBuffer(data, size); + parcels.RewindRead(0); + infosProxy->WriteInterfaceToken(parcels); + IAbilityDebugResponse::Message message = IAbilityDebugResponse::Message::ON_ABILITYS_DEBUG_STARTED; + infosProxy->SendRequest(message, tokens); + message = IAbilityDebugResponse::Message::ON_ABILITYS_DEBUG_STOPED; + infosProxy->SendRequest(message, tokens); + message = IAbilityDebugResponse::Message::ON_ABILITYS_ASSERT_DEBUG; + infosProxy->SendRequest(message, tokens); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer.h b/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer.h new file mode 100644 index 0000000000..660be13b33 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMGRAPPDEBUGLISTTENERPROXY_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMGRAPPDEBUGLISTTENERPROXY_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityinterfacesappmgrappdebuglistenerproxy_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMGRAPPDEBUGLISTTENERPROXY_FUZZER_H diff --git a/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/corpus/init b/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/project.xml b/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrabilitydebugresponseproxy_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/BUILD.gn b/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/BUILD.gn new file mode 100644 index 0000000000..4f3df9a1d7 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/BUILD.gn @@ -0,0 +1,82 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityInterfacesAppMgrAppDebugListenerProxyFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityinterfacesappmgrappdebuglistenerproxy_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:perm_verification", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityInterfacesAppMgrAppDebugListenerProxyFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer.cpp b/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer.cpp new file mode 100644 index 0000000000..cd85ad9ba1 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer.cpp @@ -0,0 +1,121 @@ +/* + * 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 "abilityinterfacesappmgrappdebuglistenerproxy_fuzzer.h" + +#include +#include + +#define private public +#include "app_debug_listener_proxy.h" +#include "app_debug_listener_interface.h" +#undef private + +#include "securec.h" +#include "parcel.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +const std::u16string AMSMGR_INTERFACE_TOKEN = u"ohos.appexecfwk.IAmsMgr"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + sptr impl; + std::shared_ptr infosProxy = std::make_shared(impl); + std::vector debugInfos; + infosProxy->OnAppDebugStarted(debugInfos); + infosProxy->OnAppDebugStoped(debugInfos); + MessageParcel parcels; + parcels.WriteInterfaceToken(AMSMGR_INTERFACE_TOKEN); + parcels.WriteBuffer(data, size); + parcels.RewindRead(0); + infosProxy->WriteInterfaceToken(parcels); + IAppDebugListener::Message message = IAppDebugListener::Message::ON_APP_DEBUG_STARTED; + infosProxy->SendRequest(message, debugInfos); + message = IAppDebugListener::Message::ON_APP_DEBUG_STOPED; + infosProxy->SendRequest(message, debugInfos); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer.h b/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer.h new file mode 100644 index 0000000000..660be13b33 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMGRAPPDEBUGLISTTENERPROXY_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMGRAPPDEBUGLISTTENERPROXY_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityinterfacesappmgrappdebuglistenerproxy_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMGRAPPDEBUGLISTTENERPROXY_FUZZER_H diff --git a/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/corpus/init b/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/project.xml b/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrappdebuglistenerproxy_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/BUILD.gn b/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/BUILD.gn new file mode 100644 index 0000000000..280a47a4d1 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/BUILD.gn @@ -0,0 +1,82 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityInterfacesAppMgrChildSchedulerProxyFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityinterfacesappmgrchildschedulerproxy_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:perm_verification", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityInterfacesAppMgrChildSchedulerProxyFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/abilityinterfacesappmgrchildschedulerproxy_fuzzer.cpp b/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/abilityinterfacesappmgrchildschedulerproxy_fuzzer.cpp new file mode 100644 index 0000000000..4e155c7e5c --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/abilityinterfacesappmgrchildschedulerproxy_fuzzer.cpp @@ -0,0 +1,118 @@ +/* + * 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 "abilityinterfacesappmgrchildschedulerproxy_fuzzer.h" + +#include +#include + +#define private public +#include "child_scheduler_proxy.h" +#include "child_scheduler_interface.h" +#undef private + +#include "securec.h" +#include "parcel.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +const std::u16string AMSMGR_INTERFACE_TOKEN = u"ohos.appexecfwk.IAmsMgr"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + sptr impl; + std::shared_ptr infosProxy = std::make_shared(impl); + infosProxy->ScheduleLoadJs(); + infosProxy->ScheduleExitProcessSafely(); + sptr mainProcessCb; + infosProxy->ScheduleRunNativeProc(mainProcessCb); + MessageParcel parcels; + parcels.WriteInterfaceToken(AMSMGR_INTERFACE_TOKEN); + parcels.WriteBuffer(data, size); + parcels.RewindRead(0); + infosProxy->WriteInterfaceToken(parcels); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/abilityinterfacesappmgrchildschedulerproxy_fuzzer.h b/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/abilityinterfacesappmgrchildschedulerproxy_fuzzer.h new file mode 100644 index 0000000000..e364748861 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/abilityinterfacesappmgrchildschedulerproxy_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMGRCHILDSCHEDULERPROXY_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMGRCHILDSCHEDULERPROXY_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityinterfacesappmgrchildschedulerproxy_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMGRCHILDSCHEDULERPROXY_FUZZER_H diff --git a/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/corpus/init b/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/project.xml b/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrchildschedulerproxy_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/BUILD.gn b/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/BUILD.gn new file mode 100644 index 0000000000..d5b569f2e9 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/BUILD.gn @@ -0,0 +1,82 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityInterfacesAppMgrNativeChildNotifyProxyFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilityinterfacesappmgrnativechildnotifyproxy_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:perm_verification", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityInterfacesAppMgrNativeChildNotifyProxyFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer.cpp b/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer.cpp new file mode 100644 index 0000000000..02f4aaafa6 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer.cpp @@ -0,0 +1,128 @@ +/* + * 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 "abilityinterfacesappmgrnativechildnotifyproxy_fuzzer.h" + +#include +#include + +#define private public +#include "native_child_notify_proxy.h" +#include "native_child_notify_interface.h" +#undef private + +#include "securec.h" +#include "parcel.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +const std::u16string AMSMGR_INTERFACE_TOKEN = u"ohos.appexecfwk.IAmsMgr"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + sptr impl; + std::shared_ptr infosProxy = std::make_shared(impl); + sptr nativeChild; + infosProxy->OnNativeChildStarted(nativeChild); + int32_t errCode = static_cast(GetU32Data(data)); + infosProxy->OnError(errCode); + MessageParcel parcel; + parcel.WriteInterfaceToken(AMSMGR_INTERFACE_TOKEN); + parcel.WriteBuffer(data, size); + parcel.RewindRead(0); + MessageParcel parcels; + parcels.WriteInterfaceToken(AMSMGR_INTERFACE_TOKEN); + parcels.WriteBuffer(data, size); + parcels.RewindRead(0); + infosProxy->WriteInterfaceToken(parcels); + uint32_t codeOne = static_cast(INPUT_ZERO); + MessageParcel reply; + MessageOption option; + infosProxy->SendRequest(codeOne, parcel, reply, option); + uint32_t codeTwo = static_cast(INPUT_ONE); + infosProxy->SendRequest(codeTwo, parcel, reply, option); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer.h b/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer.h new file mode 100644 index 0000000000..b9f14d511d --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMGRNATIVECHILDNOTIFYPROXY_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMGRNATIVECHILDNOTIFYPROXY_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityinterfacesappmgrnativechildnotifyproxy_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYINTERFACESAPPMGRNATIVECHILDNOTIFYPROXY_FUZZER_H diff --git a/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/corpus/init b/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/project.xml b/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilityinterfacesappmgrnativechildnotifyproxy_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymanagereventsubscriber_fuzzer/BUILD.gn b/test/fuzztest/abilitymanagereventsubscriber_fuzzer/BUILD.gn new file mode 100644 index 0000000000..dd465e3d02 --- /dev/null +++ b/test/fuzztest/abilitymanagereventsubscriber_fuzzer/BUILD.gn @@ -0,0 +1,82 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityManagerEventSubscriberFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymanagereventsubscriber_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ability_manager_event_subscriber.cpp", + "abilitymanagereventsubscriber_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityManagerEventSubscriberFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymanagereventsubscriber_fuzzer/abilitymanagereventsubscriber_fuzzer.cpp b/test/fuzztest/abilitymanagereventsubscriber_fuzzer/abilitymanagereventsubscriber_fuzzer.cpp new file mode 100644 index 0000000000..c68a87c05b --- /dev/null +++ b/test/fuzztest/abilitymanagereventsubscriber_fuzzer/abilitymanagereventsubscriber_fuzzer.cpp @@ -0,0 +1,96 @@ +/* + * 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 "abilitymanagereventsubscriber_fuzzer.h" + +#include +#include +#include + +#define private public +#include "ability_manager_event_subscriber.h" +#undef private +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr uint8_t ENABLE = 2; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + EventFwk::CommonEventData eventData; + EventFwk::CommonEventSubscribeInfo subscribeInfo; + std::function callback; + std::function userScreenUnlockCallback; + auto abilityManagerEventSubscriber = std::make_shared + (subscribeInfo, callback, userScreenUnlockCallback); + abilityManagerEventSubscriber->OnReceiveEvent(eventData); + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymanagereventsubscriber_fuzzer/abilitymanagereventsubscriber_fuzzer.h b/test/fuzztest/abilitymanagereventsubscriber_fuzzer/abilitymanagereventsubscriber_fuzzer.h new file mode 100644 index 0000000000..eac163ff0e --- /dev/null +++ b/test/fuzztest/abilitymanagereventsubscriber_fuzzer/abilitymanagereventsubscriber_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMANAGEREVENTSUBSCRIBER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMANAGEREVENTSUBSCRIBER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymanagereventsubscriber_fuzzer" + +#endif diff --git a/test/fuzztest/abilitymanagereventsubscriber_fuzzer/corpus/init b/test/fuzztest/abilitymanagereventsubscriber_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymanagereventsubscriber_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymanagereventsubscriber_fuzzer/project.xml b/test/fuzztest/abilitymanagereventsubscriber_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymanagereventsubscriber_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymanagerservicefifth_fuzzer/abilitymanagerservicefifth_fuzzer.cpp b/test/fuzztest/abilitymanagerservicefifth_fuzzer/abilitymanagerservicefifth_fuzzer.cpp index e3a616066f..75cf994cc4 100755 --- a/test/fuzztest/abilitymanagerservicefifth_fuzzer/abilitymanagerservicefifth_fuzzer.cpp +++ b/test/fuzztest/abilitymanagerservicefifth_fuzzer/abilitymanagerservicefifth_fuzzer.cpp @@ -88,6 +88,7 @@ bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) abilityms->DoAbilityBackground(token, uint32Param); abilityms->DelegatorMoveMissionToFront(int32Param); abilityms->UpdateCallerInfo(*want, token); + abilityms->OpenLink(*want, token, int32Param, int32Param); abilityms->JudgeMultiUserConcurrency(int32Param); #ifdef ABILITY_COMMAND_FOR_TEST abilityms->ForceTimeoutForTest(stringParam, stringParam); diff --git a/test/fuzztest/abilitymanagerservicefirst_fuzzer/abilitymanagerservicefirst_fuzzer.cpp b/test/fuzztest/abilitymanagerservicefirst_fuzzer/abilitymanagerservicefirst_fuzzer.cpp index 296d59c318..b3120b5832 100755 --- a/test/fuzztest/abilitymanagerservicefirst_fuzzer/abilitymanagerservicefirst_fuzzer.cpp +++ b/test/fuzztest/abilitymanagerservicefirst_fuzzer/abilitymanagerservicefirst_fuzzer.cpp @@ -96,7 +96,7 @@ void DoSomethingInterestingWithMyAPI1(AbilityManagerService &abilityms, Want& wa abilityms.CheckOptExtensionAbility(want, abilityRequest, int32Param, extensionType); AppExecFwk::AbilityInfo abilityInfo; abilityms.ReportAbilitStartInfoToRSS(abilityInfo); - abilityms.ReportEventToRSS(abilityInfo); + abilityms.ReportEventToRSS(abilityInfo, token); abilityms.StartExtensionAbility(want, token, int32Param, extensionType); abilityms.StopExtensionAbility(want, token, int32Param, extensionType); abilityms.TerminateAbility(token, intParam, &want); diff --git a/test/fuzztest/abilitymemorylevelinfo_fuzzer/BUILD.gn b/test/fuzztest/abilitymemorylevelinfo_fuzzer/BUILD.gn new file mode 100644 index 0000000000..8bde6833ed --- /dev/null +++ b/test/fuzztest/abilitymemorylevelinfo_fuzzer/BUILD.gn @@ -0,0 +1,63 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +##############################fuzztest########################################## +module_output_path = "ability_runtime/appmgrservice" +ohos_fuzztest("AbilityMemoryLevelInfoFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitymemorylevelinfo_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilitymemorylevelinfo_fuzzer.cpp" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:want", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "ffrt:libffrt", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "samgr:samgr_proxy", + "window_manager:libwm", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMemoryLevelInfoFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymemorylevelinfo_fuzzer/abilitymemorylevelinfo_fuzzer.cpp b/test/fuzztest/abilitymemorylevelinfo_fuzzer/abilitymemorylevelinfo_fuzzer.cpp new file mode 100644 index 0000000000..6ab1c5050b --- /dev/null +++ b/test/fuzztest/abilitymemorylevelinfo_fuzzer/abilitymemorylevelinfo_fuzzer.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "abilitymemorylevelinfo_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "memory_level_info.h" +#undef protected +#undef private +#include "parcel.h" +#include +#include "securec.h" +#include "configuration.h" + +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + + std::shared_ptrmemLevelInfo = std::make_shared(); + if (memLevelInfo == nullptr) { + return false; + } + Parcel parcel; + memLevelInfo->GetProcLevelMap(); + memLevelInfo->Marshalling(parcel); + memLevelInfo->ReadFromParcel(parcel); + MemoryLevelInfo::Unmarshalling(parcel); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymemorylevelinfo_fuzzer/abilitymemorylevelinfo_fuzzer.h b/test/fuzztest/abilitymemorylevelinfo_fuzzer/abilitymemorylevelinfo_fuzzer.h new file mode 100644 index 0000000000..af781c52c6 --- /dev/null +++ b/test/fuzztest/abilitymemorylevelinfo_fuzzer/abilitymemorylevelinfo_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMEMORYLEVELINFO_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMEMORYLEVELINFO_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymemorylevelinfo_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMANAGERSERVICEA_FUZZER_H diff --git a/test/fuzztest/abilitymemorylevelinfo_fuzzer/corpus/init b/test/fuzztest/abilitymemorylevelinfo_fuzzer/corpus/init new file mode 100644 index 0000000000..8eb5a7d6eb --- /dev/null +++ b/test/fuzztest/abilitymemorylevelinfo_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymemorylevelinfo_fuzzer/project.xml b/test/fuzztest/abilitymemorylevelinfo_fuzzer/project.xml new file mode 100644 index 0000000000..6e8ad2cfde --- /dev/null +++ b/test/fuzztest/abilitymemorylevelinfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/BUILD.gn new file mode 100644 index 0000000000..eec6ffc222 --- /dev/null +++ b/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/BUILD.gn @@ -0,0 +1,102 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityMgrAbilityManagerStubFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymgrabilitymanagerstub_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_services_path}/common/include", + "${ability_runtime_path}/interfaces/kits/native/session_info/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/utils/native/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilitymgrabilitymanagerstub_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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_services_path}/common:task_handler_wrap", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "ability_runtime:ability_manager", + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbeget_proxy", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMgrAbilityManagerStubFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/abilitymgrabilitymanagerstub_fuzzer.cpp b/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/abilitymgrabilitymanagerstub_fuzzer.cpp new file mode 100644 index 0000000000..bb4e9821f3 --- /dev/null +++ b/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/abilitymgrabilitymanagerstub_fuzzer.cpp @@ -0,0 +1,122 @@ +/* + * 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 "abilitymgrabilitymanagerstub_fuzzer.h" + +#include +#include + +#define private public +#include "ability_manager_service.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +const std::u16string ABILITYMGR_INTERFACE_TOKEN = u"ohos.aafwk.AbilityManager"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + uint32_t codeOne = static_cast(AbilityManagerInterfaceCode::GET_PENDING_WANT_TYPE); + MessageParcel parcel; + parcel.WriteInterfaceToken(ABILITYMGR_INTERFACE_TOKEN); + parcel.WriteBuffer(data, size); + parcel.RewindRead(0); + MessageParcel reply; + MessageOption option; + std::shared_ptr abmsOne = std::make_shared(); + abmsOne->OnRemoteRequest(codeOne, parcel, reply, option); + + uint32_t codeTwo = static_cast(AbilityManagerInterfaceCode::START_UI_EXTENSION_ABILITY); + MessageParcel parcels; + parcels.WriteInterfaceToken(ABILITYMGR_INTERFACE_TOKEN); + parcels.WriteBuffer(data, size); + parcels.RewindRead(0); + std::shared_ptr abmsTwo = std::make_shared(); + abmsTwo->OnRemoteRequest(codeTwo, parcels, reply, option); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/abilitymgrabilitymanagerstub_fuzzer.h b/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/abilitymgrabilitymanagerstub_fuzzer.h new file mode 100644 index 0000000000..b28b73cbe6 --- /dev/null +++ b/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/abilitymgrabilitymanagerstub_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRABILITYMANAGERSTUB_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRABILITYMANAGERSTUB_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrabilitymanagerstub_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRABILITYMANAGERSTUB_FUZZER_H diff --git a/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/corpus/init b/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/project.xml b/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrabilitymanagerstub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/BUILD.gn new file mode 100644 index 0000000000..7e9c6e219d --- /dev/null +++ b/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/BUILD.gn @@ -0,0 +1,123 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityMgrAppExitReasonHelperFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymgrappexitreasonhelper_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_services_path}/abilitymgr/include/scene_board", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/app_exit_reason_data_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/app_exit_reason_helper.cpp", + "${ability_runtime_services_path}/abilitymgr/src/process_options.cpp", + "${ability_runtime_services_path}/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/sub_managers_helper.cpp", + "${ability_runtime_services_path}/common/src/event_handler_wrap.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", + "abilitymgrappexitreasonhelper_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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:perm_verification", + "${ability_runtime_services_path}/common:task_handler_wrap", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libmodal_system_ui_extension_client", + "window_manager:libwsutils", + "window_manager:scene_session", + "window_manager:session_manager_lite", + "window_manager:sms", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMgrAppExitReasonHelperFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/abilitymgrappexitreasonhelper_fuzzer.cpp b/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/abilitymgrappexitreasonhelper_fuzzer.cpp new file mode 100644 index 0000000000..d5e95fc987 --- /dev/null +++ b/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/abilitymgrappexitreasonhelper_fuzzer.cpp @@ -0,0 +1,127 @@ +/* + * 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 "abilitymgrappexitreasonhelper_fuzzer.h" + +#include +#include + +#define private public +#include "app_exit_reason_helper.h" +#include "ability_manager_service.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr subManagersHelper; + std::shared_ptr infos = std::make_shared(subManagersHelper); + std::string jsonStr(data, size); + Reason reasonmin = Reason::REASON_MIN; + Reason reasonmax = Reason::REASON_MAX; + for (int i = reasonmin; i <= reasonmax; ++i) { + Reason reason = static_cast(i); + ExitReason exitReason(reason, jsonStr); + infos->RecordAppExitReason(exitReason); + int32_t uid = static_cast(GetU32Data(data)); + int32_t appIndex = static_cast(GetU32Data(data)); + infos->RecordAppExitReason(jsonStr, uid, appIndex, exitReason); + int32_t pid = static_cast(GetU32Data(data)); + infos->RecordProcessExtensionExitReason(pid, jsonStr, exitReason); + infos->RecordProcessExitReason(pid, exitReason); + uint32_t accessTokenId = static_cast(GetU32Data(data)); + infos->RecordProcessExitReason(pid, jsonStr, uid, accessTokenId, exitReason); + std::vector abilityLists; + infos->GetActiveAbilityList(uid, abilityLists, pid); + infos->GetActiveAbilityListFromUIAbilityManager(uid, abilityLists, pid); + infos->IsExitReasonValid(exitReason); + } + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/abilitymgrappexitreasonhelper_fuzzer.h b/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/abilitymgrappexitreasonhelper_fuzzer.h new file mode 100644 index 0000000000..138bab283b --- /dev/null +++ b/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/abilitymgrappexitreasonhelper_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRAPPEXITREASONHELPER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRAPPEXITREASONHELPER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrappexitreasonhelper_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRAPPEXITREASONHELPER_FUZZER_H diff --git a/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/corpus/init b/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/project.xml b/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrappexitreasonhelper_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/BUILD.gn new file mode 100644 index 0000000000..6f5f0be7f8 --- /dev/null +++ b/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/BUILD.gn @@ -0,0 +1,97 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityMgrControlInterceptorFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymgrcontrolinterceptor_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/app_scheduler.cpp", + "${ability_runtime_services_path}/abilitymgr/src/start_ability_utils.cpp", + "abilitymgrcontrolinterceptor_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMgrControlInterceptorFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/abilitymgrcontrolinterceptor_fuzzer.cpp b/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/abilitymgrcontrolinterceptor_fuzzer.cpp new file mode 100644 index 0000000000..186060973d --- /dev/null +++ b/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/abilitymgrcontrolinterceptor_fuzzer.cpp @@ -0,0 +1,116 @@ +/* + * 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 "abilitymgrcontrolinterceptor_fuzzer.h" + +#include +#include + +#define private public +#include "interceptor/control_interceptor.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr executer = std::make_shared(); + Want want; + ElementName element("", "com.test.control", "MainAbility"); + want.SetElement(element); + int requestCode = static_cast(GetU32Data(data)); + int32_t userId = static_cast(GetU32Data(data)); + bool boolParam = *data % ENABLE; + sptr callerToken = GetFuzzAbilityToken(); + AbilityInterceptorParam param(want, requestCode, userId, boolParam, callerToken); + executer->DoProcess(param); + AppExecFwk::AppRunningControlRuleResult controlRule; + executer->CheckControl(want, userId, controlRule); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/abilitymgrcontrolinterceptor_fuzzer.h b/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/abilitymgrcontrolinterceptor_fuzzer.h new file mode 100644 index 0000000000..142e090a41 --- /dev/null +++ b/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/abilitymgrcontrolinterceptor_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRCONTROLINTERCEPTOR_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRCONTROLINTERCEPTOR_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrcontrolinterceptor_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRCONTROLINTERCEPTOR_FUZZER_H diff --git a/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/corpus/init b/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/project.xml b/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrcontrolinterceptor_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/BUILD.gn new file mode 100644 index 0000000000..c263bb833b --- /dev/null +++ b/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilitymgrDisposedRuleInterceptorFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include/interceptor", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilitymgrdisposedruleinterceptor_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilitymgrDisposedRuleInterceptorFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/abilitymgrdisposedruleinterceptor_fuzzer.cpp b/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/abilitymgrdisposedruleinterceptor_fuzzer.cpp new file mode 100644 index 0000000000..8f8559d3d8 --- /dev/null +++ b/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/abilitymgrdisposedruleinterceptor_fuzzer.cpp @@ -0,0 +1,128 @@ +/* + * 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 "abilitymgrdisposedruleinterceptor_fuzzer.h" + +#include +#include + +#include "ability_record.h" +#include "securec.h" + +#define private public +#include "disposed_rule_interceptor.h" +#undef private + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +#define DISABLE_FUZZ +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr executer = std::make_shared(); + Want want; + AppExecFwk::DisposedRule disposedRule; + std::string stringParam(data, size); + int requestCode = static_cast(GetU32Data(data)); + int32_t userId = static_cast(GetU32Data(data)); + bool isWithUI = *data % ENABLE; + sptr token = GetFuzzAbilityToken(); + AbilityInterceptorParam param = AbilityInterceptorParam(want, requestCode, userId, isWithUI, token); + const std::shared_ptr abilityInfo; + int32_t bundleType = static_cast(GetU32Data(data)); + + executer-> DoProcess(param); + executer-> CheckControl(want, userId, disposedRule); + executer-> CheckDisposedRule(want, disposedRule); + executer-> StartNonBlockRule(want, disposedRule); + executer-> GetAppMgr(); + executer-> UnregisterObserver(stringParam); + executer-> CreateModalUIExtension(want, token); + executer-> SetInterceptInfo(want, disposedRule); + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + +#ifndef DISABLE_FUZZ + OHOS::DoSomethingInterestingWithMyAPI(ch, size); +#endif + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/abilitymgrdisposedruleinterceptor_fuzzer.h b/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/abilitymgrdisposedruleinterceptor_fuzzer.h new file mode 100644 index 0000000000..e4cc7477b1 --- /dev/null +++ b/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/abilitymgrdisposedruleinterceptor_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRDISPOSEDRULEINTERCEPTOR_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRDISPOSEDRULEINTERCEPTOR_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrdisposedruleinterceptor_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRDISPOSEDRULEINTERCEPTOR_FUZZER_H diff --git a/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/corpus/init b/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/project.xml b/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrdisposedruleinterceptor_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/BUILD.gn new file mode 100644 index 0000000000..be1644c415 --- /dev/null +++ b/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/BUILD.gn @@ -0,0 +1,95 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilitymgrEcologicalRuleInterceptorFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include/interceptor", + "${ability_runtime_services_path}/abilitymgr/include/ecological_rule", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilitymgrecologicalruleinterceptor_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilitymgrEcologicalRuleInterceptorFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/abilitymgrecologicalruleinterceptor_fuzzer.cpp b/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/abilitymgrecologicalruleinterceptor_fuzzer.cpp new file mode 100644 index 0000000000..e46d5be091 --- /dev/null +++ b/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/abilitymgrecologicalruleinterceptor_fuzzer.cpp @@ -0,0 +1,124 @@ +/* + * 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 "abilitymgrecologicalruleinterceptor_fuzzer.h" + +#include +#include + +#define private public +#include "ecological_rule_interceptor.h" +#undef private + +#include "ability_ecological_rule_mgr_service_param.h" +#include "ability_record.h" +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | + (ptr[INPUT_TWO] << OFFSET_TWO) | ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = + AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr executer = + std::make_shared(); + Want want; + int requestCode = static_cast(GetU32Data(data)); + int32_t userId = static_cast(GetU32Data(data)); + bool isWithUI = *data % ENABLE; + sptr token = GetFuzzAbilityToken(); + AbilityInterceptorParam param = + AbilityInterceptorParam(want, requestCode, userId, isWithUI, token); + const std::shared_ptr abilityInfo; + AbilityCallerInfo callerInfo; + int32_t bundleType = static_cast(GetU32Data(data)); + executer->DoProcess(param); + executer->DoProcess(want, userId); + executer->GetEcologicalTargetInfo(want, abilityInfo, callerInfo); + executer->GetEcologicalCallerInfo(want, callerInfo, userId, token); + executer->InitErmsCallerInfo(want, abilityInfo, callerInfo, userId, token); + executer->GetAppTypeByBundleType(bundleType); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/abilitymgrecologicalruleinterceptor_fuzzer.h b/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/abilitymgrecologicalruleinterceptor_fuzzer.h new file mode 100644 index 0000000000..34b854132a --- /dev/null +++ b/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/abilitymgrecologicalruleinterceptor_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRECOLOGICALRULEINTERCEPTOR_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRECOLOGICALRULEINTERCEPTOR_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrecologicalruleinterceptor_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRECOLOGICALRULEINTERCEPTOR_FUZZER_H diff --git a/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/corpus/init b/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/project.xml b/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrecologicalruleinterceptor_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/BUILD.gn new file mode 100644 index 0000000000..afb89420e5 --- /dev/null +++ b/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/BUILD.gn @@ -0,0 +1,99 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityMgrEcologicalRuleMgrServiceParamFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ecological_rule/ability_ecological_rule_mgr_service_param.cpp", + "abilitymgrecologicalrulemgrserviceparam_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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_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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMgrEcologicalRuleMgrServiceParamFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/abilitymgrecologicalrulemgrserviceparam_fuzzer.cpp b/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/abilitymgrecologicalrulemgrserviceparam_fuzzer.cpp new file mode 100644 index 0000000000..61a47e3548 --- /dev/null +++ b/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/abilitymgrecologicalrulemgrserviceparam_fuzzer.cpp @@ -0,0 +1,97 @@ +/* + * 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 "abilitymgrecologicalrulemgrserviceparam_fuzzer.h" +#include "ability_record.h" + +#include +#include + +#define private public +#include "ecological_rule/ability_ecological_rule_mgr_service_param.h" +#include "ecological_rule/ability_ecological_rule_mgr_service_interface.h" +#undef private +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + EcologicalRuleMgrService::AbilityExperienceRule abilityExperienceRule; + Parcel parcel; + abilityExperienceRule.Marshalling(parcel); + EcologicalRuleMgrService::AbilityCallerInfo abilityCallerInfo; + abilityCallerInfo.ReadFromParcel(parcel); + abilityCallerInfo.Marshalling(parcel); + abilityCallerInfo.DoMarshallingOne(parcel); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/abilitymgrecologicalrulemgrserviceparam_fuzzer.h b/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/abilitymgrecologicalrulemgrserviceparam_fuzzer.h new file mode 100644 index 0000000000..2f4ca6793e --- /dev/null +++ b/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/abilitymgrecologicalrulemgrserviceparam_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRECOLOGICALRULEMGRSERVICEPARAM_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRECOLOGICALRULEMGRSERVICEPARAM_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrecologicalrulemgrserviceparam_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRECOLOGICALRULEMGRSERVICEPARAM_FUZZER_H diff --git a/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/corpus/init b/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/project.xml b/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrecologicalrulemgrserviceparam_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrextensionrecord_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrextensionrecord_fuzzer/BUILD.gn new file mode 100644 index 0000000000..b3527bfca3 --- /dev/null +++ b/test/fuzztest/abilitymgrextensionrecord_fuzzer/BUILD.gn @@ -0,0 +1,99 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityMgrExtensionRecordFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitymgrextensionrecord_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/extension_record.cpp", + "${ability_runtime_services_path}/abilitymgr/src/preload_uiext_state_observer.cpp", + "abilitymgrextensionrecord_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMgrExtensionRecordFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrextensionrecord_fuzzer/abilitymgrextensionrecord_fuzzer.cpp b/test/fuzztest/abilitymgrextensionrecord_fuzzer/abilitymgrextensionrecord_fuzzer.cpp new file mode 100644 index 0000000000..82631b8892 --- /dev/null +++ b/test/fuzztest/abilitymgrextensionrecord_fuzzer/abilitymgrextensionrecord_fuzzer.cpp @@ -0,0 +1,116 @@ +/* + * 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 "abilitymgrextensionrecord_fuzzer.h" + +#include +#include + +#define private public +#include "extension_record.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr abilityRecord; + AbilityRuntime::ExtensionRecord infos(abilityRecord); + infos.GetCallToken(); + infos.GetRootCallerToken(); + sptr token = GetFuzzAbilityToken(); + + infos.SetRootCallerToken(token); + infos.ContinueToGetCallerToken(); + AAFwk::AbilityRequest abilityRequest; + infos.Update(abilityRequest); + std::string jsonStr(data, size); + infos.RegisterStateObserver(jsonStr); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgrextensionrecord_fuzzer/abilitymgrextensionrecord_fuzzer.h b/test/fuzztest/abilitymgrextensionrecord_fuzzer/abilitymgrextensionrecord_fuzzer.h new file mode 100644 index 0000000000..656f328a51 --- /dev/null +++ b/test/fuzztest/abilitymgrextensionrecord_fuzzer/abilitymgrextensionrecord_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGREXTENSIONRECORD_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGREXTENSIONRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrextensionrecord_fuzzer" + +#endif // ABILITYMGREXTENSIONRECORD_FUZZER_H diff --git a/test/fuzztest/abilitymgrextensionrecord_fuzzer/corpus/init b/test/fuzztest/abilitymgrextensionrecord_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrextensionrecord_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrextensionrecord_fuzzer/project.xml b/test/fuzztest/abilitymgrextensionrecord_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrextensionrecord_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/BUILD.gn new file mode 100644 index 0000000000..ea9815226b --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/BUILD.gn @@ -0,0 +1,101 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityMgrInsightIntentExecuteManagerFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/insight_intent_profile.cpp", + "${ability_runtime_services_path}/abilitymgr/src/insight_intent_utils.cpp", + "abilitymgrinsightintentexecutemanager_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "ability_runtime:ability_manager", + "bundle_framework:libappexecfwk_common", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMgrInsightIntentExecuteManagerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/abilitymgrinsightintentexecutemanager_fuzzer.cpp b/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/abilitymgrinsightintentexecutemanager_fuzzer.cpp new file mode 100644 index 0000000000..f691072e03 --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/abilitymgrinsightintentexecutemanager_fuzzer.cpp @@ -0,0 +1,143 @@ +/* + * 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 "abilitymgrinsightintentexecutemanager_fuzzer.h" + +#include +#include + +#define private public +#include "insight_intent_execute_manager.h" +#include "insight_intent_execute_param.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr infos = std::make_shared(); + AppExecFwk::ElementName element; + sptr remoteObject; + int resultCod = static_cast(GetU32Data(data)); + infos->OnAbilityConnectDone(element, remoteObject, resultCod); + infos->OnAbilityDisconnectDone(element, resultCod); + uint64_t intentId = static_cast(GetU32Data(data)); + + InsightIntentExecuteRecipient Rinfos(intentId); + wptr remote; + Rinfos.OnRemoteDied(remote); + sptr callerToken = GetFuzzAbilityToken(); + + std::shared_ptr Minfos = std::make_shared(); + std::shared_ptr paramPtr; + uint64_t key = static_cast(GetU32Data(data)); + Minfos->CheckAndUpdateParam(key, callerToken, paramPtr); + Want want; + ExecuteMode executeMode = UI_ABILITY_FOREGROUND; + Minfos->CheckAndUpdateWant(want, executeMode); + executeMode = UI_ABILITY_BACKGROUND; + Minfos->CheckAndUpdateWant(want, executeMode); + executeMode = UI_EXTENSION_ABILITY; + Minfos->CheckAndUpdateWant(want, executeMode); + executeMode = SERVICE_EXTENSION_ABILITY; + Minfos->CheckAndUpdateWant(want, executeMode); + + Minfos->RemoveExecuteIntent(intentId); + int32_t resultCode = static_cast(GetU32Data(data)); + InsightIntentExecuteResult result; + Minfos->ExecuteIntentDone(intentId, resultCode, result); + Minfos->RemoteDied(intentId); + std::string jsonStr(data, size); + Minfos->GetBundleName(intentId, jsonStr); + Minfos->AddRecord(key, callerToken, jsonStr, intentId); + Minfos->GenerateWant(paramPtr, want); + Minfos->IsValidCall(want); + Minfos->CheckCallerPermission(); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/abilitymgrinsightintentexecutemanager_fuzzer.h b/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/abilitymgrinsightintentexecutemanager_fuzzer.h new file mode 100644 index 0000000000..e735045fb9 --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/abilitymgrinsightintentexecutemanager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRINSIGHTINTENTEXECUTEMANAGER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRINSIGHTINTENTEXECUTEMANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrinsightintentexecutemanager_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRINSIGHTINTENTEXECUTEMANAGER_FUZZER_H diff --git a/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/corpus/init b/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/project.xml b/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentexecutemanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/BUILD.gn new file mode 100644 index 0000000000..d9bdaff7e7 --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/BUILD.gn @@ -0,0 +1,101 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityMgrInsightIntentExecuteResultFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_result.cpp", + "${ability_runtime_services_path}/abilitymgr/src/insight_intent_profile.cpp", + "${ability_runtime_services_path}/abilitymgr/src/insight_intent_utils.cpp", + "abilitymgrinsightintentexecuteresult_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "ability_runtime:ability_manager", + "bundle_framework:libappexecfwk_common", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMgrInsightIntentExecuteResultFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/abilitymgrinsightintentexecuteresult_fuzzer.cpp b/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/abilitymgrinsightintentexecuteresult_fuzzer.cpp new file mode 100644 index 0000000000..89293190b3 --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/abilitymgrinsightintentexecuteresult_fuzzer.cpp @@ -0,0 +1,111 @@ +/* + * 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 "abilitymgrinsightintentexecuteresult_fuzzer.h" + +#include +#include + +#define private public +#include "insight_intent_execute_result.h" +#include "insight_intent_execute_param.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr infos = std::make_shared(); + Parcel parcel; + infos->ReadFromParcel(parcel); + infos->Marshalling(parcel); + std::shared_ptr result; + infos->CheckResult(result); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/abilitymgrinsightintentexecuteresult_fuzzer.h b/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/abilitymgrinsightintentexecuteresult_fuzzer.h new file mode 100644 index 0000000000..28acd5be9c --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/abilitymgrinsightintentexecuteresult_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRINSIGHTINTENTEXECUTERESULT_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRINSIGHTINTENTEXECUTERESULT_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrinsightintentexecuteresult_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRINSIGHTINTENTEXECUTERESULT_FUZZER_H diff --git a/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/corpus/init b/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/project.xml b/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentexecuteresult_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrinsightintentutils_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrinsightintentutils_fuzzer/BUILD.gn new file mode 100644 index 0000000000..fa1f42046b --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentutils_fuzzer/BUILD.gn @@ -0,0 +1,101 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityMgrInsightIntentUtilsFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymgrinsightintentutils_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/insight_intent_execute_result.cpp", + "${ability_runtime_services_path}/abilitymgr/src/insight_intent_profile.cpp", + "${ability_runtime_services_path}/abilitymgr/src/insight_intent_utils.cpp", + "abilitymgrinsightintentutils_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "ability_runtime:ability_manager", + "bundle_framework:libappexecfwk_common", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMgrInsightIntentUtilsFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrinsightintentutils_fuzzer/abilitymgrinsightintentutils_fuzzer.cpp b/test/fuzztest/abilitymgrinsightintentutils_fuzzer/abilitymgrinsightintentutils_fuzzer.cpp new file mode 100644 index 0000000000..1f6179114a --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentutils_fuzzer/abilitymgrinsightintentutils_fuzzer.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 "abilitymgrinsightintentutils_fuzzer.h" + +#include +#include + +#define private public +#include "insight_intent_utils.h" +#include "insight_intent_execute_param.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr infos = std::make_shared(); + std::string jsonStr(data, size); + infos->GetSrcEntry(jsonStr, jsonStr, jsonStr); + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgrinsightintentutils_fuzzer/abilitymgrinsightintentutils_fuzzer.h b/test/fuzztest/abilitymgrinsightintentutils_fuzzer/abilitymgrinsightintentutils_fuzzer.h new file mode 100644 index 0000000000..dbae56a598 --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentutils_fuzzer/abilitymgrinsightintentutils_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRINSIGHTINTENTUTILS_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRINSIGHTINTENTUTILS_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrinsightintentutils_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRINSIGHTINTENTUTILS_FUZZER_H diff --git a/test/fuzztest/abilitymgrinsightintentutils_fuzzer/corpus/init b/test/fuzztest/abilitymgrinsightintentutils_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentutils_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrinsightintentutils_fuzzer/project.xml b/test/fuzztest/abilitymgrinsightintentutils_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrinsightintentutils_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/BUILD.gn new file mode 100644 index 0000000000..21ad5b56cd --- /dev/null +++ b/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/BUILD.gn @@ -0,0 +1,98 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityMgrInterceptorExecuterFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymgrinterceptorexecuter_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/app_scheduler.cpp", + "${ability_runtime_services_path}/abilitymgr/src/start_ability_utils.cpp", + "abilitymgrinterceptorexecuter_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMgrInterceptorExecuterFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/abilitymgrinterceptorexecuter_fuzzer.cpp b/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/abilitymgrinterceptorexecuter_fuzzer.cpp new file mode 100644 index 0000000000..20a4bd745a --- /dev/null +++ b/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/abilitymgrinterceptorexecuter_fuzzer.cpp @@ -0,0 +1,119 @@ +/* + * 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 "abilitymgrinterceptorexecuter_fuzzer.h" + +#include +#include + +#define private public +#include "interceptor/ability_interceptor_executer.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr executer = std::make_shared(); + std::string jsonStr(data, size); + std::shared_ptr interceptor; + executer->AddInterceptor(jsonStr, interceptor); + executer->RemoveInterceptor(jsonStr); + Want want; + int requestCode = static_cast(GetU32Data(data)); + int32_t userId = static_cast(GetU32Data(data)); + bool boolParam = *data % ENABLE; + sptr callerToken = GetFuzzAbilityToken(); + AbilityInterceptorParam param(want, requestCode, userId, boolParam, callerToken); + executer->DoProcess(param); + std::shared_ptr taskHandler; + executer->SetTaskHandler(taskHandler); + executer->GetInterceptorMapCopy(); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/abilitymgrinterceptorexecuter_fuzzer.h b/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/abilitymgrinterceptorexecuter_fuzzer.h new file mode 100644 index 0000000000..892271187a --- /dev/null +++ b/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/abilitymgrinterceptorexecuter_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRINTERCEPTOREXECUTER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRINTERCEPTOREXECUTER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrinterceptorexecuter_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRINTERCEPTOREXECUTER_FUZZER_H diff --git a/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/corpus/init b/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/project.xml b/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrinterceptorexecuter_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/BUILD.gn new file mode 100644 index 0000000000..7fa590d8fb --- /dev/null +++ b/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/BUILD.gn @@ -0,0 +1,99 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityMgrJumpInterceptorFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitymgrjumpinterceptor_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/app_scheduler.cpp", + "${ability_runtime_services_path}/abilitymgr/src/start_ability_utils.cpp", + "abilitymgrjumpinterceptor_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMgrJumpInterceptorFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/abilitymgrjumpinterceptor_fuzzer.cpp b/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/abilitymgrjumpinterceptor_fuzzer.cpp new file mode 100644 index 0000000000..db92f7715b --- /dev/null +++ b/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/abilitymgrjumpinterceptor_fuzzer.cpp @@ -0,0 +1,122 @@ +/* + * 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 "abilitymgrjumpinterceptor_fuzzer.h" + +#include +#include + +#define private public +#include "interceptor/ability_jump_interceptor.h" +#include "bundle_mgr_helper.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr interceptor = std::make_shared(); + std::string jsonStr(data, size); + Want want; + ElementName element("", "com.acts.disposedrulehap", "MainAbility", "entry"); + want.SetElement(element); + int requestCode = static_cast(GetU32Data(data)); + int32_t userId = static_cast(GetU32Data(data)); + bool boolParam = *data % ENABLE; + sptr callerToken = GetFuzzAbilityToken(); + AbilityInterceptorParam param(want, requestCode, userId, boolParam, callerToken); + interceptor->DoProcess(param); + std::shared_ptr bundleMgrHelper = std::make_shared(); + AppExecFwk::AppJumpControlRule controlRule; + interceptor->CheckControl(bundleMgrHelper, want, userId, controlRule); + interceptor->CheckIfJumpExempt(controlRule, userId); + interceptor->CheckIfExemptByBundleName(jsonStr, jsonStr, userId); + interceptor->LoadAppLabelInfo(want, controlRule, userId); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/abilitymgrjumpinterceptor_fuzzer.h b/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/abilitymgrjumpinterceptor_fuzzer.h new file mode 100644 index 0000000000..7f260ddef0 --- /dev/null +++ b/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/abilitymgrjumpinterceptor_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRJUMPINTERCEPTOR_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRJUMPINTERCEPTOR_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrjumpinterceptor_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRJUMPINTERCEPTOR_FUZZER_H diff --git a/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/corpus/init b/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/project.xml b/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrjumpinterceptor_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/BUILD.gn new file mode 100644 index 0000000000..45d1f3d15a --- /dev/null +++ b/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/BUILD.gn @@ -0,0 +1,92 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilitymgrPreloadUiextStateObserverFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/ability_state_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_mgr_client.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_service_manager.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_state_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/application_state_observer_stub.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/page_state_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/process_data.cpp", + "${ability_runtime_services_path}/abilitymgr/src/extension_record.cpp", + "${ability_runtime_services_path}/abilitymgr/src/preload_uiext_state_observer.cpp", + "${bundlefwk_inner_api_path}/appexecfwk_base/src/application_info.cpp", + "abilitymgrpreloaduiextstateobserver_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilitymgrPreloadUiextStateObserverFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/abilitymgrpreloaduiextstateobserver_fuzzer.cpp b/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/abilitymgrpreloaduiextstateobserver_fuzzer.cpp new file mode 100644 index 0000000000..d7b0d96575 --- /dev/null +++ b/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/abilitymgrpreloaduiextstateobserver_fuzzer.cpp @@ -0,0 +1,78 @@ +/* + * 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 "abilitymgrpreloaduiextstateobserver_fuzzer.h" + +#include +#include +#include "securec.h" +#include +#define private public +#include "preload_uiext_state_observer.h" +#undef private + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +} // namespace + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + std::weak_ptr extensionRecord; + std::shared_ptr preLoadUIExtStateObserver = + std::make_shared(extensionRecord); + ProcessData processData; + preLoadUIExtStateObserver-> OnProcessDied(processData); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/abilitymgrpreloaduiextstateobserver_fuzzer.h b/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/abilitymgrpreloaduiextstateobserver_fuzzer.h new file mode 100644 index 0000000000..644efe2fbe --- /dev/null +++ b/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/abilitymgrpreloaduiextstateobserver_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRPRELOADUIEXTSTATEOBSERVER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRPRELOADUIEXTSTATEOBSERVER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrpreloaduiextstateobserver_fuzzer" + +#endif diff --git a/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/corpus/init b/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/project.xml b/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrpreloaduiextstateobserver_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrrdbparserutil_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrrdbparserutil_fuzzer/BUILD.gn new file mode 100644 index 0000000000..f05f03a987 --- /dev/null +++ b/test/fuzztest/abilitymgrrdbparserutil_fuzzer/BUILD.gn @@ -0,0 +1,101 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityMgrRdbParserUtilFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitymgrrdbparserutil_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_services_path}/abilitymgr/include/rdb", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/rdb/parser_util.cpp", + "abilitymgrrdbparserutil_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/json:nlohmann_json_static", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMgrRdbParserUtilFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrrdbparserutil_fuzzer/abilitymgrrdbparserutil_fuzzer.cpp b/test/fuzztest/abilitymgrrdbparserutil_fuzzer/abilitymgrrdbparserutil_fuzzer.cpp new file mode 100644 index 0000000000..f4d0ccd269 --- /dev/null +++ b/test/fuzztest/abilitymgrrdbparserutil_fuzzer/abilitymgrrdbparserutil_fuzzer.cpp @@ -0,0 +1,115 @@ +/* + * 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 "abilitymgrrdbparserutil_fuzzer.h" + +#include +#include + +#define private public +#include "rdb/parser_util.h" +#include "config_policy_utils.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + AbilityRuntime::ParserUtil &instance = AbilityRuntime::ParserUtil::GetInstance(); + std::vector> list; + instance.GetResidentProcessRawData(list); + std::string jsonStr(data, size); + instance.ParsePreInstallAbilityConfig(jsonStr, list); + std::vector rootDirList; + instance.GetPreInstallRootDirList(rootDirList); + nlohmann::json jsonBuf; + instance.ReadFileIntoJson(jsonStr, jsonBuf); + instance.FilterInfoFromJson(jsonBuf, list); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgrrdbparserutil_fuzzer/abilitymgrrdbparserutil_fuzzer.h b/test/fuzztest/abilitymgrrdbparserutil_fuzzer/abilitymgrrdbparserutil_fuzzer.h new file mode 100644 index 0000000000..07fd42b0ec --- /dev/null +++ b/test/fuzztest/abilitymgrrdbparserutil_fuzzer/abilitymgrrdbparserutil_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRRDBPARSERUTIL_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRRDBPARSERUTIL_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrrdbparserutil_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRRDBPARSERUTIL_FUZZER_H diff --git a/test/fuzztest/abilitymgrrdbparserutil_fuzzer/corpus/init b/test/fuzztest/abilitymgrrdbparserutil_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrrdbparserutil_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrrdbparserutil_fuzzer/project.xml b/test/fuzztest/abilitymgrrdbparserutil_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrrdbparserutil_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgrrestartappmanager_fuzzer/BUILD.gn b/test/fuzztest/abilitymgrrestartappmanager_fuzzer/BUILD.gn new file mode 100644 index 0000000000..d5bf300c62 --- /dev/null +++ b/test/fuzztest/abilitymgrrestartappmanager_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilitymgrRestartAppManagerFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitymgrrestartappmanager_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/running_process_info.cpp", + "${ability_runtime_services_path}/abilitymgr/src/restart_app_manager.cpp", + "abilitymgrrestartappmanager_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilitymgrRestartAppManagerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgrrestartappmanager_fuzzer/abilitymgrrestartappmanager_fuzzer.cpp b/test/fuzztest/abilitymgrrestartappmanager_fuzzer/abilitymgrrestartappmanager_fuzzer.cpp new file mode 100644 index 0000000000..731cb29079 --- /dev/null +++ b/test/fuzztest/abilitymgrrestartappmanager_fuzzer/abilitymgrrestartappmanager_fuzzer.cpp @@ -0,0 +1,97 @@ +/* + * 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 "abilitymgrrestartappmanager_fuzzer.h" + +#include +#include +#include "securec.h" +#include +#include +#define private public +#include "restart_app_manager.h" +#undef private + +using namespace OHOS::AAFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + std::shared_ptr restartAppManager = std::make_shared(); + std::string stringParam(data, size); + int32_t restartUserId = static_cast(GetU32Data(data)); + RestartAppKeyType key(stringParam, restartUserId); + time_t currentTime = static_cast(GetU32Data(data)); + restartAppManager-> GetInstance(); + restartAppManager-> IsRestartAppFrequent(key, currentTime); + restartAppManager-> AddRestartAppHistory(key, currentTime); + restartAppManager-> IsForegroundToRestartApp(); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/abilitymgrrestartappmanager_fuzzer/abilitymgrrestartappmanager_fuzzer.h b/test/fuzztest/abilitymgrrestartappmanager_fuzzer/abilitymgrrestartappmanager_fuzzer.h new file mode 100644 index 0000000000..8cd88e0924 --- /dev/null +++ b/test/fuzztest/abilitymgrrestartappmanager_fuzzer/abilitymgrrestartappmanager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRRESTARTAPPMANAGER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRRESTARTAPPMANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgrrestartappmanager_fuzzer" + +#endif diff --git a/test/fuzztest/abilitymgrrestartappmanager_fuzzer/corpus/init b/test/fuzztest/abilitymgrrestartappmanager_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgrrestartappmanager_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgrrestartappmanager_fuzzer/project.xml b/test/fuzztest/abilitymgrrestartappmanager_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgrrestartappmanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgruiextensionrecord_fuzzer/BUILD.gn b/test/fuzztest/abilitymgruiextensionrecord_fuzzer/BUILD.gn new file mode 100644 index 0000000000..8e1df1e27d --- /dev/null +++ b/test/fuzztest/abilitymgruiextensionrecord_fuzzer/BUILD.gn @@ -0,0 +1,100 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilityMgrUiExtensionRecordFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitymgruiextensionrecord_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/extension_record.cpp", + "${ability_runtime_services_path}/abilitymgr/src/preload_uiext_state_observer.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ui_extension_record.cpp", + "abilitymgruiextensionrecord_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityMgrUiExtensionRecordFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgruiextensionrecord_fuzzer/abilitymgruiextensionrecord_fuzzer.cpp b/test/fuzztest/abilitymgruiextensionrecord_fuzzer/abilitymgruiextensionrecord_fuzzer.cpp new file mode 100644 index 0000000000..f992af99e5 --- /dev/null +++ b/test/fuzztest/abilitymgruiextensionrecord_fuzzer/abilitymgruiextensionrecord_fuzzer.cpp @@ -0,0 +1,121 @@ +/* + * 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 "abilitymgruiextensionrecord_fuzzer.h" + +#include +#include + +#define private public +#include "ui_extension_record.h" +#undef private + +#include "securec.h" +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr abilityRecord; + AbilityRuntime::UIExtensionRecord infos(abilityRecord); + infos.ContinueToGetCallerToken(); + AAFwk::AbilityRequest abilityRequest; + infos.Update(abilityRequest); + infos.LoadTimeout(); + infos.ForegroundTimeout(); + infos.BackgroundTimeout(); + infos.TerminateTimeout(); + AbilityRuntime::UIExtensionRecord::ErrorCode code = AbilityRuntime::UIExtensionRecord::ErrorCode::LOAD_TIMEOUT; + infos.HandleNotifyUIExtensionTimeout(code); + code = AbilityRuntime::UIExtensionRecord::ErrorCode::FOREGROUND_TIMEOUT; + infos.HandleNotifyUIExtensionTimeout(code); + code = AbilityRuntime::UIExtensionRecord::ErrorCode::BACKGROUND_TIMEOUT; + infos.HandleNotifyUIExtensionTimeout(code); + code = AbilityRuntime::UIExtensionRecord::ErrorCode::TERMINATE_TIMEOUT; + infos.HandleNotifyUIExtensionTimeout(code); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitymgruiextensionrecord_fuzzer/abilitymgruiextensionrecord_fuzzer.h b/test/fuzztest/abilitymgruiextensionrecord_fuzzer/abilitymgruiextensionrecord_fuzzer.h new file mode 100644 index 0000000000..7d613149d2 --- /dev/null +++ b/test/fuzztest/abilitymgruiextensionrecord_fuzzer/abilitymgruiextensionrecord_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRUIEXTENSIONRECORD_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRUIEXTENSIONRECORD_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgruiextensionrecord_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRUIEXTENSIONRECORD_FUZZER_H diff --git a/test/fuzztest/abilitymgruiextensionrecord_fuzzer/corpus/init b/test/fuzztest/abilitymgruiextensionrecord_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgruiextensionrecord_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgruiextensionrecord_fuzzer/project.xml b/test/fuzztest/abilitymgruiextensionrecord_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgruiextensionrecord_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/BUILD.gn b/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/BUILD.gn new file mode 100644 index 0000000000..7d39e116a5 --- /dev/null +++ b/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/BUILD.gn @@ -0,0 +1,81 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AbilitymgrUiExtensionSessionInfoFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/abilitymgruiextensionsessioninfo_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ui_extension_session_info.cpp", + "abilitymgruiextensionsessioninfo_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilitymgrUiExtensionSessionInfoFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/abilitymgruiextensionsessioninfo_fuzzer.cpp b/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/abilitymgruiextensionsessioninfo_fuzzer.cpp new file mode 100644 index 0000000000..2fb0f2f45d --- /dev/null +++ b/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/abilitymgruiextensionsessioninfo_fuzzer.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 "abilitymgruiextensionsessioninfo_fuzzer.h" + +#include +#include +#include "securec.h" +#include +#define private public +#include "ui_extension_session_info.h" +#undef private + +using namespace OHOS::AAFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +} // namespace + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + std::shared_ptr uiExtensionSessionInfo = std::make_shared(); + Parcel parcel; + uiExtensionSessionInfo-> Marshalling(parcel); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/abilitymgruiextensionsessioninfo_fuzzer.h b/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/abilitymgruiextensionsessioninfo_fuzzer.h new file mode 100644 index 0000000000..2f7d0077e2 --- /dev/null +++ b/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/abilitymgruiextensionsessioninfo_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRUIEXTENSIONSESSIONINFO_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYMGRUIEXTENSIONSESSIONINFO_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitymgruiextensionsessioninfo_fuzzer" + +#endif diff --git a/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/corpus/init b/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/project.xml b/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/abilitymgruiextensionsessioninfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/abilitystubinterface_fuzzer/BUILD.gn b/test/fuzztest/abilitystubinterface_fuzzer/BUILD.gn new file mode 100644 index 0000000000..33d3ed293a --- /dev/null +++ b/test/fuzztest/abilitystubinterface_fuzzer/BUILD.gn @@ -0,0 +1,76 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +##############################fuzztest########################################## +ohos_fuzztest("AbilityStubInterfaceFuzzTest") { + module_out_path = fuzz_test_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/abilitystubinterface_fuzzer" + include_dirs = [ "${ability_runtime_innerkits_path}/ability_manager/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "abilitystubinterface_fuzzer.cpp" ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ + "input:libmmi-client", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AbilityStubInterfaceFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/abilitystubinterface_fuzzer/abilitystubinterface_fuzzer.cpp b/test/fuzztest/abilitystubinterface_fuzzer/abilitystubinterface_fuzzer.cpp new file mode 100644 index 0000000000..94d4caa591 --- /dev/null +++ b/test/fuzztest/abilitystubinterface_fuzzer/abilitystubinterface_fuzzer.cpp @@ -0,0 +1,90 @@ +/* + * 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 "abilitystubinterface_fuzzer.h" + +#include +#include + +#define private public +#include "ability_manager_service.h" +#undef private +#include "message_parcel.h" +#include "securec.h" + +using namespace OHOS::AAFwk; + +namespace OHOS { +namespace { +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +} +const std::u16string ABILITYMGR_INTERFACE_TOKEN = u"ohos.aafwk.AbilityManager"; + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + for (uint32_t code = 0; + code <= static_cast(AbilityManagerInterfaceCode::NOTIFY_DEBUG_ASSERT_RESULT); ++code) { + MessageParcel parcel; + parcel.WriteInterfaceToken(ABILITYMGR_INTERFACE_TOKEN); + parcel.WriteBuffer(data, size); + parcel.RewindRead(0); + MessageParcel reply; + MessageOption option; + DelayedSingleton::GetInstance()->subManagersHelper_ = + std::make_shared(nullptr, nullptr); + DelayedSingleton::GetInstance()->subManagersHelper_->currentUIAbilityManager_ = + std::make_shared(); + DelayedSingleton::GetInstance()->OnRemoteRequest(code, parcel, reply, option); + } + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = static_cast(malloc(size + 1)); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/abilitystubinterface_fuzzer/abilitystubinterface_fuzzer.h b/test/fuzztest/abilitystubinterface_fuzzer/abilitystubinterface_fuzzer.h new file mode 100644 index 0000000000..3a9508bec2 --- /dev/null +++ b/test/fuzztest/abilitystubinterface_fuzzer/abilitystubinterface_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYSTUBINTERFACE_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYSTUBINTERFACE_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitystubinterface_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYSTUBINTERFACE_FUZZER_H diff --git a/test/fuzztest/abilitystubinterface_fuzzer/corpus/init b/test/fuzztest/abilitystubinterface_fuzzer/corpus/init new file mode 100644 index 0000000000..8eb5a7d6eb --- /dev/null +++ b/test/fuzztest/abilitystubinterface_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/abilitystubinterface_fuzzer/project.xml b/test/fuzztest/abilitystubinterface_fuzzer/project.xml new file mode 100644 index 0000000000..6e8ad2cfde --- /dev/null +++ b/test/fuzztest/abilitystubinterface_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/appforegroundstateobserverproxy_fuzzer/BUILD.gn b/test/fuzztest/appforegroundstateobserverproxy_fuzzer/BUILD.gn new file mode 100644 index 0000000000..b6578c00c9 --- /dev/null +++ b/test/fuzztest/appforegroundstateobserverproxy_fuzzer/BUILD.gn @@ -0,0 +1,75 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/appmgr" + +##############################fuzztest########################################## +ohos_fuzztest("AppForegroundStateObserverProxyTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/appforegroundstateobserverproxy_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "appforegroundstateobserverproxy_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/appmgr:appmgr_config" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AppForegroundStateObserverProxyTest", + ] +} +############################################################################### diff --git a/test/fuzztest/appforegroundstateobserverproxy_fuzzer/appforegroundstateobserverproxy_fuzzer.cpp b/test/fuzztest/appforegroundstateobserverproxy_fuzzer/appforegroundstateobserverproxy_fuzzer.cpp new file mode 100644 index 0000000000..3d6a11aed1 --- /dev/null +++ b/test/fuzztest/appforegroundstateobserverproxy_fuzzer/appforegroundstateobserverproxy_fuzzer.cpp @@ -0,0 +1,102 @@ +/* + * 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 "appforegroundstateobserverproxy_fuzzer.h" + +#include +#include + +#define private public +#include "app_foreground_state_observer_proxy.h" +#undef private + +#include "ability_record.h" +#include "parcel.h" +#include "securec.h" +#include "want.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +const std::u16string APPMGR_INTERFACE_TOKEN = u"ohos.aafwk.AppManager"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + sptr impl; + auto appForegroundStateObserverProxy = std::make_shared(impl); + AppStateData appStateData; + appForegroundStateObserverProxy->OnAppStateChanged(appStateData); + MessageParcel dataParcel; + dataParcel.WriteInterfaceToken(APPMGR_INTERFACE_TOKEN); + dataParcel.WriteBuffer(data, size); + dataParcel.RewindRead(0); + appForegroundStateObserverProxy->WriteInterfaceToken(dataParcel); + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} diff --git a/test/fuzztest/appforegroundstateobserverproxy_fuzzer/appforegroundstateobserverproxy_fuzzer.h b/test/fuzztest/appforegroundstateobserverproxy_fuzzer/appforegroundstateobserverproxy_fuzzer.h new file mode 100644 index 0000000000..a72df3f54e --- /dev/null +++ b/test/fuzztest/appforegroundstateobserverproxy_fuzzer/appforegroundstateobserverproxy_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_APPFOREGROUNDSTATEOBSERVERPROXY_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_APPFOREGROUNDSTATEOBSERVERPROXY_FUZZER_H + +#define FUZZ_PROJECT_NAME "appforegroundstateobserverproxy_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_APPFOREGROUNDSTATEOBSERVERPROXY_FUZZER_H diff --git a/test/fuzztest/appforegroundstateobserverproxy_fuzzer/corpus/init b/test/fuzztest/appforegroundstateobserverproxy_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/appforegroundstateobserverproxy_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/appforegroundstateobserverproxy_fuzzer/project.xml b/test/fuzztest/appforegroundstateobserverproxy_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/appforegroundstateobserverproxy_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/applicationanrlistener_fuzzer/applicationanrlistener_fuzzer.cpp b/test/fuzztest/applicationanrlistener_fuzzer/applicationanrlistener_fuzzer.cpp index 20dbf02568..76df529fbe 100755 --- a/test/fuzztest/applicationanrlistener_fuzzer/applicationanrlistener_fuzzer.cpp +++ b/test/fuzztest/applicationanrlistener_fuzzer/applicationanrlistener_fuzzer.cpp @@ -117,7 +117,7 @@ bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) // fuzz for ApplicationAnrListener auto applicationAnrListener = std::make_shared(); - applicationAnrListener->OnAnr(int32Param); + applicationAnrListener->OnAnr(int32Param, 0); // fuzz for FreeInstallManager auto abilityms = std::make_shared(); diff --git a/test/fuzztest/appmanager_fuzzer/appmanager_fuzzer.cpp b/test/fuzztest/appmanager_fuzzer/appmanager_fuzzer.cpp index 92bef0ff95..495cd7e24c 100644 --- a/test/fuzztest/appmanager_fuzzer/appmanager_fuzzer.cpp +++ b/test/fuzztest/appmanager_fuzzer/appmanager_fuzzer.cpp @@ -48,16 +48,17 @@ uint32_t GetU32Data(const char* ptr) bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) { - uint32_t code = GetU32Data(data) % (static_cast(AppMgrInterfaceCode::JUDGE_SANDBOX_BY_PID) + 1); - - MessageParcel parcel; - parcel.WriteInterfaceToken(APPMGR_INTERFACE_TOKEN); - parcel.WriteBuffer(data, size); - parcel.RewindRead(0); - MessageParcel reply; - MessageOption option; - std::shared_ptr appMgr = std::make_shared(); - appMgr->OnRemoteRequest(code, parcel, reply, option); + for (uint32_t code = 0; + code <= static_cast(AppMgrInterfaceCode::RESTART_RESIDENT_PROCESS_DEPENDED_ON_WEB); ++code) { + MessageParcel parcel; + parcel.WriteInterfaceToken(APPMGR_INTERFACE_TOKEN); + parcel.WriteBuffer(data, size); + parcel.RewindRead(0); + MessageParcel reply; + MessageOption option; + std::shared_ptr appMgr = std::make_shared(); + appMgr->OnRemoteRequest(code, parcel, reply, option); + } return true; } diff --git a/test/fuzztest/appmgrstub_fuzzer/BUILD.gn b/test/fuzztest/appmgrstub_fuzzer/BUILD.gn new file mode 100644 index 0000000000..c721c73b1d --- /dev/null +++ b/test/fuzztest/appmgrstub_fuzzer/BUILD.gn @@ -0,0 +1,75 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/appmgr" + +##############################fuzztest########################################## +ohos_fuzztest("AppmgrStubFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/appmgrstub_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "appmgrstub_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/appmgr:appmgr_config" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AppmgrStubFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/appmgrstub_fuzzer/appmgrstub_fuzzer.cpp b/test/fuzztest/appmgrstub_fuzzer/appmgrstub_fuzzer.cpp new file mode 100644 index 0000000000..4c2d7d4dee --- /dev/null +++ b/test/fuzztest/appmgrstub_fuzzer/appmgrstub_fuzzer.cpp @@ -0,0 +1,108 @@ +/* + * 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 "appmgrstub_fuzzer.h" + +#include +#include + +#define private public +#include "app_mgr_stub.h" +#include "app_mgr_service.h" +#undef private + +#include "ability_record.h" +#include "parcel.h" +#include "securec.h" +#include "want.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} +const std::u16string APPMGR_INTERFACE_TOKEN = u"ohos.aafwk.AppManager"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + auto appMgrStub = std::make_shared(); + MessageParcel dataParcel; + MessageParcel reply; + dataParcel.WriteInterfaceToken(APPMGR_INTERFACE_TOKEN); + dataParcel.WriteBuffer(data, size); + dataParcel.RewindRead(0); + appMgrStub->HandleApplicationForegrounded(dataParcel, reply); + appMgrStub->HandleApplicationTerminated(dataParcel, reply); + appMgrStub->HandleClearUpApplicationData(dataParcel, reply); + appMgrStub->HandleGetProcessRunningInfosByUserId(dataParcel, reply); + appMgrStub->HandleAddAbilityStageDone(dataParcel, reply); + appMgrStub->HandleUnregisterApplicationStateObserver(dataParcel, reply); + appMgrStub->HandleGetForegroundApplications(dataParcel, reply); + appMgrStub->HandleAttachRenderProcess(dataParcel, reply); + appMgrStub->HandleJudgeSandboxByPid(dataParcel, reply); + appMgrStub->HandleDumpHeapMemory(dataParcel, reply); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} diff --git a/test/fuzztest/appmgrstub_fuzzer/appmgrstub_fuzzer.h b/test/fuzztest/appmgrstub_fuzzer/appmgrstub_fuzzer.h new file mode 100644 index 0000000000..0207995be8 --- /dev/null +++ b/test/fuzztest/appmgrstub_fuzzer/appmgrstub_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_APPMGRSTUB_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_APPMGRSTUB_FUZZER_H + +#define FUZZ_PROJECT_NAME "appmgrstub_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_APPMGRSTUB_FUZZER_H diff --git a/test/fuzztest/appmgrstub_fuzzer/corpus/init b/test/fuzztest/appmgrstub_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/appmgrstub_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/appmgrstub_fuzzer/project.xml b/test/fuzztest/appmgrstub_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/appmgrstub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/apprunningstatusproxy_fuzzer/BUILD.gn b/test/fuzztest/apprunningstatusproxy_fuzzer/BUILD.gn new file mode 100644 index 0000000000..0ddd71d7e2 --- /dev/null +++ b/test/fuzztest/apprunningstatusproxy_fuzzer/BUILD.gn @@ -0,0 +1,76 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/appmgr" + +##############################fuzztest########################################## +ohos_fuzztest("AppRunningStatusProxyFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/apprunningstatusproxy_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "apprunningstatusproxy_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/appmgr:appmgr_config" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AppRunningStatusProxyFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/apprunningstatusproxy_fuzzer/apprunningstatusproxy_fuzzer.cpp b/test/fuzztest/apprunningstatusproxy_fuzzer/apprunningstatusproxy_fuzzer.cpp new file mode 100644 index 0000000000..9634fa15df --- /dev/null +++ b/test/fuzztest/apprunningstatusproxy_fuzzer/apprunningstatusproxy_fuzzer.cpp @@ -0,0 +1,99 @@ +/* + * 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 "apprunningstatusproxy_fuzzer.h" + +#include +#include + +#include "app_running_status_proxy.h" + +#include "ability_record.h" +#include "parcel.h" +#include "securec.h" +#include "want.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +const std::u16string APPMGR_INTERFACE_TOKEN = u"ohos.aafwk.AppManager"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + sptr impl; + auto appRunningStatusProxy = std::make_shared(impl); + std::string bundle(data, size); + int32_t uid = static_cast(GetU32Data(data)); + AbilityRuntime::RunningStatus runningStatus = AbilityRuntime::RunningStatus::APP_RUNNING_START; + appRunningStatusProxy->NotifyAppRunningStatus(bundle, uid, runningStatus); + runningStatus = AbilityRuntime::RunningStatus::APP_RUNNING_STOP; + appRunningStatusProxy->NotifyAppRunningStatus(bundle, uid, runningStatus); + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} diff --git a/test/fuzztest/apprunningstatusproxy_fuzzer/apprunningstatusproxy_fuzzer.h b/test/fuzztest/apprunningstatusproxy_fuzzer/apprunningstatusproxy_fuzzer.h new file mode 100644 index 0000000000..7608ce3637 --- /dev/null +++ b/test/fuzztest/apprunningstatusproxy_fuzzer/apprunningstatusproxy_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_APPRUNNINGSTATUSPROXY_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_APPRUNNINGSTATUSPROXY_FUZZER_H + +#define FUZZ_PROJECT_NAME "apprunningstatusproxy_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_APPRUNNINGSTATUSPROXY_FUZZER_H diff --git a/test/fuzztest/apprunningstatusproxy_fuzzer/corpus/init b/test/fuzztest/apprunningstatusproxy_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/apprunningstatusproxy_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/apprunningstatusproxy_fuzzer/project.xml b/test/fuzztest/apprunningstatusproxy_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/apprunningstatusproxy_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/appstateobservermanager_fuzzer/BUILD.gn b/test/fuzztest/appstateobservermanager_fuzzer/BUILD.gn index 5ce7fbf0af..b83622aad8 100755 --- a/test/fuzztest/appstateobservermanager_fuzzer/BUILD.gn +++ b/test/fuzztest/appstateobservermanager_fuzzer/BUILD.gn @@ -49,7 +49,8 @@ ohos_fuzztest("AppStateObserverManagerFuzzTest") { external_deps = [ "ability_base:want", "ability_base:zuri", - "appspawn:appspawn_socket_client", + "access_token:libaccesstoken_sdk", + "appspawn:appspawn_client", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", diff --git a/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/BUILD.gn b/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/BUILD.gn new file mode 100644 index 0000000000..d97805ef37 --- /dev/null +++ b/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/BUILD.gn @@ -0,0 +1,89 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AssertFaultCallbackDeathMgrFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/assertfaultcallbackdeathmgr_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/assert_fault_callback_death_mgr.cpp", + "${ability_runtime_services_path}/abilitymgr/src/assert_fault_proxy.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", + "assertfaultcallbackdeathmgr_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AssertFaultCallbackDeathMgrFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/assertfaultcallbackdeathmgr_fuzzer.cpp b/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/assertfaultcallbackdeathmgr_fuzzer.cpp new file mode 100644 index 0000000000..d6269c766e --- /dev/null +++ b/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/assertfaultcallbackdeathmgr_fuzzer.cpp @@ -0,0 +1,99 @@ +/* + * 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 "assertfaultcallbackdeathmgr_fuzzer.h" + +#include +#include + +#include "assert_fault_callback_death_mgr.h" +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + sptr remote; + wptr remotes; + time_t timeParam = static_cast(GetU32Data(data)); + uint64_t u64Param = static_cast(GetU32Data(data)); + AbilityRuntime::AssertFaultCallbackDeathMgr::CallbackTask callback; + bool boolParam = *data % ENABLE; + auto assertFaultCallbackDeathMgr = std::make_shared(); + assertFaultCallbackDeathMgr->AddAssertFaultCallback(remote, callback); + assertFaultCallbackDeathMgr->RemoveAssertFaultCallback(remotes, boolParam); + remote = nullptr; + assertFaultCallbackDeathMgr->AddAssertFaultCallback(remote, callback); + AAFwk::UserStatus status = AAFwk::UserStatus::ASSERT_TERMINATE; + assertFaultCallbackDeathMgr->CallAssertFaultCallback(u64Param, status); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/assertfaultcallbackdeathmgr_fuzzer.h b/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/assertfaultcallbackdeathmgr_fuzzer.h new file mode 100644 index 0000000000..5b8987ffef --- /dev/null +++ b/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/assertfaultcallbackdeathmgr_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ASSERTFAULTCALLBACKDEATHMGR_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ASSERTFAULTCALLBACKDEATHMGR_FUZZER_H + +#define FUZZ_PROJECT_NAME "assertfaultcallbackdeathmgr_fuzzer" + +#endif diff --git a/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/corpus/init b/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/project.xml b/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/assertfaultcallbackdeathmgr_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/assertfaultproxy_fuzzer/BUILD.gn b/test/fuzztest/assertfaultproxy_fuzzer/BUILD.gn new file mode 100644 index 0000000000..bf1c3cca6e --- /dev/null +++ b/test/fuzztest/assertfaultproxy_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AssertFaultProxyFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/assertfaultproxy_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/assert_fault_proxy.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", + "assertfaultproxy_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AssertFaultProxyFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/assertfaultproxy_fuzzer/assertfaultproxy_fuzzer.cpp b/test/fuzztest/assertfaultproxy_fuzzer/assertfaultproxy_fuzzer.cpp new file mode 100644 index 0000000000..6d077cf889 --- /dev/null +++ b/test/fuzztest/assertfaultproxy_fuzzer/assertfaultproxy_fuzzer.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "assertfaultproxy_fuzzer.h" + +#include +#include + +#define private public +#include "assert_fault_proxy.h" +#undef private +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + AAFwk::UserStatus status = AAFwk::ASSERT_TERMINATE; + wptr remote; + sptr impl; + auto assertFaultProxy = std::make_shared(impl); + assertFaultProxy->NotifyDebugAssertResult(status); + + AbilityRuntime::AssertFaultRemoteDeathRecipient::RemoteDiedHandler handler; + auto assertFaultRemoteDeathRecipient = + std::make_shared(handler); + assertFaultRemoteDeathRecipient->OnRemoteDied(remote); + + auto modalSystemAssertUIExtension = std::make_shared(); + Want want; + modalSystemAssertUIExtension->CreateModalUIExtension(want); + + auto assertDialogConnection = + std::make_shared(); + assertDialogConnection->SetReqeustAssertDialogWant(want); + AppExecFwk::ElementName element; + sptr remoteObject; + int intParam = static_cast(GetU32Data(data)); + assertDialogConnection->OnAbilityConnectDone(element, remoteObject, intParam); + assertDialogConnection->OnAbilityDisconnectDone(element, intParam); + modalSystemAssertUIExtension->DisconnectSystemUI(); + modalSystemAssertUIExtension->TryNotifyOneWaitingThread(); + modalSystemAssertUIExtension->TryNotifyOneWaitingThreadInner(); + modalSystemAssertUIExtension->GetConnection(); + modalSystemAssertUIExtension->dialogConnectionCallback_ = nullptr; + modalSystemAssertUIExtension->GetConnection(); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/assertfaultproxy_fuzzer/assertfaultproxy_fuzzer.h b/test/fuzztest/assertfaultproxy_fuzzer/assertfaultproxy_fuzzer.h new file mode 100644 index 0000000000..72b1cc7082 --- /dev/null +++ b/test/fuzztest/assertfaultproxy_fuzzer/assertfaultproxy_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ASSER_TFAULT_PROXY_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ASSER_TFAULT_PROXY_FUZZER_H + +#define FUZZ_PROJECT_NAME "assertfaultproxy_fuzzer" + +#endif diff --git a/test/fuzztest/assertfaultproxy_fuzzer/corpus/init b/test/fuzztest/assertfaultproxy_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/assertfaultproxy_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/assertfaultproxy_fuzzer/project.xml b/test/fuzztest/assertfaultproxy_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/assertfaultproxy_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/autostartupinfo_fuzzer/BUILD.gn b/test/fuzztest/autostartupinfo_fuzzer/BUILD.gn new file mode 100644 index 0000000000..e5ad593681 --- /dev/null +++ b/test/fuzztest/autostartupinfo_fuzzer/BUILD.gn @@ -0,0 +1,85 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("AutoStartupInfoFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/autostartupinfo_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/auto_startup_info.cpp", + "autostartupinfo_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":AutoStartupInfoFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/autostartupinfo_fuzzer/autostartupinfo_fuzzer.cpp b/test/fuzztest/autostartupinfo_fuzzer/autostartupinfo_fuzzer.cpp new file mode 100644 index 0000000000..a41bb3e202 --- /dev/null +++ b/test/fuzztest/autostartupinfo_fuzzer/autostartupinfo_fuzzer.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "autostartupinfo_fuzzer.h" + +#include +#include +#include + +#include "auto_startup_info.h" +#include "ability_record.h" +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + Parcel parcel; + auto autoStartupInfo = std::make_shared(); + autoStartupInfo->ReadFromParcel(parcel); + autoStartupInfo->Marshalling(parcel); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/autostartupinfo_fuzzer/autostartupinfo_fuzzer.h b/test/fuzztest/autostartupinfo_fuzzer/autostartupinfo_fuzzer.h new file mode 100644 index 0000000000..e346aea5a3 --- /dev/null +++ b/test/fuzztest/autostartupinfo_fuzzer/autostartupinfo_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_AUTOSTARTUPINFO_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_AUTOSTARTUPINFO_FUZZER_H + +#define FUZZ_PROJECT_NAME "autostartupinfo_fuzzer" + +#endif diff --git a/test/fuzztest/autostartupinfo_fuzzer/corpus/init b/test/fuzztest/autostartupinfo_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/autostartupinfo_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/autostartupinfo_fuzzer/project.xml b/test/fuzztest/autostartupinfo_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/autostartupinfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/bundlemgrhelper_fuzzer/BUILD.gn b/test/fuzztest/bundlemgrhelper_fuzzer/BUILD.gn new file mode 100755 index 0000000000..683c4626c7 --- /dev/null +++ b/test/fuzztest/bundlemgrhelper_fuzzer/BUILD.gn @@ -0,0 +1,102 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("BundleMgrHelperFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/bundlemgrhelper_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "bundlemgrhelper_fuzzer.cpp" ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:auto_startup_callback", + "${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", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:libappexecfwk_common", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":BundleMgrHelperFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/bundlemgrhelper_fuzzer/bundlemgrhelper_fuzzer.cpp b/test/fuzztest/bundlemgrhelper_fuzzer/bundlemgrhelper_fuzzer.cpp new file mode 100755 index 0000000000..708862901b --- /dev/null +++ b/test/fuzztest/bundlemgrhelper_fuzzer/bundlemgrhelper_fuzzer.cpp @@ -0,0 +1,192 @@ +/* + * 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 "bundlemgrhelper_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "bundle_mgr_helper.h" +#undef protected +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void BundleMgrHelperFuzztest1(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr bmHelper = std::make_shared(); // branch constructor + bmHelper->GetNameForUid(int32Param, stringParam); // branch + BundleInfo bundleInfo; + bmHelper->GetBundleInfo(stringParam, boolParam, bundleInfo, int32Param); // branch + bmHelper->InstallSandboxApp(stringParam, int32Param, int32Param, int32Param); // branch + bmHelper->UninstallSandboxApp(stringParam, int32Param, int32Param); // branch + bmHelper->GetUninstalledBundleInfo(stringParam, bundleInfo); // branch + bmHelper->GetSandboxBundleInfo(stringParam, int32Param, int32Param, bundleInfo); // branch + Want want; + AbilityInfo abilityInfo; + bmHelper->GetSandboxAbilityInfo(want, int32Param, int32Param, int32Param, abilityInfo); + std::vector extensionInfos; + bmHelper->GetSandboxExtAbilityInfos(want, int32Param, int32Param, int32Param, extensionInfos); + HapModuleInfo hapModuleInfo; + bmHelper->GetSandboxHapModuleInfo(abilityInfo, int32Param, int32Param, hapModuleInfo); + bmHelper->Connect(); + bmHelper->ConnectBundleInstaller(); + bmHelper->OnDeath(); + bmHelper->GetBundleInfo(stringParam, int32Param, bundleInfo, int32Param); + bmHelper->GetHapModuleInfo(abilityInfo, hapModuleInfo); + bmHelper->GetAbilityLabel(stringParam, stringParam); + bmHelper->GetAppType(stringParam); + std::vector baseSharedBundleInfos; + bmHelper->GetBaseSharedBundleInfos( + stringParam, baseSharedBundleInfos, static_cast(int32Param)); + bmHelper->GetBundleInfoForSelf(int32Param, bundleInfo); + bmHelper->GetDependentBundleInfo(stringParam, bundleInfo, static_cast(int32Param)); + bmHelper->GetGroupDir(stringParam, stringParam); + bmHelper->GetOverlayManagerProxy(); + bmHelper->QueryAbilityInfo(want, abilityInfo); + bmHelper->QueryAbilityInfo(want, int32Param, int32Param, abilityInfo); + std::vector bundleInfos; + bmHelper->GetBundleInfos(int32Param, bundleInfos, int32Param); + bmHelper->GetBundleInfos(static_cast(int32Param), bundleInfos, int32Param); + bmHelper->GetQuickFixManagerProxy(); + bmHelper->ProcessPreload(want); + bmHelper->GetAppControlProxy(); + bmHelper->QueryExtensionAbilityInfos(want, int32Param, int32Param, extensionInfos); + bmHelper->GetBundleInfoV9(stringParam, int32Param, bundleInfo, int32Param); +} + +void BundleMgrHelperFuzztest2(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr bmHelper = std::make_shared(); // branch constructor + ApplicationInfo appInfo; + Want want; + bmHelper->GetApplicationInfo(stringParam, static_cast(int32Param), int32Param, appInfo); + bmHelper->GetApplicationInfo(stringParam, int32Param, int32Param, appInfo); + bmHelper->GetApplicationInfoWithAppIndex(stringParam, int32Param, int32Param, appInfo); + bmHelper->UnregisterBundleEventCallback(nullptr); // branch null + ExtensionAbilityInfo extensionAbilityInfo; + bmHelper->QueryExtensionAbilityInfoByUri(stringParam, int32Param, extensionAbilityInfo); + AbilityInfo abilityInfo; + bmHelper->ImplicitQueryInfoByPriority(want, int32Param, int32Param, abilityInfo, extensionAbilityInfo); + bmHelper->QueryAbilityInfoByUri(stringParam, int32Param, abilityInfo); + bmHelper->QueryAbilityInfo(want, int32Param, int32Param, abilityInfo, nullptr); + bmHelper->UpgradeAtomicService(want, int32Param); + std::vector abilityInfos; + std::vector extensionInfos; + bmHelper->ImplicitQueryInfos(want, int32Param, int32Param, boolParam, abilityInfos, extensionInfos, boolParam); + bmHelper->CleanBundleDataFiles(stringParam, int32Param, int32Param); + std::vector infos; + bmHelper->QueryDataGroupInfos(stringParam, int32Param, infos); + bmHelper->RegisterBundleEventCallback(nullptr); + HapModuleInfo hapModuleInfo; + bmHelper->GetHapModuleInfo(abilityInfo, int32Param, hapModuleInfo); + bmHelper->QueryAppGalleryBundleName(stringParam); + bmHelper->GetUidByBundleName(stringParam, int32Param, int32Param); + bmHelper->QueryExtensionAbilityInfosOnlyWithTypeName(stringParam, int32Param, int32Param, extensionInfos); + bmHelper->GetDefaultAppProxy(); + bmHelper->GetJsonProfile(static_cast(int32Param), stringParam, stringParam, stringParam, int32Param); + bmHelper->GetLaunchWantForBundle(stringParam, want, int32Param); + ElementName element; + bmHelper->QueryCloneAbilityInfo(element, int32Param, int32Param, abilityInfo, int32Param); + BundleInfo bundleInfo; + bmHelper->GetCloneBundleInfo(stringParam, int32Param, int32Param, bundleInfo, int32Param); + ExtensionAbilityInfo extensionInfo; + bmHelper->QueryCloneExtensionAbilityInfoWithAppIndex(element, int32Param, int32Param, extensionInfo, int32Param); +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + BundleMgrHelperFuzztest1(boolParam, stringParam, int32Param); + BundleMgrHelperFuzztest2(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/bundlemgrhelper_fuzzer/bundlemgrhelper_fuzzer.h b/test/fuzztest/bundlemgrhelper_fuzzer/bundlemgrhelper_fuzzer.h new file mode 100755 index 0000000000..cd4a7ce47a --- /dev/null +++ b/test/fuzztest/bundlemgrhelper_fuzzer/bundlemgrhelper_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_BUNDLEMGRHELPER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_BUNDLEMGRHELPER_FUZZER_H + +#define FUZZ_PROJECT_NAME "bundlemgrhelper_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_BUNDLEMGRHELPER_FUZZER_H diff --git a/test/fuzztest/bundlemgrhelper_fuzzer/corpus/init b/test/fuzztest/bundlemgrhelper_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/bundlemgrhelper_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/bundlemgrhelper_fuzzer/project.xml b/test/fuzztest/bundlemgrhelper_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/bundlemgrhelper_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/cacheprocessmanagera_fuzzer/BUILD.gn b/test/fuzztest/cacheprocessmanagera_fuzzer/BUILD.gn new file mode 100755 index 0000000000..e38123fd97 --- /dev/null +++ b/test/fuzztest/cacheprocessmanagera_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("CacheProcessManageraFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/cacheprocessmanagera_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/appmgr/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_services_path}/appmgr/src/cache_process_manager.cpp", + "cacheprocessmanagera_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":CacheProcessManageraFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/cacheprocessmanagera_fuzzer/cacheprocessmanagera_fuzzer.cpp b/test/fuzztest/cacheprocessmanagera_fuzzer/cacheprocessmanagera_fuzzer.cpp new file mode 100755 index 0000000000..7501babffb --- /dev/null +++ b/test/fuzztest/cacheprocessmanagera_fuzzer/cacheprocessmanagera_fuzzer.cpp @@ -0,0 +1,228 @@ +/* + * 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 "cacheprocessmanagera_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "cache_process_manager.h" +#include "ability_record.h" +#undef protected +#undef private + +#include "app_mgr_service_inner.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void CacheProcessManagerFuzztestFunc1(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr mgr = std::make_shared(); + std::shared_ptr serviceInner1; + mgr->SetAppMgr(serviceInner1); // null mgr + mgr->RefreshCacheNum(); // called. + mgr->QueryEnableProcessCache(); // called. + mgr->maxProcCacheNum_ = 0; + mgr->PenddingCacheProcess(nullptr); // called. + mgr->maxProcCacheNum_ = int32Param; + + std::shared_ptr appInfo = std::make_shared(); + std::shared_ptr appRecord1 = std::make_shared(appInfo, int32Param, stringParam); + mgr->PenddingCacheProcess(nullptr); // nullptr + appRecord1->isKeepAliveApp_ = true; + appRecord1->isSingleton_ = true; + appRecord1->isMainProcess_ = true; + mgr->PenddingCacheProcess(appRecord1); // keepalive + std::shared_ptr appRecord2 = std::make_shared(appInfo, int32Param, stringParam); + mgr->PenddingCacheProcess(appRecord2); // not alive + + mgr->maxProcCacheNum_ = 0; + mgr->CheckAndCacheProcess(nullptr); // nullptr + mgr->maxProcCacheNum_ = int32Param; + mgr->CheckAndCacheProcess(appRecord2); // not cached + mgr->cachedAppRecordQueue_.emplace_back(appRecord2); + mgr->CheckAndCacheProcess(appRecord2); // cached + + mgr->CheckAndNotifyCachedState(nullptr); + std::shared_ptr serviceInner = std::make_shared(); + mgr->SetAppMgr(serviceInner); + mgr->CheckAndNotifyCachedState(appRecord2); // appMgr not null +} + +void CacheProcessManagerFuzztestFunc2(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr mgr = std::make_shared(); + std::shared_ptr serviceInner1; + mgr->SetAppMgr(serviceInner1); + mgr->IsCachedProcess(nullptr); // called. + std::shared_ptr appInfo = std::make_shared(); + std::shared_ptr appRecord2 = std::make_shared(appInfo, int32Param, stringParam); + mgr->IsCachedProcess(appRecord2); // not cached called. + mgr->cachedAppRecordQueue_.emplace_back(appRecord2); + mgr->IsCachedProcess(appRecord2); // cached called. + mgr->cachedAppRecordQueue_.clear(); // clear + + mgr->maxProcCacheNum_ = int32Param; + mgr->OnProcessKilled(nullptr); // nullptr called. + mgr->OnProcessKilled(appRecord2); // not cached called. + mgr->cachedAppRecordQueue_.emplace_back(appRecord2); + mgr->OnProcessKilled(appRecord2); // cached called. + mgr->cachedAppRecordQueue_.clear(); // clear + + mgr->maxProcCacheNum_ = int32Param; + mgr->ReuseCachedProcess(nullptr); + mgr->ReuseCachedProcess(appRecord2); // not cached + mgr->cachedAppRecordQueue_.emplace_back(appRecord2); + mgr->ReuseCachedProcess(appRecord2); // cached + mgr->cachedAppRecordQueue_.clear(); // clear + + std::shared_ptr serviceInner = std::make_shared(); + mgr->SetAppMgr(serviceInner); // appInner not null + mgr->cachedAppRecordQueue_.emplace_back(appRecord2); + mgr->ReuseCachedProcess(appRecord2); // cached + + mgr->IsAppSupportProcessCache(nullptr); // null ptr check + std::shared_ptr appRecord3 = std::make_shared(nullptr, int32Param, stringParam); + mgr->IsAppSupportProcessCache(appRecord3); // null appInfo + mgr->srvExtRecords.emplace(appRecord2); + mgr->IsAppSupportProcessCache(appRecord2); // appInfo not null + mgr->srvExtRecords.clear(); + + appRecord2->SetAttachedToStatusBar(true); + mgr->IsAppSupportProcessCache(appRecord2); // appInfo not null &attached true + appRecord2->SetAttachedToStatusBar(false); + mgr->IsAppSupportProcessCache(appRecord2); // appInfo not null &attached false + appRecord2->isKeepAliveApp_ = true; + appRecord2->isSingleton_ = true; + appRecord2->isMainProcess_ = true; + mgr->IsAppSupportProcessCache(appRecord2); // appInfo not null &attached false & keepalive called +} + +void CacheProcessManagerFuzztestFunc3(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr mgr = std::make_shared(); + std::shared_ptr serviceInner1; + mgr->SetAppMgr(serviceInner1); + mgr->IsAppSupportProcessCacheInnerFirst(nullptr); // nullptr + std::shared_ptr appInfo = std::make_shared(); + std::shared_ptr appRecord1 = std::make_shared(appInfo, int32Param, stringParam); + mgr->shouldCheckSupport = true; + appRecord1->procCacheSupportState_ = SupportProcessCacheState::UNSPECIFIED; + mgr->IsAppSupportProcessCacheInnerFirst(appRecord1); // case CacheState UNSPECIFIED + appRecord1->procCacheSupportState_ = SupportProcessCacheState::SUPPORT; + mgr->IsAppSupportProcessCacheInnerFirst(appRecord1); // case CacheState SUPPORT + appRecord1->procCacheSupportState_ = SupportProcessCacheState::NOT_SUPPORT; + mgr->IsAppSupportProcessCacheInnerFirst(appRecord1); // case CacheState SUPPORT + int32_t num = static_cast(SupportProcessCacheState::NOT_SUPPORT) + 1; + appRecord1->procCacheSupportState_ = static_cast(num); + mgr->IsAppSupportProcessCacheInnerFirst(appRecord1); // case CacheState default branch + + mgr->shouldCheckSupport = false; + appRecord1->procCacheSupportState_ = SupportProcessCacheState::UNSPECIFIED; + mgr->IsAppSupportProcessCacheInnerFirst(appRecord1); // case CacheState UNSPECIFIED + + mgr->IsAppShouldCache(nullptr); // called. + mgr->maxProcCacheNum_ = int32Param; + mgr->IsAppShouldCache(appRecord1); // not ccached called. + mgr->cachedAppRecordQueue_.emplace_back(appRecord1); + mgr->IsAppShouldCache(appRecord1); //ccached called. + + mgr->IsAppAbilitiesEmpty(nullptr); // called + mgr->IsAppAbilitiesEmpty(appRecord1); // called +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + CacheProcessManagerFuzztestFunc1(boolParam, stringParam, int32Param); + CacheProcessManagerFuzztestFunc2(boolParam, stringParam, int32Param); + CacheProcessManagerFuzztestFunc3(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/cacheprocessmanagera_fuzzer/cacheprocessmanagera_fuzzer.h b/test/fuzztest/cacheprocessmanagera_fuzzer/cacheprocessmanagera_fuzzer.h new file mode 100755 index 0000000000..6b39faf750 --- /dev/null +++ b/test/fuzztest/cacheprocessmanagera_fuzzer/cacheprocessmanagera_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_CACHEPROCESSMANAGERA_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_CACHEPROCESSMANAGERA_FUZZER_H + +#define FUZZ_PROJECT_NAME "cacheprocessmanagera_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_CACHEPROCESSMANAGERA_FUZZER_H diff --git a/test/fuzztest/cacheprocessmanagera_fuzzer/corpus/init b/test/fuzztest/cacheprocessmanagera_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/cacheprocessmanagera_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/cacheprocessmanagera_fuzzer/project.xml b/test/fuzztest/cacheprocessmanagera_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/cacheprocessmanagera_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/cacheprocessmanagerb_fuzzer/BUILD.gn b/test/fuzztest/cacheprocessmanagerb_fuzzer/BUILD.gn new file mode 100755 index 0000000000..449e9bd42d --- /dev/null +++ b/test/fuzztest/cacheprocessmanagerb_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("CacheProcessManagerbFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/cacheprocessmanagerb_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/appmgr/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_services_path}/appmgr/src/cache_process_manager.cpp", + "cacheprocessmanagerb_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":CacheProcessManagerbFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/cacheprocessmanagerb_fuzzer/cacheprocessmanagerb_fuzzer.cpp b/test/fuzztest/cacheprocessmanagerb_fuzzer/cacheprocessmanagerb_fuzzer.cpp new file mode 100755 index 0000000000..f968ac6ab9 --- /dev/null +++ b/test/fuzztest/cacheprocessmanagerb_fuzzer/cacheprocessmanagerb_fuzzer.cpp @@ -0,0 +1,175 @@ +/* + * 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 "cacheprocessmanagerb_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "cache_process_manager.h" +#include "ability_record.h" +#undef protected +#undef private + +#include "app_mgr_service_inner.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void CacheProcessManagerFuzztestFunc1(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr mgr = std::make_shared(); + std::shared_ptr serviceInner1; + mgr->GetCurrentCachedProcNum(); // called. + std::shared_ptr appInfo = std::make_shared(); + std::shared_ptr appRecord1 = std::make_shared(appInfo, int32Param, stringParam); + std::shared_ptr appRecord2 = std::make_shared(nullptr, int32Param, stringParam); + mgr->cachedAppRecordQueue_.emplace_back(appRecord1); + mgr->RemoveCacheRecord(appRecord1); // called branch cached. + mgr->RemoveCacheRecord(appRecord2); // called branch not cached. + mgr->cachedAppRecordQueue_.clear(); + + mgr->maxProcCacheNum_ = 0; + mgr->ShrinkAndKillCache(); // called branch + mgr->maxProcCacheNum_ = 1; // 1 means maxProcCacheNum + mgr->ShrinkAndKillCache(); // called branch current < maxProcCacheNum. + mgr->cachedAppRecordQueue_.emplace_back(appRecord1); + mgr->cachedAppRecordQueue_.emplace_back(appRecord2); + mgr->ShrinkAndKillCache(); // called branch current > maxProcCacheNum. + mgr->cachedAppRecordQueue_.clear(); + + mgr->SetAppMgr(serviceInner1); + mgr->KillProcessByRecord(nullptr); // called branch appMgr is nullptr. + mgr->KillProcessByRecord(appRecord2); // called branch appRecord not null. + std::shared_ptr serviceInner2 = std::make_shared(); + mgr->SetAppMgr(serviceInner2); + mgr->KillProcessByRecord(appRecord2); // called branch appRecord not null. + + mgr->cachedAppRecordQueue_.emplace_back(appRecord1); + mgr->cachedAppRecordQueue_.emplace_back(appRecord2); + mgr->PrintCacheQueue(); // called branch apprecord exist, + mgr->cachedAppRecordQueue_.clear(); + mgr->PrintCacheQueue(); // called branch no apprecord. + + mgr->AddToApplicationSet(nullptr); // called nullptr. + mgr->AddToApplicationSet(appRecord2); // called. + mgr->RemoveFromApplicationSet(nullptr); // called nullptr. + mgr->RemoveFromApplicationSet(appRecord2); // called. +} + +void CacheProcessManagerFuzztestFunc2(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr mgr = std::make_shared(); + std::shared_ptr serviceInner1; + std::shared_ptr appInfo = std::make_shared(); + std::shared_ptr appRecord1 = std::make_shared(appInfo, int32Param, stringParam); + std::shared_ptr appRecord2 = std::make_shared(nullptr, int32Param, stringParam); + + mgr->maxProcCacheNum_ = 0; + mgr->PrepareActivateCache(nullptr); // branch 0 maxProcCacheNum_ + mgr->maxProcCacheNum_ = 1; // 1 means maxProcCacheNum. + mgr->PrepareActivateCache(nullptr); // branch 0 null apprecord + mgr->PrepareActivateCache(appRecord1); + + mgr->SetAppMgr(serviceInner1); + mgr->cachedAppRecordQueue_.emplace_back(appRecord1); + mgr->PrepareActivateCache(appRecord1); // // branch cached & appMgr null. + std::shared_ptr serviceInner2 = std::make_shared(); + mgr->SetAppMgr(serviceInner2); + mgr->cachedAppRecordQueue_.emplace_back(appRecord1); + mgr->PrepareActivateCache(appRecord1); // branch cached & appMgr not null. +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + CacheProcessManagerFuzztestFunc1(boolParam, stringParam, int32Param); + CacheProcessManagerFuzztestFunc2(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/cacheprocessmanagerb_fuzzer/cacheprocessmanagerb_fuzzer.h b/test/fuzztest/cacheprocessmanagerb_fuzzer/cacheprocessmanagerb_fuzzer.h new file mode 100755 index 0000000000..bdd219b561 --- /dev/null +++ b/test/fuzztest/cacheprocessmanagerb_fuzzer/cacheprocessmanagerb_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_CACHEPROCESSMANAGERB_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_CACHEPROCESSMANAGERB_FUZZER_H + +#define FUZZ_PROJECT_NAME "cacheprocessmanagerb_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_CACHEPROCESSMANAGERA_FUZZER_H diff --git a/test/fuzztest/cacheprocessmanagerb_fuzzer/corpus/init b/test/fuzztest/cacheprocessmanagerb_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/cacheprocessmanagerb_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/cacheprocessmanagerb_fuzzer/project.xml b/test/fuzztest/cacheprocessmanagerb_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/cacheprocessmanagerb_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/connectability_fuzzer/BUILD.gn b/test/fuzztest/connectability_fuzzer/BUILD.gn index 24a5283107..a228c3559d 100755 --- a/test/fuzztest/connectability_fuzzer/BUILD.gn +++ b/test/fuzztest/connectability_fuzzer/BUILD.gn @@ -55,7 +55,7 @@ ohos_fuzztest("ConnectAbilityFuzzTest") { external_deps = [ "ability_base:want", "ability_runtime:ability_manager", - "appspawn:appspawn_socket_client", + "appspawn:appspawn_client", "c_utils:utils", "common_event_service:cesfwk_innerkits", "ipc:ipc_core", diff --git a/test/fuzztest/crowdtestinterceptor_fuzzer/BUILD.gn b/test/fuzztest/crowdtestinterceptor_fuzzer/BUILD.gn new file mode 100644 index 0000000000..23d0dc5264 --- /dev/null +++ b/test/fuzztest/crowdtestinterceptor_fuzzer/BUILD.gn @@ -0,0 +1,95 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("CrowdTestInterceptorFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/crowdtestinterceptor_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include/interceptor", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "crowdtestinterceptor_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":CrowdTestInterceptorFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/crowdtestinterceptor_fuzzer/corpus/init b/test/fuzztest/crowdtestinterceptor_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/crowdtestinterceptor_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/crowdtestinterceptor_fuzzer/crowdtestinterceptor_fuzzer.cpp b/test/fuzztest/crowdtestinterceptor_fuzzer/crowdtestinterceptor_fuzzer.cpp new file mode 100644 index 0000000000..dac41ebe45 --- /dev/null +++ b/test/fuzztest/crowdtestinterceptor_fuzzer/crowdtestinterceptor_fuzzer.cpp @@ -0,0 +1,111 @@ +/* + * 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 "crowdtestinterceptor_fuzzer.h" + +#include +#include + +#define private public +#include "crowd_test_interceptor.h" +#undef private +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + int intParam = static_cast(GetU32Data(data)); + int32_t int32Param = static_cast(GetU32Data(data)); + std::shared_ptr crowdTestInterceptor = std::make_shared(); + Want want; + bool boolParam = *data % ENABLE; + sptr token = GetFuzzAbilityToken(); + AbilityInterceptorParam param = AbilityInterceptorParam(want, intParam, int32Param, boolParam, token); + crowdTestInterceptor->DoProcess(param); + crowdTestInterceptor->CheckCrowdtest(want, int32Param); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/crowdtestinterceptor_fuzzer/crowdtestinterceptor_fuzzer.h b/test/fuzztest/crowdtestinterceptor_fuzzer/crowdtestinterceptor_fuzzer.h new file mode 100644 index 0000000000..69b484d124 --- /dev/null +++ b/test/fuzztest/crowdtestinterceptor_fuzzer/crowdtestinterceptor_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_CROWDTESTINTERCEPTOR_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_CROWDTESTINTERCEPTOR_FUZZER_H + +#define FUZZ_PROJECT_NAME "crowdtestinterceptor_fuzzer" + +#endif diff --git a/test/fuzztest/crowdtestinterceptor_fuzzer/project.xml b/test/fuzztest/crowdtestinterceptor_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/crowdtestinterceptor_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/dialogsessioninfo_fuzzer/BUILD.gn b/test/fuzztest/dialogsessioninfo_fuzzer/BUILD.gn new file mode 100644 index 0000000000..2bcc724651 --- /dev/null +++ b/test/fuzztest/dialogsessioninfo_fuzzer/BUILD.gn @@ -0,0 +1,82 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("DialogSessionInfoFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/dialogsessioninfo_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "dialogsessioninfo_fuzzer.cpp" ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":DialogSessionInfoFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/dialogsessioninfo_fuzzer/corpus/init b/test/fuzztest/dialogsessioninfo_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/dialogsessioninfo_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/dialogsessioninfo_fuzzer/dialogsessioninfo_fuzzer.cpp b/test/fuzztest/dialogsessioninfo_fuzzer/dialogsessioninfo_fuzzer.cpp new file mode 100644 index 0000000000..e14d99d065 --- /dev/null +++ b/test/fuzztest/dialogsessioninfo_fuzzer/dialogsessioninfo_fuzzer.cpp @@ -0,0 +1,91 @@ +/* + * 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 "dialogsessioninfo_fuzzer.h" + +#include +#include + +#include "dialog_session_info.h" + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + Parcel parcel; + auto dialogSessionInfo = std::make_shared(); + dialogSessionInfo->ReadFromParcel(parcel); + dialogSessionInfo->Marshalling(parcel); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/dialogsessioninfo_fuzzer/dialogsessioninfo_fuzzer.h b/test/fuzztest/dialogsessioninfo_fuzzer/dialogsessioninfo_fuzzer.h new file mode 100644 index 0000000000..095195dded --- /dev/null +++ b/test/fuzztest/dialogsessioninfo_fuzzer/dialogsessioninfo_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_DIALOG_SESSION_INFO_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_DIALOG_SESSION_INFO_FUZZER_H + +#define FUZZ_PROJECT_NAME "dialogsessioninfo_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/dialogsessioninfo_fuzzer/project.xml b/test/fuzztest/dialogsessioninfo_fuzzer/project.xml new file mode 100644 index 0000000000..6d3e765c7d --- /dev/null +++ b/test/fuzztest/dialogsessioninfo_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/disposedobserver_fuzzer/BUILD.gn b/test/fuzztest/disposedobserver_fuzzer/BUILD.gn new file mode 100644 index 0000000000..715a91328b --- /dev/null +++ b/test/fuzztest/disposedobserver_fuzzer/BUILD.gn @@ -0,0 +1,91 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("DisposedObserverFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/disposedobserver_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/ability_state_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_state_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/application_state_observer_stub.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/page_state_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/process_data.cpp", + "${ability_runtime_services_path}/abilitymgr/src/disposed_observer.cpp", + "disposedobserver_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libmodal_system_ui_extension_client", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":DisposedObserverFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/disposedobserver_fuzzer/corpus/init b/test/fuzztest/disposedobserver_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/disposedobserver_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/disposedobserver_fuzzer/disposedobserver_fuzzer.cpp b/test/fuzztest/disposedobserver_fuzzer/disposedobserver_fuzzer.cpp new file mode 100644 index 0000000000..5d28526286 --- /dev/null +++ b/test/fuzztest/disposedobserver_fuzzer/disposedobserver_fuzzer.cpp @@ -0,0 +1,95 @@ +/* + * 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 "disposedobserver_fuzzer.h" + +#include +#include + +#define private public +#include "disposed_observer.h" +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + AppExecFwk::DisposedRule disposedRule; + std::shared_ptr interceptor; + auto disposedObserver = std::make_shared(disposedRule, interceptor); + AppExecFwk::AbilityStateData abilityStateData; + disposedObserver->OnAbilityStateChanged(abilityStateData); + AppExecFwk::PageStateData pageStateData; + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/disposedobserver_fuzzer/disposedobserver_fuzzer.h b/test/fuzztest/disposedobserver_fuzzer/disposedobserver_fuzzer.h new file mode 100644 index 0000000000..97d20a8359 --- /dev/null +++ b/test/fuzztest/disposedobserver_fuzzer/disposedobserver_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_DISPOSED_OBSERVER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_DISPOSED_OBSERVER_FUZZER_H + +#define FUZZ_PROJECT_NAME "disposedobserver_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/disposedobserver_fuzzer/project.xml b/test/fuzztest/disposedobserver_fuzzer/project.xml new file mode 100644 index 0000000000..6d3e765c7d --- /dev/null +++ b/test/fuzztest/disposedobserver_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/extensionconfig_fuzzer/BUILD.gn b/test/fuzztest/extensionconfig_fuzzer/BUILD.gn new file mode 100644 index 0000000000..04b2d733f6 --- /dev/null +++ b/test/fuzztest/extensionconfig_fuzzer/BUILD.gn @@ -0,0 +1,86 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("ExtensionConfigFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/extensionconfig_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/extension_config.cpp", + "extensionconfig_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":ExtensionConfigFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/extensionconfig_fuzzer/corpus/init b/test/fuzztest/extensionconfig_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/extensionconfig_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/extensionconfig_fuzzer/extensionconfig_fuzzer.cpp b/test/fuzztest/extensionconfig_fuzzer/extensionconfig_fuzzer.cpp new file mode 100644 index 0000000000..0bc1d83a35 --- /dev/null +++ b/test/fuzztest/extensionconfig_fuzzer/extensionconfig_fuzzer.cpp @@ -0,0 +1,102 @@ +/* + * 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 "extensionconfig_fuzzer.h" + +#include +#include + +#include "ability_record.h" +#define private public +#include "extension_config.h" +#define private public + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + std::string strParam(data, size); + auto extensionConfig = std::make_shared(); + extensionConfig->LoadExtensionConfiguration(); + extensionConfig->GetExtensionAutoDisconnectTime(strParam); + extensionConfig->IsExtensionStartThirdPartyAppEnable(strParam); + extensionConfig->IsExtensionStartServiceEnable(strParam, strParam); + nlohmann::json object; + extensionConfig->LoadExtensionConfig(object); + extensionConfig->ReadFileInfoJson(strParam, object); + extensionConfig->GetExtensionConfigPath(); + extensionConfig->LoadExtensionAutoDisconnectTime(object, strParam); + extensionConfig->LoadExtensionThirdPartyAppBlockedList(object, strParam); + extensionConfig->LoadExtensionServiceBlockedList(object, strParam); + extensionConfig->CheckServiceExtensionUriValid(strParam); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/extensionconfig_fuzzer/extensionconfig_fuzzer.h b/test/fuzztest/extensionconfig_fuzzer/extensionconfig_fuzzer.h new file mode 100644 index 0000000000..660360cf42 --- /dev/null +++ b/test/fuzztest/extensionconfig_fuzzer/extensionconfig_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_EXTENSION_CONFIG_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_EXTENSION_CONFIG_FUZZER_H + +#define FUZZ_PROJECT_NAME "extensionconfig_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/extensionconfig_fuzzer/project.xml b/test/fuzztest/extensionconfig_fuzzer/project.xml new file mode 100644 index 0000000000..6d3e765c7d --- /dev/null +++ b/test/fuzztest/extensionconfig_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/extensioncontrolinterceptor_fuzzer/BUILD.gn b/test/fuzztest/extensioncontrolinterceptor_fuzzer/BUILD.gn new file mode 100644 index 0000000000..9a9493f070 --- /dev/null +++ b/test/fuzztest/extensioncontrolinterceptor_fuzzer/BUILD.gn @@ -0,0 +1,99 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("ExtensionControlInterceptorFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/extensioncontrolinterceptor_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include/interceptor", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/app_scheduler.cpp", + "${ability_runtime_services_path}/abilitymgr/src/start_ability_utils.cpp", + "extension_control_interceptor_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + 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_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", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":ExtensionControlInterceptorFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/extensioncontrolinterceptor_fuzzer/corpus/init b/test/fuzztest/extensioncontrolinterceptor_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/extensioncontrolinterceptor_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/extensioncontrolinterceptor_fuzzer/extension_control_interceptor_fuzzer.cpp b/test/fuzztest/extensioncontrolinterceptor_fuzzer/extension_control_interceptor_fuzzer.cpp new file mode 100644 index 0000000000..dd3ac58a67 --- /dev/null +++ b/test/fuzztest/extensioncontrolinterceptor_fuzzer/extension_control_interceptor_fuzzer.cpp @@ -0,0 +1,110 @@ +/* + * 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 "extension_control_interceptor_fuzzer.h" + +#include +#include + +#include "extension_control_interceptor.h" + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + int intParam = static_cast(GetU32Data(data)); + int32_t int32Param = static_cast(GetU32Data(data)); + std::shared_ptr extensionControlInterceptor = + std::make_shared(); + Want want; + bool boolParam = *data % ENABLE; + sptr token = GetFuzzAbilityToken(); + AbilityInterceptorParam param = AbilityInterceptorParam(want, intParam, int32Param, boolParam, token); + extensionControlInterceptor->DoProcess(param); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/extensioncontrolinterceptor_fuzzer/extension_control_interceptor_fuzzer.h b/test/fuzztest/extensioncontrolinterceptor_fuzzer/extension_control_interceptor_fuzzer.h new file mode 100644 index 0000000000..e19dcc9310 --- /dev/null +++ b/test/fuzztest/extensioncontrolinterceptor_fuzzer/extension_control_interceptor_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_EXTENSION_CONTROL_INTERCEPTOR_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_EXTENSION_CONTROL_INTERCEPTOR_FUZZER_H + +#define FUZZ_PROJECT_NAME "extensioncontrolinterceptor_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/extensioncontrolinterceptor_fuzzer/project.xml b/test/fuzztest/extensioncontrolinterceptor_fuzzer/project.xml new file mode 100644 index 0000000000..6d3e765c7d --- /dev/null +++ b/test/fuzztest/extensioncontrolinterceptor_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/extensionrecordfactory_fuzzer/BUILD.gn b/test/fuzztest/extensionrecordfactory_fuzzer/BUILD.gn new file mode 100644 index 0000000000..21e2f35b54 --- /dev/null +++ b/test/fuzztest/extensionrecordfactory_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("ExtensionRecordFactoryFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/extensionrecordfactory_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/extension_record_factory.cpp", + "${ability_runtime_services_path}/common/src/app_utils.cpp", + "${ability_runtime_services_path}/common/src/json_utils.cpp", + "extensionrecordfactory_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":ExtensionRecordFactoryFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/extensionrecordfactory_fuzzer/corpus/init b/test/fuzztest/extensionrecordfactory_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/extensionrecordfactory_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/extensionrecordfactory_fuzzer/extensionrecordfactory_fuzzer.cpp b/test/fuzztest/extensionrecordfactory_fuzzer/extensionrecordfactory_fuzzer.cpp new file mode 100644 index 0000000000..dcbb38e147 --- /dev/null +++ b/test/fuzztest/extensionrecordfactory_fuzzer/extensionrecordfactory_fuzzer.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 "extensionrecordfactory_fuzzer.h" + +#include +#include + +#define protected public +#include "extension_record_factory.h" +#undef protected + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + auto extensionRecordFactory = std::make_shared(); + AAFwk::AbilityRequest abilityRequest; + int32_t int32Param = static_cast(GetU32Data(data)); + extensionRecordFactory->NeedReuse(abilityRequest, int32Param); + std::string strParam(data, size); + extensionRecordFactory->PreCheck(abilityRequest, strParam); + abilityRequest.extensionType = ExtensionAbilityType::WORK_SCHEDULER; + extensionRecordFactory->PreCheck(abilityRequest, strParam); + abilityRequest.extensionType = ExtensionAbilityType::INPUTMETHOD; + extensionRecordFactory->PreCheck(abilityRequest, strParam); + std::shared_ptr extensionRecord; + extensionRecordFactory->CreateRecord(abilityRequest, extensionRecord); + AAFwk::AbilityRequest abilityRequest01; + bool boolParam = *data % ENABLE; + extensionRecordFactory->GetExtensionProcessMode(abilityRequest01, boolParam); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/extensionrecordfactory_fuzzer/extensionrecordfactory_fuzzer.h b/test/fuzztest/extensionrecordfactory_fuzzer/extensionrecordfactory_fuzzer.h new file mode 100644 index 0000000000..b4cfc7d191 --- /dev/null +++ b/test/fuzztest/extensionrecordfactory_fuzzer/extensionrecordfactory_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_EXTENSION_RECORD_FACTORY_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_EXTENSION_RECORD_FACTORY_FUZZER_H + +#define FUZZ_PROJECT_NAME "extensionrecordfactory_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/extensionrecordfactory_fuzzer/project.xml b/test/fuzztest/extensionrecordfactory_fuzzer/project.xml new file mode 100644 index 0000000000..6d3e765c7d --- /dev/null +++ b/test/fuzztest/extensionrecordfactory_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/extensionrecordmanager_fuzzer/BUILD.gn b/test/fuzztest/extensionrecordmanager_fuzzer/BUILD.gn new file mode 100644 index 0000000000..a57b1bb3fd --- /dev/null +++ b/test/fuzztest/extensionrecordmanager_fuzzer/BUILD.gn @@ -0,0 +1,100 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("ExtensionRecordManagerFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/extensionrecordmanager_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/ability_state_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_mgr_client.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_service_manager.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_state_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/application_state_observer_stub.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/page_state_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/process_data.cpp", + "${ability_runtime_services_path}/abilitymgr/src/extension_record.cpp", + "${ability_runtime_services_path}/abilitymgr/src/extension_record_factory.cpp", + "${ability_runtime_services_path}/abilitymgr/src/extension_record_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/preload_uiext_state_observer.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ui_extension_record.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ui_extension_record_factory.cpp", + "${ability_runtime_services_path}/common/src/app_utils.cpp", + "${ability_runtime_services_path}/common/src/json_utils.cpp", + "extensionrecordmanager_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":ExtensionRecordManagerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/extensionrecordmanager_fuzzer/corpus/init b/test/fuzztest/extensionrecordmanager_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/extensionrecordmanager_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/extensionrecordmanager_fuzzer/extensionrecordmanager_fuzzer.cpp b/test/fuzztest/extensionrecordmanager_fuzzer/extensionrecordmanager_fuzzer.cpp new file mode 100644 index 0000000000..c5a996fe61 --- /dev/null +++ b/test/fuzztest/extensionrecordmanager_fuzzer/extensionrecordmanager_fuzzer.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 "extensionrecordmanager_fuzzer.h" + +#include +#include + +#define private public +#include "extension_record_manager.h" +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + int32_t int32Param = static_cast(GetU32Data(data)); + auto extensionRecordManager = std::make_shared(int32Param); + extensionRecordManager->GenerateExtensionRecordId(int32Param); + std::shared_ptr record; + extensionRecordManager->AddExtensionRecord(int32Param, record); + extensionRecordManager->RemoveExtensionRecord(int32Param); + extensionRecordManager->AddExtensionRecordToTerminatedList(int32Param); + AppExecFwk::AbilityInfo abilityInfo; + extensionRecordManager->IsBelongToManager(abilityInfo); + auto focusToken = GetFuzzAbilityToken(); + extensionRecordManager->IsFocused(int32Param, focusToken); + std::vector extensionList; + extensionRecordManager->GetActiveUIExtensionList(int32Param, extensionList); + std::string strParam(data, size); + extensionRecordManager->GetActiveUIExtensionList(strParam, extensionList); + AAFwk::AbilityRequest abilityRequest; + extensionRecordManager->StartAbility(abilityRequest); + std::shared_ptr extensionRecord; + extensionRecordManager->CreateExtensionRecord(abilityRequest, strParam, extensionRecord, int32Param); + bool boolParam = *data % ENABLE; + extensionRecordManager->IsPreloadExtensionRecord(abilityRequest, strParam, extensionRecord, boolParam); + std::shared_ptr abilityRecord; + extensionRecordManager->AddPreloadUIExtensionRecord(abilityRecord); + AbilityRuntime::ExtensionRecordManager::PreLoadUIExtensionMapKey preLoadUIExtensionInfo; + extensionRecordManager->RemoveAllPreloadUIExtensionRecord(preLoadUIExtensionInfo); + std::tuple extensionRecordMapKey; + extensionRecordManager->RemovePreloadUIExtensionRecord(extensionRecordMapKey); + extensionRecordManager->RemovePreloadUIExtensionRecordById(extensionRecordMapKey, int32Param); + extensionRecordManager->GetOrCreateExtensionRecord(abilityRequest, strParam, abilityRecord, boolParam); + sptr sessionInfo; + extensionRecordManager->GetAbilityRecordBySessionInfo(sessionInfo); + auto token = GetFuzzAbilityToken(); + extensionRecordManager->GetUIExtensionRootHostInfo(token); + UIExtensionSessionInfo uiExtensionSessionInfo; + extensionRecordManager->GetUIExtensionSessionInfo(token, uiExtensionSessionInfo); + extensionRecordManager->LoadTimeout(int32Param); + extensionRecordManager->ForegroundTimeout(int32Param); + extensionRecordManager->BackgroundTimeout(int32Param); + extensionRecordManager->TerminateTimeout(int32Param); + extensionRecordManager->GetHostBundleNameForExtensionId(int32Param, strParam); + extensionRecordManager->GetRootCallerTokenLocked(int32Param); + extensionRecordManager->GetOrCreateExtensionRecordInner(abilityRequest, strParam, extensionRecord, boolParam); + extensionRecordManager->IsHostSpecifiedProcessValid(abilityRequest, record, strParam); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/extensionrecordmanager_fuzzer/extensionrecordmanager_fuzzer.h b/test/fuzztest/extensionrecordmanager_fuzzer/extensionrecordmanager_fuzzer.h new file mode 100644 index 0000000000..9e1dd2d5f6 --- /dev/null +++ b/test/fuzztest/extensionrecordmanager_fuzzer/extensionrecordmanager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_EXTENSION_RECORD_MANAGER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_EXTENSION_RECORD_MANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "extensionrecordmanager_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/extensionrecordmanager_fuzzer/project.xml b/test/fuzztest/extensionrecordmanager_fuzzer/project.xml new file mode 100644 index 0000000000..6d3e765c7d --- /dev/null +++ b/test/fuzztest/extensionrecordmanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/extensionrecordmanagera_fuzzer/BUILD.gn b/test/fuzztest/extensionrecordmanagera_fuzzer/BUILD.gn new file mode 100755 index 0000000000..5bbedaa8a7 --- /dev/null +++ b/test/fuzztest/extensionrecordmanagera_fuzzer/BUILD.gn @@ -0,0 +1,116 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("ExtensionRecordManageraFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/extensionrecordmanagera_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/ability_state_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_mgr_client.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_service_manager.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/app_state_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/application_state_observer_stub.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/page_state_data.cpp", + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/process_data.cpp", + "${ability_runtime_services_path}/abilitymgr/src/extension_record.cpp", + "${ability_runtime_services_path}/abilitymgr/src/extension_record_factory.cpp", + "${ability_runtime_services_path}/abilitymgr/src/extension_record_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/preload_uiext_state_observer.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ui_extension_record.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ui_extension_record_factory.cpp", + "${ability_runtime_services_path}/common/src/app_utils.cpp", + "${ability_runtime_services_path}/common/src/json_utils.cpp", + "extensionrecordmanagera_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":ExtensionRecordManageraFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/extensionrecordmanagera_fuzzer/corpus/init b/test/fuzztest/extensionrecordmanagera_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/extensionrecordmanagera_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/extensionrecordmanagera_fuzzer/extensionrecordmanagera_fuzzer.cpp b/test/fuzztest/extensionrecordmanagera_fuzzer/extensionrecordmanagera_fuzzer.cpp new file mode 100755 index 0000000000..55c4261231 --- /dev/null +++ b/test/fuzztest/extensionrecordmanagera_fuzzer/extensionrecordmanagera_fuzzer.cpp @@ -0,0 +1,216 @@ +/* + * 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 "extensionrecordmanagera_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "extension_record_manager.h" +#undef protected +#undef private + +#include "ability_record.h" +#include "extension_record.h" +#include "extension_record_factory.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void FuzztestExtensionRecordManagerFunc1(std::shared_ptr mgr, bool boolParam, + const std::string &stringParam, int32_t int32Param) +{ + Want want; + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + std::shared_ptr abilityRecord = + std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr record = std::make_shared(abilityRecord); + mgr->GenerateExtensionRecordId(int32Param); + mgr->AddExtensionRecord(int32Param, record); + mgr->RemoveExtensionRecord(int32Param); + mgr->AddExtensionRecordToTerminatedList(int32Param); + mgr->AddExtensionRecordToTerminatedList(1); // 1 means valid id, construct exist recordId + mgr->AddExtensionRecord(1, record); // 1 means valid id + std::shared_ptr extensionRecord = std::make_shared(abilityRecord); + mgr->GetExtensionRecord(1, stringParam, extensionRecord, boolParam); // 1 means valid id + mgr->GetExtensionRecord(int32Param, stringParam, extensionRecord, boolParam); + mgr->IsBelongToManager(abilityInfo); + std::vector extensionList; + mgr->GetActiveUIExtensionList(int32Param, extensionList); + mgr->GetActiveUIExtensionList(stringParam, extensionList); + mgr->GetAbilityRecordBySessionInfo(nullptr); + sptr sessionInfo = new (std::nothrow) SessionInfo(); + sessionInfo->uiExtensionComponentId = int32Param; + mgr->AddExtensionRecord(int32Param, nullptr); + record->abilityRecord_ = abilityRecord; + mgr->AddExtensionRecord(int32Param, record); + record->abilityRecord_->sessionInfo_ = sessionInfo; + mgr->GetAbilityRecordBySessionInfo(sessionInfo); + mgr->extensionRecords_.clear(); + mgr->GetAbilityRecordBySessionInfo(sessionInfo); +} + +void FuzztestExtensionRecordManagerFunc2(std::shared_ptr mgr, bool boolParam, + const std::string &stringParam, int32_t int32Param) +{ + Want want; + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + std::shared_ptr abilityRecord = std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr record = std::make_shared(abilityRecord); + AAFwk::AbilityRequest abilityRequest; + sptr sessionInfo = new (std::nothrow) SessionInfo(); + sessionInfo->uiExtensionComponentId = int32Param; + mgr->AddExtensionRecord(int32Param, nullptr); + record->abilityRecord_ = abilityRecord; + mgr->AddExtensionRecord(int32Param, record); + record->abilityRecord_->sessionInfo_ = sessionInfo; + mgr->IsHostSpecifiedProcessValid(abilityRequest, record, stringParam); + + record->processMode_ = PROCESS_MODE_INSTANCE; + mgr->UpdateProcessName(abilityRequest, record); + record->processMode_ = PROCESS_MODE_TYPE; + mgr->UpdateProcessName(abilityRequest, record); + record->processMode_ = PROCESS_MODE_HOST_SPECIFIED; + mgr->UpdateProcessName(abilityRequest, record); + std::string bundleName = "bundleName"; + mgr->GetHostBundleNameForExtensionId(1, bundleName); // 1 means id + mgr->AddExtensionRecord(1, record); // 1 means id + mgr->GetHostBundleNameForExtensionId(1, bundleName); // 1 means id, exist. + mgr->GetHostBundleNameForExtensionId(int32Param, bundleName); // 1 means id, exist. + abilityRecord->SetUIExtensionAbilityId(-1); + mgr->AddExtensionRecord(1, record); // 1 means id + abilityRecord->SetUIExtensionAbilityId(1); + mgr->AddPreloadUIExtensionRecord(abilityRecord); + ExtensionRecordManager::PreLoadUIExtensionMapKey key; + mgr->RemoveAllPreloadUIExtensionRecord(key); // called + mgr->IsPreloadExtensionRecord(abilityRequest, stringParam, record, boolParam); // called + mgr->RemovePreloadUIExtensionRecordById(key, int32Param); // called + mgr->RemovePreloadUIExtensionRecord(key); // called + mgr->GetOrCreateExtensionRecordInner(abilityRequest, stringParam, record, boolParam); // called + mgr->StartAbility(abilityRequest); // called + mgr->IsFocused(int32Param, nullptr); // called + mgr->AddExtensionRecord(0, record); // 1 means id + mgr->GetRootCallerTokenLocked(int32Param); + mgr->CreateExtensionRecord(abilityRequest, stringParam, record, int32Param); + mgr->GetUIExtensionRootHostInfo(nullptr); + sptr token = GetFuzzAbilityToken(); + mgr->GetUIExtensionRootHostInfo(token); + mgr->extensionRecords_.clear(); +} + +void FuzztestExtensionRecordManagerFunc3(std::shared_ptr mgr, bool boolParam, + const std::string &stringParam, int32_t int32Param) +{ + Want want; + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + std::shared_ptr abilityRecord = std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr record = std::make_shared(abilityRecord); + AAFwk::AbilityRequest abilityRequest; + UIExtensionSessionInfo uiExtensionSessionInfo; + mgr->GetUIExtensionSessionInfo(nullptr, uiExtensionSessionInfo); + mgr->AddExtensionRecord(0, record); + mgr->AddExtensionRecord(1, record); // 1 means id + mgr->LoadTimeout(int32Param); // called + mgr->ForegroundTimeout(int32Param); // called + mgr->BackgroundTimeout(int32Param); // called + mgr->TerminateTimeout(int32Param); // called +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + std::shared_ptr mgr = std::make_shared(100); // 100 mainUserId + FuzztestExtensionRecordManagerFunc1(mgr, boolParam, stringParam, int32Param); + FuzztestExtensionRecordManagerFunc2(mgr, boolParam, stringParam, int32Param); + FuzztestExtensionRecordManagerFunc3(mgr, boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/extensionrecordmanagera_fuzzer/extensionrecordmanagera_fuzzer.h b/test/fuzztest/extensionrecordmanagera_fuzzer/extensionrecordmanagera_fuzzer.h new file mode 100755 index 0000000000..1aa0d39990 --- /dev/null +++ b/test/fuzztest/extensionrecordmanagera_fuzzer/extensionrecordmanagera_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPDATAMANAGERA_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPDATAMANAGERA_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityautostartupdatamanagera_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPDATAMANAGERA_FUZZER_H diff --git a/test/fuzztest/extensionrecordmanagera_fuzzer/project.xml b/test/fuzztest/extensionrecordmanagera_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/extensionrecordmanagera_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/faultdata_fuzzer/BUILD.gn b/test/fuzztest/faultdata_fuzzer/BUILD.gn new file mode 100755 index 0000000000..be7a79ae88 --- /dev/null +++ b/test/fuzztest/faultdata_fuzzer/BUILD.gn @@ -0,0 +1,96 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("FaultDataFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/faultdata_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/fault_data.cpp", + "faultdata_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":FaultDataFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/faultdata_fuzzer/corpus/init b/test/fuzztest/faultdata_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/faultdata_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/faultdata_fuzzer/faultdata_fuzzer.cpp b/test/fuzztest/faultdata_fuzzer/faultdata_fuzzer.cpp new file mode 100755 index 0000000000..7dd60609d1 --- /dev/null +++ b/test/fuzztest/faultdata_fuzzer/faultdata_fuzzer.cpp @@ -0,0 +1,184 @@ +/* + * 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 "faultdata_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "fault_data.h" +#undef protected +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +Want& SetElement(Want &want) +{ + return want.SetElementName("deviceId", "bundleName", "ability", "moduleName"); +} + +void FaultDataFuzztest1(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + FaultData faultData; + Parcel parcel1; + parcel1.WriteInt32(int32Param); + faultData.ReadFromParcel(parcel1); // branch name failed + Parcel parcel2; + parcel2.WriteString(stringParam); + parcel2.WriteInt32(int32Param); + faultData.ReadFromParcel(parcel2); // branch message failed + Parcel parcel3; + parcel3.WriteString(stringParam); + parcel3.WriteString(stringParam); + faultData.ReadFromParcel(parcel3); // branch stack failed + Parcel parcel4; + parcel4.WriteString(stringParam); + parcel4.WriteString(stringParam); + parcel4.WriteString(stringParam); + faultData.ReadFromParcel(parcel4); // branch FaultType failed + + Parcel parcel5; + parcel5.WriteString(stringParam); + parcel5.WriteString(stringParam); + parcel5.WriteString(stringParam); + parcel5.WriteInt32(int32Param); + faultData.ReadFromParcel(parcel5); // branch FaultType failed + + Parcel parcel6; + parcel6.WriteString(stringParam); + parcel6.WriteString(stringParam); + parcel6.WriteString(stringParam); + parcel6.WriteInt32(int32Param); + parcel6.WriteString(stringParam); + faultData.ReadFromParcel(parcel6); // branch FaultType failed + parcel6.WriteBool(boolParam); + faultData.ReadFromParcel(parcel6); + Parcel parcel7; + faultData.Marshalling(parcel7); +} + +void FaultDataFuzztest2(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + AppFaultDataBySA faultData; + Parcel appParcel1; + appParcel1.WriteInt32(int32Param); + faultData.ReadFromParcel(appParcel1); // branch name failed + Parcel appParcel2; + appParcel2.WriteString(stringParam); + appParcel2.WriteInt32(int32Param); + faultData.ReadFromParcel(appParcel2); // branch message failed + Parcel appParcel3; + appParcel3.WriteString(stringParam); + appParcel3.WriteString(stringParam); + faultData.ReadFromParcel(appParcel3); // branch stack failed + Parcel appParcel4; + appParcel4.WriteString(stringParam); + appParcel4.WriteString(stringParam); + appParcel4.WriteString(stringParam); + faultData.ReadFromParcel(appParcel4); // branch FaultType failed + Parcel appParcel5; + appParcel5.WriteString(stringParam); + appParcel5.WriteString(stringParam); + appParcel5.WriteString(stringParam); + appParcel5.WriteInt32(int32Param); + faultData.ReadFromParcel(appParcel5); // branch FaultType failed + Parcel appParcel6; + faultData.Marshalling(appParcel6); +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + FaultDataFuzztest1(boolParam, stringParam, int32Param); + FaultDataFuzztest2(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/faultdata_fuzzer/faultdata_fuzzer.h b/test/fuzztest/faultdata_fuzzer/faultdata_fuzzer.h new file mode 100755 index 0000000000..1180410d1c --- /dev/null +++ b/test/fuzztest/faultdata_fuzzer/faultdata_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYCACHEMANAGERA_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYCACHEMANAGERA_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilitycachemanagera_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYCACHEMANAGERA_FUZZER_H diff --git a/test/fuzztest/faultdata_fuzzer/project.xml b/test/fuzztest/faultdata_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/faultdata_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/freezeutil_fuzzer/BUILD.gn b/test/fuzztest/freezeutil_fuzzer/BUILD.gn new file mode 100644 index 0000000000..a8d8e40f3a --- /dev/null +++ b/test/fuzztest/freezeutil_fuzzer/BUILD.gn @@ -0,0 +1,99 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/freeze_util" + +##############################fuzztest########################################## +ohos_fuzztest("FreezeUtilFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/freezeutil_fuzzer" + include_dirs = [ + "${ability_runtime_services_path}/common/include", + "${ability_runtime_utils_path}/global/freeze/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/app_scheduler.cpp", + "${ability_runtime_services_path}/abilitymgr/src/start_ability_utils.cpp", + "freezeutil_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_utils_path}/global/freeze:freeze_util_config" ] + + 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_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:perm_verification", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":FreezeUtilFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/freezeutil_fuzzer/corpus/init b/test/fuzztest/freezeutil_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/freezeutil_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/freezeutil_fuzzer/freezeutil_fuzzer.cpp b/test/fuzztest/freezeutil_fuzzer/freezeutil_fuzzer.cpp new file mode 100644 index 0000000000..f3e3cbfa88 --- /dev/null +++ b/test/fuzztest/freezeutil_fuzzer/freezeutil_fuzzer.cpp @@ -0,0 +1,102 @@ +/* + * 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 "freezeutil_fuzzer.h" +#include "ability_record.h" + +#include +#include + +#define private public +#include "freeze_util.h" +#undef private +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + FreezeUtil::LifecycleFlow flow; + std::string JsonStr(data, size); + FreezeUtil::GetInstance(); + sptr token = GetFuzzAbilityToken(); + if (!token) { + std::cout << "Get ability token failed." << std::endl; + return false; + }; + FreezeUtil::GetInstance().AddLifecycleEvent(flow, JsonStr); + FreezeUtil::GetInstance().GetLifecycleEvent(flow); + FreezeUtil::GetInstance().DeleteLifecycleEvent(flow); + FreezeUtil::GetInstance().DeleteLifecycleEvent(token); + FreezeUtil::GetInstance().DeleteLifecycleEventInner(flow); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/freezeutil_fuzzer/freezeutil_fuzzer.h b/test/fuzztest/freezeutil_fuzzer/freezeutil_fuzzer.h new file mode 100644 index 0000000000..c6bc4d87cc --- /dev/null +++ b/test/fuzztest/freezeutil_fuzzer/freezeutil_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_FREEZEUTIL_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_FREEZEUTIL_FUZZER_H + +#define FUZZ_PROJECT_NAME "freezeutil_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/freezeutil_fuzzer/project.xml b/test/fuzztest/freezeutil_fuzzer/project.xml new file mode 100644 index 0000000000..6d3e765c7d --- /dev/null +++ b/test/fuzztest/freezeutil_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/insightintentexecutecallbackstub_fuzzer/BUILD.gn b/test/fuzztest/insightintentexecutecallbackstub_fuzzer/BUILD.gn new file mode 100644 index 0000000000..dd43de2a30 --- /dev/null +++ b/test/fuzztest/insightintentexecutecallbackstub_fuzzer/BUILD.gn @@ -0,0 +1,83 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("InsightIntentExecuteCallbackStubFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = "${ability_runtime_test_path}/fuzztest/insightintentexecutecallbackstub_fuzzer" + + include_dirs = [ "${ability_runtime_innerkits_path}/wantagent/include" ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "insightintentexecutecallbackstub_fuzzer.cpp" ] + + configs = [ + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + ] + cflags = [] + if (target_cpu == "arm") { + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "init:libbeget_proxy", + "ipc:ipc_core", + "napi:ace_napi", + "relational_store:native_appdatafwk", + "relational_store:native_dataability", + "relational_store:native_rdb", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":InsightIntentExecuteCallbackStubFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/insightintentexecutecallbackstub_fuzzer/corpus/init b/test/fuzztest/insightintentexecutecallbackstub_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/insightintentexecutecallbackstub_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/insightintentexecutecallbackstub_fuzzer/insightintentexecutecallbackstub_fuzzer.cpp b/test/fuzztest/insightintentexecutecallbackstub_fuzzer/insightintentexecutecallbackstub_fuzzer.cpp new file mode 100644 index 0000000000..7c16545b33 --- /dev/null +++ b/test/fuzztest/insightintentexecutecallbackstub_fuzzer/insightintentexecutecallbackstub_fuzzer.cpp @@ -0,0 +1,112 @@ +/* + * 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 "insightintentexecutecallbackstub_fuzzer.h" + +#include +#include + +#define private public +#include "insight_intent_execute_callback_stub.h" +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +const std::u16string APPMGR_INTERFACE_TOKEN = u"ohos.aafwk.AppManager"; + +class InsightIntentExecuteCallbackStubFuzzTest : public InsightIntentExecuteCallbackStub { +public: + InsightIntentExecuteCallbackStubFuzzTest() = default; + virtual ~InsightIntentExecuteCallbackStubFuzzTest() + {} + void OnExecuteDone(uint64_t key, int32_t resultCode, + const AppExecFwk::InsightIntentExecuteResult &executeResult) override {} +}; + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + uint32_t code = static_cast(GetU32Data(data)); + std::shared_ptr backStub = + std::make_shared(); + MessageParcel dataParcel; + MessageParcel reply; + MessageOption option; + dataParcel.WriteInterfaceToken(APPMGR_INTERFACE_TOKEN); + dataParcel.WriteBuffer(data, size); + dataParcel.RewindRead(0); + backStub->OnRemoteRequest(code, dataParcel, reply, option); + backStub->OnExecuteDoneInner(dataParcel, reply); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/insightintentexecutecallbackstub_fuzzer/insightintentexecutecallbackstub_fuzzer.h b/test/fuzztest/insightintentexecutecallbackstub_fuzzer/insightintentexecutecallbackstub_fuzzer.h new file mode 100644 index 0000000000..070b886091 --- /dev/null +++ b/test/fuzztest/insightintentexecutecallbackstub_fuzzer/insightintentexecutecallbackstub_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_INSIGHTINTENTEXECUTECALLBACKSTUB_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_INSIGHTINTENTEXECUTECALLBACKSTUB_FUZZER_H + +#define FUZZ_PROJECT_NAME "insightintentexecutecallbackstub_fuzzer" + +#endif diff --git a/test/fuzztest/insightintentexecutecallbackstub_fuzzer/project.xml b/test/fuzztest/insightintentexecutecallbackstub_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/insightintentexecutecallbackstub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/jsabilityautostartupmanager_fuzzer/BUILD.gn b/test/fuzztest/jsabilityautostartupmanager_fuzzer/BUILD.gn new file mode 100755 index 0000000000..4be56ede4b --- /dev/null +++ b/test/fuzztest/jsabilityautostartupmanager_fuzzer/BUILD.gn @@ -0,0 +1,107 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("JsAbilityAutoStartupManagerFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/jsabilityautostartupmanager_fuzzer" + + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/ability/native/ability_business_error", + "${ability_runtime_napi_path}/ability_auto_startup_manager", + "${ability_runtime_napi_path}/ability_auto_startup_callback", + "${ability_runtime_innerkits_path}/ability_manager/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_napi_path}/ability_auto_startup_manager/js_ability_auto_startup_manager.cpp", + "jsabilityautostartupmanager_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_napi_path}/ability_auto_startup_callback:autostartupcallback", + "${ability_runtime_napi_path}/ability_auto_startup_manager:autostartupmanager", + "${ability_runtime_native_path}/ability/native:ability_business_error", + + #"${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:auto_startup_callback", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:libappexecfwk_common", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":JsAbilityAutoStartupManagerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/jsabilityautostartupmanager_fuzzer/corpus/init b/test/fuzztest/jsabilityautostartupmanager_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/jsabilityautostartupmanager_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/jsabilityautostartupmanager_fuzzer/jsabilityautostartupmanager_fuzzer.cpp b/test/fuzztest/jsabilityautostartupmanager_fuzzer/jsabilityautostartupmanager_fuzzer.cpp new file mode 100755 index 0000000000..a5d70456cc --- /dev/null +++ b/test/fuzztest/jsabilityautostartupmanager_fuzzer/jsabilityautostartupmanager_fuzzer.cpp @@ -0,0 +1,122 @@ +/* + * 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 "jsabilityautostartupmanager_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "js_ability_auto_startup_manager.h" +#undef protected +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void JsAbilityAutostartupManagerFuzztest1(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr mgr = std::make_shared(); + napi_env env = nullptr; + mgr->Finalizer(env, nullptr, nullptr); // branch + napi_callback_info info = nullptr; + mgr->RegisterAutoStartupCallback(env, info); // branch + mgr->UnregisterAutoStartupCallback(env, info); // branch + mgr->SetApplicationAutoStartup(env, info); // branch + mgr->CancelApplicationAutoStartup(env, info); // branch + mgr->QueryAllAutoStartupApplications(env, info); // branch +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + JsAbilityAutostartupManagerFuzztest1(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/jsabilityautostartupmanager_fuzzer/jsabilityautostartupmanager_fuzzer.h b/test/fuzztest/jsabilityautostartupmanager_fuzzer/jsabilityautostartupmanager_fuzzer.h new file mode 100755 index 0000000000..82fc620ea3 --- /dev/null +++ b/test/fuzztest/jsabilityautostartupmanager_fuzzer/jsabilityautostartupmanager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_JSABILITYAUTOSTARTUPMANAGER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_JSABILITYAUTOSTARTUPMANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "jsabilityautostartupmanager_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_JSABILITYAUTOSTARTUPMANAGER_FUZZER_H diff --git a/test/fuzztest/jsabilityautostartupmanager_fuzzer/project.xml b/test/fuzztest/jsabilityautostartupmanager_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/jsabilityautostartupmanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/missioninfomgra_fuzzer/BUILD.gn b/test/fuzztest/missioninfomgra_fuzzer/BUILD.gn index f6bea7e122..c44da7004f 100644 --- a/test/fuzztest/missioninfomgra_fuzzer/BUILD.gn +++ b/test/fuzztest/missioninfomgra_fuzzer/BUILD.gn @@ -48,6 +48,7 @@ ohos_fuzztest("MissionInfoMgrAFuzzTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "//third_party/jsoncpp:jsoncpp", ] diff --git a/test/fuzztest/missioninfomgrb_fuzzer/BUILD.gn b/test/fuzztest/missioninfomgrb_fuzzer/BUILD.gn index 627ba42c2e..5075c3d6a9 100644 --- a/test/fuzztest/missioninfomgrb_fuzzer/BUILD.gn +++ b/test/fuzztest/missioninfomgrb_fuzzer/BUILD.gn @@ -48,6 +48,7 @@ ohos_fuzztest("MissionInfoMgrBFuzzTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "//third_party/jsoncpp:jsoncpp", ] diff --git a/test/fuzztest/missioninfomgrc_fuzzer/BUILD.gn b/test/fuzztest/missioninfomgrc_fuzzer/BUILD.gn index 376550c552..dc4c2c43bd 100644 --- a/test/fuzztest/missioninfomgrc_fuzzer/BUILD.gn +++ b/test/fuzztest/missioninfomgrc_fuzzer/BUILD.gn @@ -48,6 +48,7 @@ ohos_fuzztest("MissionInfoMgrCFuzzTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "//third_party/jsoncpp:jsoncpp", ] diff --git a/test/fuzztest/missionlistmanagerfourth_fuzzer/BUILD.gn b/test/fuzztest/missionlistmanagerfourth_fuzzer/BUILD.gn index c66e053b01..cdcc24426b 100644 --- a/test/fuzztest/missionlistmanagerfourth_fuzzer/BUILD.gn +++ b/test/fuzztest/missionlistmanagerfourth_fuzzer/BUILD.gn @@ -48,6 +48,7 @@ ohos_fuzztest("MissionListManagerFourthFuzzTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "//third_party/jsoncpp:jsoncpp", ] diff --git a/test/fuzztest/missionlistmanagersecond_fuzzer/BUILD.gn b/test/fuzztest/missionlistmanagersecond_fuzzer/BUILD.gn index ef2b9788b4..b3e2c524a0 100644 --- a/test/fuzztest/missionlistmanagersecond_fuzzer/BUILD.gn +++ b/test/fuzztest/missionlistmanagersecond_fuzzer/BUILD.gn @@ -49,6 +49,7 @@ ohos_fuzztest("MissionListManagerSecondFuzzTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "//third_party/jsoncpp:jsoncpp", ] diff --git a/test/fuzztest/missionlistmanagerthird_fuzzer/BUILD.gn b/test/fuzztest/missionlistmanagerthird_fuzzer/BUILD.gn index 11d90f1196..5f6341059b 100644 --- a/test/fuzztest/missionlistmanagerthird_fuzzer/BUILD.gn +++ b/test/fuzztest/missionlistmanagerthird_fuzzer/BUILD.gn @@ -48,6 +48,7 @@ ohos_fuzztest("MissionListManagerThirdFuzzTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "//third_party/jsoncpp:jsoncpp", ] diff --git a/test/fuzztest/napicommonwant_fuzzer/BUILD.gn b/test/fuzztest/napicommonwant_fuzzer/BUILD.gn new file mode 100755 index 0000000000..b55ff32493 --- /dev/null +++ b/test/fuzztest/napicommonwant_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("NapiCommonWantFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/napicommonwant_fuzzer" + + include_dirs = [ + "${ability_runtime_napi_path}/inner/napi_common", + "${ability_runtime_innerkits_path}/ability_manager/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "napicommonwant_fuzzer.cpp" ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + deps = [ + "${ability_base_path}:base", + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_napi_path}/ability_auto_startup_callback:autostartupcallback", + "${ability_runtime_napi_path}/ability_auto_startup_manager:autostartupmanager", + "${ability_runtime_napi_path}/inner/napi_common:napi_common", + "${ability_runtime_native_path}/ability/native:ability_business_error", + + #"${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:auto_startup_callback", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_path}/js_environment/frameworks/js_environment:js_environment", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:libappexecfwk_common", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":NapiCommonWantFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/napicommonwant_fuzzer/corpus/init b/test/fuzztest/napicommonwant_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/napicommonwant_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/napicommonwant_fuzzer/napicommonwant_fuzzer.cpp b/test/fuzztest/napicommonwant_fuzzer/napicommonwant_fuzzer.cpp new file mode 100755 index 0000000000..df478dd4be --- /dev/null +++ b/test/fuzztest/napicommonwant_fuzzer/napicommonwant_fuzzer.cpp @@ -0,0 +1,391 @@ +/* + * 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 "napicommonwant_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "napi_common_want.h" +#undef protected +#undef private + +#include "ability_record.h" +#include "array_wrapper.h" +#include "bool_wrapper.h" +#include "byte_wrapper.h" +#include "double_wrapper.h" +#include "float_wrapper.h" +#include "int_wrapper.h" +#include "long_wrapper.h" +#include "short_wrapper.h" +#include "string_wrapper.h" +#include "zchar_wrapper.h" +#include "remote_object_wrapper.h" +#include "native_runtime_impl.h" +#include "js_environment.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void NapiCommonWantFuzztest1(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + napi_env env = nullptr; + ElementName elementName; + elementName.SetDeviceID(stringParam); + elementName.SetBundleName(stringParam); + elementName.SetAbilityName(stringParam); + elementName.SetModuleName(stringParam); + WrapElementName(env, elementName); // branch failed + napi_value param = nullptr; + UnwrapElementName(env, param, elementName); // branch failed + AAFwk::WantParams wantParams1; + WrapWantParams(env, wantParams1); // branch failed + wantParams1.SetParam("intf1", String::Box(stringParam)); + wantParams1.SetParam("intf2", Long::Box(int32Param)); + wantParams1.SetParam("intf3", Boolean::Box(boolParam)); + wantParams1.SetParam("intf4", Integer::Box(int32Param)); + wantParams1.SetParam("intf5", Float::Box(int32Param)); + wantParams1.SetParam("intf5", RemoteObjectWrap::Box(nullptr)); + wantParams1.SetParam("intf6", Char::Box(int32Param)); + wantParams1.SetParam("intf7", Double::Box(int32Param)); + wantParams1.SetParam("intf8", Byte::Box(int32Param)); + std::size_t size = 3; // 3 means arraysize. + sptr ao = new (std::nothrow) Array(size, g_IID_IBoolean); + if (ao != nullptr) { + for (std::size_t i = 0; i < size; i++) { + ao->Set(i, Boolean::Box(boolParam)); + } + wantParams1.SetParam("intf8", ao); + } + WrapWantParams(env, wantParams1); // branch failed + UnwrapWantParams(env, param, wantParams1); // branch failed + BlackListFilter(Want::PARAM_RESV_WINDOW_MODE); // branch + BlackListFilter(Want::PARAM_RESV_DISPLAY_ID); // branch + BlackListFilter(stringParam); // branch + Want want; + WrapWant(env, want); // branch + UnwrapWant(env, param, want); // branch + int resultCode = 0; + WrapAbilityResult(env, resultCode, want); // branch + UnWrapAbilityResult(env, param, resultCode, want); // branch + napi_value jsProValue = nullptr; + HandleNapiObject(env, param, jsProValue, stringParam, wantParams1); // branch + IsSpecialObject(env, param, stringParam, stringParam, static_cast(int32Param)); // branch + HandleFdObject(env, param, stringParam, wantParams1); // branch + HandleRemoteObject(env, param, stringParam, wantParams1); // branch + CreateJsWant(env, want); // branch + CreateJsWantParams(env, wantParams1); // branch +} + +void NapiCommonWantFuzztest2(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + napi_env env = nullptr; + AAFwk::WantParams wantParams1; + napi_value object = nullptr; + InnerWrapJsWantParamsWantParams(env, object, stringParam, wantParams1); // failed + std::size_t size = 3; // 3 means arraysize. + sptr ao = new (std::nothrow) Array(size, g_IID_IBoolean); + if (ao != nullptr) { + for (std::size_t i = 0; i < size; i++) { + ao->Set(i, Boolean::Box(boolParam)); + } + } + WrapJsWantParamsArray(env, object, stringParam, ao); // branch +} + +void NapiCommonWantFuzztest3(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + std::shared_ptr jsEnv = nullptr; + AbilityRuntime::JsRuntime::Options options; + auto err = NativeRuntimeImpl::GetNativeRuntimeImpl().CreateJsEnv(options, jsEnv); + napi_env env = reinterpret_cast(jsEnv->GetNativeEngine()); + ElementName elementName1; + elementName1.SetDeviceID(stringParam); + elementName1.SetBundleName(stringParam); + elementName1.SetAbilityName(stringParam); + elementName1.SetModuleName(stringParam); + napi_value jsObject = WrapElementName(env, elementName1); // branch + + napi_value param = nullptr; + ElementName elementName2; + UnwrapElementName(env, param, elementName2); // branch null param + ElementName elementName3; + UnwrapElementName(env, jsObject, elementName3); // branch not null param + + AAFwk::WantParams wantParams1; + WrapWantParams(env, wantParams1); + wantParams1.SetParam("intf1", String::Box(stringParam)); + wantParams1.SetParam("intf2", Long::Box(int32Param)); + wantParams1.SetParam("intf3", Boolean::Box(boolParam)); + wantParams1.SetParam("intf4", Integer::Box(int32Param)); + wantParams1.SetParam("intf5", Float::Box(int32Param)); + wantParams1.SetParam("intf5", RemoteObjectWrap::Box(nullptr)); + wantParams1.SetParam("intf6", Char::Box(int32Param)); + wantParams1.SetParam("intf7", Double::Box(int32Param)); + wantParams1.SetParam("intf8", Byte::Box(int32Param)); + std::size_t size = 3; // 3 means arraysize. + sptr ao = new (std::nothrow) Array(size, g_IID_IBoolean); + if (ao != nullptr) { + for (std::size_t i = 0; i < size; i++) { + ao->Set(i, Boolean::Box(boolParam)); + } + wantParams1.SetParam("intf8", ao); + } + WrapWantParams(env, wantParams1); // branch null param + UnwrapWantParams(env, param, wantParams1); // branch null param + UnwrapWantParams(env, jsObject, wantParams1); // branch not null param +} + +void NapiCommonWantFuzztest4(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + napi_value param = nullptr; + std::shared_ptr jsEnv = nullptr; + AbilityRuntime::JsRuntime::Options options; + auto err = NativeRuntimeImpl::GetNativeRuntimeImpl().CreateJsEnv(options, jsEnv); + napi_env env = reinterpret_cast(jsEnv->GetNativeEngine()); + Want want; + want.SetElementName(stringParam, stringParam, stringParam, stringParam); + WrapWant(env, want); // wrap + + UnwrapWant(env, param, want); // branch null param + ElementName elementName1; + elementName1.SetDeviceID(stringParam); + elementName1.SetBundleName(stringParam); + elementName1.SetAbilityName(stringParam); + elementName1.SetModuleName(stringParam); + napi_value jsObject = WrapElementName(env, elementName1); // branch + UnwrapWant(env, jsObject, want); // branch not null param + + int resultCode = 0; + napi_value jsonObject1 = WrapAbilityResult(env, resultCode, want); // env not null + UnWrapAbilityResult(env, param, resultCode, want); // null param + UnWrapAbilityResult(env, jsonObject1, resultCode, want); // null param + + napi_value jsProValue = nullptr; + AAFwk::WantParams wantParams1; + HandleNapiObject(env, param, jsProValue, stringParam, wantParams1); // param null + HandleNapiObject(env, jsObject, jsProValue, stringParam, wantParams1); // param not null jsProValue null. + + IsSpecialObject(env, param, stringParam, stringParam, static_cast(int32Param)); // param null + IsSpecialObject(env, jsObject, stringParam, stringParam, static_cast(int32Param)); // param not null + + HandleFdObject(env, param, stringParam, wantParams1); // branch null param + HandleRemoteObject(env, param, stringParam, wantParams1); // branch null param + CreateJsWant(env, want); // branch + CreateJsWantParams(env, wantParams1); // branch + napi_value object = nullptr; + InnerWrapJsWantParamsWantParams(env, object, stringParam, wantParams1); // branch null object + napi_value jsObject2 = nullptr; + napi_create_object(env, &jsObject2); + InnerWrapJsWantParamsWantParams(env, jsObject2, stringParam, wantParams1); // branch object, key not exist. + AAFwk::WantParams wantParams2; + wantParams2.SetParam("intf1", String::Box(stringParam)); + InnerWrapJsWantParamsWantParams(env, jsObject2, "intf1", wantParams2); // branch object, key exist. +} + +void NapiCommonWantFuzztest5(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + napi_value param = nullptr; + std::shared_ptr jsEnv = nullptr; + AbilityRuntime::JsRuntime::Options options; + auto err = NativeRuntimeImpl::GetNativeRuntimeImpl().CreateJsEnv(options, jsEnv); + napi_env env = reinterpret_cast(jsEnv->GetNativeEngine()); + napi_value nullObject = nullptr; + std::size_t size = 3; // 3 means arraysize. + sptr ao1 = new (std::nothrow) Array(size, g_IID_IBoolean); + if (ao1 != nullptr) { + for (std::size_t i = 0; i < size; i++) { + ao1->Set(i, Boolean::Box(boolParam)); + } + } + WrapJsWantParamsArray(env, nullObject, stringParam, ao1); // null object. + napi_value jsObject1 = nullptr; + napi_create_object(env, &jsObject1); + WrapJsWantParamsArray(env, jsObject1, stringParam, ao1); // not null object. + + sptr ao2 = new (std::nothrow) Array(size, g_IID_IChar); + if (ao2 != nullptr) { + for (std::size_t i = 0; i < size; i++) { + ao2->Set(i, Char::Box(int32Param)); + } + } + WrapJsWantParamsArray(env, nullObject, stringParam, ao2); // null object. + napi_value jsObject2 = nullptr; + napi_create_object(env, &jsObject2); + WrapJsWantParamsArray(env, jsObject2, stringParam, ao2); // not null object. + + sptr ao3 = new (std::nothrow) Array(size, g_IID_IByte); + if (ao3 != nullptr) { + for (std::size_t i = 0; i < size; i++) { + ao3->Set(i, Byte::Box(int32Param)); + } + } + WrapJsWantParamsArray(env, nullObject, stringParam, ao3); // null object. + napi_value jsObject3 = nullptr; + napi_create_object(env, &jsObject3); + WrapJsWantParamsArray(env, jsObject3, stringParam, ao3); // not null object. + + sptr ao4 = new (std::nothrow) Array(size, g_IID_IShort); + if (ao4 != nullptr) { + for (std::size_t i = 0; i < size; i++) { + ao4->Set(i, Short::Box(int32Param)); + } + } + WrapJsWantParamsArray(env, nullObject, stringParam, ao4); // null object. + napi_value jsObject4 = nullptr; + napi_create_object(env, &jsObject4); + WrapJsWantParamsArray(env, jsObject4, stringParam, ao4); // not null object. +} + +void NapiCommonWantFuzztest6(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + napi_value param = nullptr; + std::shared_ptr jsEnv = nullptr; + AbilityRuntime::JsRuntime::Options options; + auto err = NativeRuntimeImpl::GetNativeRuntimeImpl().CreateJsEnv(options, jsEnv); + napi_env env = reinterpret_cast(jsEnv->GetNativeEngine()); + napi_value nullObject = nullptr; + std::size_t size = 3; // 3 means arraysize. + sptr ao1 = new (std::nothrow) Array(size, g_IID_ILong); + if (ao1 != nullptr) { + for (std::size_t i = 0; i < size; i++) { + ao1->Set(i, Long::Box(int32Param)); + } + } + WrapJsWantParamsArray(env, nullObject, stringParam, ao1); // null object. + napi_value jsObject1 = nullptr; + napi_create_object(env, &jsObject1); + WrapJsWantParamsArray(env, jsObject1, stringParam, ao1); // not null object. + + sptr ao2 = new (std::nothrow) Array(size, g_IID_IFloat); + if (ao2 != nullptr) { + for (std::size_t i = 0; i < size; i++) { + ao2->Set(i, Float::Box(int32Param)); + } + } + WrapJsWantParamsArray(env, nullObject, stringParam, ao2); // null object. + napi_value jsObject2 = nullptr; + napi_create_object(env, &jsObject2); + WrapJsWantParamsArray(env, jsObject2, stringParam, ao2); // not null object. + + sptr ao3 = new (std::nothrow) Array(size, g_IID_IDouble); + if (ao3 != nullptr) { + for (std::size_t i = 0; i < size; i++) { + ao3->Set(i, Double::Box(int32Param)); + } + } + WrapJsWantParamsArray(env, nullObject, stringParam, ao3); // null object. + napi_value jsObject3 = nullptr; + napi_create_object(env, &jsObject3); + WrapJsWantParamsArray(env, jsObject3, stringParam, ao3); // not null object. + + sptr ao4 = new (std::nothrow) Array(size, g_IID_IString); + if (ao4 != nullptr) { + for (std::size_t i = 0; i < size; i++) { + ao4->Set(i, String::Box(stringParam)); + } + } + WrapJsWantParamsArray(env, nullObject, stringParam, ao4); // null object. + napi_value jsObject4 = nullptr; + napi_create_object(env, &jsObject4); + WrapJsWantParamsArray(env, jsObject4, stringParam, ao4); // not null object. +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + NapiCommonWantFuzztest1(boolParam, stringParam, int32Param); + NapiCommonWantFuzztest2(boolParam, stringParam, int32Param); + NapiCommonWantFuzztest3(boolParam, stringParam, int32Param); + NapiCommonWantFuzztest4(boolParam, stringParam, int32Param); + NapiCommonWantFuzztest5(boolParam, stringParam, int32Param); + NapiCommonWantFuzztest6(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/napicommonwant_fuzzer/napicommonwant_fuzzer.h b/test/fuzztest/napicommonwant_fuzzer/napicommonwant_fuzzer.h new file mode 100755 index 0000000000..cca3406c9b --- /dev/null +++ b/test/fuzztest/napicommonwant_fuzzer/napicommonwant_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_NAPICOMMONWANT_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_NAPICOMMONWANT_FUZZER_H + +#define FUZZ_PROJECT_NAME "napicommonwant_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_NAPICOMMONWANT_FUZZER_H diff --git a/test/fuzztest/napicommonwant_fuzzer/project.xml b/test/fuzztest/napicommonwant_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/napicommonwant_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/openlinkoptions_fuzzer/BUILD.gn b/test/fuzztest/openlinkoptions_fuzzer/BUILD.gn new file mode 100644 index 0000000000..c446f52b1d --- /dev/null +++ b/test/fuzztest/openlinkoptions_fuzzer/BUILD.gn @@ -0,0 +1,100 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("OpenLinkOptionsFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/openlinkoptions_fuzzer" + include_dirs = [ + "${ability_runtime_services_path}/common/include", + "${ability_runtime_utils_path}/global/freeze/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/app_scheduler.cpp", + "${ability_runtime_services_path}/abilitymgr/src/start_ability_utils.cpp", + "openlinkoptions_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + + 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_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:perm_verification", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":OpenLinkOptionsFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/openlinkoptions_fuzzer/corpus/init b/test/fuzztest/openlinkoptions_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/openlinkoptions_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/openlinkoptions_fuzzer/openlinkoptions_fuzzer.cpp b/test/fuzztest/openlinkoptions_fuzzer/openlinkoptions_fuzzer.cpp new file mode 100644 index 0000000000..e30b1560e5 --- /dev/null +++ b/test/fuzztest/openlinkoptions_fuzzer/openlinkoptions_fuzzer.cpp @@ -0,0 +1,97 @@ +/* + * 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 "openlinkoptions_fuzzer.h" +#include "ability_record.h" + +#include +#include + +#define private public +#include "open_link_options.h" +#undef private +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr openLinkOptions = std::make_shared(); + if (!openLinkOptions) { + return false; + }; + Parcel parcel; + WantParams wantParams; + bool boolParam = *data % ENABLE; + openLinkOptions->SetParameters(wantParams); + openLinkOptions->ReadParameters(parcel); + openLinkOptions->ReadFromParcel(parcel); + openLinkOptions->GetParameters(); + openLinkOptions->WriteParameters(wantParams, parcel); + openLinkOptions->SetAppLinkingOnly(boolParam); + openLinkOptions->GetAppLinkingOnly(); + openLinkOptions->Marshalling(parcel); + openLinkOptions->Unmarshalling(parcel); + std::shared_ptr openLinkOptions2 = std::make_shared(); + if (!openLinkOptions2) { + return false; + }; + openLinkOptions = openLinkOptions2; + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/openlinkoptions_fuzzer/openlinkoptions_fuzzer.h b/test/fuzztest/openlinkoptions_fuzzer/openlinkoptions_fuzzer.h new file mode 100644 index 0000000000..1513d6bdaa --- /dev/null +++ b/test/fuzztest/openlinkoptions_fuzzer/openlinkoptions_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_OPENLINKOPTIONS_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_OPENLINKOPTIONS_FUZZER_H + +#define FUZZ_PROJECT_NAME "openlinkoptions_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/openlinkoptions_fuzzer/project.xml b/test/fuzztest/openlinkoptions_fuzzer/project.xml new file mode 100644 index 0000000000..6d3e765c7d --- /dev/null +++ b/test/fuzztest/openlinkoptions_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/pendingwantmanager_fuzzer/BUILD.gn b/test/fuzztest/pendingwantmanager_fuzzer/BUILD.gn index 6f7fdd1989..7dd0b053e6 100644 --- a/test/fuzztest/pendingwantmanager_fuzzer/BUILD.gn +++ b/test/fuzztest/pendingwantmanager_fuzzer/BUILD.gn @@ -49,6 +49,7 @@ ohos_fuzztest("PendingWantManagerFuzzTest") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "//third_party/jsoncpp:jsoncpp", ] diff --git a/test/fuzztest/registerapplicationstateobserver_fuzzer/BUILD.gn b/test/fuzztest/registerapplicationstateobserver_fuzzer/BUILD.gn index 6e9d05046f..454af903b3 100644 --- a/test/fuzztest/registerapplicationstateobserver_fuzzer/BUILD.gn +++ b/test/fuzztest/registerapplicationstateobserver_fuzzer/BUILD.gn @@ -46,9 +46,10 @@ ohos_fuzztest("RegisterApplicationStateObserverFuzzTest") { "ability_base:base", "ability_runtime:ability_deps_wrapper", "ability_runtime:app_manager", - "appspawn:appspawn_socket_client", + "appspawn:appspawn_client", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", + "c_utils:utils", "ffrt:libffrt", "init:libbeget_proxy", "init:libbegetutil", diff --git a/test/fuzztest/renderstateobserverproxy_fuzzer/BUILD.gn b/test/fuzztest/renderstateobserverproxy_fuzzer/BUILD.gn new file mode 100644 index 0000000000..2d9bf7d9e6 --- /dev/null +++ b/test/fuzztest/renderstateobserverproxy_fuzzer/BUILD.gn @@ -0,0 +1,76 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/appmgr" + +##############################fuzztest########################################## +ohos_fuzztest("RenderStateObserverProxyFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/renderstateobserverproxy_fuzzer" + include_dirs = [ "${ability_runtime_services_path}/appmgr/include" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "renderstateobserverproxy_fuzzer.cpp" ] + + configs = [ "${ability_runtime_services_path}/appmgr:appmgr_config" ] + + deps = [ + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "appspawn:appspawn_client", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":RenderStateObserverProxyFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/renderstateobserverproxy_fuzzer/corpus/init b/test/fuzztest/renderstateobserverproxy_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/renderstateobserverproxy_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/renderstateobserverproxy_fuzzer/project.xml b/test/fuzztest/renderstateobserverproxy_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/renderstateobserverproxy_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/renderstateobserverproxy_fuzzer/renderstateobserverproxy_fuzzer.cpp b/test/fuzztest/renderstateobserverproxy_fuzzer/renderstateobserverproxy_fuzzer.cpp new file mode 100644 index 0000000000..6efd380546 --- /dev/null +++ b/test/fuzztest/renderstateobserverproxy_fuzzer/renderstateobserverproxy_fuzzer.cpp @@ -0,0 +1,108 @@ +/* + * 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 "renderstateobserverproxy_fuzzer.h" + +#include +#include + +#define private public +#include "render_state_observer_proxy.h" +#undef private + +#include "ability_record.h" +#include "parcel.h" +#include "securec.h" +#include "want.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +const std::u16string APPMGR_INTERFACE_TOKEN = u"ohos.aafwk.AppManager"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + sptr impl; + auto renderStateObserverProxy = std::make_shared(impl); + std::string bundle(data, size); + int32_t uid = static_cast(GetU32Data(data)); + RenderStateData renderStateData; + MessageParcel dataParcel; + dataParcel.WriteInterfaceToken(APPMGR_INTERFACE_TOKEN); + dataParcel.WriteBuffer(data, size); + dataParcel.RewindRead(0); + MessageParcel reply; + MessageOption option; + renderStateObserverProxy->OnRenderStateChanged(renderStateData); + renderStateObserverProxy->WriteInterfaceToken(dataParcel); + uint32_t code = static_cast(GetU32Data(data)); + renderStateObserverProxy->SendTransactCmd(code, dataParcel, reply, option); + + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} diff --git a/test/fuzztest/renderstateobserverproxy_fuzzer/renderstateobserverproxy_fuzzer.h b/test/fuzztest/renderstateobserverproxy_fuzzer/renderstateobserverproxy_fuzzer.h new file mode 100644 index 0000000000..393f712ef0 --- /dev/null +++ b/test/fuzztest/renderstateobserverproxy_fuzzer/renderstateobserverproxy_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_RENDERSTATEOBSERVERPROXY_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_RENDERSTATEOBSERVERPROXY_FUZZER_H + +#define FUZZ_PROJECT_NAME "renderstateobserverproxy_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_RENDERSTATEOBSERVERPROXY_FUZZER_H diff --git a/test/fuzztest/screenunlockinterceptor_fuzzer/BUILD.gn b/test/fuzztest/screenunlockinterceptor_fuzzer/BUILD.gn new file mode 100644 index 0000000000..5678861789 --- /dev/null +++ b/test/fuzztest/screenunlockinterceptor_fuzzer/BUILD.gn @@ -0,0 +1,99 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("ScreenUnlockInterceptorFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/screenunlockinterceptor_fuzzer" + cflags_cc = [] + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_services_path}/abilitymgr/include/interceptor", + "${ability_runtime_utils_path}/server/startup/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_path}/frameworks/native/appkit/ability_bundle_manager_helper/bundle_mgr_helper.cpp", + "${ability_runtime_services_path}/abilitymgr/src/app_scheduler.cpp", + "${ability_runtime_services_path}/abilitymgr/src/interceptor/screen_unlock_interceptor.cpp", + "${ability_runtime_services_path}/abilitymgr/src/start_ability_utils.cpp", + "screenunlockinterceptor_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:perm_verification", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "samgr:samgr_proxy", + "screenlock_mgr:screenlock_client", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":ScreenUnlockInterceptorFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/screenunlockinterceptor_fuzzer/corpus/init b/test/fuzztest/screenunlockinterceptor_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/screenunlockinterceptor_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/screenunlockinterceptor_fuzzer/project.xml b/test/fuzztest/screenunlockinterceptor_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/screenunlockinterceptor_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/screenunlockinterceptor_fuzzer/screenunlockinterceptor_fuzzer.cpp b/test/fuzztest/screenunlockinterceptor_fuzzer/screenunlockinterceptor_fuzzer.cpp new file mode 100644 index 0000000000..990bf80f62 --- /dev/null +++ b/test/fuzztest/screenunlockinterceptor_fuzzer/screenunlockinterceptor_fuzzer.cpp @@ -0,0 +1,113 @@ +/* + * 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 "screenunlockinterceptor_fuzzer.h" + +#include +#include + +#include "bundle_mgr_helper.h" +#include "screen_unlock_interceptor.h" + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr uint8_t ENABLE = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = + AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + std::shared_ptr screenUnlockInterceptor = + std::make_shared(); + std::string strParam(data, size); + int intParam = static_cast(GetU32Data(data)); + int32_t int32Param = static_cast(GetU32Data(data)); + Want want; + bool boolParam = *data % ENABLE; + sptr token = GetFuzzAbilityToken(); + AbilityInterceptorParam param(want, intParam, int32Param, boolParam, token); + screenUnlockInterceptor->DoProcess(param); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/screenunlockinterceptor_fuzzer/screenunlockinterceptor_fuzzer.h b/test/fuzztest/screenunlockinterceptor_fuzzer/screenunlockinterceptor_fuzzer.h new file mode 100644 index 0000000000..f60263c9c5 --- /dev/null +++ b/test/fuzztest/screenunlockinterceptor_fuzzer/screenunlockinterceptor_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_SCREENUMLOCKUNTERCEPTOR_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_SCREENUMLOCKUNTERCEPTOR_FUZZER_H + +#define FUZZ_PROJECT_NAME "screenunlockinterceptor_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/startability_fuzzer/BUILD.gn b/test/fuzztest/startability_fuzzer/BUILD.gn index de661e3377..6cdc816bd9 100755 --- a/test/fuzztest/startability_fuzzer/BUILD.gn +++ b/test/fuzztest/startability_fuzzer/BUILD.gn @@ -42,7 +42,6 @@ ohos_fuzztest("StartAbilityFuzzTest") { 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}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", diff --git a/test/fuzztest/startabilityutils_fuzzer/BUILD.gn b/test/fuzztest/startabilityutils_fuzzer/BUILD.gn new file mode 100755 index 0000000000..ebfc3cb0c5 --- /dev/null +++ b/test/fuzztest/startabilityutils_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("StartAbilityUtilsFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/startabilityutils_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/dataobs_manager/include", + "${multimodalinput_path}/interfaces/native/innerkits/event/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/start_ability_utils.cpp", + "startabilityutils_fuzzer.cpp", + ] + + configs = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + ] + + 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}/uri_permission:uri_permission_mgr", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:auto_startup_callback", + "${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", + "//third_party/jsoncpp:jsoncpp", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:libappexecfwk_common", + "c_utils:utils", + "common_event_service:cesfwk_core", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "os_account:os_account_innerkits", + "relational_store:native_dataability", + "relational_store:native_rdb", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":StartAbilityUtilsFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/startabilityutils_fuzzer/corpus/init b/test/fuzztest/startabilityutils_fuzzer/corpus/init new file mode 100755 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/startabilityutils_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/startabilityutils_fuzzer/project.xml b/test/fuzztest/startabilityutils_fuzzer/project.xml new file mode 100755 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/startabilityutils_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/startabilityutils_fuzzer/startabilityutils_fuzzer.cpp b/test/fuzztest/startabilityutils_fuzzer/startabilityutils_fuzzer.cpp new file mode 100755 index 0000000000..0be939fea5 --- /dev/null +++ b/test/fuzztest/startabilityutils_fuzzer/startabilityutils_fuzzer.cpp @@ -0,0 +1,127 @@ +/* + * 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 "startabilityutils_fuzzer.h" + +#include +#include + +#define private public +#define protected public +#include "start_ability_utils.h" +#undef protected +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityRuntime; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr uint8_t ENABLE = 2; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[ENABLE] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void StartAbilityUtilsFuzztest1(bool boolParam, std::string &stringParam, int32_t int32Param) +{ + Want want; + sptr callerToken = GetFuzzAbilityToken(); + StartAbilityUtils::GetAppIndex(want, callerToken, int32Param); + AppExecFwk::ApplicationInfo appInfo; + StartAbilityUtils::GetApplicationInfo(stringParam, int32Param, appInfo); + AppExecFwk::AbilityInfo abilityInfo; + StartAbilityUtils::GetCallerAbilityInfo(nullptr, abilityInfo); + StartAbilityUtils::GetCallerAbilityInfo(callerToken, abilityInfo); + StartAbilityUtils::CheckAppProvisionMode(want, int32Param); + std::shared_ptr startAbilityInfoWrap = + std::make_shared(want, int32Param, int32Param, callerToken, boolParam); + StartAbilityInfo::CreateStartAbilityInfo(want, int32Param, int32Param); + StartAbilityInfo::CreateCallerAbilityInfo(nullptr); + StartAbilityInfo::CreateCallerAbilityInfo(callerToken); +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + bool boolParam = *data % ENABLE; + std::string stringParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + StartAbilityUtilsFuzztest1(boolParam, stringParam, int32Param); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + return 0; + } + + /* Validate the length of size */ + if (size < OHOS::U32_AT_SIZE || size > OHOS::FOO_MAX_LEN) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} + diff --git a/test/fuzztest/startabilityutils_fuzzer/startabilityutils_fuzzer.h b/test/fuzztest/startabilityutils_fuzzer/startabilityutils_fuzzer.h new file mode 100755 index 0000000000..57edc0fab1 --- /dev/null +++ b/test/fuzztest/startabilityutils_fuzzer/startabilityutils_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPSERVICEA_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPSERVICEA_FUZZER_H + +#define FUZZ_PROJECT_NAME "abilityautostartupservicea_fuzzer" + +#endif // FUZZTEST_OHOS_ABILITY_RUNTIME_ABILITYAUTOSTARTUPSERVICEA_FUZZER_H diff --git a/test/fuzztest/startotherappinterceptor_fuzzer/BUILD.gn b/test/fuzztest/startotherappinterceptor_fuzzer/BUILD.gn new file mode 100644 index 0000000000..538bd2c25b --- /dev/null +++ b/test/fuzztest/startotherappinterceptor_fuzzer/BUILD.gn @@ -0,0 +1,96 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("StartOtherappinterceptorFuzzTest") { + module_out_path = module_output_path + + cflags_cc = [] + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/startotherappinterceptor_fuzzer" + cflags_cc = [] + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_services_path}/abilitymgr/include/interceptor", + "${ability_runtime_utils_path}/server/startup/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/app_scheduler.cpp", + "${ability_runtime_services_path}/abilitymgr/src/interceptor/start_other_app_interceptor.cpp", + "${ability_runtime_services_path}/abilitymgr/src/start_ability_utils.cpp", + "startotherappinterceptor_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_services_path}/common:perm_verification", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":StartOtherappinterceptorFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/startotherappinterceptor_fuzzer/corpus/init b/test/fuzztest/startotherappinterceptor_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/startotherappinterceptor_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/startotherappinterceptor_fuzzer/project.xml b/test/fuzztest/startotherappinterceptor_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/startotherappinterceptor_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/startotherappinterceptor_fuzzer/startotherappinterceptor_fuzzer.cpp b/test/fuzztest/startotherappinterceptor_fuzzer/startotherappinterceptor_fuzzer.cpp new file mode 100644 index 0000000000..5833e37204 --- /dev/null +++ b/test/fuzztest/startotherappinterceptor_fuzzer/startotherappinterceptor_fuzzer.cpp @@ -0,0 +1,119 @@ +/* + * 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 "startotherappinterceptor_fuzzer.h" + +#include +#include +#define private public +#include "start_other_app_interceptor.h" +#undef private +#include "ability_record.h" +#include "start_ability_utils.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + int intParam = static_cast(GetU32Data(data)); + int32_t int32Param = static_cast(GetU32Data(data)); + auto startOtherAppInterceptor = std::make_shared(); + Want want; + bool boolParam = *data % ENABLE; + AppExecFwk::ApplicationInfo appInfo; + sptr token = GetFuzzAbilityToken(); + AbilityInterceptorParam param = AbilityInterceptorParam(want, intParam, int32Param, boolParam, token); + startOtherAppInterceptor->DoProcess(param); + startOtherAppInterceptor->CheckNativeCall(); + startOtherAppInterceptor->CheckCallerIsSystemApp(); + startOtherAppInterceptor->CheckTargetIsSystemApp(appInfo); + startOtherAppInterceptor->GetApplicationInfo(token, appInfo); + startOtherAppInterceptor->CheckAncoShellCall(appInfo, want); + startOtherAppInterceptor->CheckStartOtherApp(want); + startOtherAppInterceptor->CheckCallerApiBelow12(appInfo); + startOtherAppInterceptor->IsDelegatorCall(want); + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/startotherappinterceptor_fuzzer/startotherappinterceptor_fuzzer.h b/test/fuzztest/startotherappinterceptor_fuzzer/startotherappinterceptor_fuzzer.h new file mode 100644 index 0000000000..4af5dd4af3 --- /dev/null +++ b/test/fuzztest/startotherappinterceptor_fuzzer/startotherappinterceptor_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_STARTOTHERAPPINTERCEPTOR_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_STARTOTHERAPPINTERCEPTOR_FUZZER_H + +#define FUZZ_PROJECT_NAME "startotherappinterceptor_fuzzer" + +#endif diff --git a/test/fuzztest/startserviceextensionability_fuzzer/BUILD.gn b/test/fuzztest/startserviceextensionability_fuzzer/BUILD.gn index 27b76a3373..969f4610b0 100755 --- a/test/fuzztest/startserviceextensionability_fuzzer/BUILD.gn +++ b/test/fuzztest/startserviceextensionability_fuzzer/BUILD.gn @@ -49,8 +49,9 @@ ohos_fuzztest("StartServiceExtensionAbilityFuzzTest") { external_deps = [ "ability_base:want", "ability_runtime:ability_manager", - "appspawn:appspawn_socket_client", + "appspawn:appspawn_client", "bundle_framework:appexecfwk_base", + "c_utils:utils", "common_event_service:cesfwk_innerkits", "ipc:ipc_core", "napi:ace_napi", diff --git a/test/fuzztest/statusbardelegatemanager_fuzzer/BUILD.gn b/test/fuzztest/statusbardelegatemanager_fuzzer/BUILD.gn new file mode 100644 index 0000000000..c6b72b3d09 --- /dev/null +++ b/test/fuzztest/statusbardelegatemanager_fuzzer/BUILD.gn @@ -0,0 +1,102 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("StatusBarDelegateManagerFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/statusbardelegatemanager_fuzzer" + include_dirs = [ + "${ability_runtime_services_path}/common/include", + "${ability_runtime_utils_path}/global/freeze/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/app_scheduler.cpp", + "${ability_runtime_services_path}/abilitymgr/src/process_options.cpp", + "${ability_runtime_services_path}/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/start_ability_utils.cpp", + "statusbardelegatemanager_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + + 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_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:perm_verification", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libjpeg-turbo:turbojpeg_static", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_deps_wrapper", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + deps += [] + external_deps += [ + "i18n:intl_util", + "window_manager:libwm", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":StatusBarDelegateManagerFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/statusbardelegatemanager_fuzzer/corpus/init b/test/fuzztest/statusbardelegatemanager_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/statusbardelegatemanager_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/statusbardelegatemanager_fuzzer/project.xml b/test/fuzztest/statusbardelegatemanager_fuzzer/project.xml new file mode 100644 index 0000000000..6d3e765c7d --- /dev/null +++ b/test/fuzztest/statusbardelegatemanager_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/statusbardelegatemanager_fuzzer/statusbardelegatemanager_fuzzer.cpp b/test/fuzztest/statusbardelegatemanager_fuzzer/statusbardelegatemanager_fuzzer.cpp new file mode 100644 index 0000000000..32b39ee60e --- /dev/null +++ b/test/fuzztest/statusbardelegatemanager_fuzzer/statusbardelegatemanager_fuzzer.cpp @@ -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. + */ + +#include "statusbardelegatemanager_fuzzer.h" +#include "ability_record.h" + +#include +#include + +#define private public +#include "scene_board/status_bar_delegate_manager.h" +#undef private +#include "securec.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +} + +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + std::shared_ptr statusBarDelegate = std::make_shared(); + if (!statusBarDelegate) { + return false; + }; + sptr delegate; + statusBarDelegate->RegisterStatusBarDelegate(delegate); + statusBarDelegate->GetStatusBarDelegate(); + statusBarDelegate->IsCallerInStatusBar(); + std::shared_ptr abilityRecord; + statusBarDelegate->DoProcessAttachment(abilityRecord); + return true; +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char* ch = (char*)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/statusbardelegatemanager_fuzzer/statusbardelegatemanager_fuzzer.h b/test/fuzztest/statusbardelegatemanager_fuzzer/statusbardelegatemanager_fuzzer.h new file mode 100644 index 0000000000..e0766a8afa --- /dev/null +++ b/test/fuzztest/statusbardelegatemanager_fuzzer/statusbardelegatemanager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_STATUSBARDELEGATEMANAGER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_STATUSBARDELEGATEMANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "statusbardelegatemanager_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/stopserviceextensionability_fuzzer/BUILD.gn b/test/fuzztest/stopserviceextensionability_fuzzer/BUILD.gn index c45c342ba2..cf9067a155 100644 --- a/test/fuzztest/stopserviceextensionability_fuzzer/BUILD.gn +++ b/test/fuzztest/stopserviceextensionability_fuzzer/BUILD.gn @@ -50,8 +50,9 @@ ohos_fuzztest("StopServiceExtensionAbilityFuzzTest") { external_deps = [ "ability_base:want", "ability_runtime:ability_manager", - "appspawn:appspawn_socket_client", + "appspawn:appspawn_client", "bundle_framework:appexecfwk_base", + "c_utils:utils", "common_event_service:cesfwk_innerkits", "ipc:ipc_core", "napi:ace_napi", diff --git a/test/fuzztest/terminateability_fuzzer/BUILD.gn b/test/fuzztest/terminateability_fuzzer/BUILD.gn index 0866f09f0f..ef545206a4 100644 --- a/test/fuzztest/terminateability_fuzzer/BUILD.gn +++ b/test/fuzztest/terminateability_fuzzer/BUILD.gn @@ -52,9 +52,10 @@ ohos_fuzztest("TerminateAbilityFuzzTest") { external_deps = [ "ability_base:want", "ability_runtime:ability_manager", - "appspawn:appspawn_socket_client", + "appspawn:appspawn_client", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", + "c_utils:utils", "ffrt:libffrt", "ipc:ipc_core", "napi:ace_napi", diff --git a/test/fuzztest/testobserverstub_fuzzer/BUILD.gn b/test/fuzztest/testobserverstub_fuzzer/BUILD.gn new file mode 100644 index 0000000000..bafbcc89e2 --- /dev/null +++ b/test/fuzztest/testobserverstub_fuzzer/BUILD.gn @@ -0,0 +1,58 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_tools/tools" + +##############################fuzztest########################################## +ohos_fuzztest("TestObserverStubFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/testobserverstub_fuzzer" + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [] + sources = [ "testobserverstub_fuzzer.cpp" ] + deps = [ + "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", + ] + external_deps = [ + "ability_base:configuration", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":TestObserverStubFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/testobserverstub_fuzzer/corpus/init b/test/fuzztest/testobserverstub_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/testobserverstub_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/testobserverstub_fuzzer/project.xml b/test/fuzztest/testobserverstub_fuzzer/project.xml new file mode 100644 index 0000000000..6d3e765c7d --- /dev/null +++ b/test/fuzztest/testobserverstub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/testobserverstub_fuzzer/testobserverstub_fuzzer.cpp b/test/fuzztest/testobserverstub_fuzzer/testobserverstub_fuzzer.cpp new file mode 100644 index 0000000000..cf2b18025a --- /dev/null +++ b/test/fuzztest/testobserverstub_fuzzer/testobserverstub_fuzzer.cpp @@ -0,0 +1,101 @@ +/* + * 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 "testobserverstub_fuzzer.h" + +#include +#include + +#define private public +#include "test_observer_stub.h" +#include "test_observer.h" +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +const std::u16string APPMGR_INTERFACE_TOKEN = u"ohos.aafwk.AppManager"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + auto testObserverStub = std::make_shared(); + MessageParcel ParcelData; + ParcelData.WriteInterfaceToken(APPMGR_INTERFACE_TOKEN); + ParcelData.WriteBuffer(data, size); + ParcelData.RewindRead(0); + MessageParcel reply; + MessageOption option; + uint32_t code = static_cast(GetU32Data(data)); + testObserverStub->OnRemoteRequest(code, ParcelData, reply, option); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/testobserverstub_fuzzer/testobserverstub_fuzzer.h b/test/fuzztest/testobserverstub_fuzzer/testobserverstub_fuzzer.h new file mode 100644 index 0000000000..09567e804d --- /dev/null +++ b/test/fuzztest/testobserverstub_fuzzer/testobserverstub_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_UI_TESTOBSERVERSTUB_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_UI_TESTOBSERVERSTUB_FUZZER_H + +#define FUZZ_PROJECT_NAME "testobserverstub_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/toolstestobserver_fuzzer/BUILD.gn b/test/fuzztest/toolstestobserver_fuzzer/BUILD.gn new file mode 100644 index 0000000000..2c66524181 --- /dev/null +++ b/test/fuzztest/toolstestobserver_fuzzer/BUILD.gn @@ -0,0 +1,54 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("ToolsTestObserverFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/toolstestobserver_fuzzer" + include_dirs = [] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + configs = [] + sources = [ "toolstestobserver_fuzzer.cpp" ] + deps = [ + "${ability_runtime_path}/tools/aa:tools_aa_source_set", + "${ability_runtime_services_path}/abilitymgr:abilityms", + ] + external_deps = [ + "ability_base:configuration", + "bundle_framework:appexecfwk_base", + "hilog:libhilog", + "ipc:ipc_core", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":ToolsTestObserverFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/toolstestobserver_fuzzer/corpus/init b/test/fuzztest/toolstestobserver_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/toolstestobserver_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/toolstestobserver_fuzzer/project.xml b/test/fuzztest/toolstestobserver_fuzzer/project.xml new file mode 100644 index 0000000000..7133b2b924 --- /dev/null +++ b/test/fuzztest/toolstestobserver_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/toolstestobserver_fuzzer/toolstestobserver_fuzzer.cpp b/test/fuzztest/toolstestobserver_fuzzer/toolstestobserver_fuzzer.cpp new file mode 100644 index 0000000000..156f4dc7bb --- /dev/null +++ b/test/fuzztest/toolstestobserver_fuzzer/toolstestobserver_fuzzer.cpp @@ -0,0 +1,98 @@ +/* + * 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 "toolstestobserver_fuzzer.h" + +#include +#include +#include "securec.h" +#include +#define private public +#include "test_observer.h" +#undef private + +using namespace OHOS::AAFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + std::shared_ptr testObserver = std::make_shared(); + std::string stringParam(data, size); + std::string cmd(data, size); + int64_t resultCode = static_cast(GetU32Data(data)); + int64_t timeoutSec = static_cast(GetU32Data(data)); + int64_t timeoutMs = static_cast(GetU32Data(data)); + + testObserver-> TestStatus(stringParam, resultCode); + testObserver-> ExecuteShellCommand(cmd, timeoutSec); + testObserver->TestFinished(stringParam, resultCode); + testObserver-> WaitForFinish(timeoutMs); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/toolstestobserver_fuzzer/toolstestobserver_fuzzer.h b/test/fuzztest/toolstestobserver_fuzzer/toolstestobserver_fuzzer.h new file mode 100644 index 0000000000..b4c41771a0 --- /dev/null +++ b/test/fuzztest/toolstestobserver_fuzzer/toolstestobserver_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_TOOLSTESTOBSERVER_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_TOOLSTESTOBSERVER_FUZZER_H + +#define FUZZ_PROJECT_NAME "toolstestobserver_fuzzer" + +#endif diff --git a/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/BUILD.gn b/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/BUILD.gn new file mode 100644 index 0000000000..72c90f12ed --- /dev/null +++ b/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/BUILD.gn @@ -0,0 +1,112 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("UiAbilityLifeCycleManagerAFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/uiabilitylifecyclemanagera_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_services_path}/appdfr/include", + "${ability_runtime_services_path}/abilitymgr/include/", + "${ability_runtime_services_path}/abilitymgr/include/scene_board/", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + ] + + public_configs = + [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp", + "uiabilitylifecyclemanagera_fuzzer.cpp", + ] + + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/ability_manager:process_options", + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${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:event_report", + "${ability_runtime_services_path}/common:perm_verification", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbeget_proxy", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libmodal_system_ui_extension_client", + "window_manager:libwsutils", + "window_manager:scene_session", + "window_manager:session_manager_lite", + "window_manager:sms", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ + "window_manager:libwsutils", + "window_manager:scene_session", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":UiAbilityLifeCycleManagerAFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/corpus/init b/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/corpus/init new file mode 100644 index 0000000000..d27c29f2d9 --- /dev/null +++ b/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/project.xml b/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/project.xml new file mode 100644 index 0000000000..e7b69a52e6 --- /dev/null +++ b/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/uiabilitylifecyclemanagera_fuzzer.cpp b/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/uiabilitylifecyclemanagera_fuzzer.cpp new file mode 100644 index 0000000000..c2fc66cfc9 --- /dev/null +++ b/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/uiabilitylifecyclemanagera_fuzzer.cpp @@ -0,0 +1,185 @@ +/* + * 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 "uiabilitylifecyclemanagera_fuzzer.h" + +#include +#include + +#define private public +#include "ui_ability_lifecycle_manager.h" +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void DoSomethingInterestingWithMyAPI1(const char *data, size_t size) +{ + int32_t userId = static_cast(GetU32Data(data)); + auto uIAbilityLifecycleManager = std::make_shared(userId); + Want want1; + bool boolParam = *data % ENABLE; + std::string strParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + uint32_t requestId = static_cast(GetU32Data(data)); + uIAbilityLifecycleManager->OnAcceptWantResponse(want1, strParam, requestId); + uIAbilityLifecycleManager->OnStartSpecifiedProcessResponse(want1, strParam, requestId); + uIAbilityLifecycleManager->OnStartSpecifiedAbilityTimeoutResponse(want1, requestId); + uIAbilityLifecycleManager->OnStartSpecifiedProcessTimeoutResponse(want1, requestId); + uIAbilityLifecycleManager->StartSpecifiedAbilityBySCB(want1); + sptr callStub; + std::shared_ptr abilityRecord4; + uIAbilityLifecycleManager->CallRequestDone(abilityRecord4, callStub); + sptr connect; + AppExecFwk::ElementName element; + sptr token = GetFuzzAbilityToken(); + uIAbilityLifecycleManager->ReleaseCallLocked(connect, element); + std::shared_ptr callRecord; + uIAbilityLifecycleManager->OnCallConnectDied(callRecord); + uIAbilityLifecycleManager->GetSessionIdByAbilityToken(token); + std::vector abilityList; + uIAbilityLifecycleManager->GetActiveAbilityList(int32Param, abilityList, int32Param); + std::shared_ptr abilityRecord5; + uIAbilityLifecycleManager->PrepareTerminateAbility(abilityRecord5); + uIAbilityLifecycleManager->GetAbilityRecordsById(int32Param); + uIAbilityLifecycleManager->CheckAbilityNumber(strParam, strParam, strParam); + uIAbilityLifecycleManager->MoreAbilityNumbersSendEventInfo(int32Param, strParam, strParam, strParam); + AppInfo info; + info.state = AppState::TERMINATED; + uIAbilityLifecycleManager->OnAppStateChanged(info); + info.state = AppState::END; + uIAbilityLifecycleManager->OnAppStateChanged(info); +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + int32_t userId = static_cast(GetU32Data(data)); + auto uIAbilityLifecycleManager = std::make_shared(userId); + std::string strParam(data, size); + uIAbilityLifecycleManager->SignRestartAppFlag(strParam); + AbilityRequest abilityRequest; + sptr sessionInfo; + bool boolParam = *data % ENABLE; + uIAbilityLifecycleManager->StartUIAbility(abilityRequest, sessionInfo, boolParam); + sptr token = GetFuzzAbilityToken(); + int intParam = static_cast(GetU32Data(data)); + AppExecFwk::PacMap saveData; + uIAbilityLifecycleManager->AbilityTransactionDone(token, intParam, saveData); + sptr scheduler; + uIAbilityLifecycleManager->AttachAbilityThread(scheduler, token); + int32_t int32Param = static_cast(GetU32Data(data)); + uIAbilityLifecycleManager->OnAbilityRequestDone(token, int32Param); + uIAbilityLifecycleManager->IsContainsAbility(token); + std::shared_ptr abilityRecord; + uIAbilityLifecycleManager->NotifySCBToMinimizeUIAbility(abilityRecord, token); + std::shared_ptr abilityRecord1; + uIAbilityLifecycleManager->MinimizeUIAbility(abilityRecord1, boolParam); + sptr sessionInfo1; + uIAbilityLifecycleManager->GetUIAbilityRecordBySessionInfo(sessionInfo1); + Want *want; + std::shared_ptr abilityRecord2; + uIAbilityLifecycleManager->CloseUIAbility(abilityRecord2, intParam, want, boolParam); + sptr rootSceneSession; + uIAbilityLifecycleManager->SetRootSceneSession(rootSceneSession); + AbilityRequest abilityRequest1; + uIAbilityLifecycleManager->NotifySCBToStartUIAbility(abilityRequest1); + sptr sessionInfo2; + AbilityRequest abilityRequest2; + uIAbilityLifecycleManager->NotifySCBToPreStartUIAbility(abilityRequest2, sessionInfo2); + uint32_t msgId = static_cast(GetU32Data(data)); + int64_t abilityRecordId = static_cast(GetU32Data(data)); + uIAbilityLifecycleManager->OnTimeOut(msgId, abilityRecordId, boolParam); + std::shared_ptr abilityRecord3; + AbilityRequest abilityRequest3; + uIAbilityLifecycleManager->OnAbilityDied(abilityRecord3); + uIAbilityLifecycleManager->ResolveLocked(abilityRequest3); + sptr sessionInfo3; + uIAbilityLifecycleManager->CallUIAbilityBySCB(sessionInfo3, boolParam); + DoSomethingInterestingWithMyAPI1(data, size); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/uiabilitylifecyclemanagera_fuzzer.h b/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/uiabilitylifecyclemanagera_fuzzer.h new file mode 100644 index 0000000000..a96d64c964 --- /dev/null +++ b/test/fuzztest/uiabilitylifecyclemanagera_fuzzer/uiabilitylifecyclemanagera_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_UI_ABILITY_LIFE_CYCLE_MANAGERA_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_UI_ABILITY_LIFE_CYCLE_MANAGERA_FUZZER_H + +#define FUZZ_PROJECT_NAME "uiabilitylifecyclemanagera_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/BUILD.gn b/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/BUILD.gn new file mode 100644 index 0000000000..3f58b20c3d --- /dev/null +++ b/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/BUILD.gn @@ -0,0 +1,112 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("UiAbilityLifeCycleManagerBFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/uiabilitylifecyclemanagerb_fuzzer" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_services_path}/appdfr/include", + "${ability_runtime_services_path}/abilitymgr/include/", + "${ability_runtime_services_path}/abilitymgr/include/scene_board/", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", + ] + + public_configs = + [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp", + "uiabilitylifecyclemanagerb_fuzzer.cpp", + ] + + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/ability_manager:process_options", + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${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:event_report", + "${ability_runtime_services_path}/common:perm_verification", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbeget_proxy", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libmodal_system_ui_extension_client", + "window_manager:libwsutils", + "window_manager:scene_session", + "window_manager:session_manager_lite", + "window_manager:sms", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ + "window_manager:libwsutils", + "window_manager:scene_session", + ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":UiAbilityLifeCycleManagerBFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/corpus/init b/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/corpus/init new file mode 100644 index 0000000000..d27c29f2d9 --- /dev/null +++ b/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/project.xml b/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/project.xml new file mode 100644 index 0000000000..e7b69a52e6 --- /dev/null +++ b/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/uiabilitylifecyclemanagerb_fuzzer.cpp b/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/uiabilitylifecyclemanagerb_fuzzer.cpp new file mode 100644 index 0000000000..3d039467c8 --- /dev/null +++ b/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/uiabilitylifecyclemanagerb_fuzzer.cpp @@ -0,0 +1,178 @@ +/* + * 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 "uiabilitylifecyclemanagerb_fuzzer.h" + +#include +#include + +#define private public +#include "ui_ability_lifecycle_manager.h" +#undef private + +#include "ability_record.h" +#include "ability_state.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +sptr GetFuzzAbilityToken() +{ + sptr token = nullptr; + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + return token; +} + +void DoSomethingInterestingWithMyAPI1(const char *data, size_t size) +{ + int32_t userId = static_cast(GetU32Data(data)); + auto uIAbilityLifecycleManager = std::make_shared(userId); + int32_t int32Param = static_cast(GetU32Data(data)); + bool boolParam = *data % ENABLE; + uIAbilityLifecycleManager->CompleteFirstFrameDrawing(int32Param); + uIAbilityLifecycleManager->GetAbilityStateByPersistentId(int32Param, boolParam); + AbilityRequest abilityRequest1; + uIAbilityLifecycleManager->GetPersistentIdByAbilityRequest(abilityRequest1, boolParam); + abilityRequest1.collaboratorType = CollaboratorType::RESERVE_TYPE; + if (abilityRequest1.collaboratorType == CollaboratorType::RESERVE_TYPE) { + uIAbilityLifecycleManager->GetPersistentIdByAbilityRequest(abilityRequest1, boolParam); + } + + abilityRequest1.abilityInfo.launchMode = AppExecFwk::LaunchMode::SPECIFIED; + if (abilityRequest1.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) { + uIAbilityLifecycleManager->GetPersistentIdByAbilityRequest(abilityRequest1, boolParam); + } + + abilityRequest1.abilityInfo.launchMode = AppExecFwk::LaunchMode::STANDARD; + if (abilityRequest1.abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) { + uIAbilityLifecycleManager->GetPersistentIdByAbilityRequest(abilityRequest1, boolParam); + } + + uIAbilityLifecycleManager->GetReusedSpecifiedPersistentId(abilityRequest1, boolParam); + abilityRequest1.abilityInfo.launchMode = AppExecFwk::LaunchMode::SPECIFIED; + if (abilityRequest1.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) { + uIAbilityLifecycleManager->GetReusedSpecifiedPersistentId(abilityRequest1, boolParam); + } +} +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + int32_t userId = static_cast(GetU32Data(data)); + auto uIAbilityLifecycleManager = std::make_shared(userId); + std::string strParam(data, size); + int32_t int32Param = static_cast(GetU32Data(data)); + uIAbilityLifecycleManager->UninstallApp(strParam, int32Param); + std::vector info; + bool boolParam = *data % ENABLE; + uIAbilityLifecycleManager->GetAbilityRunningInfos(info, boolParam); + int intParam = static_cast(GetU32Data(data)); + + #ifdef ABILITY_COMMAND_FOR_TEST + uIAbilityLifecycleManager->BlockAbility(intParam); + #endif + + std::vector info1; + uIAbilityLifecycleManager->Dump(info1); + uIAbilityLifecycleManager->DumpMissionList(info1, boolParam, strParam); + std::vector params; + uIAbilityLifecycleManager->DumpMissionListByRecordId(info1, boolParam, int32Param, params); + std::shared_ptr startOptions; + uIAbilityLifecycleManager->MoveMissionToFront(int32Param, startOptions); + AbilityRequest abilityRequest; + std::shared_ptr targetRecord; + uIAbilityLifecycleManager->IsAbilityStarted(abilityRequest, targetRecord); + std::list sessionInfos; + std::vector sessionIds; + uIAbilityLifecycleManager->UpdateSessionInfoBySCB(sessionInfos, sessionIds); + uIAbilityLifecycleManager->IsCallerInStatusBar(); + std::vector pids; + uIAbilityLifecycleManager->KillProcessWithPrepareTerminate(pids); + sptr token = GetFuzzAbilityToken(); + uIAbilityLifecycleManager->ChangeAbilityVisibility(token, boolParam); + sptr sessionInfo; + uIAbilityLifecycleManager->ChangeUIAbilityVisibilityBySCB(sessionInfo, boolParam); + AppExecFwk::ElementName element; + uIAbilityLifecycleManager->GetAbilityRecordsByName(element); + uIAbilityLifecycleManager->GetAbilityRecordByToken(token); + + #ifdef SUPPORT_GRAPHICS + uIAbilityLifecycleManager->CompleteFirstFrameDrawing(token); + #endif + DoSomethingInterestingWithMyAPI1(data, size); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/uiabilitylifecyclemanagerb_fuzzer.h b/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/uiabilitylifecyclemanagerb_fuzzer.h new file mode 100644 index 0000000000..e363148b3c --- /dev/null +++ b/test/fuzztest/uiabilitylifecyclemanagerb_fuzzer/uiabilitylifecyclemanagerb_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_UI_ABILITY_LIFE_CYCLE_MANAGERB_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_UI_ABILITY_LIFE_CYCLE_MANAGERB_FUZZER_H + +#define FUZZ_PROJECT_NAME "uiabilitylifecyclemanagerb_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/uiextensionrecordfactory_fuzzer/BUILD.gn b/test/fuzztest/uiextensionrecordfactory_fuzzer/BUILD.gn new file mode 100644 index 0000000000..89810bba5f --- /dev/null +++ b/test/fuzztest/uiextensionrecordfactory_fuzzer/BUILD.gn @@ -0,0 +1,89 @@ +# 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("UIExtensionRecordFactoryFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/uiextensionrecordfactory_fuzzer" + include_dirs = [ + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_services_path}/abilitymgr/include", + ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/extension_record_factory.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ui_extension_record_factory.cpp", + "${ability_runtime_services_path}/common/src/app_utils.cpp", + "${ability_runtime_services_path}/common/src/json_utils.cpp", + "uiextensionrecordfactory_fuzzer.cpp", + ] + + configs = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libwsutils", + ] + + if (ability_runtime_graphics) { + external_deps += [ "input:libmmi-client" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":UIExtensionRecordFactoryFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/uiextensionrecordfactory_fuzzer/corpus/init b/test/fuzztest/uiextensionrecordfactory_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/uiextensionrecordfactory_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/uiextensionrecordfactory_fuzzer/project.xml b/test/fuzztest/uiextensionrecordfactory_fuzzer/project.xml new file mode 100644 index 0000000000..6d3e765c7d --- /dev/null +++ b/test/fuzztest/uiextensionrecordfactory_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/uiextensionrecordfactory_fuzzer/uiextensionrecordfactory_fuzzer.cpp b/test/fuzztest/uiextensionrecordfactory_fuzzer/uiextensionrecordfactory_fuzzer.cpp new file mode 100644 index 0000000000..4f163d1627 --- /dev/null +++ b/test/fuzztest/uiextensionrecordfactory_fuzzer/uiextensionrecordfactory_fuzzer.cpp @@ -0,0 +1,97 @@ +/* + * 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 "uiextensionrecordfactory_fuzzer.h" + +#include +#include + +#define protected public +#include "ui_extension_record_factory.h" +#undef protected + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + auto factory = DelayedSingleton::GetInstance(); + AAFwk::AbilityRequest abilityRequest; + int32_t int32Param = static_cast(GetU32Data(data)); + std::string strParam(data, size); + factory->PreCheck(abilityRequest, strParam); + std::shared_ptr extensionRecord; + factory->CreateRecord(abilityRequest, extensionRecord); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/uiextensionrecordfactory_fuzzer/uiextensionrecordfactory_fuzzer.h b/test/fuzztest/uiextensionrecordfactory_fuzzer/uiextensionrecordfactory_fuzzer.h new file mode 100644 index 0000000000..f84c73971e --- /dev/null +++ b/test/fuzztest/uiextensionrecordfactory_fuzzer/uiextensionrecordfactory_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_UI_EXTENSION_RECORD_FACTORY_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_UI_EXTENSION_RECORD_FACTORY_FUZZER_H + +#define FUZZ_PROJECT_NAME "uiextensionrecordfactory_fuzzer" + +#endif \ No newline at end of file diff --git a/test/fuzztest/unregisterapplicationstateobserver_fuzzer/BUILD.gn b/test/fuzztest/unregisterapplicationstateobserver_fuzzer/BUILD.gn index fdf68043eb..de3577bb10 100644 --- a/test/fuzztest/unregisterapplicationstateobserver_fuzzer/BUILD.gn +++ b/test/fuzztest/unregisterapplicationstateobserver_fuzzer/BUILD.gn @@ -47,9 +47,10 @@ ohos_fuzztest("UnregisterApplicationStateObserverFuzzTest") { "ability_base:base", "ability_runtime:ability_deps_wrapper", "ability_runtime:app_manager", - "appspawn:appspawn_socket_client", + "appspawn:appspawn_client", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", + "c_utils:utils", "ffrt:libffrt", "init:libbeget_proxy", "init:libbegetutil", diff --git a/test/fuzztest/updateconfiguration_fuzzer/BUILD.gn b/test/fuzztest/updateconfiguration_fuzzer/BUILD.gn index 95410d2637..cc7fae31e9 100644 --- a/test/fuzztest/updateconfiguration_fuzzer/BUILD.gn +++ b/test/fuzztest/updateconfiguration_fuzzer/BUILD.gn @@ -48,9 +48,10 @@ ohos_fuzztest("UpdateConfigurationFuzzTest") { "ability_base:configuration", "ability_base:want", "ability_base:zuri", - "appspawn:appspawn_socket_client", + "appspawn:appspawn_client", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", + "c_utils:utils", "eventhandler:libeventhandler", "ipc:ipc_core", "safwk:system_ability_fwk", diff --git a/test/fuzztest/usercallbackstub_fuzzer/BUILD.gn b/test/fuzztest/usercallbackstub_fuzzer/BUILD.gn new file mode 100644 index 0000000000..f55e56d639 --- /dev/null +++ b/test/fuzztest/usercallbackstub_fuzzer/BUILD.gn @@ -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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +module_output_path = "ability_runtime/abilitymgr" + +##############################fuzztest########################################## +ohos_fuzztest("UserCallbackStubFuzzTest") { + module_out_path = module_output_path + + fuzz_config_file = + "${ability_runtime_test_path}/fuzztest/usercallbackstub_fuzzer" + + include_dirs = [ "${ability_runtime_innerkits_path}/wantagent/include" ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "usercallbackstub_fuzzer.cpp" ] + + configs = [ + "${ability_runtime_services_path}/abilitymgr:abilityms_config", + "${ability_runtime_innerkits_path}/ability_manager:ability_manager_public_config", + ] + cflags = [] + if (target_cpu == "arm") { + 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", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "init:libbeget_proxy", + "ipc:ipc_core", + "napi:ace_napi", + "relational_store:native_appdatafwk", + "relational_store:native_dataability", + "relational_store:native_rdb", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [] + deps += [ + # deps file + ":UserCallbackStubFuzzTest", + ] +} +############################################################################### diff --git a/test/fuzztest/usercallbackstub_fuzzer/corpus/init b/test/fuzztest/usercallbackstub_fuzzer/corpus/init new file mode 100644 index 0000000000..6198079a28 --- /dev/null +++ b/test/fuzztest/usercallbackstub_fuzzer/corpus/init @@ -0,0 +1,16 @@ +/* + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/test/fuzztest/usercallbackstub_fuzzer/project.xml b/test/fuzztest/usercallbackstub_fuzzer/project.xml new file mode 100644 index 0000000000..6d3e765c7d --- /dev/null +++ b/test/fuzztest/usercallbackstub_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/fuzztest/usercallbackstub_fuzzer/usercallbackstub_fuzzer.cpp b/test/fuzztest/usercallbackstub_fuzzer/usercallbackstub_fuzzer.cpp new file mode 100644 index 0000000000..2d9693914f --- /dev/null +++ b/test/fuzztest/usercallbackstub_fuzzer/usercallbackstub_fuzzer.cpp @@ -0,0 +1,111 @@ +/* + * 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 "usercallbackstub_fuzzer.h" + +#include +#include + +#define private public +#include "user_callback_stub.h" +#undef private + +#include "ability_record.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +constexpr int INPUT_ZERO = 0; +constexpr int INPUT_ONE = 1; +constexpr int INPUT_TWO = 2; +constexpr int INPUT_THREE = 3; +constexpr size_t FOO_MAX_LEN = 1024; +constexpr size_t U32_AT_SIZE = 4; +constexpr size_t OFFSET_ZERO = 24; +constexpr size_t OFFSET_ONE = 16; +constexpr size_t OFFSET_TWO = 8; +constexpr uint8_t ENABLE = 2; +} // namespace + +class UserCallbackStubFuzzTest : public UserCallbackStub { +public: + UserCallbackStubFuzzTest() = default; + virtual ~UserCallbackStubFuzzTest() + {} + void OnStopUserDone(int userId, int errcode) override + {} + void OnStartUserDone(int userId, int errcode) override {} +}; +const std::u16string APPMGR_INTERFACE_TOKEN = u"ohos.aafwk.AppManager"; +uint32_t GetU32Data(const char* ptr) +{ + // convert fuzz input data to an integer + return (ptr[INPUT_ZERO] << OFFSET_ZERO) | (ptr[INPUT_ONE] << OFFSET_ONE) | (ptr[INPUT_TWO] << OFFSET_TWO) | + ptr[INPUT_THREE]; +} + +bool DoSomethingInterestingWithMyAPI(const char *data, size_t size) +{ + uint32_t code = static_cast(GetU32Data(data)); + std::shared_ptr backStub = std::make_shared(); + MessageParcel dataParcel; + dataParcel.WriteInterfaceToken(APPMGR_INTERFACE_TOKEN); + dataParcel.WriteBuffer(data, size); + dataParcel.RewindRead(0); + MessageParcel reply; + MessageOption option; + backStub->OnRemoteRequest(code, dataParcel, reply, option); + backStub->OnStopUserDoneInner(dataParcel, reply); + backStub->OnStartUserDoneInner(dataParcel, reply); + + return true; +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + /* Run your code on data */ + if (data == nullptr) { + std::cout << "invalid data" << std::endl; + return 0; + } + + /* Validate the length of size */ + if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) { + return 0; + } + + char *ch = (char *)malloc(size + 1); + if (ch == nullptr) { + std::cout << "malloc failed." << std::endl; + return 0; + } + + (void)memset_s(ch, size + 1, 0x00, size + 1); + if (memcpy_s(ch, size + 1, data, size) != EOK) { + std::cout << "copy failed." << std::endl; + free(ch); + ch = nullptr; + return 0; + } + + OHOS::DoSomethingInterestingWithMyAPI(ch, size); + free(ch); + ch = nullptr; + return 0; +} \ No newline at end of file diff --git a/test/fuzztest/usercallbackstub_fuzzer/usercallbackstub_fuzzer.h b/test/fuzztest/usercallbackstub_fuzzer/usercallbackstub_fuzzer.h new file mode 100644 index 0000000000..5bc68e8786 --- /dev/null +++ b/test/fuzztest/usercallbackstub_fuzzer/usercallbackstub_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 FUZZTEST_OHOS_ABILITY_RUNTIME_USERCALLBACKSTUB_FUZZER_H +#define FUZZTEST_OHOS_ABILITY_RUNTIME_USERCALLBACKSTUB_FUZZER_H + +#define FUZZ_PROJECT_NAME "usercallbackstub_fuzzer" + +#endif \ No newline at end of file diff --git a/test/mock/common/include/mock_bundle_manager_service.h b/test/mock/common/include/mock_bundle_manager_service.h index b791cfbb70..08c79a5696 100644 --- a/test/mock/common/include/mock_bundle_manager_service.h +++ b/test/mock/common/include/mock_bundle_manager_service.h @@ -47,11 +47,6 @@ public: return overlayModuleProxy; } - bool GetBundleGidsByUid(const std::string &bundleName, const int &uid, std::vector &gids) - { - return true; - } - bool GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, AppExecFwk::BundleInfo &bundleInfo, int32_t userId) override { diff --git a/test/mock/frameworks_kits_ability_ability_runtime_test/AMS/mock_ability_manager_client.cpp b/test/mock/frameworks_kits_ability_ability_runtime_test/AMS/mock_ability_manager_client.cpp index 54f7e151be..68e8de8000 100644 --- a/test/mock/frameworks_kits_ability_ability_runtime_test/AMS/mock_ability_manager_client.cpp +++ b/test/mock/frameworks_kits_ability_ability_runtime_test/AMS/mock_ability_manager_client.cpp @@ -21,7 +21,6 @@ #include "ability_manager_interface.h" #include "string_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" diff --git a/test/mock/frameworks_kits_ability_ability_runtime_test/AMS/mock_serviceability_manager_service.cpp b/test/mock/frameworks_kits_ability_ability_runtime_test/AMS/mock_serviceability_manager_service.cpp index ee4abcfddb..1b18573791 100644 --- a/test/mock/frameworks_kits_ability_ability_runtime_test/AMS/mock_serviceability_manager_service.cpp +++ b/test/mock/frameworks_kits_ability_ability_runtime_test/AMS/mock_serviceability_manager_service.cpp @@ -46,7 +46,7 @@ int MockServiceAbilityManagerService::StartAbility( int MockServiceAbilityManagerService::StartAbilityAsCaller( const Want& want, const sptr& callerToken, sptr asCallerSourceToken, - int32_t userId, int requestCode, bool isSendDialogResult) + int32_t userId, int requestCode) { return 0; } diff --git a/test/mock/frameworks_kits_ability_ability_runtime_test/AMS/mock_serviceability_manager_service.h b/test/mock/frameworks_kits_ability_ability_runtime_test/AMS/mock_serviceability_manager_service.h index b7f3e3be1d..04bc819ac9 100644 --- a/test/mock/frameworks_kits_ability_ability_runtime_test/AMS/mock_serviceability_manager_service.h +++ b/test/mock/frameworks_kits_ability_ability_runtime_test/AMS/mock_serviceability_manager_service.h @@ -55,8 +55,7 @@ public: const sptr& callerToken, sptr asCallerSourceToken, int32_t userId = DEFAULT_INVAL_VALUE, - int requestCode = DEFAULT_INVAL_VALUE, - bool isSendDialogResult = false) override; + int requestCode = DEFAULT_INVAL_VALUE) override; int StartAbilityAsCaller( const Want& want, const StartOptions& startOptions, @@ -119,6 +118,7 @@ public: MOCK_METHOD2(KillProcess, int(const std::string& bundleName, const bool clearPageStack)); MOCK_METHOD2(UninstallApp, int(const std::string& bundleName, int32_t uid)); + MOCK_METHOD3(UninstallApp, int32_t(const std::string& bundleName, int32_t uid, int32_t appIndex)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo& wantSenderInfo, const sptr& callerToken)); MOCK_METHOD2(SendWantSender, int(sptr target, const SenderInfo& senderInfo)); @@ -300,7 +300,8 @@ public: return 0; } - int RegisterWindowManagerServiceHandler(const sptr& handler) override + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true) override { return 0; } diff --git a/test/mock/frameworks_kits_ability_native_test/include/mock_ability.cpp b/test/mock/frameworks_kits_ability_native_test/include/mock_ability.cpp index 9b43582117..bda59e0ad2 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/mock_ability.cpp +++ b/test/mock/frameworks_kits_ability_native_test/include/mock_ability.cpp @@ -17,7 +17,6 @@ #include #include "ability_loader.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iservice_registry.h" #include "system_ability_definition.h" diff --git a/test/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_client.h b/test/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_client.h index 9df28895f3..df48c6a532 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_client.h +++ b/test/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_client.h @@ -18,17 +18,17 @@ #include #include -#include "abs_shared_result_set.h" -#include "data_ability_predicates.h" -#include "values_bucket.h" + #include "ability_connect_callback_interface.h" #include "ability_manager_errors.h" -#include "ability_context.h" #include "ability_manager_interface.h" #include "ability_scheduler_interface.h" -#include "hilog_wrapper.h" +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "fa_ability_context.h" #include "iremote_object.h" #include "iremote_stub.h" +#include "values_bucket.h" #include "want.h" #define OPENFILENUM (1246) diff --git a/test/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_clientex.cpp b/test/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_clientex.cpp index 7bfd65f700..5b4693b66e 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_clientex.cpp +++ b/test/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_clientex.cpp @@ -21,7 +21,6 @@ #include "ability_manager_interface.h" #include "string_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" diff --git a/test/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_service.h b/test/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_service.h index b238492a41..8b74259d38 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_service.h +++ b/test/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_service.h @@ -147,8 +147,8 @@ public: MOCK_METHOD4(StartAbilityByCall, int(const Want&, const sptr&, const sptr&, int32_t)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD6(StartAbilityAsCaller, int(const Want &want, const StartOptions &startOptions, const sptr& callerToken, sptr asCallerSourceToken, int32_t userId, int requestCode)); @@ -264,7 +264,8 @@ public: return 0; } - int RegisterWindowManagerServiceHandler(const sptr& handler) override + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true) override { return 0; } diff --git a/test/mock/frameworks_kits_ability_native_test/include/mock_data_ability_impl.cpp b/test/mock/frameworks_kits_ability_native_test/include/mock_data_ability_impl.cpp index 83b2ee2244..c74eec6b95 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/mock_data_ability_impl.cpp +++ b/test/mock/frameworks_kits_ability_native_test/include/mock_data_ability_impl.cpp @@ -18,7 +18,6 @@ #include "values_bucket.h" #include "data_ability_impl.h" #include -#include "hilog_wrapper.h" const int returnValueOpenfile = 11; const int returnValueInsert = 22; diff --git a/test/mock/frameworks_kits_ability_native_test/include/mock_form_supply_callback.cpp b/test/mock/frameworks_kits_ability_native_test/include/mock_form_supply_callback.cpp index 2fcce466f2..ae3da5fdf4 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/mock_form_supply_callback.cpp +++ b/test/mock/frameworks_kits_ability_native_test/include/mock_form_supply_callback.cpp @@ -14,7 +14,6 @@ */ #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_form_supply_callback.h" namespace OHOS { diff --git a/test/mock/frameworks_kits_ability_native_test/include/mock_overlay_manager.cpp b/test/mock/frameworks_kits_ability_native_test/include/mock_overlay_manager.cpp index 2fa7d799fd..bc5914a250 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/mock_overlay_manager.cpp +++ b/test/mock/frameworks_kits_ability_native_test/include/mock_overlay_manager.cpp @@ -16,7 +16,6 @@ #include "ability_info.h" #include "application_info.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/test/mock/frameworks_kits_ability_native_test/include/mock_overlay_manager.h b/test/mock/frameworks_kits_ability_native_test/include/mock_overlay_manager.h index bc36f11a68..2f855928b8 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/mock_overlay_manager.h +++ b/test/mock/frameworks_kits_ability_native_test/include/mock_overlay_manager.h @@ -22,7 +22,7 @@ #include "want.h" #include "iremote_proxy.h" #include "iremote_stub.h" -#include "foundation/bundlemanager/bundle_framework/interfaces/inner_api/appexecfwk_core/include/overlay/overlay_manager_interface.h" +#include "overlay_manager_interface.h" namespace OHOS { namespace AppExecFwk { diff --git a/test/mock/frameworks_kits_ability_native_test/include/mock_replace_ability_impl.cpp b/test/mock/frameworks_kits_ability_native_test/include/mock_replace_ability_impl.cpp index c073b1d88f..cb66694d7e 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/mock_replace_ability_impl.cpp +++ b/test/mock/frameworks_kits_ability_native_test/include/mock_replace_ability_impl.cpp @@ -18,7 +18,6 @@ #include "ability_impl.h" #include "ability_local_record.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ohos_application.h" namespace OHOS { 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 75a3f84243..61926301f7 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 @@ -99,6 +99,7 @@ public: MOCK_METHOD1(SubscribeContainerModalButtonsRectChange, void( std::function &&callback)); MOCK_METHOD0(GetFormSerializedGesture, SerializedGesture()); + MOCK_METHOD1(SetForceSplitEnable, void(bool isForceSplit)); #ifndef PREVIEW MOCK_METHOD4( diff --git a/test/mock/frameworks_kits_ability_native_test/include/sys_mgr_client_mock.cpp b/test/mock/frameworks_kits_ability_native_test/include/sys_mgr_client_mock.cpp index 832b73d097..0265aea63a 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/sys_mgr_client_mock.cpp +++ b/test/mock/frameworks_kits_ability_native_test/include/sys_mgr_client_mock.cpp @@ -15,7 +15,6 @@ #include #include "sys_mgr_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" diff --git a/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_ability_delegator_stub.cpp b/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_ability_delegator_stub.cpp index 4fcdd85271..f2444dc66f 100644 --- a/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_ability_delegator_stub.cpp +++ b/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_ability_delegator_stub.cpp @@ -462,7 +462,8 @@ int MockAbilityDelegatorStub::SetMissionIcon( return 0; } -int MockAbilityDelegatorStub::RegisterWindowManagerServiceHandler(const sptr& handler) +int MockAbilityDelegatorStub::RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled) { return 0; } @@ -473,7 +474,8 @@ int MockAbilityDelegatorStub2::SetMissionIcon( return 0; } -int MockAbilityDelegatorStub2::RegisterWindowManagerServiceHandler(const sptr& handler) +int MockAbilityDelegatorStub2::RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled) { return 0; } diff --git a/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_ability_delegator_stub.h b/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_ability_delegator_stub.h index 95e6b82909..20ec0449fa 100644 --- a/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_ability_delegator_stub.h +++ b/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_ability_delegator_stub.h @@ -21,7 +21,6 @@ #include "string_ex.h" #include "ability_manager_errors.h" #include "ability_manager_stub.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { @@ -32,8 +31,8 @@ public: int requestCode = DEFAULT_INVAL_VALUE) override; MOCK_METHOD4(StartAbility, int(const Want& want, const sptr& callerToken, int32_t userId, int requestCode)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD5(StartAbility, int(const Want& want, const AbilityStartSetting& abilityStartSetting, const sptr& callerToken, int32_t userId, int requestCode)); MOCK_METHOD4(StartAbilityByInsightIntent, int32_t(const Want& want, const sptr& callerToken, @@ -72,6 +71,7 @@ public: MOCK_METHOD1(RemoveStack, int(int id)); MOCK_METHOD2(KillProcess, int(const std::string& bundleName, const bool clearPageStack)); MOCK_METHOD2(UninstallApp, int(const std::string& bundleName, int32_t uid)); + MOCK_METHOD3(UninstallApp, int32_t(const std::string& bundleName, int32_t uid, int32_t appIndex)); MOCK_METHOD2(MoveMissionToEnd, int(const sptr& token, const bool nonFirst)); MOCK_METHOD1(IsFirstInMission, bool(const sptr& token)); MOCK_METHOD4(CompelVerifyPermission, int(const std::string& permission, int pid, int uid, std::string& message)); @@ -181,7 +181,8 @@ public: MOCK_METHOD2(SetMissionLabel, int(const sptr& token, const std::string& label)); int SetMissionIcon( const sptr& token, const std::shared_ptr& icon) override; - int RegisterWindowManagerServiceHandler(const sptr& handler); + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true); void CompleteFirstFrameDrawing(const sptr& abilityToken) override {} #endif MOCK_METHOD2(IsValidMissionIds, int32_t(const std::vector&, std::vector&)); @@ -212,8 +213,8 @@ public: int StartAbility(const Want& want, int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = -1) override; MOCK_METHOD4(StartAbility, int(const Want& want, const sptr& callerToken, int32_t userId, int requestCode)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD5(StartAbility, int(const Want& want, const AbilityStartSetting& abilityStartSetting, const sptr& callerToken, int32_t userId, int requestCode)); MOCK_METHOD4(StartAbilityByInsightIntent, int32_t(const Want& want, const sptr& callerToken, @@ -252,6 +253,7 @@ public: MOCK_METHOD1(RemoveStack, int(int id)); MOCK_METHOD2(KillProcess, int(const std::string& bundleName, const bool clearPageStack)); MOCK_METHOD2(UninstallApp, int(const std::string& bundleName, int32_t uid)); + MOCK_METHOD3(UninstallApp, int32_t(const std::string& bundleName, int32_t uid, int32_t appIndex)); MOCK_METHOD2(MoveMissionToEnd, int(const sptr& token, const bool nonFirst)); MOCK_METHOD1(IsFirstInMission, bool(const sptr& token)); MOCK_METHOD4(CompelVerifyPermission, int(const std::string& permission, int pid, int uid, std::string& message)); @@ -361,7 +363,8 @@ public: MOCK_METHOD2(SetMissionLabel, int(const sptr& token, const std::string& label)); int SetMissionIcon( const sptr& token, const std::shared_ptr& icon) override; - int RegisterWindowManagerServiceHandler(const sptr& handler); + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true); void CompleteFirstFrameDrawing(const sptr& abilityToken) override {} #endif MOCK_METHOD2(IsValidMissionIds, int32_t(const std::vector&, std::vector&)); diff --git a/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_iability_monitor.cpp b/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_iability_monitor.cpp index 6c4d24cf79..849f3efa5f 100644 --- a/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_iability_monitor.cpp +++ b/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_iability_monitor.cpp @@ -15,7 +15,6 @@ #include "mock_iability_monitor.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace { const std::string ABILITY_NAME = "com.example.myapplication.MainAbility"; diff --git a/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_test_observer_stub.cpp b/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_test_observer_stub.cpp index 77244ecd85..2da09cf572 100644 --- a/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_test_observer_stub.cpp +++ b/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_test_observer_stub.cpp @@ -15,7 +15,6 @@ #include "mock_test_observer_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_test_runner.cpp b/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_test_runner.cpp index 578da4a5ce..dc9d9c5745 100644 --- a/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_test_runner.cpp +++ b/test/mock/frameworks_kits_appkit_native_test/ability_delegator/mock_test_runner.cpp @@ -15,7 +15,6 @@ #include "mock_test_runner.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/test/mock/frameworks_kits_appkit_test/include/mock_ability_mgr_service.h b/test/mock/frameworks_kits_appkit_test/include/mock_ability_mgr_service.h index eea499963f..db6b762be3 100644 --- a/test/mock/frameworks_kits_appkit_test/include/mock_ability_mgr_service.h +++ b/test/mock/frameworks_kits_appkit_test/include/mock_ability_mgr_service.h @@ -31,8 +31,8 @@ public: const sptr& callerToken, int32_t userId, int requestCode)); MOCK_METHOD4(StartAbilityByInsightIntent, int32_t(const Want& want, const sptr& callerToken, uint64_t intentId, int32_t userId)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD6(StartAbilityAsCaller, int(const Want &want, const StartOptions &startOptions, const sptr &callerToken, sptr asCallerSourceToken, int32_t userId, int requestCode)); @@ -67,6 +67,7 @@ public: MOCK_METHOD2(KillProcess, int(const std::string& bundleName, const bool clearPageStack)); MOCK_METHOD2(UninstallApp, int(const std::string& bundleName, int32_t uid)); + MOCK_METHOD3(UninstallApp, int32_t(const std::string& bundleName, int32_t uid, int32_t appIndex)); MOCK_METHOD1(TerminateAbilityByRecordId, int(const int64_t recordId)); MOCK_METHOD1(LockMissionForCleanup, int(int32_t missionId)); 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 d7fcf63004..91948e2146 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 @@ -22,7 +22,6 @@ #include "app_scheduler_interface.h" #include "app_mgr_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "app_malloc_info.h" #include "app_jsheap_mem_info.h" @@ -77,7 +76,7 @@ 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_METHOD3(StartChildProcess, int32_t(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount)); + MOCK_METHOD2(StartChildProcess, int32_t(pid_t &childPid, const ChildProcessRequest &request)); MOCK_METHOD1(GetChildProcessInfoForSelf, int32_t(ChildProcessInfo &info)); MOCK_METHOD1(AttachChildProcess, void(const sptr &childScheduler)); MOCK_METHOD0(ExitChildProcessSafely, void()); @@ -129,6 +128,7 @@ public: MOCK_METHOD2(UpdateApplicationInfoInstalled, int(const std::string&, const int uid)); MOCK_METHOD2(KillApplication, int(const std::string& appName, const bool clearPageStack)); + MOCK_METHOD3(ForceKillApplication, int(const std::string& appName, const int userId, const int appIndex)); MOCK_METHOD2(KillApplicationByUid, int(const std::string&, const int uid)); MOCK_METHOD0(IsFinalAppProcess, bool()); diff --git a/test/mock/frameworks_kits_appkit_test/include/sys_mgr_client_mock.cpp b/test/mock/frameworks_kits_appkit_test/include/sys_mgr_client_mock.cpp index 752edcd047..42b0e59081 100644 --- a/test/mock/frameworks_kits_appkit_test/include/sys_mgr_client_mock.cpp +++ b/test/mock/frameworks_kits_appkit_test/include/sys_mgr_client_mock.cpp @@ -16,7 +16,6 @@ #include #include "sys_mgr_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "ipc_skeleton.h" diff --git a/test/mock/frameworks_kits_runtime_test/mock_runtime.h b/test/mock/frameworks_kits_runtime_test/mock_runtime.h index 4af4217006..d2ff739231 100644 --- a/test/mock/frameworks_kits_runtime_test/mock_runtime.h +++ b/test/mock/frameworks_kits_runtime_test/mock_runtime.h @@ -57,7 +57,7 @@ public: { return; } - void DumpCpuProfile(bool isPrivate) override + void DumpCpuProfile() override { return; } diff --git a/test/mock/frameworks_kits_test/AMS/mock_ability_manager_client.cpp b/test/mock/frameworks_kits_test/AMS/mock_ability_manager_client.cpp index 5bda4abc96..511e9137af 100644 --- a/test/mock/frameworks_kits_test/AMS/mock_ability_manager_client.cpp +++ b/test/mock/frameworks_kits_test/AMS/mock_ability_manager_client.cpp @@ -21,7 +21,6 @@ #include "ability_manager_interface.h" #include "string_ex.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" diff --git a/test/mock/frameworks_kits_test/AMS/mock_ability_manager_service.cpp b/test/mock/frameworks_kits_test/AMS/mock_ability_manager_service.cpp index aabeeff394..3939157b66 100644 --- a/test/mock/frameworks_kits_test/AMS/mock_ability_manager_service.cpp +++ b/test/mock/frameworks_kits_test/AMS/mock_ability_manager_service.cpp @@ -74,7 +74,7 @@ int MockAbilityManagerService::StartAbility(const Want& want, const sptr& callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult) + sptr asCallerSourceToken, int32_t userId, int requestCode) { return 0; } diff --git a/test/mock/frameworks_kits_test/AMS/mock_ability_manager_service.h b/test/mock/frameworks_kits_test/AMS/mock_ability_manager_service.h index 1a83ee69d9..b97c37b73f 100644 --- a/test/mock/frameworks_kits_test/AMS/mock_ability_manager_service.h +++ b/test/mock/frameworks_kits_test/AMS/mock_ability_manager_service.h @@ -53,8 +53,7 @@ public: const sptr& callerToken, sptr asCallerSourceToken, int32_t userId = DEFAULT_INVAL_VALUE, - int requestCode = -1, - bool isSendDialogResult = false) override; + int requestCode = -1) override; int StartAbilityAsCaller( const Want& want, const StartOptions& startOptions, @@ -111,6 +110,7 @@ public: MOCK_METHOD2(KillProcess, int(const std::string& bundleName, const bool clearPageStack)); MOCK_METHOD2(UninstallApp, int(const std::string& bundleName, int32_t uid)); + MOCK_METHOD3(UninstallApp, int32_t(const std::string& bundleName, int32_t uid, int32_t appIndex)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo& wantSenderInfo, const sptr& callerToken)); MOCK_METHOD2(SendWantSender, int(sptr target, const SenderInfo& senderInfo)); @@ -255,7 +255,8 @@ public: return 0; } - int RegisterWindowManagerServiceHandler(const sptr& handler) override + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true) override { return 0; } diff --git a/test/mock/frameworks_kits_test/AMS/mock_serviceability_manager_service.cpp b/test/mock/frameworks_kits_test/AMS/mock_serviceability_manager_service.cpp index 9c7b58d10e..c9396df81c 100644 --- a/test/mock/frameworks_kits_test/AMS/mock_serviceability_manager_service.cpp +++ b/test/mock/frameworks_kits_test/AMS/mock_serviceability_manager_service.cpp @@ -55,7 +55,7 @@ int MockServiceAbilityManagerService::StartAbility( int MockServiceAbilityManagerService::StartAbilityAsCaller( const Want& want, const sptr& callerToken, sptr asCallerSourceToken, - int32_t userId, int requestCode, bool isSendDialogResult) + int32_t userId, int requestCode) { return 0; } diff --git a/test/mock/frameworks_kits_test/AMS/mock_serviceability_manager_service.h b/test/mock/frameworks_kits_test/AMS/mock_serviceability_manager_service.h index 1dad4bd71a..93319db51a 100644 --- a/test/mock/frameworks_kits_test/AMS/mock_serviceability_manager_service.h +++ b/test/mock/frameworks_kits_test/AMS/mock_serviceability_manager_service.h @@ -57,8 +57,7 @@ public: const sptr& callerToken, const sptr asCallerSourceToken, int32_t userId = DEFAULT_INVAL_VALUE, - int requestCode = DEFAULT_INVAL_VALUE, - bool isSendDialogResult = false) override; + int requestCode = DEFAULT_INVAL_VALUE) override; int StartAbilityAsCaller( const Want& want, const StartOptions& startOptions, @@ -112,6 +111,7 @@ public: MOCK_METHOD2(KillProcess, int(const std::string& bundleName, const bool clearPageStack)); MOCK_METHOD2(UninstallApp, int(const std::string& bundleName, int32_t uid)); + MOCK_METHOD3(UninstallApp, int32_t(const std::string& bundleName, int32_t uid, int32_t appIndex)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo& wantSenderInfo, const sptr& callerToken)); MOCK_METHOD2(SendWantSender, int(sptr target, const SenderInfo& senderInfo)); @@ -278,7 +278,8 @@ public: return 0; } - int RegisterWindowManagerServiceHandler(const sptr& handler) override + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true) override { return 0; } 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 dd8d0450a7..5ca593650d 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 @@ -17,7 +17,6 @@ #define MOCK_OHOS_ABILITY_RUNTIME_MOCK_APP_MGR_SERVICE_INNER_H #include "gmock/gmock.h" -#include "hilog_wrapper.h" #include "semaphore_ex.h" #include "app_mgr_service_inner.h" @@ -62,8 +61,7 @@ public: MOCK_METHOD0(GetConfiguration, std::shared_ptr()); MOCK_METHOD2(IsSharedBundleRunning, bool(const std::string &bundleName, uint32_t versionCode)); MOCK_METHOD3(GetBundleNameByPid, int32_t(const int pid, std::string &bundleName, int32_t &uid)); - MOCK_METHOD5(StartChildProcess, int32_t(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid, - int32_t childProcessCount, bool inStartWithDebug)); + MOCK_METHOD3(StartChildProcess, int32_t(const pid_t hostPid, pid_t &childPid, const ChildProcessRequest &request)); MOCK_METHOD1(GetChildProcessInfoForSelf, int32_t(ChildProcessInfo &info)); MOCK_METHOD4(PreloadApplication, int32_t(const std::string&, int32_t, AppExecFwk::PreloadMode, int32_t)); MOCK_METHOD4(StartNativeChildProcess, int32_t(const pid_t hostPid, const std::string &libName, diff --git a/test/mock/services_abilitymgr_test/appmgr_test_service/src/appmgr_test_service.cpp b/test/mock/services_abilitymgr_test/appmgr_test_service/src/appmgr_test_service.cpp index 7c90423aeb..c457e3d3fb 100644 --- a/test/mock/services_abilitymgr_test/appmgr_test_service/src/appmgr_test_service.cpp +++ b/test/mock/services_abilitymgr_test/appmgr_test_service/src/appmgr_test_service.cpp @@ -20,7 +20,6 @@ #include "ability_scheduler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/test/mock/services_abilitymgr_test/include/mock_app_mgr_client.h b/test/mock/services_abilitymgr_test/include/mock_app_mgr_client.h index 0091040add..1b8f2cfeb2 100644 --- a/test/mock/services_abilitymgr_test/include/mock_app_mgr_client.h +++ b/test/mock/services_abilitymgr_test/include/mock_app_mgr_client.h @@ -19,7 +19,6 @@ #include "gmock/gmock.h" #include "app_mgr_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/test/mock/services_abilitymgr_test/libs/aakit/BUILD.gn b/test/mock/services_abilitymgr_test/libs/aakit/BUILD.gn index 63ec8fdd3a..d78450dec0 100644 --- a/test/mock/services_abilitymgr_test/libs/aakit/BUILD.gn +++ b/test/mock/services_abilitymgr_test/libs/aakit/BUILD.gn @@ -31,6 +31,7 @@ ohos_static_library("aakit_mock") { cfi = true cfi_cross_dso = true debug = false + blocklist = "../../../../cfi_blocklist.txt" } branch_protector_ret = "pac_ret" diff --git a/test/mock/services_abilitymgr_test/libs/aakit/src/ability_scheduler.cpp b/test/mock/services_abilitymgr_test/libs/aakit/src/ability_scheduler.cpp index 3b15345d8f..7ba8cb175a 100644 --- a/test/mock/services_abilitymgr_test/libs/aakit/src/ability_scheduler.cpp +++ b/test/mock/services_abilitymgr_test/libs/aakit/src/ability_scheduler.cpp @@ -16,7 +16,6 @@ #include "ability_scheduler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/test/mock/services_abilitymgr_test/libs/aakit/src/mock_ability_connect_callback.cpp b/test/mock/services_abilitymgr_test/libs/aakit/src/mock_ability_connect_callback.cpp index cc673f064e..02cdd33792 100644 --- a/test/mock/services_abilitymgr_test/libs/aakit/src/mock_ability_connect_callback.cpp +++ b/test/mock/services_abilitymgr_test/libs/aakit/src/mock_ability_connect_callback.cpp @@ -15,7 +15,6 @@ #include "mock_ability_connect_callback.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/test/mock/services_abilitymgr_test/libs/ability_scheduler_mock/ability_scheduler_mock.h b/test/mock/services_abilitymgr_test/libs/ability_scheduler_mock/ability_scheduler_mock.h index 3f8553b3a4..a4cb4fc1c5 100644 --- a/test/mock/services_abilitymgr_test/libs/ability_scheduler_mock/ability_scheduler_mock.h +++ b/test/mock/services_abilitymgr_test/libs/ability_scheduler_mock/ability_scheduler_mock.h @@ -21,7 +21,6 @@ #include #include #include "ability_scheduler_interface.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { 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 db078d8ea2..9b37ed7a51 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/BUILD.gn +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/BUILD.gn @@ -30,7 +30,13 @@ config("appexecfwk_core_mock_config") { ohos_static_library("appexecfwk_appmgr_mock") { # sources = [ "src/appmgr/mock_app_manager.cpp" ] - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" configs = [ ":appexecfwk_core_mock_config" ] cflags = [] if (target_cpu == "arm") { @@ -55,6 +61,13 @@ ohos_static_library("appexecfwk_appmgr_mock") { } ohos_source_set("appexecfwk_bundlemgr_mock") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" sources = [ "src/bundlemgr/mock_app_control_manager.cpp", "src/bundlemgr/mock_bundle_manager.cpp", diff --git a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/include/appmgr/app_mgr_client.h b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/include/appmgr/app_mgr_client.h index e9b08c88d5..092fc3f569 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/include/appmgr/app_mgr_client.h +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/include/appmgr/app_mgr_client.h @@ -171,7 +171,7 @@ public: virtual AppMgrResultCode GetAppFreezingTime(int& time); virtual void AbilityAttachTimeOut(const sptr& token); - virtual void PrepareTerminate(const sptr& token); + virtual void PrepareTerminate(const sptr& token, bool clearMissionFlag = false); void GetRunningProcessInfoByToken(const sptr& token, AppExecFwk::RunningProcessInfo& info); diff --git a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/include/bundlemgr/mock_app_control_manager.h b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/include/bundlemgr/mock_app_control_manager.h index 5db69d8587..1cca41f8c0 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/include/bundlemgr/mock_app_control_manager.h +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/include/bundlemgr/mock_app_control_manager.h @@ -18,7 +18,7 @@ #include "want.h" #include -#include "foundation/bundlemanager/bundle_framework/interfaces/inner_api/appexecfwk_core/include/app_control/app_control_interface.h" +#include "app_control_interface.h" #include "iremote_proxy.h" namespace OHOS { diff --git a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp index 8023501fd6..f6ff62b1d3 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_mgr_client.cpp @@ -109,7 +109,7 @@ AppMgrResultCode AppMgrClient::ConnectAppMgrService() void AppMgrClient::AbilityAttachTimeOut(const sptr& token) {} -void AppMgrClient::PrepareTerminate(const sptr& token) +void AppMgrClient::PrepareTerminate(const sptr& token, bool clearMissionFlag) {} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp index dfde2d0993..84698be489 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_host.cpp @@ -16,7 +16,6 @@ #include "app_state_callback_host.h" #include "appexecfwk_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "iremote_object.h" #include "app_state_callback_proxy.h" diff --git a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp index 1105ea90ba..ecf32a30bd 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/app_state_callback_proxy.cpp @@ -16,7 +16,6 @@ #include "app_state_callback_proxy.h" #include "bundle_info.h" -#include "hilog_wrapper.h" #include "ipc_types.h" 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 c003a2dac8..b8e0bac942 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 @@ -16,7 +16,6 @@ #include "app_scheduler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ability_util.h" #include "ability_manager_errors.h" #include "appmgr/app_mgr_constants.h" @@ -121,7 +120,7 @@ void AppScheduler::AttachTimeOut(const sptr& token) TAG_LOGI(AAFwkTag::TEST, "Test AppScheduler::AttachTimeOut()"); } -void AppScheduler::PrepareTerminate(const sptr& token) +void AppScheduler::PrepareTerminate(const sptr& token, bool clearMissionFlag) { TAG_LOGI(AAFwkTag::TEST, "Test AppScheduler::PrepareTerminate()"); } diff --git a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp index 678d38d5ed..25721f586d 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/src/bundlemgr/mock_bundle_manager.cpp @@ -17,7 +17,6 @@ #include "clean_cache_callback_interface.h" #include "ability_info.h" #include "application_info.h" -#include "hilog_wrapper.h" #include "ability_config.h" namespace OHOS { diff --git a/test/mock/services_abilitymgr_test/libs/arkui_mock/src/ui_service_mgr_client_mock.cpp b/test/mock/services_abilitymgr_test/libs/arkui_mock/src/ui_service_mgr_client_mock.cpp index 26fecf90bc..0353ffbb26 100644 --- a/test/mock/services_abilitymgr_test/libs/arkui_mock/src/ui_service_mgr_client_mock.cpp +++ b/test/mock/services_abilitymgr_test/libs/arkui_mock/src/ui_service_mgr_client_mock.cpp @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" diff --git a/test/mock/services_abilitymgr_test/libs/sa_mgr/src/sa_mgr_client_mock.cpp b/test/mock/services_abilitymgr_test/libs/sa_mgr/src/sa_mgr_client_mock.cpp index 1c63c1ef49..7518c52964 100644 --- a/test/mock/services_abilitymgr_test/libs/sa_mgr/src/sa_mgr_client_mock.cpp +++ b/test/mock/services_abilitymgr_test/libs/sa_mgr/src/sa_mgr_client_mock.cpp @@ -15,7 +15,6 @@ #include "sa_mgr_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" 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 5b88e69774..da907a4dd3 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 @@ -38,10 +38,11 @@ public: MOCK_METHOD3(KillProcessWithAccount, int(const std::string&, const int, const bool clearPageStack)); MOCK_METHOD2(UpdateApplicationInfoInstalled, int(const std::string&, const int uid)); MOCK_METHOD2(KillApplication, int32_t(const std::string& bundleName, const bool clearPageStack)); + MOCK_METHOD3(ForceKillApplication, int32_t(const std::string& appName, const int userId, const int appIndex)); MOCK_METHOD2(KillApplicationByUid, int(const std::string&, const int uid)); MOCK_METHOD0(IsReady, bool()); MOCK_METHOD1(AbilityAttachTimeOut, void(const sptr& token)); - MOCK_METHOD1(PrepareTerminate, void(const sptr& token)); + MOCK_METHOD2(PrepareTerminate, void(const sptr& token, bool clearMissionFlag)); MOCK_METHOD2(GetRunningProcessInfoByToken, void(const sptr& token, OHOS::AppExecFwk::RunningProcessInfo& info)); MOCK_METHOD1(SetAbilityForegroundingFlagToAppRecord, void(const pid_t pid)); 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 cd2fe2f138..f51b30ba72 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 @@ -41,6 +41,7 @@ public: MOCK_METHOD1(AbilityCleaned, void(const sptr& token)); MOCK_METHOD2(UpdateApplicationInfoInstalled, int(const std::string&, const int uid)); MOCK_METHOD2(KillApplication, int32_t(const std::string& appName, const bool clearPageStack)); + MOCK_METHOD3(ForceKillApplication, int32_t(const std::string& appName, const int userId, const int appIndex)); MOCK_METHOD2(KillApplicationByUid, int(const std::string&, const int uid)); MOCK_METHOD1(IsBackgroundRunningRestricted, int(const std::string& bundleName)); MOCK_METHOD1(GetAllRunningProcesses, int(std::vector& info)); @@ -95,8 +96,7 @@ public: MOCK_METHOD2(IsApplicationRunning, int32_t(const std::string &bundleName, bool &isRunning)); MOCK_METHOD3(IsAppRunning, int32_t(const std::string &bundleName, int32_t appCloneIndex, bool &isRunning)); - MOCK_METHOD4(StartChildProcess, int32_t(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount, - bool isStartWithNative)); + MOCK_METHOD2(StartChildProcess, int32_t(pid_t &childPid, const ChildProcessRequest &request)); MOCK_METHOD1(GetChildProcessInfoForSelf, int32_t(ChildProcessInfo &info)); MOCK_METHOD1(AttachChildProcess, void(const sptr &childScheduler)); MOCK_METHOD0(ExitChildProcessSafely, void()); @@ -226,6 +226,11 @@ public: int code_; + virtual bool SetAppFreezeFilter(int32_t pid) + { + return false; + } + virtual int32_t ChangeAppGcState(pid_t pid, int32_t state) { return 0; 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 c8ff9b5f31..83f774b163 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 @@ -17,7 +17,6 @@ #define MOCK_OHOS_ABILITY_RUNTIME_MOCK_APP_MGR_SERVICE_INNER_H #include "gmock/gmock.h" -#include "hilog_wrapper.h" #include "semaphore_ex.h" #include "app_mgr_service_inner.h" @@ -63,8 +62,7 @@ public: MOCK_METHOD0(GetConfiguration, std::shared_ptr()); MOCK_METHOD2(IsSharedBundleRunning, bool(const std::string &bundleName, uint32_t versionCode)); MOCK_METHOD3(GetBundleNameByPid, int32_t(const int pid, std::string &bundleName, int32_t &uid)); - MOCK_METHOD5(StartChildProcess, int32_t(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid, - int32_t childProcessCount, bool isStartWithNative)); + MOCK_METHOD3(StartChildProcess, int32_t(const pid_t hostPid, pid_t &childPid, const ChildProcessRequest &request)); MOCK_METHOD1(GetChildProcessInfoForSelf, int32_t(ChildProcessInfo &info)); MOCK_METHOD2(SetAppWaitingDebug, int32_t(const std::string &bundleName, bool isPersist)); MOCK_METHOD0(CancelAppWaitingDebug, int32_t()); diff --git a/test/mock/services_appmgr_test/include/mock_app_service_mgr.h b/test/mock/services_appmgr_test/include/mock_app_service_mgr.h index eb04fa6220..dfc4931bad 100644 --- a/test/mock/services_appmgr_test/include/mock_app_service_mgr.h +++ b/test/mock/services_appmgr_test/include/mock_app_service_mgr.h @@ -19,7 +19,6 @@ #include "iremote_object.h" #include "app_service_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_app_mgr_service.h" namespace OHOS { diff --git a/test/mock/services_appmgr_test/include/mock_bundle_manager.h b/test/mock/services_appmgr_test/include/mock_bundle_manager.h index ad2d3bbdd0..574959563b 100644 --- a/test/mock/services_appmgr_test/include/mock_bundle_manager.h +++ b/test/mock/services_appmgr_test/include/mock_bundle_manager.h @@ -100,8 +100,6 @@ public: const std::string& bundleName, const BundleFlag flag, BundleInfo& bundleInfo, int32_t userId) override; virtual bool GetBundleInfos( const BundleFlag flag, std::vector& bundleInfos, int32_t userId) override; - bool GetBundleGidsByUid( - const std::string& bundleName, const int& uid, std::vector& gids) override; virtual bool GetBundleGids(const std::string& bundleName, std::vector& gids) override; virtual bool GetHapModuleInfo(const AbilityInfo& abilityInfo, HapModuleInfo& hapModuleInfo); virtual bool GetHapModuleInfo( diff --git a/test/mock/services_appmgr_test/include/mock_overlay_manager.h b/test/mock/services_appmgr_test/include/mock_overlay_manager.h index bc36f11a68..2f855928b8 100644 --- a/test/mock/services_appmgr_test/include/mock_overlay_manager.h +++ b/test/mock/services_appmgr_test/include/mock_overlay_manager.h @@ -22,7 +22,7 @@ #include "want.h" #include "iremote_proxy.h" #include "iremote_stub.h" -#include "foundation/bundlemanager/bundle_framework/interfaces/inner_api/appexecfwk_core/include/overlay/overlay_manager_interface.h" +#include "overlay_manager_interface.h" namespace OHOS { namespace AppExecFwk { diff --git a/test/mock/services_appmgr_test/src/mock_bundle_manager.cpp b/test/mock/services_appmgr_test/src/mock_bundle_manager.cpp index e72157a97f..63e480a21e 100644 --- a/test/mock/services_appmgr_test/src/mock_bundle_manager.cpp +++ b/test/mock/services_appmgr_test/src/mock_bundle_manager.cpp @@ -19,7 +19,6 @@ #include "ability_info.h" #include "application_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_overlay_manager.h" namespace { const int32_t HQF_VERSION_CODE = 1000; @@ -275,12 +274,6 @@ bool BundleMgrService::GetBundleInfos( return true; } -bool BundleMgrService::GetBundleGidsByUid( - const std::string& bundleName, const int& uid, std::vector& gids) -{ - return true; -} - void BundleMgrService::PushTestHelloIndexAbility(int index) { AbilityInfo info; diff --git a/test/mock/services_appmgr_test/src/mock_overlay_manager.cpp b/test/mock/services_appmgr_test/src/mock_overlay_manager.cpp index 3986e03fc6..c8198657d0 100644 --- a/test/mock/services_appmgr_test/src/mock_overlay_manager.cpp +++ b/test/mock/services_appmgr_test/src/mock_overlay_manager.cpp @@ -19,7 +19,6 @@ #include "ability_info.h" #include "application_info.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { diff --git a/test/mock/services_appmgr_test/src/sys_mgr_client_mock.cpp b/test/mock/services_appmgr_test/src/sys_mgr_client_mock.cpp index e8d2676ab6..fa4b33769d 100644 --- a/test/mock/services_appmgr_test/src/sys_mgr_client_mock.cpp +++ b/test/mock/services_appmgr_test/src/sys_mgr_client_mock.cpp @@ -15,7 +15,6 @@ #include "sys_mgr_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" diff --git a/test/moduletest/ability_delegator_test/ability_delegator_args_module_test.cpp b/test/moduletest/ability_delegator_test/ability_delegator_args_module_test.cpp index b07744fad4..5b8753ea4b 100644 --- a/test/moduletest/ability_delegator_test/ability_delegator_args_module_test.cpp +++ b/test/moduletest/ability_delegator_test/ability_delegator_args_module_test.cpp @@ -22,7 +22,6 @@ #undef private #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "want.h" using namespace testing::ext; diff --git a/test/moduletest/ability_delegator_test/ability_delegator_module_test.cpp b/test/moduletest/ability_delegator_test/ability_delegator_module_test.cpp index b707aae663..5e3cda2168 100644 --- a/test/moduletest/ability_delegator_test/ability_delegator_module_test.cpp +++ b/test/moduletest/ability_delegator_test/ability_delegator_module_test.cpp @@ -24,19 +24,18 @@ #include "ability_delegator_infos.h" #include "ability_delegator_registry.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/context_impl.h" #include "app_loader.h" +#include "context_impl.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_delegator_stub.h" #include "mock_iability_monitor.h" #include "mock_test_observer_stub.h" #include "ohos_application.h" +#include "scene_board_judgement.h" #include "test_observer_stub.h" #include "test_observer.h" #include "test_runner.h" #include "want.h" -#include "scene_board_judgement.h" using namespace testing::ext; using namespace OHOS; diff --git a/test/moduletest/ability_delegator_test/ability_delegator_registry_module_test.cpp b/test/moduletest/ability_delegator_test/ability_delegator_registry_module_test.cpp index 395380c2da..526f8acd5f 100644 --- a/test/moduletest/ability_delegator_test/ability_delegator_registry_module_test.cpp +++ b/test/moduletest/ability_delegator_test/ability_delegator_registry_module_test.cpp @@ -19,7 +19,6 @@ #include "ability_runtime/context/context_impl.h" #include "app_loader.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_delegator_stub.h" #include "ohos_application.h" diff --git a/test/moduletest/ability_delegator_test/delegator_thread_module_test.cpp b/test/moduletest/ability_delegator_test/delegator_thread_module_test.cpp index 248a711f9a..fa9dddd0dd 100644 --- a/test/moduletest/ability_delegator_test/delegator_thread_module_test.cpp +++ b/test/moduletest/ability_delegator_test/delegator_thread_module_test.cpp @@ -20,7 +20,6 @@ #undef private #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing::ext; using namespace OHOS; diff --git a/test/moduletest/ability_delegator_test/iability_monitor_module_test.cpp b/test/moduletest/ability_delegator_test/iability_monitor_module_test.cpp index 42e315e058..f661c9f786 100644 --- a/test/moduletest/ability_delegator_test/iability_monitor_module_test.cpp +++ b/test/moduletest/ability_delegator_test/iability_monitor_module_test.cpp @@ -30,7 +30,6 @@ #undef private #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_delegator_stub.h" using namespace testing; diff --git a/test/moduletest/ability_delegator_test/js_test_runner_module_test.cpp b/test/moduletest/ability_delegator_test/js_test_runner_module_test.cpp index da69403300..52625ddd15 100644 --- a/test/moduletest/ability_delegator_test/js_test_runner_module_test.cpp +++ b/test/moduletest/ability_delegator_test/js_test_runner_module_test.cpp @@ -31,7 +31,6 @@ #include "app_loader.h" #include "event_runner.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi/native_common.h" #include "mock_ability_delegator_stub.h" #include "mock_test_observer_stub.h" diff --git a/test/moduletest/ability_delegator_test/shell_cmd_result_module_test.cpp b/test/moduletest/ability_delegator_test/shell_cmd_result_module_test.cpp index cfe96c86b2..d73e242c9a 100644 --- a/test/moduletest/ability_delegator_test/shell_cmd_result_module_test.cpp +++ b/test/moduletest/ability_delegator_test/shell_cmd_result_module_test.cpp @@ -17,7 +17,6 @@ #include "shell_cmd_result.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing::ext; using namespace OHOS; diff --git a/test/moduletest/ability_manager_client_test/BUILD.gn b/test/moduletest/ability_manager_client_test/BUILD.gn index 72ce459e22..cfea44ecb0 100644 --- a/test/moduletest/ability_manager_client_test/BUILD.gn +++ b/test/moduletest/ability_manager_client_test/BUILD.gn @@ -23,8 +23,11 @@ ohos_moduletest("ability_manager_client_test") { configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + defines = [] + deps = [ "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "//third_party/googletest:gtest_main", ] diff --git a/test/moduletest/ability_manager_client_test/ability_manager_client_test.cpp b/test/moduletest/ability_manager_client_test/ability_manager_client_test.cpp index 2ec3226b9b..0dd7ba4097 100644 --- a/test/moduletest/ability_manager_client_test/ability_manager_client_test.cpp +++ b/test/moduletest/ability_manager_client_test/ability_manager_client_test.cpp @@ -17,8 +17,14 @@ #include "ability_manager_client.h" #include "ability_manager_errors.h" +#include "ability_state_data.h" +#include "element_name.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" +#include "ipc_object_stub.h" +#include "start_options.h" +#include "status_bar_delegate_proxy.h" +#include "ui_extension_session_info.h" +#include "want.h" using namespace testing; using namespace testing::ext; @@ -28,6 +34,9 @@ namespace AAFwk { namespace { const int USER_ID = 100; const size_t SIZE_ONE = 1; +const int32_t ABILITYID = 1002; +const int32_t UID = 10000; +const int REQUESTCODE = 1008; } // namespace class AbilityManagerClientTest : public testing::Test { @@ -36,6 +45,7 @@ public: static void TearDownTestCase(); void SetUp() override; void TearDown() override; + void SetWant(Want& want, const std::string bundleName); }; void AbilityManagerClientTest::SetUpTestCase(void) @@ -50,6 +60,14 @@ void AbilityManagerClientTest::SetUp() void AbilityManagerClientTest::TearDown() {} +void AbilityManagerClientTest::SetWant(Want& want, const std::string bundleName) +{ + AppExecFwk::ElementName name; + name.SetBundleName(bundleName); + name.SetAbilityName("testAbility"); + want.SetElement(name); +} + /** * @tc.name: AbilityManagerClient_DumpSysState_0100 * @tc.desc: DumpSysState @@ -101,7 +119,7 @@ HWTEST_F(AbilityManagerClientTest, AbilityManagerClient_RecordAppExitReason_0100 TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_RecordAppExitReason_0100 start"); ExitReason exitReason = { REASON_JS_ERROR, "Js Error." }; auto result = AbilityManagerClient::GetInstance()->RecordAppExitReason(exitReason); - EXPECT_EQ(result, GET_BUNDLE_INFO_FAILED); + EXPECT_EQ(result, ERR_NAME_NOT_FOUND); TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_RecordAppExitReason_0100 end"); } @@ -115,8 +133,142 @@ HWTEST_F(AbilityManagerClientTest, AbilityManagerClient_RecordProcessExitReason_ TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_RecordProcessExitReason_0100 start"); ExitReason exitReason = { REASON_JS_ERROR, "Js Error." }; auto result = AbilityManagerClient::GetInstance()->RecordAppExitReason(exitReason); - EXPECT_EQ(result, GET_BUNDLE_INFO_FAILED); + EXPECT_EQ(result, ERR_NAME_NOT_FOUND); TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_RecordProcessExitReason_0100 end"); } + +/** + * @tc.name: AbilityManagerClient_RegisterStatusBarDelegate_0100 + * @tc.desc: RegisterStatusBarDelegate + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerClientTest, AbilityManagerClient_RegisterStatusBarDelegate_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_RegisterStatusBarDelegate_001 start"); + sptr impl(new IPCObjectStub()); + sptr delegate(new AbilityRuntime::StatusBarDelegateProxy(impl)); + auto result = AbilityManagerClient::GetInstance()->RegisterStatusBarDelegate(delegate); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_RegisterStatusBarDelegate_001 result %{public}d", result); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_RegisterStatusBarDelegate_001 end"); +} + +/** + * @tc.name: AbilityManagerClient_ScheduleClearRecoveryPageStack_0100 + * @tc.desc: ScheduleClearRecoveryPageStack + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerClientTest, AbilityManagerClient_ScheduleClearRecoveryPageStack_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_ScheduleClearRecoveryPageStack_001 start"); + AbilityManagerClient::GetInstance()->ScheduleClearRecoveryPageStack(); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_ScheduleClearRecoveryPageStack_001 end"); +} + +/** + * @tc.name: AbilityManagerClient_IsValidMissionIds_0100 + * @tc.desc: IsValidMissionIds + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerClientTest, AbilityManagerClient_IsValidMissionIds_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_IsValidMissionIds_001 start"); + std::vector missionIds; + missionIds.push_back(ABILITYID); + std::vector results; + auto result = AbilityManagerClient::GetInstance()->IsValidMissionIds(missionIds, results); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_IsValidMissionIds_001 result %{public}d", result); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_IsValidMissionIds_001 end"); +} + +/** + * @tc.name: AbilityManagerClient_GetForegroundUIAbilities_0100 + * @tc.desc: GetForegroundUIAbilities + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerClientTest, AbilityManagerClient_GetForegroundUIAbilities_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_GetForegroundUIAbilities_001 start"); + std::vector list; + auto result = AbilityManagerClient::GetInstance()->GetForegroundUIAbilities(list); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_GetForegroundUIAbilities_001 result %{public}d", result); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_GetForegroundUIAbilities_001 end"); +} + +/** + * @tc.name: AbilityManagerClient_GetUIExtensionSessionInfo_0100 + * @tc.desc: GetUIExtensionSessionInfo + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerClientTest, AbilityManagerClient_GetUIExtensionSessionInfo_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_GetUIExtensionSessionInfo_001 start"); + sptr token_(new IPCObjectStub()); + UIExtensionSessionInfo uiExtensionSessionInfo; + auto result = AbilityManagerClient::GetInstance()->GetUIExtensionSessionInfo(token_, + uiExtensionSessionInfo, USER_ID); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_GetUIExtensionSessionInfo_001 result %{public}d", result); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_GetUIExtensionSessionInfo_001 end"); +} + +/** + * @tc.name: AbilityManagerClient_StartShortCut_0100 + * @tc.desc: StartShortCut + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerClientTest, AbilityManagerClient_StartShortCut_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_StartShortCut_001 start"); + Want want; + StartOptions startOptions; + SetWant(want, "bundleName"); + auto result = AbilityManagerClient::GetInstance()->StartShortcut(want, startOptions); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_StartShortCut_001 result %{public}d", result); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_StartShortCut_001 end"); +} + +/** + * @tc.name: AbilityManagerClient_NotifyFrozenProcessByRSS_0100 + * @tc.desc: NotifyFrozenProcessByRSS + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerClientTest, AbilityManagerClient_NotifyFrozenProcessByRSS_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_NotifyFrozenProcessByRSS_001 start"); + std::vector pidList; + pidList.push_back(19082); + AbilityManagerClient::GetInstance()->NotifyFrozenProcessByRSS(pidList, UID); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_NotifyFrozenProcessByRSS_001 end"); +} + +/** + * @tc.name: AbilityManagerClient_PreStartMission_0100 + * @tc.desc: PreStartMission + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerClientTest, AbilityManagerClient_PreStartMission_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_PreStartMission_001 start"); + auto result = AbilityManagerClient::GetInstance()->PreStartMission("com.ix.hiservcie", "entry", + "ServiceAbility", "2024-07-19 10:00:00"); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_PreStartMission_001 result %{public}d", result); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_PreStartMission_001 end"); +} + +/** + * @tc.name: AbilityManagerClient_OpenLink_0100 + * @tc.desc: OpenLink + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerClientTest, AbilityManagerClient_OpenLink, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_OpenLink start"); + Want want; + sptr token_(new IPCObjectStub()); + SetWant(want, "bundleName"); + auto result = AbilityManagerClient::GetInstance()->OpenLink(want, token_, + USER_ID, REQUESTCODE); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_OpenLink result %{public}d", result); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerClient_OpenLink end"); +} } // namespace AAFwk } // namespace OHOS diff --git a/test/moduletest/ability_manager_service_dump_test/BUILD.gn b/test/moduletest/ability_manager_service_dump_test/BUILD.gn index 8680b9c2c0..f9e31f9cf9 100644 --- a/test/moduletest/ability_manager_service_dump_test/BUILD.gn +++ b/test/moduletest/ability_manager_service_dump_test/BUILD.gn @@ -29,6 +29,7 @@ ohos_moduletest("ability_manager_service_dump_test") { "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", ] 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 0a40f909e4..9b0f561042 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 @@ -17,6 +17,7 @@ #define private public #define protected public #include "ability_manager_service.h" +#include "mission_list_manager.h" #undef private #undef protected #include "scene_board_judgement.h" @@ -212,9 +213,10 @@ HWTEST_F(AbilityManagerServiceDumpTest, AbilityManagerService_OnAppStateChanged_ EXPECT_NE(abilityRecord, nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - abilityMs_->subManagersHelper_->currentMissionListManager_ = std::make_shared(USER_ID); - EXPECT_NE(abilityMs_->subManagersHelper_->currentMissionListManager_, nullptr); - abilityMs_->subManagersHelper_->currentMissionListManager_->terminateAbilityList_.push_back(abilityRecord); + auto missionListManager = std::make_shared(USER_ID); + missionListManager->Init(); + abilityMs_->subManagersHelper_->currentMissionListManager_ = missionListManager; + missionListManager->terminateAbilityList_.push_back(abilityRecord); abilityMs_->subManagersHelper_->currentDataAbilityManager_ = std::make_shared(); EXPECT_NE(abilityMs_->subManagersHelper_->currentDataAbilityManager_, nullptr); @@ -224,7 +226,7 @@ HWTEST_F(AbilityManagerServiceDumpTest, AbilityManagerService_OnAppStateChanged_ info.state = AppState::TERMINATED; abilityMs_->OnAppStateChanged(info); - abilityRecord = abilityMs_->subManagersHelper_->currentMissionListManager_->terminateAbilityList_.front(); + abilityRecord = missionListManager->terminateAbilityList_.front(); EXPECT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetAppState(), AppState::TERMINATED); } diff --git a/test/moduletest/ability_test/BUILD.gn b/test/moduletest/ability_test/BUILD.gn index 2b1cb7c2a5..338cc91f6c 100644 --- a/test/moduletest/ability_test/BUILD.gn +++ b/test/moduletest/ability_test/BUILD.gn @@ -24,7 +24,6 @@ config("module_private_config") { cflags += [ "-DBINDER_IPC_32BIT" ] } include_dirs = [ - "//third_party/json/include", "${ability_runtime_innerkits_path}/ability_manager/include", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", "${ability_runtime_services_path}/common/include", @@ -58,7 +57,6 @@ ohos_moduletest("ability_moduletest") { 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:ability_thread", "${ability_runtime_native_path}/ability/native:abilitykit_native", @@ -83,6 +81,7 @@ ohos_moduletest("ability_moduletest") { "hilog:libhilog", "init:libbegetutil", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", "relational_store:native_appdatafwk", "relational_store:native_dataability", @@ -142,6 +141,7 @@ ohos_moduletest("ability_conetxt_test") { "hilog:libhilog", "init:libbegetutil", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", "relational_store:native_appdatafwk", "relational_store:native_dataability", @@ -180,6 +180,7 @@ ohos_moduletest("ability_thread_call_request_module_test") { "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", "hilog:libhilog", + "json:nlohmann_json_static", "napi:ace_napi", ] } @@ -224,6 +225,7 @@ ohos_moduletest("data_ability_operation_moduletest") { "c_utils:utils", "hilog:libhilog", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", "relational_store:native_appdatafwk", "relational_store:native_dataability", @@ -279,6 +281,7 @@ ohos_moduletest("data_ability_helper_module_test") { "eventhandler:libeventhandler", "hilog:libhilog", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", "relational_store:native_appdatafwk", "relational_store:native_dataability", @@ -326,6 +329,7 @@ ohos_moduletest("ability_post_event_timeout_test") { "eventhandler:libeventhandler", "hilog:libhilog", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", "relational_store:native_appdatafwk", "relational_store:native_dataability", diff --git a/test/moduletest/ability_test/ability_test.cpp b/test/moduletest/ability_test/ability_test.cpp index cdd8ebd46e..5ff98d231e 100644 --- a/test/moduletest/ability_test/ability_test.cpp +++ b/test/moduletest/ability_test/ability_test.cpp @@ -1153,7 +1153,7 @@ HWTEST_F(AbilityTerminateTest, AaFwk_IAbilityManager_AddFreeInstallObserver_0100 OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); sptr abms = iface_cast(remoteObject_); EXPECT_NE(abms, nullptr); - EXPECT_EQ(0, abms->AddFreeInstallObserver(nullptr)); + EXPECT_EQ(0, abms->AddFreeInstallObserver(nullptr, nullptr)); GTEST_LOG_(INFO) << "AaFwk_IAbilityManager_AddFreeInstallObserver_0100"; } diff --git a/test/moduletest/ability_timeout_module_test/BUILD.gn b/test/moduletest/ability_timeout_module_test/BUILD.gn index 0814506457..f55fbafe3a 100644 --- a/test/moduletest/ability_timeout_module_test/BUILD.gn +++ b/test/moduletest/ability_timeout_module_test/BUILD.gn @@ -63,6 +63,7 @@ ohos_moduletest("ability_timeout_module_test") { "${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}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:event_report", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_services_path}/common:task_handler_wrap", diff --git a/test/moduletest/ability_timeout_module_test/ability_timeout_module_test.cpp b/test/moduletest/ability_timeout_module_test/ability_timeout_module_test.cpp index 0b3f76cd4f..2f8f51e310 100644 --- a/test/moduletest/ability_timeout_module_test/ability_timeout_module_test.cpp +++ b/test/moduletest/ability_timeout_module_test/ability_timeout_module_test.cpp @@ -18,6 +18,7 @@ #define protected public #include "ability_manager_service.h" #include "ability_event_handler.h" +#include "mission_list_manager.h" #undef private #undef protected @@ -121,13 +122,7 @@ void AbilityTimeoutModuleTest::SetUp() void AbilityTimeoutModuleTest::TearDown() { WaitUntilTaskFinishedByTimer(); - abilityMs_->subManagersHelper_->currentMissionListManager_->terminateAbilityList_.clear(); - abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_->missions_.clear(); - abilityMs_->subManagersHelper_->currentMissionListManager_->defaultStandardList_->missions_.clear(); - abilityMs_->subManagersHelper_->currentMissionListManager_->defaultSingleList_->missions_.clear(); - abilityMs_->subManagersHelper_->currentMissionListManager_->currentMissionLists_.clear(); - abilityMs_->subManagersHelper_->currentMissionListManager_->currentMissionLists_ - .push_front(abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_); + abilityMs_->subManagersHelper_->currentMissionListManager_.reset(); } void AbilityTimeoutModuleTest::MockOnStart() @@ -185,11 +180,13 @@ void AbilityTimeoutModuleTest::MockOnStop() std::shared_ptr AbilityTimeoutModuleTest::CreateRootLauncher() { - if (!abilityMs_->subManagersHelper_->currentMissionListManager_ || - !abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_) { + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + if (!curListManager || + !curListManager->launcherList_) { return nullptr; } - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; + auto lauList = curListManager->launcherList_; AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; abilityRequest.abilityInfo.name = AbilityConfig::LAUNCHER_ABILITY_NAME; @@ -208,11 +205,13 @@ std::shared_ptr AbilityTimeoutModuleTest::CreateRootLauncher() std::shared_ptr AbilityTimeoutModuleTest::CreateLauncherAbility() { - if (!abilityMs_->subManagersHelper_->currentMissionListManager_ || - !abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_) { + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + if (!curListManager || + !curListManager->launcherList_) { return nullptr; } - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; + auto lauList = curListManager->launcherList_; AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; abilityRequest.abilityInfo.name = "com.ix.hiworld.SecAbility"; @@ -230,7 +229,8 @@ std::shared_ptr AbilityTimeoutModuleTest::CreateLauncherAbility() std::shared_ptr AbilityTimeoutModuleTest::CreateServiceAbility() { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); if (!curListManager) { return nullptr; } @@ -247,7 +247,8 @@ std::shared_ptr AbilityTimeoutModuleTest::CreateServiceAbility() std::shared_ptr AbilityTimeoutModuleTest::CreateExtensionAbility() { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); if (!curListManager) { return nullptr; } @@ -265,7 +266,8 @@ std::shared_ptr AbilityTimeoutModuleTest::CreateExtensionAbility( std::shared_ptr AbilityTimeoutModuleTest::CreateCommonAbility() { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); if (!curListManager) { return nullptr; } @@ -301,8 +303,10 @@ HWTEST_F(AbilityTimeoutModuleTest, OnAbilityDied_001, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); int maxRestart = -1; @@ -316,7 +320,7 @@ HWTEST_F(AbilityTimeoutModuleTest, OnAbilityDied_001, TestSize.Level1) EXPECT_TRUE(rootLauncher->IsLauncherRoot()); GTEST_LOG_(INFO) << "userId:" << abilityMs_->GetUserId(); - GTEST_LOG_(INFO) << "currentmanager userId" << abilityMs_->subManagersHelper_->currentMissionListManager_->userId_; + GTEST_LOG_(INFO) << "currentmanager userId" << curListManager->userId_; // died rootlauncher ability rootLauncher->SetAbilityState(AbilityState::FOREGROUND); @@ -341,8 +345,10 @@ HWTEST_F(AbilityTimeoutModuleTest, OnAbilityDied_002, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); int maxRestart = -1; @@ -359,14 +365,14 @@ HWTEST_F(AbilityTimeoutModuleTest, OnAbilityDied_002, TestSize.Level1) // add common ability to abilityMs auto commonAbility = CreateCommonAbility(); - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonAbility); topAbility->SetAbilityState(AbilityState::FOREGROUND); // died rootlauncher ability abilityMs_->OnAbilityDied(rootLauncher); WaitUntilTaskFinishedByTimer(); - topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_TRUE(topAbility != nullptr); EXPECT_EQ(topAbility, rootLauncher); EXPECT_TRUE(lauList->GetAbilityRecordByToken(rootLauncher->GetToken()) != nullptr); @@ -386,8 +392,10 @@ HWTEST_F(AbilityTimeoutModuleTest, OnAbilityDied_003, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); int maxRestart = -1; @@ -427,12 +435,12 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_001, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); - // add rootlauncher to abilityMs. auto ability = CreateRootLauncher(); auto rootLauncher = lauList->GetTopAbility(); @@ -457,9 +465,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_002, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); // add rootlauncher to abilityMs. @@ -471,7 +480,7 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_002, TestSize.Level1) // add common ability to abilityMs auto commonAbility = CreateCommonAbility(); - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonAbility); // rootlauncher load timeout @@ -493,9 +502,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_003, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); // add rootlauncher to abilityMs. @@ -507,14 +517,14 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_003, TestSize.Level1) // add common ability to abilityMs as caller auto callerAbility = CreateCommonAbility(); - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, callerAbility); callerAbility->SetAbilityState(AbilityState::FOREGROUND); // add common ability to abilityMs auto commonAbility = CreateCommonAbility(); commonAbility->AddCallerRecord(callerAbility->GetToken(), -1); - topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonAbility); // rootlauncher load timeout @@ -536,9 +546,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_004, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); // add rootlauncher to abilityMs. @@ -550,14 +561,14 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_004, TestSize.Level1) // add launcher ability to abilityMs as caller auto callerAbility = CreateLauncherAbility(); - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, callerAbility); callerAbility->SetAbilityState(AbilityState::FOREGROUND); // add common ability to abilityMs auto commonAbility = CreateCommonAbility(); commonAbility->AddCallerRecord(callerAbility->GetToken(), -1); - topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonAbility); // rootlauncher load timeout @@ -579,9 +590,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_005, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); // add rootlauncher to abilityMs. @@ -597,8 +609,8 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_005, TestSize.Level1) // add common ability to abilityMs auto commonAbility = CreateCommonAbility(); commonAbility->AddCallerRecord(callerAbility->GetToken(), -1); - auto currentList = abilityMs_->subManagersHelper_->currentMissionListManager_->currentMissionLists_; - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto currentList = curListManager->currentMissionLists_; + auto topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonAbility); // rootlauncher load timeout @@ -620,9 +632,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_006, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); // add rootlauncher to abilityMs. @@ -638,8 +651,8 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_006, TestSize.Level1) // add common ability to abilityMs auto commonAbility = CreateCommonAbility(); commonAbility->AddCallerRecord(callerAbility->GetToken(), -1); - auto currentList = abilityMs_->subManagersHelper_->currentMissionListManager_->currentMissionLists_; - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto currentList = curListManager->currentMissionLists_; + auto topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonAbility); // rootlauncher load timeout @@ -661,9 +674,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_007, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); // add rootlauncher to abilityMs. @@ -675,7 +689,7 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleLoadTimeOut_007, TestSize.Level1) // add common laucher ability to abilityMs auto commonLauncherAbility = CreateLauncherAbility(); - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonLauncherAbility); // rootlauncher load timeout @@ -697,9 +711,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_001, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); @@ -728,9 +743,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_002, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); // add rootlauncher to abilityMs. @@ -742,7 +758,7 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_002, TestSize.Level1) // add common ability to abilityMs auto commonAbility = CreateCommonAbility(); - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonAbility); commonAbility->SetAbilityState(AbilityState::FOREGROUNDING); @@ -765,9 +781,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_003, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); // add rootlauncher to abilityMs. @@ -779,14 +796,14 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_003, TestSize.Level1) // add common ability to abilityMs as caller auto callerAbility = CreateCommonAbility(); - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = curListManager>GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, callerAbility); callerAbility->SetAbilityState(AbilityState::FOREGROUND); // add common ability to abilityMs auto commonAbility = CreateCommonAbility(); commonAbility->AddCallerRecord(callerAbility->GetToken(), -1); - topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonAbility); commonAbility->SetAbilityState(AbilityState::FOREGROUNDING); @@ -809,9 +826,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_004, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); // add rootlauncher to abilityMs. @@ -823,14 +841,14 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_004, TestSize.Level1) // add launcher ability to abilityMs as caller auto callerAbility = CreateLauncherAbility(); - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, callerAbility); callerAbility->SetAbilityState(AbilityState::FOREGROUND); // add common ability to abilityMs auto commonAbility = CreateCommonAbility(); commonAbility->AddCallerRecord(callerAbility->GetToken(), -1); - topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonAbility); commonAbility->SetAbilityState(AbilityState::FOREGROUNDING); @@ -853,9 +871,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_005, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); // add rootlauncher to abilityMs. @@ -871,8 +890,8 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_005, TestSize.Level1) // add common ability to abilityMs auto commonAbility = CreateCommonAbility(); commonAbility->AddCallerRecord(callerAbility->GetToken(), -1); - auto currentList = abilityMs_->subManagersHelper_->currentMissionListManager_->currentMissionLists_; - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto currentList = curListManager->currentMissionLists_; + auto topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonAbility); commonAbility->SetAbilityState(AbilityState::FOREGROUNDING); @@ -895,9 +914,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_006, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); // add rootlauncher to abilityMs. @@ -913,8 +933,8 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_006, TestSize.Level1) // add common ability to abilityMs auto commonAbility = CreateCommonAbility(); commonAbility->AddCallerRecord(callerAbility->GetToken(), -1); - auto currentList = abilityMs_->subManagersHelper_->currentMissionListManager_->currentMissionLists_; - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto currentList = curListManager->currentMissionLists_; + auto topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonAbility); commonAbility->SetAbilityState(AbilityState::FOREGROUNDING); @@ -937,9 +957,10 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_007, TestSize.Level1) { // test config is success. EXPECT_TRUE(abilityMs_ != nullptr); - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; + auto curListManager = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get()); + EXPECT_TRUE(curListManager != nullptr); + auto lauList = curListManager->launcherList_; EXPECT_TRUE(lauList != nullptr); // add rootlauncher to abilityMs. @@ -951,7 +972,7 @@ HWTEST_F(AbilityTimeoutModuleTest, HandleForegroundTimeOut_007, TestSize.Level1) // add common laucher ability to abilityMs auto commonLauncherAbility = CreateLauncherAbility(); - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = curListManager->GetCurrentTopAbilityLocked(); EXPECT_EQ(topAbility, commonLauncherAbility); commonLauncherAbility->SetAbilityState(AbilityState::FOREGROUNDING); diff --git a/test/moduletest/app_mgr_client_test/app_mgr_client_test.cpp b/test/moduletest/app_mgr_client_test/app_mgr_client_test.cpp index 692319aaad..c0929af8ee 100644 --- a/test/moduletest/app_mgr_client_test/app_mgr_client_test.cpp +++ b/test/moduletest/app_mgr_client_test/app_mgr_client_test.cpp @@ -18,7 +18,6 @@ #include "app_mgr_client.h" #include "configuration.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_configuration_observer.h" #include "mock_native_token.h" #include "mock_sa_call.h" diff --git a/test/moduletest/common/ams/BUILD.gn b/test/moduletest/common/ams/BUILD.gn index 7c2c4c6f93..1936399484 100644 --- a/test/moduletest/common/ams/BUILD.gn +++ b/test/moduletest/common/ams/BUILD.gn @@ -24,10 +24,8 @@ ohos_source_set("appmgr_mst_source") { defines = [ "AMS_LOG_TAG = \"AppMgrService\"" ] - include_dirs = [ - "//third_party/json/include", - "${ability_runtime_test_path}/mock/services_appmgr_test/include", - ] + include_dirs = + [ "${ability_runtime_test_path}/mock/services_appmgr_test/include" ] public_configs = [ "${ability_runtime_test_path}/moduletest:services_module_test_config", @@ -80,6 +78,7 @@ ohos_source_set("appmgr_mst_source") { "init:libbeget_proxy", "init:libbegetutil", "ipc:ipc_core", + "json:nlohmann_json_static", ] if (ability_runtime_graphics) { diff --git a/test/moduletest/common/ams/ability_running_record_test/BUILD.gn b/test/moduletest/common/ams/ability_running_record_test/BUILD.gn index 10befd26b5..5661f2f3ba 100644 --- a/test/moduletest/common/ams/ability_running_record_test/BUILD.gn +++ b/test/moduletest/common/ams/ability_running_record_test/BUILD.gn @@ -34,6 +34,7 @@ ohos_moduletest("AmsAbilityRunningRecordModuleTest") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "appspawn:appspawn_client", "bundle_framework:appexecfwk_base", "ffrt:libffrt", 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 5179dcf224..c54cd3648f 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 @@ -21,7 +21,6 @@ #include "application_info.h" #include "app_running_record.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_token.h" using namespace testing::ext; diff --git a/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp b/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp index 2bc86a3960..e491001a13 100644 --- a/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp +++ b/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp @@ -24,7 +24,6 @@ #include "app_mgr_interface.h" #include "iremote_object.h" #include "app_state_callback_proxy.h" -#include "hilog_wrapper.h" #include "refbase.h" #include "mock_bundle_manager.h" #include "mock_ability_token.h" @@ -232,7 +231,6 @@ void AmsAppLifeCycleModuleTest::ChangeAbilityStateToForegroud(const sptrGetRecordId(); - appRunningRecord->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(recordId); } } @@ -253,7 +251,6 @@ void AmsAppLifeCycleModuleTest::ChangeAbilityStateToBackGroud(const sptrGetRecordId(); - appRunningRecord->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(recordId); } } diff --git a/test/moduletest/common/ams/app_mgr_service_test/BUILD.gn b/test/moduletest/common/ams/app_mgr_service_test/BUILD.gn index 8f11d04430..a643d934ae 100644 --- a/test/moduletest/common/ams/app_mgr_service_test/BUILD.gn +++ b/test/moduletest/common/ams/app_mgr_service_test/BUILD.gn @@ -44,6 +44,7 @@ ohos_moduletest("AmsAppMgrServiceModuleTest") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", "appspawn:appspawn_client", diff --git a/test/moduletest/common/ams/app_recent_list_test/BUILD.gn b/test/moduletest/common/ams/app_recent_list_test/BUILD.gn index a92a1cd6b6..7dc4bf0519 100644 --- a/test/moduletest/common/ams/app_recent_list_test/BUILD.gn +++ b/test/moduletest/common/ams/app_recent_list_test/BUILD.gn @@ -36,6 +36,7 @@ ohos_moduletest("AmsAppRecentListModuleTest") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "appspawn:appspawn_client", "bundle_framework:appexecfwk_base", "ffrt:libffrt", diff --git a/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp b/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp index b93919436c..a1aeb132d0 100644 --- a/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp +++ b/test/moduletest/common/ams/app_recent_list_test/ams_app_recent_list_module_test.cpp @@ -22,7 +22,6 @@ #include "refbase.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "mock_bundle_manager.h" #include "mock_ability_token.h" diff --git a/test/moduletest/common/ams/app_service_flow_test/BUILD.gn b/test/moduletest/common/ams/app_service_flow_test/BUILD.gn index 5bbf846e9e..36a6a4b24a 100644 --- a/test/moduletest/common/ams/app_service_flow_test/BUILD.gn +++ b/test/moduletest/common/ams/app_service_flow_test/BUILD.gn @@ -38,6 +38,7 @@ ohos_moduletest("AmsAppServiceFlowModuleTest") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "appspawn:appspawn_client", "bundle_framework:appexecfwk_base", "ffrt:libffrt", diff --git a/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp b/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp index bbc685c412..64731d89a7 100644 --- a/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp +++ b/test/moduletest/common/ams/app_service_flow_test/ams_app_service_flow_module_test.cpp @@ -24,7 +24,6 @@ #include "app_mgr_service_inner.h" #undef private #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_token.h" #include "mock_bundle_manager.h" #include "mock_ability_token.h" @@ -189,11 +188,9 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_BackKey_001, TestSize.Level1) // simulate press back key serviceInner_->UpdateAbilityState(abilityB1Token, AbilityState::ABILITY_STATE_FOREGROUND); - testAppB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppB.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_BACKGROUND); serviceInner_->UpdateAbilityState(abilityA2Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppB.GetAbility(abilityB1Token)->GetState()); @@ -229,10 +226,8 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_BackKey_002, TestSize.Level1) EXPECT_CALL(*(testAppA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); // simulate press back key serviceInner_->UpdateAbilityState(abilityB1Token, AbilityState::ABILITY_STATE_FOREGROUND); - testAppB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppB.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppB.GetAbility(abilityB1Token)->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppB.appRecord_->GetState()); @@ -243,10 +238,8 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_BackKey_002, TestSize.Level1) EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); // simulate press back key again serviceInner_->UpdateAbilityState(abilityC1Token, AbilityState::ABILITY_STATE_FOREGROUND); - testAppB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testappC.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(abilityB1Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppB.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testappC.GetAbility(abilityC1Token)->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testappC.appRecord_->GetState()); @@ -326,13 +319,11 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_BackKey_004, TestSize.Level1) serviceInner_->UpdateAbilityState(abilityB2Token, AbilityState::ABILITY_STATE_FOREGROUND); serviceInner_->UpdateAbilityState(abilityB1Token, AbilityState::ABILITY_STATE_FOREGROUND); - testAppB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppB.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_BACKGROUND); serviceInner_->UpdateAbilityState(abilityA2Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(abilityA1Token, false); @@ -380,10 +371,8 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_BackKey_005, TestSize.Level1) // simulate press back key, AppA to background and exit. serviceInner_->UpdateAbilityState(abilityB1Token, AbilityState::ABILITY_STATE_FOREGROUND); - testAppB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppB.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(abilityA1Token, false); serviceInner_->AbilityTerminated(abilityA1Token); @@ -398,10 +387,8 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_BackKey_005, TestSize.Level1) EXPECT_CALL(*(testAppB.mockAppScheduler_), ScheduleCleanAbility(_, _)).Times(1); // simulate press back key again serviceInner_->UpdateAbilityState(abilityC1Token, AbilityState::ABILITY_STATE_FOREGROUND); - testappC.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testappC.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(abilityB1Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppB.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(abilityB1Token, false); serviceInner_->AbilityTerminated(abilityB1Token); @@ -438,13 +425,11 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOff_001, TestSize.Level1 // simulate press screenOff key serviceInner_->UpdateAbilityState(abilityB1Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppB.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(abilityB1Token, false); serviceInner_->AbilityTerminated(abilityB1Token); serviceInner_->ApplicationTerminated(testAppB.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(abilityA1Token, false); serviceInner_->AbilityTerminated(abilityA1Token); @@ -490,11 +475,9 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOff_002, TestSize.Level1 // simulate press screenOff key serviceInner_->UpdateAbilityState(abilityB1Token, AbilityState::ABILITY_STATE_BACKGROUND); serviceInner_->UpdateAbilityState(abilityB2Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppB.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_BACKGROUND); serviceInner_->UpdateAbilityState(abilityA2Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppB.GetAbility(abilityB1Token)->GetState()); @@ -535,13 +518,11 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOff_003, TestSize.Level1 // simulate press screenOff key serviceInner_->UpdateAbilityState(abilityB1Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppB.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(abilityB1Token, false); serviceInner_->AbilityTerminated(abilityB1Token); serviceInner_->ApplicationTerminated(testAppB.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(abilityA1Token, false); serviceInner_->AbilityTerminated(abilityA1Token); @@ -590,7 +571,6 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOff_004, TestSize.Level1 // simulate press screenOff key serviceInner_->UpdateAbilityState(abilityB1Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppB.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(abilityB1Token, false); serviceInner_->AbilityTerminated(abilityB1Token); @@ -598,7 +578,6 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOff_004, TestSize.Level1 serviceInner_->AbilityTerminated(abilityB2Token); serviceInner_->ApplicationTerminated(testAppB.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); EXPECT_EQ(testAppB.GetAbility(abilityB1Token), nullptr); @@ -638,7 +617,6 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOn_001, TestSize.Level1) // simulate press ScreenOn key serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_FOREGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility(abilityA1Token)->GetState()); @@ -678,7 +656,6 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOn_002, TestSize.Level1) serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_FOREGROUND); serviceInner_->UpdateAbilityState(abilityA2Token, AbilityState::ABILITY_STATE_FOREGROUND); serviceInner_->UpdateAbilityState(abilityA3Token, AbilityState::ABILITY_STATE_FOREGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility(abilityA1Token)->GetState()); @@ -723,9 +700,7 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOn_003, TestSize.Level1) serviceInner_->UpdateAbilityState(abilityA2Token, AbilityState::ABILITY_STATE_FOREGROUND); serviceInner_->UpdateAbilityState(abilityB1Token, AbilityState::ABILITY_STATE_FOREGROUND); serviceInner_->UpdateAbilityState(abilityB2Token, AbilityState::ABILITY_STATE_FOREGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppA.appRecord_->GetRecordId()); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppB.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility(abilityA1Token)->GetState()); @@ -765,20 +740,17 @@ HWTEST_F(AmsAppServiceFlowModuleTest, ServiceFlow_ScreenOnAndOff_001, TestSize.L // simulate press ScreenOn key serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_FOREGROUND); serviceInner_->UpdateAbilityState(abilityA2Token, AbilityState::ABILITY_STATE_FOREGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppA.appRecord_->GetRecordId()); // simulate press ScreenOff key serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_BACKGROUND); serviceInner_->UpdateAbilityState(abilityA2Token, AbilityState::ABILITY_STATE_BACKGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppA.appRecord_->GetRecordId()); } // simulate press ScreenOn key serviceInner_->UpdateAbilityState(abilityA1Token, AbilityState::ABILITY_STATE_FOREGROUND); serviceInner_->UpdateAbilityState(abilityA2Token, AbilityState::ABILITY_STATE_FOREGROUND); - testAppA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppA.GetAbility(abilityA1Token)->GetState()); diff --git a/test/moduletest/common/ams/ipc_ams_mgr_test/BUILD.gn b/test/moduletest/common/ams/ipc_ams_mgr_test/BUILD.gn index c75f23f58c..8f64b85869 100644 --- a/test/moduletest/common/ams/ipc_ams_mgr_test/BUILD.gn +++ b/test/moduletest/common/ams/ipc_ams_mgr_test/BUILD.gn @@ -47,6 +47,7 @@ ohos_moduletest("AmsIpcAmsmgrModuleTest") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", "appspawn:appspawn_client", diff --git a/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp b/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp index 1fb9db6f10..03c53706eb 100644 --- a/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp +++ b/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp @@ -28,7 +28,6 @@ #undef protected #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_app_spawn_socket.h" using namespace testing::ext; diff --git a/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp b/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp index dbcc9534c8..4231103506 100644 --- a/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp +++ b/test/moduletest/common/ams/service_event_drive_test/ams_service_event_drive_module_test.cpp @@ -20,7 +20,6 @@ #undef private #undef protected #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_native_token.h" #include "semaphore_ex.h" diff --git a/test/moduletest/common/ams/service_start_process_test/BUILD.gn b/test/moduletest/common/ams/service_start_process_test/BUILD.gn index 461d9b326b..f8bb32fb95 100644 --- a/test/moduletest/common/ams/service_start_process_test/BUILD.gn +++ b/test/moduletest/common/ams/service_start_process_test/BUILD.gn @@ -36,6 +36,7 @@ ohos_moduletest("AmsServiceStartModuleTest") { ] external_deps = [ + "access_token:libaccesstoken_sdk", "appspawn:appspawn_client", "bundle_framework:appexecfwk_base", "ffrt:libffrt", diff --git a/test/moduletest/common/ams/service_start_process_test/ams_service_start_process_module_test.cpp b/test/moduletest/common/ams/service_start_process_test/ams_service_start_process_module_test.cpp index d1639e5341..4e1022f977 100644 --- a/test/moduletest/common/ams/service_start_process_test/ams_service_start_process_module_test.cpp +++ b/test/moduletest/common/ams/service_start_process_test/ams_service_start_process_module_test.cpp @@ -21,7 +21,6 @@ #undef protected #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing::ext; using namespace OHOS::AppExecFwk; diff --git a/test/moduletest/common/ams/specified_ability_service_test/BUILD.gn b/test/moduletest/common/ams/specified_ability_service_test/BUILD.gn index a68be396a5..22592243ae 100644 --- a/test/moduletest/common/ams/specified_ability_service_test/BUILD.gn +++ b/test/moduletest/common/ams/specified_ability_service_test/BUILD.gn @@ -29,6 +29,7 @@ ohos_moduletest("specified_ability_service_test") { "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", diff --git a/test/moduletest/common/ams/specified_ability_service_test/specified_ability_service_test.cpp b/test/moduletest/common/ams/specified_ability_service_test/specified_ability_service_test.cpp index 156caf1fbc..761686d2a0 100644 --- a/test/moduletest/common/ams/specified_ability_service_test/specified_ability_service_test.cpp +++ b/test/moduletest/common/ams/specified_ability_service_test/specified_ability_service_test.cpp @@ -25,6 +25,7 @@ #define protected public #include "ability_manager_errors.h" #include "ability_manager_service.h" +#include "mission_list_manager.h" #undef private #undef protected @@ -112,8 +113,9 @@ HWTEST_F(SpecifiedAbilityServiceTest, OnAcceptWantResponse_001, TestSize.Level1) abilityMgrServ_->subManagersHelper_->InitMissionListManager(11, true); Want want; want.SetElementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); - EXPECT_TRUE(abilityMgrServ_->subManagersHelper_->currentMissionListManager_); - abilityMgrServ_->subManagersHelper_->currentMissionListManager_->EnqueueWaitingAbility(abilityRequest); + auto missionListMgr = abilityMgrServ_->subManagersHelper_->currentMissionListManager_; + EXPECT_TRUE(missionListMgr); + reinterpret_cast(missionListMgr.get())->EnqueueWaitingAbility(abilityRequest); abilityMgrServ_->OnAcceptWantResponse(want, "flag"); EXPECT_EQ(false, abilityRecord->IsNewWant()); diff --git a/test/moduletest/mission_dump_test/BUILD.gn b/test/moduletest/mission_dump_test/BUILD.gn index acfb762509..ea13cf3bc7 100644 --- a/test/moduletest/mission_dump_test/BUILD.gn +++ b/test/moduletest/mission_dump_test/BUILD.gn @@ -42,6 +42,7 @@ ohos_moduletest("mission_dump_test") { "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_appmgr_mock", diff --git a/test/moduletest/mission_dump_test/mission_dump_test.cpp b/test/moduletest/mission_dump_test/mission_dump_test.cpp index 06e0a75a2c..09304c6ed9 100644 --- a/test/moduletest/mission_dump_test/mission_dump_test.cpp +++ b/test/moduletest/mission_dump_test/mission_dump_test.cpp @@ -19,6 +19,7 @@ #include "ability_manager_service.h" #include "ability_event_handler.h" #include "ams_configuration_parameter.h" +#include "mission_list_manager.h" #undef private #undef protected @@ -32,6 +33,7 @@ #include "mock_ability_token.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" + using namespace testing; using namespace testing::ext; using namespace OHOS::AppExecFwk; diff --git a/test/moduletest/mock/include/appmgr/mock_ability_mgr_host.h b/test/moduletest/mock/include/appmgr/mock_ability_mgr_host.h index 5527e22111..16c3af0a20 100644 --- a/test/moduletest/mock/include/appmgr/mock_ability_mgr_host.h +++ b/test/moduletest/mock/include/appmgr/mock_ability_mgr_host.h @@ -59,7 +59,7 @@ public: virtual int StartAbilityAsCaller(const Want& want, const sptr& callerToken, const sptr& asCallerSourceToken, int32_t userId = DEFAULT_INVAL_VALUE, - int requestCode = -1, bool isSendDialogResult = false) override + int requestCode = -1) override { return 0; } diff --git a/test/moduletest/mock/include/mock_ability_manager_proxy.h b/test/moduletest/mock/include/mock_ability_manager_proxy.h index 989ddbb47b..3469ac2a65 100644 --- a/test/moduletest/mock/include/mock_ability_manager_proxy.h +++ b/test/moduletest/mock/include/mock_ability_manager_proxy.h @@ -18,7 +18,6 @@ #include "gmock/gmock.h" #include "ability_manager_interface.h" -#include "hilog_wrapper.h" #include "iremote_proxy.h" namespace OHOS { @@ -32,8 +31,8 @@ public: MOCK_METHOD2(StartAbility, int(const Want& want, int requestCode)); MOCK_METHOD3(StartAbility, int(const Want& want, const sptr& callerToken, int requestCode)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD6(StartAbilityAsCaller, int(const Want &want, const StartOptions &startOptions, const sptr &callerToken, sptr asCallerSourceToken, int32_t userId, int requestCode)); @@ -57,6 +56,7 @@ public: MOCK_METHOD1(GetMissionIdByToken, int32_t(const sptr& token)); MOCK_METHOD2(KillProcess, int(const std::string&, const bool clearPageStack)); MOCK_METHOD2(UninstallApp, int(const std::string&, int32_t)); + MOCK_METHOD3(UninstallApp, int32_t(const std::string&, int32_t, int32_t)); MOCK_METHOD4(OnRemoteRequest, int(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)); MOCK_METHOD3(StartAbility, int(const Want& want, const sptr& callerToken, int requestCode)); MOCK_METHOD2( diff --git a/test/moduletest/mock/include/mock_ability_mgr_service.h b/test/moduletest/mock/include/mock_ability_mgr_service.h index e57037032f..bdf9fa4195 100644 --- a/test/moduletest/mock/include/mock_ability_mgr_service.h +++ b/test/moduletest/mock/include/mock_ability_mgr_service.h @@ -27,8 +27,8 @@ public: MOCK_METHOD3(StartAbility, int(const Want& want, int32_t userId, int requestCode)); MOCK_METHOD4(StartAbility, int(const Want& want, const sptr& callerToken, int32_t userId, int requestCode)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD6(StartAbilityAsCaller, int(const Want &want, const StartOptions &startOptions, const sptr &callerToken, sptr asCallerSourceToken, int32_t userId, int requestCode)); @@ -65,6 +65,7 @@ public: MOCK_METHOD2(GetAbilityTokenByCalleeObj, void(const sptr &callStub, sptr &token)); MOCK_METHOD2(KillProcess, int(const std::string&, const bool clearPageStack)); MOCK_METHOD2(UninstallApp, int(const std::string&, int32_t)); + MOCK_METHOD3(UninstallApp, int32_t(const std::string&, int32_t, int32_t)); MOCK_METHOD4(OnRemoteRequest, int(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo& wantSenderInfo, const sptr& callerToken)); @@ -189,7 +190,8 @@ public: return 0; } - virtual int RegisterWindowManagerServiceHandler(const sptr& handler) override + virtual int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true) override { return 0; } diff --git a/test/moduletest/mock/include/mock_bundle_mgr.h b/test/moduletest/mock/include/mock_bundle_mgr.h index 5afeea0231..4469ddf249 100644 --- a/test/moduletest/mock/include/mock_bundle_mgr.h +++ b/test/moduletest/mock/include/mock_bundle_mgr.h @@ -329,10 +329,6 @@ public: bool GetApplicationInfo( const std::string& appName, const ApplicationFlag flag, const int userId, ApplicationInfo& appInfo) override; - virtual bool GetBundleGidsByUid(const std::string& bundleName, const int& uid, std::vector& gids) override - { - return true; - } bool ImplicitQueryInfos(const Want& want, int32_t flags, int32_t userId, bool withDefault, std::vector& abilityInfos, std::vector& extensionInfos) override; diff --git a/test/moduletest/mock/src/appmgr/system_ability_helper.cpp b/test/moduletest/mock/src/appmgr/system_ability_helper.cpp index 0343f88048..e4599652e3 100644 --- a/test/moduletest/mock/src/appmgr/system_ability_helper.cpp +++ b/test/moduletest/mock/src/appmgr/system_ability_helper.cpp @@ -18,7 +18,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_mgr_host.h" #include "system_ability_definition.h" diff --git a/test/moduletest/mock/src/mock_bundle_mgr.cpp b/test/moduletest/mock/src/mock_bundle_mgr.cpp index 3bb178201a..6b4e65dffb 100644 --- a/test/moduletest/mock/src/mock_bundle_mgr.cpp +++ b/test/moduletest/mock/src/mock_bundle_mgr.cpp @@ -16,7 +16,6 @@ #include "mock_bundle_mgr.h" #include "ability_info.h" #include "application_info.h" -#include "hilog_wrapper.h" #include "ability_config.h" using namespace OHOS::AAFwk; diff --git a/test/moduletest/mock/src/ui_service_mgr_client_mock.cpp b/test/moduletest/mock/src/ui_service_mgr_client_mock.cpp index ab18633a13..965510d981 100644 --- a/test/moduletest/mock/src/ui_service_mgr_client_mock.cpp +++ b/test/moduletest/mock/src/ui_service_mgr_client_mock.cpp @@ -20,7 +20,6 @@ #include "ability_manager_client.h" #include "dialog_callback_stub.h" #include "display_manager.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" #include "iservice_registry.h" diff --git a/test/moduletest/on_new_want_module_test/BUILD.gn b/test/moduletest/on_new_want_module_test/BUILD.gn index 55d279ecc0..c01591d847 100644 --- a/test/moduletest/on_new_want_module_test/BUILD.gn +++ b/test/moduletest/on_new_want_module_test/BUILD.gn @@ -29,6 +29,7 @@ ohos_moduletest("on_new_want_module_test") { "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", diff --git a/test/moduletest/quick_fix/quick_fix_manager_module_test/quick_fix_manager_module_test.cpp b/test/moduletest/quick_fix/quick_fix_manager_module_test/quick_fix_manager_module_test.cpp index 3b83dc7185..736c9a97ea 100644 --- a/test/moduletest/quick_fix/quick_fix_manager_module_test/quick_fix_manager_module_test.cpp +++ b/test/moduletest/quick_fix/quick_fix_manager_module_test/quick_fix_manager_module_test.cpp @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_bundle_manager.h" #include "mock_quick_fix_util.h" #include "quick_fix_error_utils.h" diff --git a/test/moduletest/running_infos_module_test/BUILD.gn b/test/moduletest/running_infos_module_test/BUILD.gn index 0073360035..561fe9deca 100644 --- a/test/moduletest/running_infos_module_test/BUILD.gn +++ b/test/moduletest/running_infos_module_test/BUILD.gn @@ -65,6 +65,7 @@ ohos_moduletest("running_infos_module_test") { "${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}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:event_report", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_services_path}/common:task_handler_wrap", diff --git a/test/moduletest/running_infos_module_test/running_infos_module_test.cpp b/test/moduletest/running_infos_module_test/running_infos_module_test.cpp index d592a23433..82cb2a1de8 100644 --- a/test/moduletest/running_infos_module_test/running_infos_module_test.cpp +++ b/test/moduletest/running_infos_module_test/running_infos_module_test.cpp @@ -43,6 +43,7 @@ #include "wants_info.h" #include "want_receiver_stub.h" #include "want_sender_stub.h" +#include "mission_list_manager.h" using namespace std::placeholders; using namespace testing::ext; @@ -130,7 +131,8 @@ void RunningInfosModuleTest::OnStartAms() abilityMgrServ_->subManagersHelper_ = std::make_shared(nullptr, nullptr); abilityMgrServ_->subManagersHelper_->InitSubManagers(userId, true); abilityMgrServ_->subManagersHelper_->currentConnectManager_->SetTaskHandler(abilityMgrServ_->taskHandler_); - auto topAbility = abilityMgrServ_->GetMissionListManagerByUserId(userId)->GetCurrentTopAbilityLocked(); + auto topAbility = reinterpret_cast(abilityMgrServ_-> + GetMissionListManagerByUserId(userId).get())->GetCurrentTopAbilityLocked(); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -281,7 +283,8 @@ HWTEST_F(RunningInfosModuleTest, GetAbilityRunningInfos_004, TestSize.Level1) auto result = abilityMgrServ_->StartAbility(want); EXPECT_EQ(OHOS::ERR_OK, result); - auto topAbility = abilityMgrServ_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = reinterpret_cast(abilityMgrServ_->subManagersHelper_-> + currentMissionListManager_.get())->GetCurrentTopAbilityLocked(); EXPECT_TRUE(topAbility); topAbility->SetAbilityState(AbilityState::FOREGROUND); @@ -357,7 +360,8 @@ HWTEST_F(RunningInfosModuleTest, GetAbilityRunningInfos_006, TestSize.Level1) auto result = abilityMgrServ_->StartAbility(want); EXPECT_EQ(OHOS::ERR_OK, result); - auto topAbility = abilityMgrServ_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = reinterpret_cast(abilityMgrServ_->subManagersHelper_-> + currentMissionListManager_.get())->GetCurrentTopAbilityLocked(); EXPECT_TRUE(topAbility); topAbility->SetAbilityState(AbilityState::FOREGROUND); diff --git a/test/moduletest/start_ability_implicit_module_test/BUILD.gn b/test/moduletest/start_ability_implicit_module_test/BUILD.gn index 2958acbbd9..17b5c42833 100644 --- a/test/moduletest/start_ability_implicit_module_test/BUILD.gn +++ b/test/moduletest/start_ability_implicit_module_test/BUILD.gn @@ -53,6 +53,7 @@ ohos_moduletest("start_ability_implicit_module_test") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_services_path}/common:task_handler_wrap", "${distributedschedule_path}/safwk/interfaces/innerkits/safwk:system_ability_fwk", diff --git a/test/moduletest/start_ability_implicit_module_test/start_ability_implicit_module_test.cpp b/test/moduletest/start_ability_implicit_module_test/start_ability_implicit_module_test.cpp index 222165305d..4b554b108b 100644 --- a/test/moduletest/start_ability_implicit_module_test/start_ability_implicit_module_test.cpp +++ b/test/moduletest/start_ability_implicit_module_test/start_ability_implicit_module_test.cpp @@ -29,6 +29,7 @@ #include "sa_mgr_client.h" #include "system_ability_definition.h" #include "ui_service_mgr_client_mock.h" +#include "mission_list_manager.h" using namespace testing; using namespace testing::ext; @@ -113,10 +114,7 @@ void StartAbilityImplicitModuleTest::OnStartAms() const void StartAbilityImplicitModuleTest::OnStopAms() const { - abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_->missions_.clear(); - abilityMs_->subManagersHelper_->currentMissionListManager_->defaultStandardList_->missions_.clear(); - abilityMs_->subManagersHelper_->currentMissionListManager_->defaultSingleList_->missions_.clear(); - abilityMs_->subManagersHelper_->currentMissionListManager_->currentMissionLists_.clear(); + abilityMs_->subManagersHelper_->currentMissionListManager_.reset(); abilityMs_->OnStop(); } @@ -161,7 +159,8 @@ HWTEST_F(StartAbilityImplicitModuleTest, StartAbility_001, TestSize.Level1) EXPECT_TRUE(!params.empty()); EXPECT_TRUE(isCallBack); - auto abilityRecord = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto abilityRecord = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get())->GetCurrentTopAbilityLocked(); EXPECT_TRUE(abilityRecord != nullptr); GTEST_LOG_(INFO) << "ability:" << abilityRecord->GetAbilityInfo().name; @@ -193,7 +192,8 @@ HWTEST_F(StartAbilityImplicitModuleTest, StartAbility_002, TestSize.Level1) EXPECT_TRUE(!params.empty()); EXPECT_TRUE(isCallBack); - auto abilityRecord = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto abilityRecord = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get())->GetCurrentTopAbilityLocked(); EXPECT_TRUE(abilityRecord == nullptr); } @@ -222,7 +222,8 @@ HWTEST_F(StartAbilityImplicitModuleTest, StartAbility_003, TestSize.Level1) EXPECT_TRUE(params.empty()); EXPECT_TRUE(!isCallBack); - auto abilityRecord = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto abilityRecord = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get())->GetCurrentTopAbilityLocked(); EXPECT_TRUE(abilityRecord != nullptr); } @@ -251,7 +252,8 @@ HWTEST_F(StartAbilityImplicitModuleTest, StartAbility_004, TestSize.Level1) EXPECT_TRUE(!params.empty()); EXPECT_TRUE(isCallBack); - auto abilityRecord = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto abilityRecord = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get())->GetCurrentTopAbilityLocked(); EXPECT_TRUE(abilityRecord == nullptr); } diff --git a/test/moduletest/start_option_display_id_test/BUILD.gn b/test/moduletest/start_option_display_id_test/BUILD.gn index f3f6dfa979..538bd97719 100644 --- a/test/moduletest/start_option_display_id_test/BUILD.gn +++ b/test/moduletest/start_option_display_id_test/BUILD.gn @@ -26,10 +26,10 @@ ohos_moduletest("start_option_module_test") { configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] deps = [ - "${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_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", ] diff --git a/test/moduletest/start_option_display_id_test/start_option_display_id_test.cpp b/test/moduletest/start_option_display_id_test/start_option_display_id_test.cpp index a05d584e9c..8c6ad62a94 100644 --- a/test/moduletest/start_option_display_id_test/start_option_display_id_test.cpp +++ b/test/moduletest/start_option_display_id_test/start_option_display_id_test.cpp @@ -17,6 +17,7 @@ #define private public #define protected public #include "ability_manager_service.h" +#include "mission_list_manager.h" #undef private #undef protected #include "ability_manager_errors.h" @@ -64,7 +65,8 @@ HWTEST_F(StartOptionDisplayIdTest, start_option_001, TestSize.Level1) option.SetDisplayID(DISPLAY_ID); auto result = abilityMgrServ_->StartAbility(want, option, nullptr, USER_ID_U100, 0); if (result == OHOS::ERR_OK) { - auto topAbility = abilityMgrServ_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = reinterpret_cast(abilityMgrServ_-> + GetMissionListManagerByUserId(USER_ID_U100).get())->GetCurrentTopAbilityLocked(); if (topAbility) { auto defualtDisplayId = 0; auto displayId = topAbility->GetWant().GetIntParam(Want::PARAM_RESV_DISPLAY_ID, defualtDisplayId); diff --git a/test/moduletest/ui_extension_ability_test/src/ui_extension_connect_module_test_connection.cpp b/test/moduletest/ui_extension_ability_test/src/ui_extension_connect_module_test_connection.cpp index d86158432f..2474f5d7cc 100644 --- a/test/moduletest/ui_extension_ability_test/src/ui_extension_connect_module_test_connection.cpp +++ b/test/moduletest/ui_extension_ability_test/src/ui_extension_connect_module_test_connection.cpp @@ -15,7 +15,6 @@ #include "ui_extension_connect_module_test_connection.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/test/moduletest/ui_extension_ability_test/src/ui_extension_connect_module_test_observer.cpp b/test/moduletest/ui_extension_ability_test/src/ui_extension_connect_module_test_observer.cpp index 255aba06a9..a1b0a971fc 100644 --- a/test/moduletest/ui_extension_ability_test/src/ui_extension_connect_module_test_observer.cpp +++ b/test/moduletest/ui_extension_ability_test/src/ui_extension_connect_module_test_observer.cpp @@ -15,7 +15,6 @@ #include "ui_extension_connect_module_test_observer.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/test/moduletest/ui_extension_ability_test/ui_extension_connect_module_test/ui_extension_connect_module_test.cpp b/test/moduletest/ui_extension_ability_test/ui_extension_connect_module_test/ui_extension_connect_module_test.cpp index 07829367e2..9f5ddbae1c 100644 --- a/test/moduletest/ui_extension_ability_test/ui_extension_connect_module_test/ui_extension_connect_module_test.cpp +++ b/test/moduletest/ui_extension_ability_test/ui_extension_connect_module_test/ui_extension_connect_module_test.cpp @@ -22,7 +22,6 @@ #include "accesstoken_kit.h" #include "app_mgr_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "nativetoken_kit.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" 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 45ca7f017f..d424699d73 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 @@ -22,7 +22,6 @@ #include "bundle_mgr_proxy.h" #include "bundle_mgr_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "nativetoken_kit.h" diff --git a/test/moduletest/ui_extension_ability_test/ui_extension_stability_test/ui_extension_stability_test.cpp b/test/moduletest/ui_extension_ability_test/ui_extension_stability_test/ui_extension_stability_test.cpp index 879c039226..7b7f175fa6 100644 --- a/test/moduletest/ui_extension_ability_test/ui_extension_stability_test/ui_extension_stability_test.cpp +++ b/test/moduletest/ui_extension_ability_test/ui_extension_stability_test/ui_extension_stability_test.cpp @@ -22,7 +22,6 @@ #include "accesstoken_kit.h" #include "app_mgr_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "mock_sa_call.h" diff --git a/test/sample/demo_ui_extension/js/napi/demo_ui_extension_ability/BUILD.gn b/test/sample/demo_ui_extension/js/napi/demo_ui_extension_ability/BUILD.gn index b47cd7e668..b19e3cb120 100644 --- a/test/sample/demo_ui_extension/js/napi/demo_ui_extension_ability/BUILD.gn +++ b/test/sample/demo_ui_extension/js/napi/demo_ui_extension_ability/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/config/components/ets_frontend/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_demo_ui_extension_ability_abc") { diff --git a/test/sample/demo_ui_extension/native/demo_ui_extension_ability/src/js_demo_ui_extension.cpp b/test/sample/demo_ui_extension/native/demo_ui_extension_ability/src/js_demo_ui_extension.cpp index b762e34f7a..85ef057431 100644 --- a/test/sample/demo_ui_extension/native/demo_ui_extension_ability/src/js_demo_ui_extension.cpp +++ b/test/sample/demo_ui_extension/native/demo_ui_extension_ability/src/js_demo_ui_extension.cpp @@ -15,7 +15,6 @@ #include "js_demo_ui_extension.h" -#include "hilog_wrapper.h" #include "js_ui_extension_base.h" #include "js_demo_ui_extension_context.h" diff --git a/test/sample/demo_ui_extension/native/demo_ui_extension_ability/src/js_demo_ui_extension_context.cpp b/test/sample/demo_ui_extension/native/demo_ui_extension_ability/src/js_demo_ui_extension_context.cpp index b162fcfc53..d41a092453 100644 --- a/test/sample/demo_ui_extension/native/demo_ui_extension_ability/src/js_demo_ui_extension_context.cpp +++ b/test/sample/demo_ui_extension/native/demo_ui_extension_ability/src/js_demo_ui_extension_context.cpp @@ -20,7 +20,6 @@ #include "ability_manager_client.h" #include "event_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_extension_context.h" #include "js_error_utils.h" #include "js_data_struct_converter.h" diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 6dd7482377..c45fdd742b 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -57,8 +57,6 @@ ohos_source_set("appmgr_test_source") { "${ability_runtime_innerkits_path}/app_manager/src/appmgr/running_process_info.cpp", ] - include_dirs = [ "//third_party/json/include" ] - public_configs = [ ":appmgr_test_config", "${c_utils_base_path}:utils_config", @@ -94,6 +92,7 @@ ohos_source_set("appmgr_test_source") { "hilog:libhilog", "hitrace:hitrace_meter", "ipc:ipc_core", + "json:nlohmann_json_static", "kv_store:distributeddata_mgr", ] @@ -142,7 +141,7 @@ ohos_source_set("abilityms_test_source") { "${ability_runtime_services_path}/abilitymgr/src/data_ability_caller_recipient.cpp", "${ability_runtime_services_path}/abilitymgr/src/data_ability_manager.cpp", "${ability_runtime_services_path}/abilitymgr/src/data_ability_record.cpp", - "${ability_runtime_services_path}/abilitymgr/src/dialog_session_record.cpp", + "${ability_runtime_services_path}/abilitymgr/src/dialog_session/dialog_session_manager.cpp", "${ability_runtime_services_path}/abilitymgr/src/dlp_state_item.cpp", "${ability_runtime_services_path}/abilitymgr/src/ecological_rule/ability_ecological_rule_mgr_service.cpp", "${ability_runtime_services_path}/abilitymgr/src/ecological_rule/ability_ecological_rule_mgr_service_param.cpp", @@ -337,6 +336,7 @@ group("unittest") { "ability_manager_proxy_test:unittest", "ability_manager_service_dialog_test:unittest", "ability_manager_service_first_test:unittest", + "ability_manager_service_fourth_test:unittest", "ability_manager_service_second_test:unittest", "ability_manager_service_third_test:unittest", "ability_manager_stub_test:unittest", @@ -418,6 +418,23 @@ group("unittest") { "call_record_test:unittest", "child_process_capi_test:unittest", "child_process_manager_test:unittest", + "cj_ability_connect_callback_object_test:unittest", + "cj_ability_context_object_test:unittest", + "cj_ability_delegator_test:unittest", + "cj_ability_ffi_mock_test:unittest", + "cj_ability_object_test:unittest", + "cj_ability_stage_object_test:unittest", + "cj_ability_stage_test:unittest", + "cj_application_context_test:unittest", + "cj_delegator_ffi_mock_test:unittest", + "cj_element_name_ffi_test:unittest", + "cj_environment_test:unittest", + "cj_runtime_test:unittest", + "cj_test_runner_object_test:unittest", + "cj_test_runner_test:unittest", + "cj_ui_ability_test:unittest", + "cj_utils_ffi_test:unittest", + "cj_want_ffi_test:unittest", "completed_dispatcher_test:unittest", "configuration_test:unittest", "connect_server_manager_test:unittest", @@ -445,6 +462,7 @@ group("unittest") { "dlp_state_item_test:unittest", "dlp_utils_test:unittest", "dummy_values_bucket_test:unittest", + "dynamic_loader_ohos_test:unittest", "event_report_test:unittest", "extension_config_mgr_test:unittest", "extension_manager_client_test:unittest", diff --git a/test/unittest/ability_auto_startup_data_manager_test/ability_auto_startup_data_manager_test.cpp b/test/unittest/ability_auto_startup_data_manager_test/ability_auto_startup_data_manager_test.cpp index f4534fedf0..89f0b9e63e 100644 --- a/test/unittest/ability_auto_startup_data_manager_test/ability_auto_startup_data_manager_test.cpp +++ b/test/unittest/ability_auto_startup_data_manager_test/ability_auto_startup_data_manager_test.cpp @@ -23,7 +23,6 @@ #undef protected #include "auto_startup_info.h" -#include "hilog_wrapper.h" #include "types.h" using namespace testing; using namespace testing::ext; @@ -590,15 +589,32 @@ HWTEST_F(AbilityAutoStartupDataManagerTest, IsEqual_info_100, TestSize.Level1) * SubFunction: NA * FunctionPoints: AbilityAutoStartupDataManager IsEqual */ -HWTEST_F(AbilityAutoStartupDataManagerTest, IsEqual_bundleName_100, TestSize.Level1) +HWTEST_F(AbilityAutoStartupDataManagerTest, IsEqual_userId_100, TestSize.Level1) { - GTEST_LOG_(INFO) << "IsEqual_bundleName_100 start"; + GTEST_LOG_(INFO) << "IsEqual_userId_100 start"; AbilityAutoStartupDataManager abilityAutoStartupDataManager; DistributedKv::Key key; - std::string bundleName = " com.example.testbundle"; - auto result = abilityAutoStartupDataManager.IsEqual(key, bundleName); + int32_t userId = 100; + auto result = abilityAutoStartupDataManager.IsEqual(key, userId); EXPECT_FALSE(result); - GTEST_LOG_(INFO) << "IsEqual_bundleName_100 end"; + GTEST_LOG_(INFO) << "IsEqual_userId_100 end"; +} + +/** + * Feature: AbilityAutoStartupDataManager + * Function: IsEqual + * SubFunction: NA + * FunctionPoints: AbilityAutoStartupDataManager IsEqual + */ +HWTEST_F(AbilityAutoStartupDataManagerTest, IsEqual_accessTokenId_100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsEqual_userId_100 start"; + AbilityAutoStartupDataManager abilityAutoStartupDataManager; + DistributedKv::Key key; + std::string accessTokenId = "123"; + auto result = abilityAutoStartupDataManager.IsEqual(key, accessTokenId); + EXPECT_FALSE(result); + GTEST_LOG_(INFO) << "IsEqual_accessTokenId_100 end"; } } // namespace AbilityRuntime } // namespace OHOS diff --git a/test/unittest/ability_auto_startup_service_test/BUILD.gn b/test/unittest/ability_auto_startup_service_test/BUILD.gn index ce7786334c..90545ca57d 100644 --- a/test/unittest/ability_auto_startup_service_test/BUILD.gn +++ b/test/unittest/ability_auto_startup_service_test/BUILD.gn @@ -46,6 +46,7 @@ ohos_unittest("ability_auto_startup_service_test") { "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability:ability_context_native", "${ability_runtime_native_path}/ability/native:auto_startup_callback", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:perm_verification", "//third_party/googletest:gmock_main", diff --git a/test/unittest/ability_auto_startup_service_test/ability_auto_startup_service_test.cpp b/test/unittest/ability_auto_startup_service_test/ability_auto_startup_service_test.cpp index 73bfe28ad4..9b0c0b2e9a 100644 --- a/test/unittest/ability_auto_startup_service_test/ability_auto_startup_service_test.cpp +++ b/test/unittest/ability_auto_startup_service_test/ability_auto_startup_service_test.cpp @@ -19,7 +19,6 @@ #include "ability_auto_startup_service.h" #include "ability_manager_errors.h" #include "distributed_kv_data_manager.h" -#include "hilog_wrapper.h" #include "mock_my_flag.h" #include "mock_permission_verification.h" #include "mock_sa_call.h" @@ -407,8 +406,9 @@ HWTEST_F(AbilityAutoStartupServiceTest, GetBundleInfo_001, TestSize.Level1) auto abilityAutoStartupService = std::make_shared(); std::string bundleName; int32_t userId = 100; + int32_t appIndex = 0; AppExecFwk::BundleInfo bundleInfo; - auto result = abilityAutoStartupService->GetBundleInfo(bundleName, bundleInfo, -1, userId); + auto result = abilityAutoStartupService->GetBundleInfo(bundleName, bundleInfo, -1, userId, appIndex); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "AbilityAutoStartupServiceTest GetBundleInfo_001 end"; } diff --git a/test/unittest/ability_bundle_event_callback_test/BUILD.gn b/test/unittest/ability_bundle_event_callback_test/BUILD.gn index c1b5393b61..ecd783c3d7 100644 --- a/test/unittest/ability_bundle_event_callback_test/BUILD.gn +++ b/test/unittest/ability_bundle_event_callback_test/BUILD.gn @@ -42,6 +42,7 @@ ohos_unittest("ability_bundle_event_callback_test") { "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_innerkits_path}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:auto_startup_callback", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:event_report", "${ability_runtime_services_path}/common:perm_verification", diff --git a/test/unittest/ability_bundle_event_callback_test/ability_bundle_event_callback_test.cpp b/test/unittest/ability_bundle_event_callback_test/ability_bundle_event_callback_test.cpp index 85a5023f15..edf7762ea1 100644 --- a/test/unittest/ability_bundle_event_callback_test/ability_bundle_event_callback_test.cpp +++ b/test/unittest/ability_bundle_event_callback_test/ability_bundle_event_callback_test.cpp @@ -20,7 +20,6 @@ #include "ability_event_util.h" #undef private #undef protected -#include "hilog_wrapper.h" using namespace testing::ext; using namespace testing; diff --git a/test/unittest/ability_cache_manager_test/ability_cache_manager_test.cpp b/test/unittest/ability_cache_manager_test/ability_cache_manager_test.cpp index 13621d931c..e5a5c92bbb 100644 --- a/test/unittest/ability_cache_manager_test/ability_cache_manager_test.cpp +++ b/test/unittest/ability_cache_manager_test/ability_cache_manager_test.cpp @@ -78,6 +78,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerPutAndGetTest_001, TestSize abilityRecord_->Init(); std::shared_ptr rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord_); EXPECT_EQ(rec, nullptr); + int recId = abilityRecord_->GetRecordId(); AbilityRequest abilityRequest; abilityRequest.abilityInfo = abilityInfo; abilityRequest.appInfo = applicationInfo; @@ -99,6 +100,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerPutAndGetTest_001, TestSize EXPECT_EQ(rec->GetAbilityInfo().moduleName, abilityInfo.moduleName); EXPECT_EQ(rec->GetAbilityInfo().bundleName, abilityInfo.bundleName); EXPECT_EQ(rec->GetWant().GetElement().GetAbilityName(), "ability"); + EXPECT_EQ(rec->GetRecordId(), recId); rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Get(abilityRequest); EXPECT_EQ(rec, nullptr); } @@ -123,6 +125,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerRemoveTest_001, TestSize.Le auto abilityRecord_ = std::make_shared(want, abilityInfo, applicationInfo); abilityRecord_->Init(); std::shared_ptr rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord_); + int recId = abilityRecord_->GetRecordId(); EXPECT_EQ(rec, nullptr); applicationInfo.accessTokenId = 0; auto removeRec = std::make_shared(want, abilityInfo, applicationInfo); @@ -137,6 +140,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerRemoveTest_001, TestSize.Le EXPECT_EQ(rec->GetAbilityInfo().moduleName, abilityInfo.moduleName); EXPECT_EQ(rec->GetAbilityInfo().bundleName, abilityInfo.bundleName); EXPECT_EQ(rec->GetWant().GetElement().GetAbilityName(), "ability"); + EXPECT_EQ(rec->GetRecordId(), recId); rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Get(abilityRequest); EXPECT_EQ(rec, nullptr); } @@ -161,6 +165,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerRemoveTest_002, TestSize.Le auto abilityRecord_ = std::make_shared(want, abilityInfo, applicationInfo); abilityRecord_->Init(); std::shared_ptr rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord_); + int recId = abilityRecord_->GetRecordId(); EXPECT_EQ(rec, nullptr); abilityInfo.moduleName = "WrongModuleName"; auto removeRec = std::make_shared(want, abilityInfo, applicationInfo); @@ -175,6 +180,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerRemoveTest_002, TestSize.Le EXPECT_EQ(rec->GetAbilityInfo().moduleName, abilityInfo.moduleName); EXPECT_EQ(rec->GetAbilityInfo().bundleName, abilityInfo.bundleName); EXPECT_EQ(rec->GetWant().GetElement().GetAbilityName(), "ability"); + EXPECT_EQ(rec->GetRecordId(), recId); rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Get(abilityRequest); EXPECT_EQ(rec, nullptr); } @@ -199,6 +205,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerRemoveTest_003, TestSize.Le auto abilityRecord_ = std::make_shared(want, abilityInfo, applicationInfo); abilityRecord_->Init(); std::shared_ptr rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord_); + int recId = abilityRecord_->GetRecordId(); EXPECT_EQ(rec, nullptr); ElementName wrongeElement("", "", "wrongAbility", ""); want.SetElement(wrongeElement); @@ -213,6 +220,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerRemoveTest_003, TestSize.Le EXPECT_EQ(rec->GetAbilityInfo().moduleName, abilityInfo.moduleName); EXPECT_EQ(rec->GetAbilityInfo().bundleName, abilityInfo.bundleName); EXPECT_EQ(rec->GetWant().GetElement().GetAbilityName(), "ability"); + EXPECT_EQ(rec->GetRecordId(), recId); rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Get(abilityRequest); EXPECT_EQ(rec, nullptr); } @@ -237,7 +245,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerPutTest_001, TestSize.Level abilityRecord1->Init(); std::shared_ptr rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord1); EXPECT_EQ(rec, nullptr); - + int recId1 = abilityRecord1->GetRecordId(); OHOS::AppExecFwk::AbilityInfo abilityInfo2; abilityInfo2.moduleName = "TestModuleName2"; abilityInfo2.bundleName = "TestBundleName2"; @@ -260,7 +268,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerPutTest_001, TestSize.Level EXPECT_EQ(rec->GetApplicationInfo().accessTokenId, applicationInfo1.accessTokenId); EXPECT_EQ(rec->GetAbilityInfo().moduleName, abilityInfo1.moduleName); EXPECT_EQ(rec->GetAbilityInfo().bundleName, abilityInfo1.bundleName); - + EXPECT_EQ(rec->GetRecordId(), recId1); OHOS::AAFwk::AbilityCacheManager::GetInstance().Remove(abilityRecord2); OHOS::AAFwk::AbilityCacheManager::GetInstance().Remove(abilityRecord3); } @@ -294,7 +302,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerPutTest_002, TestSize.Level abilityRecord2->Init(); rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord2); EXPECT_EQ(rec, nullptr); - + int recId2 = abilityRecord2->GetRecordId(); OHOS::AppExecFwk::AbilityInfo abilityInfo3; abilityInfo3.moduleName = "TestModuleName3"; abilityInfo3.bundleName = "TestBundleName3"; @@ -307,6 +315,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerPutTest_002, TestSize.Level EXPECT_EQ(rec->GetApplicationInfo().accessTokenId, applicationInfo2.accessTokenId); EXPECT_EQ(rec->GetAbilityInfo().moduleName, abilityInfo2.moduleName); EXPECT_EQ(rec->GetAbilityInfo().bundleName, abilityInfo2.bundleName); + EXPECT_EQ(rec->GetRecordId(), recId2); OHOS::AAFwk::AbilityCacheManager::GetInstance().Remove(abilityRecord1); OHOS::AAFwk::AbilityCacheManager::GetInstance().Remove(abilityRecord3); } @@ -348,9 +357,9 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerPutTest_003, TestSize.Level abilityInfo3.bundleName = "TestBundleName3"; OHOS::AppExecFwk::ApplicationInfo applicationInfo3; applicationInfo3.accessTokenId = 3; - auto abilityRecord3 = std::make_shared(want, abilityInfo3, applicationInfo3); abilityRecord3->Init(); + int recId3 = abilityRecord3->GetRecordId(); rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord3); EXPECT_EQ(rec, nullptr); @@ -366,6 +375,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerPutTest_003, TestSize.Level EXPECT_EQ(rec->GetApplicationInfo().accessTokenId, applicationInfo3.accessTokenId); EXPECT_EQ(rec->GetAbilityInfo().moduleName, abilityInfo3.moduleName); EXPECT_EQ(rec->GetAbilityInfo().bundleName, abilityInfo3.bundleName); + EXPECT_EQ(rec->GetRecordId(), recId3); OHOS::AAFwk::AbilityCacheManager::GetInstance().Remove(abilityRecord1); OHOS::AAFwk::AbilityCacheManager::GetInstance().Remove(abilityRecord2); @@ -391,7 +401,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerPutTest_004, TestSize.Level abilityRecord1->Init(); std::shared_ptr rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord1); EXPECT_EQ(rec, nullptr); - + int recId1 = abilityRecord1->GetRecordId(); OHOS::AppExecFwk::AbilityInfo abilityInfo2; abilityInfo2.moduleName = "TestModuleName2"; abilityInfo2.bundleName = "TestBundleName2"; @@ -414,6 +424,7 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerPutTest_004, TestSize.Level EXPECT_EQ(rec->GetApplicationInfo().accessTokenId, applicationInfo1.accessTokenId); EXPECT_EQ(rec->GetAbilityInfo().moduleName, abilityInfo1.moduleName); EXPECT_EQ(rec->GetAbilityInfo().bundleName, abilityInfo1.bundleName); + EXPECT_EQ(rec->GetRecordId(), recId1); OHOS::AAFwk::AbilityCacheManager::GetInstance().Remove(abilityRecord2); OHOS::AAFwk::AbilityCacheManager::GetInstance().Remove(abilityRecord3); @@ -453,5 +464,205 @@ HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerPutAndRemoveTest_001, TestS abilityRecord1->Init(); OHOS::AAFwk::AbilityCacheManager::GetInstance().Remove(abilityRecord1); } + +/** + * @tc.name: AbilityCacheManagerFindByToken_001 + * @tc.desc: Put a single ability record into cache and find it, find will not remove cache + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerFindByToken_001, TestSize.Level0) +{ + OHOS::AAFwk::AbilityCacheManager::GetInstance().Init(10, 5); + OHOS::AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.moduleName = "TestModuleName"; + abilityInfo.bundleName = "TestBundleName"; + OHOS::AppExecFwk::ApplicationInfo applicationInfo; + applicationInfo.accessTokenId = 0; + Want want; + auto abilityRecord_ = std::make_shared(want, abilityInfo, applicationInfo); + abilityRecord_->Init(); + int recId = abilityRecord_->GetRecordId(); + std::shared_ptr rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord_); + EXPECT_EQ(rec, nullptr); + auto recordFind = OHOS::AAFwk::AbilityCacheManager::GetInstance().FindRecordByToken(abilityRecord_->GetToken()); + EXPECT_EQ(recordFind->GetApplicationInfo().accessTokenId, applicationInfo.accessTokenId); + EXPECT_EQ(recordFind->GetAbilityInfo().moduleName, abilityInfo.moduleName); + EXPECT_EQ(recordFind->GetAbilityInfo().bundleName, abilityInfo.bundleName); + EXPECT_EQ(recordFind->GetRecordId(), recId); + AbilityRequest abilityRequest; + abilityRequest.abilityInfo = abilityInfo; + abilityRequest.appInfo = applicationInfo; + auto recGet = OHOS::AAFwk::AbilityCacheManager::GetInstance().Get(abilityRequest); + EXPECT_EQ(recGet->GetApplicationInfo().accessTokenId, applicationInfo.accessTokenId); + EXPECT_EQ(recGet->GetAbilityInfo().moduleName, abilityInfo.moduleName); + EXPECT_EQ(recGet->GetAbilityInfo().bundleName, abilityInfo.bundleName); + EXPECT_EQ(recGet->GetRecordId(), recId); +} + +/** + * @tc.name: AbilityCacheManagerGetAbilityList_001 + * @tc.desc: Put a single ability record into cache and get ability list + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerGetAbilityList_001, TestSize.Level0) +{ + OHOS::AAFwk::AbilityCacheManager::GetInstance().Init(10, 5); + OHOS::AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.moduleName = "TestModuleName"; + abilityInfo.bundleName = "TestBundleName"; + OHOS::AppExecFwk::ApplicationInfo applicationInfo; + applicationInfo.accessTokenId = 0; + Want want; + auto abilityRecord_ = std::make_shared(want, abilityInfo, applicationInfo); + abilityRecord_->Init(); + int recId = abilityRecord_->GetRecordId(); + std::shared_ptr rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord_); + EXPECT_EQ(rec, nullptr); + auto abilityList = OHOS::AAFwk::AbilityCacheManager::GetInstance().GetAbilityList(); + EXPECT_EQ(abilityList.size(), 1); + auto recordFind = *(abilityList.begin()); + EXPECT_EQ(recordFind->GetApplicationInfo().accessTokenId, applicationInfo.accessTokenId); + EXPECT_EQ(recordFind->GetAbilityInfo().moduleName, abilityInfo.moduleName); + EXPECT_EQ(recordFind->GetAbilityInfo().bundleName, abilityInfo.bundleName); + EXPECT_EQ(recordFind->GetRecordId(), recId); + OHOS::AAFwk::AbilityCacheManager::GetInstance().Remove(abilityRecord_); +} + +/** + * @tc.name: AbilityCacheManagerFindBySessionId_001 + * @tc.desc: Put a single ability record into cache and find it, find will not remove cache + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerFindBySessionId_001, TestSize.Level0) +{ + OHOS::AAFwk::AbilityCacheManager::GetInstance().Init(10, 5); + OHOS::AppExecFwk::AbilityInfo abilityInfo; + std::string sessionId = "TestSessionId"; + abilityInfo.moduleName = "TestModuleName"; + abilityInfo.bundleName = "TestBundleName"; + OHOS::AppExecFwk::ApplicationInfo applicationInfo; + applicationInfo.accessTokenId = 0; + Want want; + want.SetParam(Want::PARAM_ASSERT_FAULT_SESSION_ID, sessionId); + auto abilityRecord_ = std::make_shared(want, abilityInfo, applicationInfo); + abilityRecord_->Init(); + int recId = abilityRecord_->GetRecordId(); + std::shared_ptr rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord_); + EXPECT_EQ(rec, nullptr); + auto recordFind = OHOS::AAFwk::AbilityCacheManager::GetInstance().FindRecordBySessionId(sessionId); + EXPECT_EQ(recordFind->GetApplicationInfo().accessTokenId, applicationInfo.accessTokenId); + EXPECT_EQ(recordFind->GetAbilityInfo().moduleName, abilityInfo.moduleName); + EXPECT_EQ(recordFind->GetAbilityInfo().bundleName, abilityInfo.bundleName); + EXPECT_EQ(recordFind->GetRecordId(), recId); + AbilityRequest abilityRequest; + abilityRequest.abilityInfo = abilityInfo; + abilityRequest.appInfo = applicationInfo; + auto recGet = OHOS::AAFwk::AbilityCacheManager::GetInstance().Get(abilityRequest); + EXPECT_EQ(recGet->GetApplicationInfo().accessTokenId, applicationInfo.accessTokenId); + EXPECT_EQ(recGet->GetAbilityInfo().moduleName, abilityInfo.moduleName); + EXPECT_EQ(recGet->GetAbilityInfo().bundleName, abilityInfo.bundleName); + EXPECT_EQ(recGet->GetRecordId(), recId); +} + +/** + * @tc.name: AbilityCacheManagerFindByServiceKey_001 + * @tc.desc: Put a single ability record into cache and find it, find will not remove cache + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerFindByServiceKey_001, TestSize.Level0) +{ + OHOS::AAFwk::AbilityCacheManager::GetInstance().Init(10, 5); + OHOS::AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.moduleName = "TestModuleName"; + abilityInfo.bundleName = "TestBundleName"; + OHOS::AppExecFwk::ApplicationInfo applicationInfo; + applicationInfo.accessTokenId = 0; + Want want; + auto abilityRecord_ = std::make_shared(want, abilityInfo, applicationInfo); + abilityRecord_->Init(); + int recId = abilityRecord_->GetRecordId(); + std::string serviceKey = abilityRecord_->GetURI(); + std::shared_ptr rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord_); + EXPECT_EQ(rec, nullptr); + auto recordFind = OHOS::AAFwk::AbilityCacheManager::GetInstance().FindRecordByServiceKey(serviceKey); + EXPECT_EQ(recordFind->GetApplicationInfo().accessTokenId, applicationInfo.accessTokenId); + EXPECT_EQ(recordFind->GetAbilityInfo().moduleName, abilityInfo.moduleName); + EXPECT_EQ(recordFind->GetAbilityInfo().bundleName, abilityInfo.bundleName); + EXPECT_EQ(recordFind->GetRecordId(), recId); + AbilityRequest abilityRequest; + abilityRequest.abilityInfo = abilityInfo; + abilityRequest.appInfo = applicationInfo; + auto recGet = OHOS::AAFwk::AbilityCacheManager::GetInstance().Get(abilityRequest); + EXPECT_EQ(recGet->GetApplicationInfo().accessTokenId, applicationInfo.accessTokenId); + EXPECT_EQ(recGet->GetAbilityInfo().moduleName, abilityInfo.moduleName); + EXPECT_EQ(recGet->GetAbilityInfo().bundleName, abilityInfo.bundleName); + EXPECT_EQ(recGet->GetRecordId(), recId); +} + +/** + * @tc.name: AbilityCacheManagerSignRestartAppFlag_001 + * @tc.desc: Put a single ability record into cache and sign restart app flag + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerSignRestartAppFlag_001, TestSize.Level0) +{ + OHOS::AAFwk::AbilityCacheManager::GetInstance().Init(10, 5); + OHOS::AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.moduleName = "TestModuleName"; + abilityInfo.bundleName = "TestBundleName"; + OHOS::AppExecFwk::ApplicationInfo applicationInfo; + applicationInfo.accessTokenId = 0; + applicationInfo.bundleName = abilityInfo.bundleName; + Want want; + auto abilityRecord_ = std::make_shared(want, abilityInfo, applicationInfo); + abilityRecord_->Init(); + int recId = abilityRecord_->GetRecordId(); + std::shared_ptr rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord_); + EXPECT_EQ(rec, nullptr); + OHOS::AAFwk::AbilityCacheManager::GetInstance().SignRestartAppFlag(applicationInfo.bundleName); + AbilityRequest abilityRequest; + abilityRequest.abilityInfo = abilityInfo; + abilityRequest.appInfo = applicationInfo; + auto recordFind = OHOS::AAFwk::AbilityCacheManager::GetInstance().Get(abilityRequest); + EXPECT_EQ(recordFind->GetRestartAppFlag(), true); +} + +/** + * @tc.name: AbilityCacheManagerDeleteInvalidRecord_001 + * @tc.desc: Put a single ability record into cache and delete it by bundleName + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityCacheManagerTest, AbilityCacheManagerDeleteInvalidRecord_001, TestSize.Level0) +{ + OHOS::AAFwk::AbilityCacheManager::GetInstance().Init(10, 5); + OHOS::AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.moduleName = "TestModuleName"; + abilityInfo.bundleName = "TestBundleName"; + OHOS::AppExecFwk::ApplicationInfo applicationInfo; + applicationInfo.accessTokenId = 0; + Want want; + auto abilityRecord_ = std::make_shared(want, abilityInfo, applicationInfo); + abilityRecord_->Init(); + int recId = abilityRecord_->GetRecordId(); + std::shared_ptr rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Put(abilityRecord_); + EXPECT_EQ(rec, nullptr); + AbilityRequest abilityRequest; + abilityRequest.abilityInfo = abilityInfo; + abilityRequest.appInfo = applicationInfo; + rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Get(abilityRequest); + EXPECT_EQ(rec->GetApplicationInfo().accessTokenId, applicationInfo.accessTokenId); + EXPECT_EQ(rec->GetAbilityInfo().moduleName, abilityInfo.moduleName); + EXPECT_EQ(rec->GetAbilityInfo().bundleName, abilityInfo.bundleName); + EXPECT_EQ(rec->GetRecordId(), recId); + OHOS::AAFwk::AbilityCacheManager::GetInstance().DeleteInvalidServiceRecord(abilityInfo.bundleName); + rec = OHOS::AAFwk::AbilityCacheManager::GetInstance().Get(abilityRequest); + EXPECT_EQ(rec, nullptr); +} } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/ability_debug_deal_test/ability_debug_deal_test.cpp b/test/unittest/ability_debug_deal_test/ability_debug_deal_test.cpp index d885ceaa7d..335b675e32 100644 --- a/test/unittest/ability_debug_deal_test/ability_debug_deal_test.cpp +++ b/test/unittest/ability_debug_deal_test/ability_debug_deal_test.cpp @@ -15,7 +15,6 @@ #include -#include "hilog_wrapper.h" #define private public #include "ability_debug_deal.h" #include "ability_record.h" diff --git a/test/unittest/ability_debug_response_proxy_test/ability_debug_response_proxy_test.cpp b/test/unittest/ability_debug_response_proxy_test/ability_debug_response_proxy_test.cpp index 63f7f9d11c..cc679d2e91 100644 --- a/test/unittest/ability_debug_response_proxy_test/ability_debug_response_proxy_test.cpp +++ b/test/unittest/ability_debug_response_proxy_test/ability_debug_response_proxy_test.cpp @@ -15,7 +15,6 @@ #include -#include "hilog_wrapper.h" #include "ability_debug_response_proxy.h" #include "mock_ability_debug_response_stub.h" #include "mock_ability_token.h" diff --git a/test/unittest/ability_debug_response_stub_test/ability_debug_response_stub_test.cpp b/test/unittest/ability_debug_response_stub_test/ability_debug_response_stub_test.cpp index ed80b8e0f0..f21ba7f7a6 100644 --- a/test/unittest/ability_debug_response_stub_test/ability_debug_response_stub_test.cpp +++ b/test/unittest/ability_debug_response_stub_test/ability_debug_response_stub_test.cpp @@ -16,7 +16,6 @@ #include #include "mock_ability_token.h" -#include "hilog_wrapper.h" #define private public #include "mock_ability_debug_response_stub.h" #undef private diff --git a/test/unittest/ability_event_handler_test/ability_event_handler_test.cpp b/test/unittest/ability_event_handler_test/ability_event_handler_test.cpp index 2c20509fd5..744b5198da 100644 --- a/test/unittest/ability_event_handler_test/ability_event_handler_test.cpp +++ b/test/unittest/ability_event_handler_test/ability_event_handler_test.cpp @@ -18,7 +18,6 @@ #include #include "ability_manager_service.h" #include "ability_event_handler.h" -#include "hilog_wrapper.h" using namespace testing::ext; namespace OHOS { diff --git a/test/unittest/ability_extension_base_test/ability_extension_base_test.cpp b/test/unittest/ability_extension_base_test/ability_extension_base_test.cpp index 19db7d5235..ab26dd98dd 100644 --- a/test/unittest/ability_extension_base_test/ability_extension_base_test.cpp +++ b/test/unittest/ability_extension_base_test/ability_extension_base_test.cpp @@ -25,7 +25,6 @@ #include "ability_transaction_callback_info.h" #include "configuration.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "mock_ability_token.h" #include "ohos_application.h" diff --git a/test/unittest/ability_extension_context_test/ability_extension_context_test.cpp b/test/unittest/ability_extension_context_test/ability_extension_context_test.cpp index 3d613d4d71..610ef4f108 100644 --- a/test/unittest/ability_extension_context_test/ability_extension_context_test.cpp +++ b/test/unittest/ability_extension_context_test/ability_extension_context_test.cpp @@ -24,7 +24,6 @@ #include "ability_handler.h" #include "configuration.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "mock_ability_token.h" #include "ohos_application.h" diff --git a/test/unittest/ability_extension_module_loader_test/ability_extension_module_loader_test.cpp b/test/unittest/ability_extension_module_loader_test/ability_extension_module_loader_test.cpp index 5bf0db3a93..111663fe10 100644 --- a/test/unittest/ability_extension_module_loader_test/ability_extension_module_loader_test.cpp +++ b/test/unittest/ability_extension_module_loader_test/ability_extension_module_loader_test.cpp @@ -17,7 +17,6 @@ #include "extension_module_loader.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "request_info.h" using namespace testing::ext; diff --git a/test/unittest/ability_extension_running_info_test/ability_extension_running_info_test.cpp b/test/unittest/ability_extension_running_info_test/ability_extension_running_info_test.cpp index 9d7d617375..39fcd96b75 100755 --- a/test/unittest/ability_extension_running_info_test/ability_extension_running_info_test.cpp +++ b/test/unittest/ability_extension_running_info_test/ability_extension_running_info_test.cpp @@ -17,7 +17,6 @@ #include "extension_running_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "want.h" diff --git a/test/unittest/ability_extension_test/ability_extension_test.cpp b/test/unittest/ability_extension_test/ability_extension_test.cpp index c277c05e5e..2d6e31d361 100644 --- a/test/unittest/ability_extension_test/ability_extension_test.cpp +++ b/test/unittest/ability_extension_test/ability_extension_test.cpp @@ -25,7 +25,6 @@ #include "ability_transaction_callback_info.h" #include "configuration.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "mock_ability_token.h" #include "ohos_application.h" diff --git a/test/unittest/ability_first_frame_state_observer_manager_test/ability_first_frame_state_observer_manager_test.cpp b/test/unittest/ability_first_frame_state_observer_manager_test/ability_first_frame_state_observer_manager_test.cpp index b1ed86bd2b..62fc2599f3 100644 --- a/test/unittest/ability_first_frame_state_observer_manager_test/ability_first_frame_state_observer_manager_test.cpp +++ b/test/unittest/ability_first_frame_state_observer_manager_test/ability_first_frame_state_observer_manager_test.cpp @@ -20,7 +20,6 @@ #undef protected #include #include "ability_first_frame_state_observer_stub.h" -#include "ability_manager_errors.h" #include "iremote_broker.h" #include "mock/include/mock_permission_verification.h" #include "mock/include/mock_my_flag.h" diff --git a/test/unittest/ability_interceptor_test/ability_interceptor_test.cpp b/test/unittest/ability_interceptor_test/ability_interceptor_test.cpp index 6c0451345b..2055bee7f3 100644 --- a/test/unittest/ability_interceptor_test/ability_interceptor_test.cpp +++ b/test/unittest/ability_interceptor_test/ability_interceptor_test.cpp @@ -57,6 +57,7 @@ public: void AbilityInterceptorTest::SetUpTestCase() { GTEST_LOG_(INFO) << "AbilityInterceptorTest SetUpTestCase called"; + AbilityManagerClient::GetInstance()->CleanAllMissions(); OHOS::DelayedSingleton::DestroyInstance(); OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( diff --git a/test/unittest/ability_manager_client_branch_test/BUILD.gn b/test/unittest/ability_manager_client_branch_test/BUILD.gn index 313201ab54..aed05b337b 100644 --- a/test/unittest/ability_manager_client_branch_test/BUILD.gn +++ b/test/unittest/ability_manager_client_branch_test/BUILD.gn @@ -42,7 +42,6 @@ ohos_unittest("ability_manager_client_branch_test") { } 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_native_path}/ability/native:abilitykit_native", 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 e18967d846..60430f59ca 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 @@ -24,7 +24,6 @@ #undef protected #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_connect_callback.h" #include "mock_ability_manager_collaborator.h" #include "session/host/include/session.h" @@ -1378,7 +1377,7 @@ HWTEST_F(AbilityManagerClientBranchTest, StartAbilityByCall_002, TestSize.Level1 Want want; EXPECT_EQ(client_->StartAbilityByCall(want, nullptr), ERR_OK); client_->EnableRecoverAbility(nullptr); - EXPECT_EQ(client_->AddFreeInstallObserver(nullptr), ERR_OK); + EXPECT_EQ(client_->AddFreeInstallObserver(nullptr, nullptr), ERR_OK); } /** @@ -1639,6 +1638,20 @@ HWTEST_F(AbilityManagerClientBranchTest, RegisterOffListener_0100, TestSize.Leve EXPECT_EQ(result, ERR_OK); } +/** + * @tc.name: AbilityManagerClient_RegisterOffListener_0200 + * @tc.desc: RegisterOffListener + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AbilityManagerClientBranchTest, RegisterOffListener_0200, TestSize.Level1) +{ + std::string type = "continueStateChange"; + sptr listener = nullptr; + auto result = client_->RegisterOffListener(type, listener); + EXPECT_EQ(result, ERR_OK); +} + /** * @tc.name: AbilityManagerClient_RequestDialogService_0100 * @tc.desc: RequestDialogService diff --git a/test/unittest/ability_manager_client_branch_test/ability_manager_stub_mock_test.h b/test/unittest/ability_manager_client_branch_test/ability_manager_stub_mock_test.h index c13a888cec..d8af5cad48 100644 --- a/test/unittest/ability_manager_client_branch_test/ability_manager_stub_mock_test.h +++ b/test/unittest/ability_manager_client_branch_test/ability_manager_stub_mock_test.h @@ -267,7 +267,8 @@ public: return 0; } - int RegisterWindowManagerServiceHandler(const sptr& handler) override + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true) override { return 0; } @@ -299,8 +300,8 @@ public: int32_t userId, int requestCode)); MOCK_METHOD4(StartAbilityByInsightIntent, int32_t(const Want& want, const sptr& callerToken, uint64_t intentId, int32_t userId)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo& wantSenderInfo, const sptr& callerToken)); MOCK_METHOD2(SendWantSender, int(sptr target, const SenderInfo& senderInfo)); diff --git a/test/unittest/ability_manager_proxy_test/BUILD.gn b/test/unittest/ability_manager_proxy_test/BUILD.gn index 65efd7546f..5402ce7ce4 100644 --- a/test/unittest/ability_manager_proxy_test/BUILD.gn +++ b/test/unittest/ability_manager_proxy_test/BUILD.gn @@ -43,7 +43,6 @@ ohos_unittest("ability_manager_proxy_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", diff --git a/test/unittest/ability_manager_proxy_test/ability_manager_proxy_test.cpp b/test/unittest/ability_manager_proxy_test/ability_manager_proxy_test.cpp index 6b3de757c1..f3bef30da9 100644 --- a/test/unittest/ability_manager_proxy_test/ability_manager_proxy_test.cpp +++ b/test/unittest/ability_manager_proxy_test/ability_manager_proxy_test.cpp @@ -1052,6 +1052,27 @@ HWTEST_F(AbilityManagerProxyTest, AbilityManagerProxy_UninstallApp_001, TestSize EXPECT_EQ(res, NO_ERROR); } +/* + * Feature: AbilityManagerService + * Function: UninstallApp + * SubFunction: NA + * FunctionPoints: AbilityManagerService UninstallApp + * EnvConditions: NA + * CaseDescription: Verify the normal process of UninstallApp + */ +HWTEST_F(AbilityManagerProxyTest, AbilityManagerProxy_UninstallApp_002, TestSize.Level1) +{ + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(mock_.GetRefPtr(), &AbilityManagerStubMock::InvokeSendRequest)); + std::string bundleName = ""; + int32_t uid = 1; + int32_t appIndex = 0; + auto res = proxy_->UninstallApp(bundleName, uid, appIndex); + EXPECT_EQ(static_cast(AbilityManagerInterfaceCode::UNINSTALL_APP), mock_->code_); + EXPECT_EQ(res, NO_ERROR); +} + /* * Feature: AbilityManagerService * Function: UpgradeApp @@ -1068,7 +1089,8 @@ HWTEST_F(AbilityManagerProxyTest, AbilityManagerProxy_UpgradeApp_001, TestSize.L std::string bundleName = ""; int32_t uid = 1; std::string exitMsg = "App upgrade."; - auto res = proxy_->UpgradeApp(bundleName, uid, exitMsg); + int32_t appIndex = 0; + auto res = proxy_->UpgradeApp(bundleName, uid, exitMsg, appIndex); EXPECT_EQ(static_cast(AbilityManagerInterfaceCode::UPGRADE_APP), mock_->code_); EXPECT_EQ(res, NO_ERROR); } @@ -1606,7 +1628,7 @@ HWTEST_F(AbilityManagerProxyTest, AbilityManagerProxy_SetMissionLabel_001, TestS HWTEST_F(AbilityManagerProxyTest, AbilityManagerProxy_RegisterWindowManagerServiceHandler_001, TestSize.Level1) { sptr handler = nullptr; - auto res = proxy_->RegisterWindowManagerServiceHandler(handler); + auto res = proxy_->RegisterWindowManagerServiceHandler(handler, true); EXPECT_EQ(res, INNER_ERR); } diff --git a/test/unittest/ability_manager_proxy_test/ability_manager_stub_mock.h b/test/unittest/ability_manager_proxy_test/ability_manager_stub_mock.h index 437e9cee9d..3e9df7d2d9 100644 --- a/test/unittest/ability_manager_proxy_test/ability_manager_stub_mock.h +++ b/test/unittest/ability_manager_proxy_test/ability_manager_stub_mock.h @@ -220,7 +220,8 @@ public: return 0; } - virtual int32_t UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg) + virtual int32_t UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg, + int32_t appIndex) { return 0; } @@ -288,7 +289,8 @@ public: return 0; } - int RegisterWindowManagerServiceHandler(const sptr& handler) override + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true) override { return 0; } @@ -310,8 +312,8 @@ public: int32_t userId, int requestCode)); MOCK_METHOD4(StartAbilityByInsightIntent, int32_t(const Want& want, const sptr& callerToken, uint64_t intentId, int32_t userId)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want &want, const sptr &callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want &want, const sptr &callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo& wantSenderInfo, const sptr& callerToken)); MOCK_METHOD2(SendWantSender, int(sptr target, const SenderInfo& senderInfo)); diff --git a/test/unittest/ability_manager_service_account_test/ability_manager_service_account_test.cpp b/test/unittest/ability_manager_service_account_test/ability_manager_service_account_test.cpp index c9bd177786..f3d391cbae 100644 --- a/test/unittest/ability_manager_service_account_test/ability_manager_service_account_test.cpp +++ b/test/unittest/ability_manager_service_account_test/ability_manager_service_account_test.cpp @@ -20,6 +20,7 @@ #include "ability_event_handler.h" #include "ability_connect_manager.h" #include "ams_configuration_parameter.h" +#include "mission_list_manager.h" #undef private #undef protected @@ -57,6 +58,16 @@ static void WaitUntilTaskFinished() } } } + +static std::shared_ptr GetMissionListTopAbility( + std::shared_ptr missionListMgr) +{ + if (!missionListMgr) { + return nullptr; + } + return reinterpret_cast(missionListMgr.get()).GetCurrentTopAbilityLocked(); +} + namespace { const int32_t USER_ID_U100 = 100; const int32_t ERROR_USER_ID_U256 = 256; @@ -112,7 +123,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_StartAbility_001, TestSize.Le { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_StartAbility_001 start"; abilityMs_->StartUser(USER_ID_U100, nullptr); - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -124,7 +135,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_StartAbility_001, TestSize.Le EXPECT_EQ(OHOS::ERR_OK, result); abilityMs_->StartUser(newUserId, nullptr); - topAbility = abilityMs_->GetMissionListManagerByUserId(newUserId)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(newUserId)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -147,7 +158,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_StartAbility_001, TestSize.Le HWTEST_F(AbilityManagerServiceAccountTest, Account_StartAbility_002, TestSize.Level1) { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_StartAbility_002 start"; - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -158,7 +169,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_StartAbility_002, TestSize.Le WaitUntilTaskFinished(); EXPECT_EQ(OHOS::ERR_OK, result); - topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); sptr token = nullptr; if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); @@ -186,7 +197,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_StartAbility_003, TestSize.Le GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_StartAbility_003 start"; AbilityStartSetting abilityStartSetting; // default user - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -198,7 +209,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_StartAbility_003, TestSize.Le EXPECT_EQ(OHOS::ERR_OK, result); abilityMs_->StartUser(newUserId, nullptr); - topAbility = abilityMs_->GetMissionListManagerByUserId(newUserId)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(newUserId)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -222,7 +233,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_StartAbility_004, TestSize.Le GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_StartAbility_004 start"; StartOptions abilityStartOptions; // default user - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -234,7 +245,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_StartAbility_004, TestSize.Le EXPECT_EQ(OHOS::ERR_OK, result); abilityMs_->StartUser(newUserId, nullptr); - topAbility = abilityMs_->GetMissionListManagerByUserId(newUserId)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(newUserId)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -386,7 +397,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_StartAbility_011, TestSize.Le { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_StartAbility_011 start"; abilityMs_->StartUser(USER_ID_U100, nullptr); - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -410,7 +421,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_StartAbility_011, TestSize.Le HWTEST_F(AbilityManagerServiceAccountTest, Account_TerminateAbility_001, TestSize.Level1) { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_TerminateAbility_001 start"; - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -421,7 +432,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_TerminateAbility_001, TestSiz WaitUntilTaskFinished(); EXPECT_EQ(OHOS::ERR_OK, result); - topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); sptr token = nullptr; if (topAbility) { @@ -761,7 +772,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleConnectAbilityDone_00 HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleConnectAbilityDone_002, TestSize.Level1) { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_ScheduleConnectAbilityDone_002 start"; - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -772,7 +783,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleConnectAbilityDone_00 WaitUntilTaskFinished(); EXPECT_EQ(OHOS::ERR_OK, result); - topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); sptr token = nullptr; if (topAbility) { @@ -843,7 +854,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleConnectAbilityDone_00 { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_ScheduleConnectAbilityDone_004 start"; abilityMs_->StartUser(newUserId, nullptr); - auto topAbility = abilityMs_->GetMissionListManagerByUserId(newUserId)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(newUserId)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -854,7 +865,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleConnectAbilityDone_00 WaitUntilTaskFinished(); EXPECT_EQ(OHOS::ERR_OK, result); - topAbility = abilityMs_->GetMissionListManagerByUserId(newUserId)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(newUserId)); sptr token = nullptr; if (topAbility) { @@ -923,7 +934,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleDisconnectAbilityDone HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleDisconnectAbilityDone_002, TestSize.Level1) { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_ScheduleDisconnectAbilityDone_002 start"; - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -934,7 +945,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleDisconnectAbilityDone WaitUntilTaskFinished(); EXPECT_EQ(OHOS::ERR_OK, result); - topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); sptr token = nullptr; if (topAbility) { @@ -961,7 +972,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleDisconnectAbilityDone { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_ScheduleDisconnectAbilityDone_003 start"; abilityMs_->StartUser(newUserId, nullptr); - auto topAbility = abilityMs_->GetMissionListManagerByUserId(newUserId)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(newUserId)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -972,7 +983,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleDisconnectAbilityDone WaitUntilTaskFinished(); EXPECT_EQ(OHOS::ERR_OK, result); - topAbility = abilityMs_->GetMissionListManagerByUserId(newUserId)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(newUserId)); sptr token = nullptr; if (topAbility) { @@ -1041,7 +1052,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleCommandAbilityDone_00 HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleCommandAbilityDone_002, TestSize.Level1) { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_ScheduleCommandAbilityDone_002 start"; - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -1052,7 +1063,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleCommandAbilityDone_00 WaitUntilTaskFinished(); EXPECT_EQ(OHOS::ERR_OK, result); - topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); sptr token = nullptr; if (topAbility) { @@ -1123,7 +1134,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleCommandAbilityDone_00 { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_ScheduleCommandAbilityDone_004 start"; abilityMs_->StartUser(newUserId, nullptr); - auto topAbility = abilityMs_->GetMissionListManagerByUserId(newUserId)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(newUserId)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -1134,7 +1145,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_ScheduleCommandAbilityDone_00 WaitUntilTaskFinished(); EXPECT_EQ(OHOS::ERR_OK, result); - topAbility = abilityMs_->GetMissionListManagerByUserId(newUserId)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(newUserId)); sptr token = nullptr; if (topAbility) { @@ -1306,7 +1317,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_MinimizeAbility_001, TestSize { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_MinimizeAbility_001 start"; // default user - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -1317,7 +1328,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_MinimizeAbility_001, TestSize WaitUntilTaskFinished(); EXPECT_EQ(ERR_OK, result); - topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); sptr token = nullptr; if (topAbility) { @@ -1340,7 +1351,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_AttachAbilityThread_001, Test { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_AttachAbilityThread_001 start"; // default user - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -1351,7 +1362,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_AttachAbilityThread_001, Test WaitUntilTaskFinished(); EXPECT_EQ(OHOS::ERR_OK, result); OHOS::sptr scheduler = new AbilityScheduler(); - topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); sptr token = nullptr; if (topAbility) { token = topAbility->GetToken(); @@ -1372,7 +1383,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_OnAbilityRequestDone_001, Tes { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_OnAbilityRequestDone_001 start"; // default user - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } @@ -1382,7 +1393,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_OnAbilityRequestDone_001, Tes auto result = abilityMs_->StartAbility(want, USER_ID_U100, -1); WaitUntilTaskFinished(); EXPECT_EQ(ERR_OK, result); - topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); sptr token = nullptr; if (topAbility) { token = topAbility->GetToken(); @@ -1403,7 +1414,7 @@ HWTEST_F(AbilityManagerServiceAccountTest, Account_KillProcess_001, TestSize.Lev { GTEST_LOG_(INFO) << "AbilityManagerServiceAccountTest Account_KillProcess_001 start"; // default user - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = GetMissionListTopAbility(abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)); if (topAbility) { topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND); } diff --git a/test/unittest/ability_manager_service_dialog_test/ability_manager_service_dialog_test.cpp b/test/unittest/ability_manager_service_dialog_test/ability_manager_service_dialog_test.cpp index 1ec80a3c0d..8757e1e182 100644 --- a/test/unittest/ability_manager_service_dialog_test/ability_manager_service_dialog_test.cpp +++ b/test/unittest/ability_manager_service_dialog_test/ability_manager_service_dialog_test.cpp @@ -25,7 +25,6 @@ #undef protected #include "ability_manager_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "scene_board_judgement.h" using namespace testing; @@ -120,8 +119,8 @@ HWTEST_F(AbilityMgrServiceDialogTest, AbilityMgrServiceDialog_0300, TestSize.Lev Want targetWant; auto ret = systemDialogScheduler_->GetSelectorDialogWant(dialogAppInfos, requestWant, targetWant, nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - EXPECT_EQ(targetWant.GetElement().GetBundleName(), "com.ohos.amsdialog"); - EXPECT_EQ(targetWant.GetElement().GetAbilityName(), "SelectorDialog"); + EXPECT_EQ(requestWant.GetElement().GetBundleName(), "com.ohos.amsdialog"); + EXPECT_EQ(requestWant.GetElement().GetAbilityName(), "SelectorDialog"); } EXPECT_NE(systemDialogScheduler_, nullptr); TAG_LOGI(AAFwkTag::TEST, "AbilityMgrServiceDialog_0300 end"); 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 dc1fa5528e..3837abf974 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 @@ -22,6 +22,7 @@ #include "ability_manager_service.h" #include "ability_connect_manager.h" #include "ability_connection.h" +#include "ability_scheduler.h" #include "ability_start_setting.h" #include "recovery_param.h" #undef private @@ -1132,7 +1133,8 @@ HWTEST_F(AbilityManagerServiceFirstTest, UpgradeApp_001, TestSize.Level1) std::string bundleName = ""; int32_t uid = 1; std::string exitMsg = "App upgrade."; - EXPECT_EQ(abilityMs_->UpgradeApp(bundleName, uid, exitMsg), ERR_NULL_OBJECT); + int32_t appIndex = 0; + EXPECT_EQ(abilityMs_->UpgradeApp(bundleName, uid, exitMsg, appIndex), ERR_NULL_OBJECT); TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFirstTest UpgradeApp_001 end"); } @@ -1683,5 +1685,167 @@ HWTEST_F(AbilityManagerServiceFirstTest, QueryAllAutoStartupApplications_0200, T auto result = abilityMs_->QueryAllAutoStartupApplications(infoList); EXPECT_NE(result, ERR_NO_INIT); } + +/** + * @tc.name: AbilityManagerServiceFirstTest_StopServiceAbility_002 + * @tc.desc: Test the state of StopServiceAbility + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerServiceFirstTest, StopServiceAbility_002, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFirstTest StopServiceAbility_002 start"); + MyFlag::flag_ = 1; + auto abilityMs = std::make_shared(); + Want want; + EXPECT_EQ(abilityMs->StopServiceAbility(want, USER_ID_U100), ERR_CROSS_USER); + MyFlag::flag_ = 0; + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFirstTest StopServiceAbility_002 end"); +} + +/** + * @tc.name: AbilityManagerServiceFirstTest_StopServiceAbility_003 + * @tc.desc: Test the state of StopServiceAbility + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerServiceFirstTest, StopServiceAbility_003, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFirstTest StopServiceAbility_003 start"); + MyFlag::flag_ = 1; + auto abilityMs = std::make_shared(); + const int32_t index = -1; + const int32_t userId = -1; + Want want; + want.SetBundle("com.example.abilityManagerServiceTest"); + want.SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, index); + EXPECT_EQ(abilityMs->StopServiceAbility(want, userId), ERR_APP_CLONE_INDEX_INVALID); + MyFlag::flag_ = 0; + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFirstTest StopServiceAbility_003 end"); +} + +/** + * @tc.name: AbilityManagerServiceFirstTest_KillProcess_0100 + * @tc.desc: Test the state of KillProcess + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerServiceFirstTest, KillProcess_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFirstTest KillProcess_0100 start"); + auto abilityMs = std::make_shared(); + auto resultFunction = abilityMs->KillProcess("test"); + EXPECT_EQ(resultFunction, GET_BUNDLE_INFO_FAILED); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFirstTest KillProcess_0100 end"); +} + +/** + * @tc.name: AbilityManagerServiceFirstTest_ExecuteIntent_0100 + * @tc.desc: Test ExecuteIntent without permission. + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerServiceFirstTest, ExecuteIntent_0100, TestSize.Level1) +{ + uint64_t key = 0; + sptr callerToken; + InsightIntentExecuteParam param; + auto abilityMs = std::make_shared(); + auto res = abilityMs->ExecuteIntent(key, callerToken, param); + auto expectRes = 1; + EXPECT_EQ(res, expectRes); +} + +/** + * @tc.name: AbilityManagerServiceFirstTest_IsAbilityStarted_0100 + * @tc.desc: Test when missionListMgr is nullptr and IsSceneBoardEnabled return false. + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerServiceFirstTest, IsAbilityStarted_0100, TestSize.Level1) +{ + AppExecFwk::AbilityRequest abilityRequest; + std::shared_ptr targetRecord = MockAbilityRecord(AbilityType::PAGE); + int32_t oriValidUserId = 0; + + auto abilityMs = std::make_shared(); + auto res = abilityMs->IsAbilityStarted(abilityRequest, targetRecord, oriValidUserId); + EXPECT_EQ(res, false); +} + +/** + * @tc.name: AbilityManagerServiceFirstTest_OnExecuteIntent_0100 + * @tc.desc: Test OnExecuteIntent. + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerServiceFirstTest, OnExecuteIntent_0100, TestSize.Level1) +{ + AbilityRequest abilityRequest; + std::shared_ptr targetRecord = nullptr; + auto abilityMs = std::make_shared(); + auto res = abilityMs->OnExecuteIntent(abilityRequest, targetRecord); + EXPECT_EQ(res, ERR_INVALID_VALUE); +} + +/** + * @tc.name: AbilityManagerServiceFirstTest_OnExecuteIntent_0200 + * @tc.desc: Test OnExecuteIntent. + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerServiceFirstTest, OnExecuteIntent_0200, TestSize.Level1) +{ + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "data.client.bundle"; + abilityRequest.abilityInfo.name = "ClientAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + + std::shared_ptr targetRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + + OHOS::sptr scheduler = new AbilityScheduler(); + targetRecord->SetScheduler(scheduler); + + auto abilityMs = std::make_shared(); + auto res = abilityMs->OnExecuteIntent(abilityRequest, targetRecord); + EXPECT_EQ(res, ERR_OK); +} + +/** + * @tc.name: AbilityManagerServiceFirstTest_StartAbilityWithInsightIntent_0100 + * @tc.desc: Test StartAbilityWithInsightIntent. + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerServiceFirstTest, StartAbilityWithInsightIntent_0100, TestSize.Level1) +{ + Want want; + int32_t userId = 1; + int requestCode = 0; + auto abilityMs = std::make_shared(); + auto res = abilityMs->StartAbilityWithInsightIntent(want, userId, requestCode); + EXPECT_EQ(res, ERR_INVALID_CALLER); +} + +/** + * @tc.name: AbilityManagerServiceFirstTest_StartExtensionAbilityWithInsightIntent_0100 + * @tc.desc: Test StartExtensionAbilityWithInsightIntent. + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerServiceFirstTest, StartExtensionAbilityWithInsightIntent_0100, TestSize.Level1) +{ + Want want; + AppExecFwk::ExtensionAbilityType extensionType = AppExecFwk::ExtensionAbilityType::UNSPECIFIED; + auto abilityMs = std::make_shared(); + auto res = abilityMs->StartExtensionAbilityWithInsightIntent(want, extensionType); + EXPECT_EQ(res, CHECK_PERMISSION_FAILED); +} + +/** + * @tc.name: AbilityManagerServiceFirstTest_StartAbilityByCallWithInsightIntent_0100 + * @tc.desc: Test StartAbilityByCallWithInsightIntent. + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerServiceFirstTest, StartAbilityByCallWithInsightIntent_0100, TestSize.Level1) +{ + Want want; + InsightIntentExecuteParam param; + sptr callerToken = MockToken(AbilityType::PAGE); + auto abilityMs = std::make_shared(); + auto res = abilityMs->StartAbilityByCallWithInsightIntent(want, callerToken, param); + EXPECT_EQ(res, RESOLVE_ABILITY_ERR); +} } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/ability_manager_service_first_test/mock/src/mock_permission_verification.cpp b/test/unittest/ability_manager_service_first_test/mock/src/mock_permission_verification.cpp index ef3307f180..c5507513b5 100644 --- a/test/unittest/ability_manager_service_first_test/mock/src/mock_permission_verification.cpp +++ b/test/unittest/ability_manager_service_first_test/mock/src/mock_permission_verification.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ -#include "hilog_wrapper.h" #include "mock_permission_verification.h" namespace OHOS { diff --git a/test/unittest/ability_manager_service_fourth_test/BUILD.gn b/test/unittest/ability_manager_service_fourth_test/BUILD.gn new file mode 100644 index 0000000000..8558ddb766 --- /dev/null +++ b/test/unittest/ability_manager_service_fourth_test/BUILD.gn @@ -0,0 +1,105 @@ +# 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. + +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +module_output_path = "ability_runtime/abilitymgr" + +ohos_unittest("ability_manager_service_fourth_test") { + module_out_path = module_output_path + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" + + 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_path}/services/abilitymgr/include/interceptor/", + "${ability_runtime_services_path}/abilitymgr/include", + "${ability_runtime_services_path}/common/include", + "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include", + "mock/include", + ] + + 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/exit_reason.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_fourth_test.cpp", + "mock/src/mock_ability_interceptor_executer.cpp", + "mock/src/mock_ipc_skeleton.cpp", + "mock/src/mock_my_flag.cpp", + "mock/src/mock_permission_verification.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + deps = [ + "${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", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:perm_verification", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "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", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "samgr:samgr_proxy", + ] + + if (ability_runtime_graphics) { + external_deps += [ + "window_manager:libwsutils", + "window_manager:scene_session", + ] + } +} + +group("unittest") { + testonly = true + deps = [ ":ability_manager_service_fourth_test" ] +} diff --git a/test/unittest/ability_manager_service_fourth_test/ability_manager_service_fourth_test.cpp b/test/unittest/ability_manager_service_fourth_test/ability_manager_service_fourth_test.cpp new file mode 100644 index 0000000000..e4e5cc4abd --- /dev/null +++ b/test/unittest/ability_manager_service_fourth_test/ability_manager_service_fourth_test.cpp @@ -0,0 +1,1133 @@ +/* + * 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 + + +#define private public +#define protected public +#include "mock_ipc_skeleton.h" +#include "mock_permission_verification.h" +#include "mock_my_flag.h" +#include "ability_manager_service.h" +#undef private +#undef protected +#include "hilog_tag_wrapper.h" +#include "mock_ability_token.h" +#include "ability_bundle_event_callback.h" +#include "session/host/include/session.h" +#include "system_ability_definition.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; +using OHOS::AppExecFwk::AbilityType; +using OHOS::AppExecFwk::ExtensionAbilityType; + +constexpr char DEVELOPER_MODE_STATE[] = "const.security.developermode.state"; +constexpr const char* DEBUG_APP = "debugApp"; +constexpr const char* START_ABILITY_TYPE = "ABILITY_INNER_START_WITH_ACCOUNT"; + +constexpr int32_t FOUNDATION_UID = 5523; + +namespace OHOS { +namespace AAFwk { +class AbilityManagerServiceFourthTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + std::shared_ptr MockAbilityRecord(AbilityType); + sptr MockToken(AbilityType); + sptr MockSessionInfo(int32_t persistentId); +}; + +void AbilityManagerServiceFourthTest::SetUpTestCase() {} + +void AbilityManagerServiceFourthTest::TearDownTestCase() {} + +void AbilityManagerServiceFourthTest::SetUp() {} + +void AbilityManagerServiceFourthTest::TearDown() {} + +sptr AbilityManagerServiceFourthTest::MockSessionInfo(int32_t persistentId) +{ + sptr sessionInfo = new (std::nothrow) SessionInfo(); + if (!sessionInfo) { + TAG_LOGE(AAFwkTag::TEST, "sessionInfo is nullptr"); + return nullptr; + } + sessionInfo->persistentId = persistentId; + return sessionInfo; +} + +std::shared_ptr AbilityManagerServiceFourthTest::MockAbilityRecord(AbilityType abilityType) +{ + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.test.demo"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = abilityType; + return AbilityRecord::CreateAbilityRecord(abilityRequest); +} + +sptr AbilityManagerServiceFourthTest::MockToken(AbilityType abilityType) +{ + std::shared_ptr abilityRecord = MockAbilityRecord(abilityType); + if (!abilityRecord) { + return nullptr; + } + return abilityRecord->GetToken(); +} + + +/* + * Feature: AbilityManagerService + * Function: AddFreeInstallObserver + * SubFunction: NA + * FunctionPoints: AbilityManagerService AddFreeInstallObserver + */ +HWTEST_F(AbilityManagerServiceFourthTest, AddFreeInstallObserver_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceSecondTest AddFreeInstallObserver_001 start"); + auto abilityMs_ = std::make_shared(); + sptr observer; + EXPECT_EQ(abilityMs_->AddFreeInstallObserver(nullptr, observer), ERR_INVALID_VALUE); + + abilityMs_->freeInstallManager_ = std::make_shared(abilityMs_); + EXPECT_EQ(abilityMs_->AddFreeInstallObserver(nullptr, observer), ERR_INVALID_VALUE); + + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceSecondTest AddFreeInstallObserver_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: VerifyPermission + * SubFunction: NA + * FunctionPoints: AbilityManagerService VerifyPermission + */ +HWTEST_F(AbilityManagerServiceFourthTest, VerifyPermission_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest VerifyPermission_001 start"); + auto abilityMs_ = std::make_shared(); + + std::string permission = "test_permission"; + int pid = 0; + int uid = 0; + EXPECT_EQ(abilityMs_->VerifyPermission(permission, pid, uid), CHECK_PERMISSION_FAILED); + + std::string permission2 = ""; + EXPECT_EQ(abilityMs_->VerifyPermission(permission2, pid, uid), CHECK_PERMISSION_FAILED); + + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest VerifyPermission_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: AcquireShareData + * SubFunction: NA + * FunctionPoints: AbilityManagerService AcquireShareData + */ +HWTEST_F(AbilityManagerServiceFourthTest, AcquireShareData_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest AcquireShareData_001 start"); + auto abilityMs_ = std::make_shared(); + + int32_t missionId = 1; + sptr shareData = nullptr; + EXPECT_EQ(abilityMs_->AcquireShareData(missionId, shareData), ERR_INVALID_VALUE); + + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest AcquireShareData_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: ShareDataDone + * SubFunction: NA + * FunctionPoints: AbilityManagerService ShareDataDone + */ +HWTEST_F(AbilityManagerServiceFourthTest, ShareDataDone_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ShareDataDone_001 start"); + auto abilityMs_ = std::make_shared(); + + sptr token = nullptr; + int32_t resultCode = 1; + int32_t uniqueId = 1; + WantParams wantParam; + EXPECT_EQ(abilityMs_->ShareDataDone(token, resultCode, uniqueId, wantParam), ERR_INVALID_VALUE); + + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ShareDataDone_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: NotifySaveAsResult + * SubFunction: NA + * FunctionPoints: AbilityManagerService NotifySaveAsResult + */ +HWTEST_F(AbilityManagerServiceFourthTest, NotifySaveAsResult_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest NotifySaveAsResult_001 start"); + auto abilityMs_ = std::make_shared(); + + Want want; + auto result = abilityMs_->NotifySaveAsResult(want, 0, 0); + EXPECT_EQ(result, CHECK_PERMISSION_FAILED); + + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest NotifySaveAsResult_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: InitDefaultRecoveryList + * FunctionPoints: AbilityManagerService InitDefaultRecoveryList + */ +HWTEST_F(AbilityManagerServiceFourthTest, InitDefaultRecoveryList_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->InitDefaultRecoveryList(); + EXPECT_NE(abilityMs, nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: OnStop + * FunctionPoints: AbilityManagerService OnStop + */ +HWTEST_F(AbilityManagerServiceFourthTest, OnStop_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->abilityBundleEventCallback_ = new (std::nothrow) AbilityBundleEventCallback(nullptr, nullptr); + abilityMs->OnStop(); + EXPECT_NE(abilityMs->abilityBundleEventCallback_, nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: OnStop + * FunctionPoints: AbilityManagerService OnStop + */ +HWTEST_F(AbilityManagerServiceFourthTest, OnStop_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + abilityMs->OnStop(); + EXPECT_EQ(abilityMs->abilityBundleEventCallback_, nullptr); +} + +/* + * Feature: AbilityManagerService + * Function: GetConfiguration + * SubFunction: NA + * FunctionPoints: AbilityManagerService GetConfiguration + */ +HWTEST_F(AbilityManagerServiceFourthTest, GetConfiguration_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest GetConfiguration_001 start"); + auto abilityMs_ = std::make_shared(); + AppExecFwk::Configuration config; + abilityMs_->SubscribeBackgroundTask(); + EXPECT_EQ(abilityMs_->GetConfiguration(config), 0); + abilityMs_->UnSubscribeBackgroundTask(); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest GetConfiguration_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: ReportAbilitStartInfoToRSS + * FunctionPoints: AbilityManagerService ReportAbilitStartInfoToRSS + */ +HWTEST_F(AbilityManagerServiceFourthTest, ReportAbilitStartInfoToRSS_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ReportAbilitStartInfoToRSS start"); + auto abilityMs = std::make_shared(); + AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.type = AppExecFwk::AbilityType::PAGE; + abilityMs->ReportAbilitStartInfoToRSS(abilityInfo); + EXPECT_EQ(abilityInfo.type, AppExecFwk::AbilityType::PAGE); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ReportAbilitStartInfoToRSS end"); +} + +/* + * Feature: AbilityManagerService + * Function: ReportAbilitAssociatedStartInfoToRSS + * FunctionPoints: AbilityManagerService ReportAbilitAssociatedStartInfoToRSS + */ +HWTEST_F(AbilityManagerServiceFourthTest, ReportAbilitAssociatedStartInfoToRSS_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ReportAbilitAssociatedStartInfoToRSS start"); + auto abilityMs = std::make_shared(); + AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.type = AppExecFwk::AbilityType::PAGE; + sptr callerToken = nullptr; + int64_t type = 0; + abilityMs->ReportAbilitAssociatedStartInfoToRSS(abilityInfo, type, callerToken); + callerToken = MockToken(AbilityType::PAGE); + abilityMs->ReportAbilitAssociatedStartInfoToRSS(abilityInfo, type, callerToken); + EXPECT_EQ(abilityInfo.type, AppExecFwk::AbilityType::PAGE); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ReportAbilitAssociatedStartInfoToRSS end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartExtensionAbilityInner + * FunctionPoints: AbilityManagerService StartExtensionAbilityInner + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartExtensionAbilityInner_004, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartExtensionAbilityInner_004 start"); + 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; + abilityMs->interceptorExecuter_ = std::make_shared(); + abilityMs->subManagersHelper_ = std::make_shared(nullptr, nullptr); + auto result = abilityMs->StartExtensionAbilityInner(want, callerToken, userId, extensionType, checkSystemCaller, + isImplicit, isDlp); + EXPECT_EQ(result, ERR_IMPLICIT_START_ABILITY_FAIL); + + abilityMs-> implicitStartProcessor_ = std::make_shared(); + result = abilityMs->StartExtensionAbilityInner(want, callerToken, userId, extensionType, checkSystemCaller, + isImplicit, isDlp); + EXPECT_EQ(result, ERR_IMPLICIT_START_ABILITY_FAIL); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartExtensionAbilityInner_004 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityWithSpecifyTokenId + * FunctionPoints: AbilityManagerService StartAbilityWithSpecifyTokenId + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityWithSpecifyTokenId_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Want want; + sptr callerToken; + uint32_t specifyTokenId = 0; + int32_t userId = 0; + int32_t requestCode = 0; + IPCSkeleton::SetCallingUid(FOUNDATION_UID); + auto result = abilityMs->StartAbilityWithSpecifyTokenId(want, callerToken, specifyTokenId, userId, requestCode); + EXPECT_NE(result, ERR_INVALID_CONTINUATION_FLAG); +} + +/* + * Feature: AbilityManagerService + * Function: StartUIAbilityBySCB + * FunctionPoints: AbilityManagerService StartUIAbilityBySCB + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartUIAbilityBySCB_003, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + Rosen::SessionInfo info; + sptr sessionInfo(new SessionInfo()); + sessionInfo->sessionToken = new Rosen::Session(info); + bool isColdStart = true; + auto result = abilityMs->StartUIAbilityBySCB(sessionInfo, isColdStart); + EXPECT_EQ(result, ERR_WRONG_INTERFACE_CALL); + abilityMs->subManagersHelper_ = std::make_shared(nullptr, nullptr); + result = abilityMs->StartUIAbilityBySCB(sessionInfo, isColdStart); + EXPECT_EQ(result, ERR_WRONG_INTERFACE_CALL); +} + +/* + * Feature: AbilityManagerService + * Function: RequestDialogServiceInner + * FunctionPoints: AbilityManagerService RequestDialogServiceInner + */ +HWTEST_F(AbilityManagerServiceFourthTest, RequestDialogServiceInner_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest RequestDialogServiceInner_001 start"); + auto abilityMs = std::make_shared(); + Want want; + const sptr callerToken; + int32_t userId = 0; + int requestCode = 0; + auto result = abilityMs->RequestDialogServiceInner(want, callerToken, requestCode, userId); + EXPECT_EQ(result, ERR_INVALID_CALLER); + + abilityMs->subManagersHelper_ = std::make_shared(nullptr, nullptr); + abilityMs->subManagersHelper_->currentUIAbilityManager_ = std::make_shared(); + std::shared_ptr abilityRecord = MockAbilityRecord(AbilityType::PAGE); + sptr callerToken2 = abilityRecord->GetToken(); + + result = abilityMs->RequestDialogServiceInner(want, callerToken2, requestCode, userId); + EXPECT_EQ(result, ERR_INVALID_CALLER); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest RequestDialogServiceInner_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityForOptionInner + * FunctionPoints: AbilityManagerService StartAbilityForOptionInner + */ +HWTEST_F(AbilityManagerServiceFourthTest, 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); + abilityMs->interceptorExecuter_ = std::make_shared(); + result = abilityMs->StartAbilityForOptionInner(want, startOptions, callerToken, userId, requestCode, + isStartAsCaller, specifyTokenId, isImplicit); + EXPECT_NE(result, ERR_INVALID_VALUE); + + abilityMs-> implicitStartProcessor_ = std::make_shared(); + result = abilityMs->StartAbilityForOptionInner(want, startOptions, callerToken, userId, requestCode, + isStartAsCaller, specifyTokenId, isImplicit); + EXPECT_NE(result, ERR_INVALID_VALUE); +} + + +/* + * Feature: AbilityManagerService + * Function: InitDeepLinkReserve + * SubFunction: NA + * FunctionPoints: AbilityManagerService InitDeepLinkReserve + */ +HWTEST_F(AbilityManagerServiceFourthTest, InitDeepLinkReserve_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest InitDeepLinkReserve_001 start"); + auto abilityMs_ = std::make_shared(); + abilityMs_->InitDeepLinkReserve(); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest InitDeepLinkReserve_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: InitInterceptor + * SubFunction: NA + * FunctionPoints: AbilityManagerService InitInterceptor + */ +HWTEST_F(AbilityManagerServiceFourthTest, InitInterceptor_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest InitInterceptor_001 start"); + auto abilityMs_ = std::make_shared(); + abilityMs_->InitInterceptor(); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest InitInterceptor_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: InitStartupFlag + * SubFunction: NA + * FunctionPoints: AbilityManagerService InitStartupFlag + */ +HWTEST_F(AbilityManagerServiceFourthTest, InitStartupFlag_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest InitStartupFlag_001 start"); + auto abilityMs_ = std::make_shared(); + abilityMs_->InitStartupFlag(); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest InitStartupFlag_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: InitStartAbilityChain + * SubFunction: NA + * FunctionPoints: AbilityManagerService InitStartAbilityChain + */ +HWTEST_F(AbilityManagerServiceFourthTest, InitStartAbilityChain_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest InitStartAbilityChain_001 start"); + auto abilityMs_ = std::make_shared(); + abilityMs_->InitStartAbilityChain(); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest InitStartAbilityChain_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: QueryServiceState + * SubFunction: NA + * FunctionPoints: AbilityManagerService QueryServiceState + */ +HWTEST_F(AbilityManagerServiceFourthTest, QueryServiceState_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest QueryServiceState_001 start"); + auto abilityMs_ = std::make_shared(); + abilityMs_->QueryServiceState(); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest QueryServiceState_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbility + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbility_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbility_001 start"); + Want want; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbility(want, 0, 0); + want.SetParam(DEBUG_APP, true); + want.SetParam(DEVELOPER_MODE_STATE, false); + abilityMs_->StartAbility(want, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbility_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbility + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbility_002, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbility_002 start"); + Want want; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbility(want, callerToken, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbility_002 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByFreeInstall + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityByFreeInstall + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityByFreeInstall_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityByFreeInstall_001 start"); + Want want; + want.SetParam(START_ABILITY_TYPE, true); + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityByFreeInstall(want, callerToken, 0, 0); + want.SetParam(START_ABILITY_TYPE, false); + abilityMs_->StartAbilityByFreeInstall(want, callerToken, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityByFreeInstall_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityWithSpecifyTokenIdInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityWithSpecifyTokenIdInner + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityWithSpecifyTokenIdInner_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityWithSpecifyTokenIdInner_001 start"); + Want want; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityWithSpecifyTokenIdInner(want, callerToken, 0, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityWithSpecifyTokenIdInner_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityWithSpecifyTokenIdInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityWithSpecifyTokenIdInner + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityWithSpecifyTokenIdInner_002, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityWithSpecifyTokenIdInner_002 start"); + Want want; + StartOptions startOptions; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityWithSpecifyTokenIdInner(want, startOptions, callerToken, 0, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityWithSpecifyTokenIdInner_002 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByInsightIntent + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityByInsightIntent + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityByInsightIntent_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityByInsightIntent_001 start"); + Want want; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityByInsightIntent(want, callerToken, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityByInsightIntent_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByUIContentSession + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityByUIContentSession + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityByUIContentSession_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityByUIContentSession_001 start"); + Want want; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityByUIContentSession(want, callerToken, MockSessionInfo(0), 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityByUIContentSession_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByUIContentSession + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityByUIContentSession + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityByUIContentSession_002, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityByUIContentSession_002 start"); + Want want; + StartOptions startOptions; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityByUIContentSession(want, startOptions, callerToken, MockSessionInfo(0), 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityByUIContentSession_002 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityAsCaller + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityAsCaller + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityAsCaller_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityAsCaller_001 start"); + Want want; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityAsCaller(want, callerToken, callerToken, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityAsCaller_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: ImplicitStartAbilityAsCaller + * SubFunction: NA + * FunctionPoints: AbilityManagerService ImplicitStartAbilityAsCaller + */ +HWTEST_F(AbilityManagerServiceFourthTest, ImplicitStartAbilityAsCaller_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ImplicitStartAbilityAsCaller_001 start"); + Want want; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->ImplicitStartAbilityAsCaller(want, callerToken, callerToken, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ImplicitStartAbilityAsCaller_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityAsCallerDetails + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityAsCallerDetails + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityAsCallerDetails_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityAsCallerDetails_001 start"); + Want want; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityAsCallerDetails(want, callerToken, callerToken, 0, 0, true); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityAsCallerDetails_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityPublicPrechainCheck + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityPublicPrechainCheck + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityPublicPrechainCheck_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityPublicPrechainCheck_001 start"); + Want want; + StartAbilityParams startAbilityParams(want); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityPublicPrechainCheck(startAbilityParams); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityPublicPrechainCheck_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityPrechainInterceptor + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityPrechainInterceptor + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityPrechainInterceptor_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityPrechainInterceptor_001 start"); + Want want; + StartAbilityParams startAbilityParams(want); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityPrechainInterceptor(startAbilityParams); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityPrechainInterceptor_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: SetReserveInfo + * SubFunction: NA + * FunctionPoints: AbilityManagerService SetReserveInfo + */ +HWTEST_F(AbilityManagerServiceFourthTest, SetReserveInfo_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest SetReserveInfo_001 start"); + std::string linkString; + auto abilityMs_ = std::make_shared(); + abilityMs_->SetReserveInfo(linkString); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest SetReserveInfo_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: CheckExtensionCallPermission + * SubFunction: NA + * FunctionPoints: AbilityManagerService CheckExtensionCallPermission + */ +HWTEST_F(AbilityManagerServiceFourthTest, CheckExtensionCallPermission_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest CheckExtensionCallPermission_001 start"); + Want want; + AbilityRequest abilityRequest; + auto abilityMs_ = std::make_shared(); + abilityMs_->CheckExtensionCallPermission(want, abilityRequest); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest CheckExtensionCallPermission_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: CheckServiceCallPermission + * SubFunction: NA + * FunctionPoints: AbilityManagerService CheckServiceCallPermission + */ +HWTEST_F(AbilityManagerServiceFourthTest, CheckServiceCallPermission_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest CheckServiceCallPermission_001 start"); + Want want; + AbilityRequest abilityRequest; + AppExecFwk::AbilityInfo abilityInfo; + auto abilityMs_ = std::make_shared(); + abilityMs_->CheckServiceCallPermission(abilityRequest, abilityInfo); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest CheckServiceCallPermission_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: CheckBrokerCallPermission + * SubFunction: NA + * FunctionPoints: AbilityManagerService CheckBrokerCallPermission + */ +HWTEST_F(AbilityManagerServiceFourthTest, CheckBrokerCallPermission_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest CheckBrokerCallPermission_001 start"); + Want want; + AbilityRequest abilityRequest; + AppExecFwk::AbilityInfo abilityInfo; + auto abilityMs_ = std::make_shared(); + abilityMs_->CheckBrokerCallPermission(abilityRequest, abilityInfo); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest CheckBrokerCallPermission_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: CheckAbilityCallPermission + * SubFunction: NA + * FunctionPoints: AbilityManagerService CheckAbilityCallPermission + */ +HWTEST_F(AbilityManagerServiceFourthTest, CheckAbilityCallPermission_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest CheckAbilityCallPermission_001 start"); + AbilityRequest abilityRequest; + AppExecFwk::AbilityInfo abilityInfo; + auto abilityMs_ = std::make_shared(); + abilityMs_->CheckAbilityCallPermission(abilityRequest, abilityInfo, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest CheckAbilityCallPermission_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: CheckCallPermission + * SubFunction: NA + * FunctionPoints: AbilityManagerService CheckCallPermission + */ +HWTEST_F(AbilityManagerServiceFourthTest, CheckCallPermission_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest CheckCallPermission_001 start"); + Want want; + AbilityRequest abilityRequest; + AppExecFwk::AbilityInfo abilityInfo; + std::string callerBundleName{""}; + auto abilityMs_ = std::make_shared(); + abilityMs_->CheckCallPermission(want, abilityInfo, abilityRequest, true, true, 0, callerBundleName); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest CheckCallPermission_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: PreStartFreeInstall + * SubFunction: NA + * FunctionPoints: AbilityManagerService PreStartFreeInstall + */ +HWTEST_F(AbilityManagerServiceFourthTest, PreStartFreeInstall_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest PreStartFreeInstall_001 start"); + Want want, localWant; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->PreStartFreeInstall(want, callerToken, 0, true, localWant); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest PreStartFreeInstall_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByConnectManager + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityByConnectManager + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityByConnectManager_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityByConnectManager_001 start"); + Want want; + AbilityRequest abilityRequest; + AppExecFwk::AbilityInfo abilityInfo; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityByConnectManager(want, abilityRequest, abilityInfo, 0, callerToken); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityByConnectManager_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbility + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbility + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbility_003, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbility_003 start"); + Want want; + AbilityStartSetting abilityStartSetting; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbility(want, abilityStartSetting, callerToken, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbility_003 end"); +} + +/* + * Feature: AbilityManagerService + * Function: ImplicitStartAbility + * SubFunction: NA + * FunctionPoints: AbilityManagerService ImplicitStartAbility + */ +HWTEST_F(AbilityManagerServiceFourthTest, ImplicitStartAbility_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ImplicitStartAbility_001 start"); + Want want; + AbilityStartSetting abilityStartSetting; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->ImplicitStartAbility(want, abilityStartSetting, callerToken, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ImplicitStartAbility_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityAsCaller + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityAsCaller + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityAsCaller_002, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityAsCaller_002 start"); + Want want; + StartOptions startOptions; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityAsCaller(want, startOptions, callerToken, callerToken, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityAsCaller_002 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityForResultAsCaller + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityForResultAsCaller + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityForResultAsCaller_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityForResultAsCaller_001 start"); + Want want; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityForResultAsCaller(want, callerToken, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityForResultAsCaller_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityForResultAsCaller + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityForResultAsCaller + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartAbilityAsCaller_003, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityAsCaller_003 start"); + Want want; + StartOptions startOptions; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->StartAbilityForResultAsCaller(want, startOptions, callerToken, 0, 0); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartAbilityAsCaller_003 end"); +} + +/* + * Feature: AbilityManagerService + * Function: RequestDialogService + * SubFunction: NA + * FunctionPoints: AbilityManagerService RequestDialogService + */ +HWTEST_F(AbilityManagerServiceFourthTest, RequestDialogService_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest RequestDialogService_001 start"); + Want want; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->RequestDialogService(want, callerToken); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest RequestDialogService_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: ReportDrawnCompleted + * SubFunction: NA + * FunctionPoints: AbilityManagerService ReportDrawnCompleted + */ +HWTEST_F(AbilityManagerServiceFourthTest, ReportDrawnCompleted_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ReportDrawnCompleted_001 start"); + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->ReportDrawnCompleted(callerToken); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ReportDrawnCompleted_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: StartUIAbilityBySCB + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartUIAbilityBySCB + */ +HWTEST_F(AbilityManagerServiceFourthTest, StartUIAbilityBySCB_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartUIAbilityBySCB_001 start"); + bool isColdStart; + auto abilityMs_ = std::make_shared(); + abilityMs_->StartUIAbilityBySCB(MockSessionInfo(0), isColdStart); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest StartUIAbilityBySCB_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: IsDmsAlive + * SubFunction: NA + * FunctionPoints: AbilityManagerService IsDmsAlive + */ +HWTEST_F(AbilityManagerServiceFourthTest, IsDmsAlive_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest IsDmsAlive_001 start"); + auto abilityMs_ = std::make_shared(); + abilityMs_->IsDmsAlive(); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest IsDmsAlive_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: RecordAppExitReason + * SubFunction: NA + * FunctionPoints: AbilityManagerService RecordAppExitReason + */ +HWTEST_F(AbilityManagerServiceFourthTest, RecordAppExitReason_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest RecordAppExitReason_001 start"); + AAFwk::ExitReason exitReason; + auto abilityMs_ = std::make_shared(); + abilityMs_->RecordAppExitReason(exitReason); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest RecordAppExitReason_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: OnAddSystemAbility + * SubFunction: NA + * FunctionPoints: AbilityManagerService OnAddSystemAbility + */ +HWTEST_F(AbilityManagerServiceFourthTest, OnAddSystemAbility_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest OnAddSystemAbility_001 start"); + std::string deviceId{"BACKGROUND_TASK_MANAGER_SERVICE_ID"}; + auto abilityMs_ = std::make_shared(); + abilityMs_->OnAddSystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID, deviceId); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest OnAddSystemAbility_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: OnRemoveSystemAbility + * SubFunction: NA + * FunctionPoints: AbilityManagerService OnRemoveSystemAbility + */ +HWTEST_F(AbilityManagerServiceFourthTest, OnRemoveSystemAbility_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest OnRemoveSystemAbility_001 start"); + std::string deviceId{"BACKGROUND_TASK_MANAGER_SERVICE_ID"}; + auto abilityMs_ = std::make_shared(); + abilityMs_->OnRemoveSystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID, deviceId); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest OnRemoveSystemAbility_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: SubscribeBackgroundTask + * SubFunction: NA + * FunctionPoints: AbilityManagerService SubscribeBackgroundTask + */ +HWTEST_F(AbilityManagerServiceFourthTest, SubscribeBackgroundTask_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest SubscribeBackgroundTask_001 start"); + auto abilityMs_ = std::make_shared(); + abilityMs_->SubscribeBackgroundTask(); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest SubscribeBackgroundTask_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: UnSubscribeBackgroundTask + * SubFunction: NA + * FunctionPoints: AbilityManagerService UnSubscribeBackgroundTask + */ +HWTEST_F(AbilityManagerServiceFourthTest, UnSubscribeBackgroundTask_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest UnSubscribeBackgroundTask_001 start"); + auto abilityMs_ = std::make_shared(); + abilityMs_->UnSubscribeBackgroundTask(); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest UnSubscribeBackgroundTask_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: SubscribeBundleEventCallback + * SubFunction: NA + * FunctionPoints: AbilityManagerService SubscribeBundleEventCallback + */ +HWTEST_F(AbilityManagerServiceFourthTest, SubscribeBundleEventCallback_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest SubscribeBundleEventCallback_001 start"); + auto abilityMs_ = std::make_shared(); + abilityMs_->SubscribeBundleEventCallback(); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest SubscribeBundleEventCallback_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: UnsubscribeBundleEventCallback + * SubFunction: NA + * FunctionPoints: AbilityManagerService UnsubscribeBundleEventCallback + */ +HWTEST_F(AbilityManagerServiceFourthTest, UnsubscribeBundleEventCallback_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest UnsubscribeBundleEventCallback_001 start"); + auto abilityMs_ = std::make_shared(); + abilityMs_->UnsubscribeBundleEventCallback(); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest UnsubscribeBundleEventCallback_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: ReportEventToRSS + * SubFunction: NA + * FunctionPoints: AbilityManagerService ReportEventToRSS + */ +HWTEST_F(AbilityManagerServiceFourthTest, ReportEventToRSS_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ReportEventToRSS_001 start"); + AppExecFwk::AbilityInfo abilityInfo; + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->ReportEventToRSS(abilityInfo, callerToken); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ReportEventToRSS_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: RequestModalUIExtension + * SubFunction: NA + * FunctionPoints: AbilityManagerService RequestModalUIExtension + */ +HWTEST_F(AbilityManagerServiceFourthTest, RequestModalUIExtension_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest RequestModalUIExtension_001 start"); + Want want; + auto abilityMs_ = std::make_shared(); + abilityMs_->RequestModalUIExtension(want); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest RequestModalUIExtension_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: ChangeAbilityVisibility + * SubFunction: NA + * FunctionPoints: AbilityManagerService ChangeAbilityVisibility + */ +HWTEST_F(AbilityManagerServiceFourthTest, ChangeAbilityVisibility_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ChangeAbilityVisibility_001 start"); + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->ChangeAbilityVisibility(callerToken, true); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ChangeAbilityVisibility_001 end"); +} + +/* + * Feature: AbilityManagerService + * Function: ChangeUIAbilityVisibilityBySCB + * SubFunction: NA + * FunctionPoints: AbilityManagerService ChangeUIAbilityVisibilityBySCB + */ +HWTEST_F(AbilityManagerServiceFourthTest, ChangeUIAbilityVisibilityBySCB_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ChangeUIAbilityVisibilityBySCB_001 start"); + auto callerToken = MockToken(AbilityType::PAGE); + auto abilityMs_ = std::make_shared(); + abilityMs_->ChangeUIAbilityVisibilityBySCB(MockSessionInfo(0), true); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceFourthTest ChangeUIAbilityVisibilityBySCB_001 end"); +} + +} // namespace AAFwk +} // namespace OHOS diff --git a/test/unittest/ability_manager_service_third_test/mock/include/mock_ability_interceptor_executer.h b/test/unittest/ability_manager_service_fourth_test/mock/include/mock_ability_interceptor_executer.h similarity index 98% rename from test/unittest/ability_manager_service_third_test/mock/include/mock_ability_interceptor_executer.h rename to test/unittest/ability_manager_service_fourth_test/mock/include/mock_ability_interceptor_executer.h index 60374db238..5b2569f566 100644 --- a/test/unittest/ability_manager_service_third_test/mock/include/mock_ability_interceptor_executer.h +++ b/test/unittest/ability_manager_service_fourth_test/mock/include/mock_ability_interceptor_executer.h @@ -27,7 +27,7 @@ using InterceptorMap = std::unordered_map(); TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceSecondTest CheckCallDataAbilityPermission_002 start"); abilityRequest_.abilityInfo.type = AbilityType::DATA; - abilityMs_->Init(); EXPECT_EQ(abilityMs_->CheckCallDataAbilityPermission(abilityRequest_, false), ERR_INVALID_VALUE); TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceSecondTest CheckCallDataAbilityPermission_002 end"); } diff --git a/test/unittest/ability_manager_service_third_test/BUILD.gn b/test/unittest/ability_manager_service_third_test/BUILD.gn index 58c9de5fb7..ab8ca9a624 100644 --- a/test/unittest/ability_manager_service_third_test/BUILD.gn +++ b/test/unittest/ability_manager_service_third_test/BUILD.gn @@ -29,12 +29,10 @@ ohos_unittest("ability_manager_service_third_test") { "${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_path}/services/abilitymgr/include/interceptor/", "${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", - "mock/include", ] sources = [ @@ -52,20 +50,16 @@ ohos_unittest("ability_manager_service_third_test") { "${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", - "mock/src/mock_ability_interceptor_executer.cpp", - "mock/src/mock_ipc_skeleton.cpp", - "mock/src/mock_my_flag.cpp", - "mock/src/mock_permission_verification.cpp", ] configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] deps = [ - "${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", "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", "${ability_runtime_services_path}/abilitymgr:abilityms", "${ability_runtime_services_path}/common:perm_verification", "//third_party/googletest:gmock_main", 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 be7505f9ce..171ef9597b 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 @@ -17,11 +17,9 @@ #define private public #define protected public -#include "mock_ipc_skeleton.h" -#include "mock_permission_verification.h" -#include "mock_my_flag.h" -#include "mock_permission_verification.h" #include "ability_manager_service.h" +#include "ability_connect_manager.h" +#include "ability_connection.h" #include "ability_start_setting.h" #include "recovery_param.h" #undef private @@ -30,12 +28,15 @@ #include "ability_bundle_event_callback.h" #include "ability_manager_errors.h" #include "ability_manager_stub_mock_test.h" +#include "ability_info.h" #include "connection_observer_errors.h" +#include "free_install_manager.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" +#include "uri.h" using namespace testing; using namespace testing::ext; @@ -46,21 +47,55 @@ namespace OHOS { namespace AAFwk { namespace { const int32_t USER_ID_U100 = 100; -constexpr int32_t FOUNDATION_UID = 5523; const int32_t APP_MEMORY_SIZE = 512; +const uint32_t TOKENID = 211; const std::string EMPTY_DEVICE_ID = ""; +const std::string SESSIONID = "sessionId"; +const std::string APPID = "1003"; +const int REQUESTCODE = 10; } // namespace class AbilityManagerServiceThirdTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); + std::shared_ptr MockAbilityRecord(AbilityType); + sptr MockToken(AbilityType); void SetUp(); void TearDown(); + AbilityRequest GenerateAbilityRequest(const std::string& deviceName, const std::string& abilityName, + const std::string& appName, const std::string& bundleName, const std::string& moduleName); public: + AbilityRequest abilityRequest_{}; Want want_{}; }; +AbilityRequest AbilityManagerServiceThirdTest::GenerateAbilityRequest(const std::string& deviceName, + const std::string& abilityName, const std::string& appName, const std::string& bundleName, + const std::string& moduleName) +{ + ElementName element(deviceName, bundleName, abilityName, moduleName); + want_.SetElement(element); + + AbilityInfo abilityInfo; + abilityInfo.visible = true; + abilityInfo.applicationName = appName; + abilityInfo.type = AbilityType::EXTENSION; + abilityInfo.name = abilityName; + abilityInfo.bundleName = bundleName; + abilityInfo.moduleName = moduleName; + abilityInfo.deviceId = deviceName; + ApplicationInfo appinfo; + appinfo.name = appName; + appinfo.bundleName = bundleName; + abilityInfo.applicationInfo = appinfo; + AbilityRequest abilityRequest; + abilityRequest.want = want_; + abilityRequest.abilityInfo = abilityInfo; + abilityRequest.appInfo = appinfo; + + return abilityRequest; +} void AbilityManagerServiceThirdTest::SetUpTestCase() {} @@ -70,6 +105,24 @@ void AbilityManagerServiceThirdTest::SetUp() {} void AbilityManagerServiceThirdTest::TearDown() {} +std::shared_ptr AbilityManagerServiceThirdTest::MockAbilityRecord(AbilityType abilityType) +{ + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.test.demo"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = abilityType; + return AbilityRecord::CreateAbilityRecord(abilityRequest); +} + +sptr AbilityManagerServiceThirdTest::MockToken(AbilityType abilityType) +{ + std::shared_ptr abilityRecord = MockAbilityRecord(abilityType); + if (!abilityRecord) { + return nullptr; + } + return abilityRecord->GetToken(); +} + /* * Feature: AbilityManagerService * Function: HandleActiveTimeOut @@ -946,109 +999,10 @@ HWTEST_F(AbilityManagerServiceThirdTest, CheckUIExtensionIsFocused_001, TestSize TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest CheckUIExtensionIsFocused_001 start"); auto abilityMs_ = std::make_shared(); bool isFocused = false; - MyFlag::flag_ = 0; EXPECT_EQ(abilityMs_->CheckUIExtensionIsFocused(0, isFocused), CHECK_PERMISSION_FAILED); - MyFlag::flag_ = 1; TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest CheckUIExtensionIsFocused_001 end"); } -/* - * Feature: AbilityManagerService - * Function: AddFreeInstallObserver - * SubFunction: NA - * FunctionPoints: AbilityManagerService AddFreeInstallObserver - */ -HWTEST_F(AbilityManagerServiceThirdTest, AddFreeInstallObserver_001, TestSize.Level1) -{ - TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest AddFreeInstallObserver_001 start"); - auto abilityMs_ = std::make_shared(); - sptr observer; - EXPECT_EQ(abilityMs_->AddFreeInstallObserver(observer), ERR_INVALID_VALUE); - - abilityMs_->freeInstallManager_ = std::make_shared(abilityMs_); - EXPECT_EQ(abilityMs_->AddFreeInstallObserver(observer), ERR_INVALID_VALUE); - - TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest AddFreeInstallObserver_001 end"); -} - -/* - * Feature: AbilityManagerService - * Function: VerifyPermission - * SubFunction: NA - * FunctionPoints: AbilityManagerService VerifyPermission - */ -HWTEST_F(AbilityManagerServiceThirdTest, VerifyPermission_001, TestSize.Level1) -{ - TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest VerifyPermission_001 start"); - auto abilityMs_ = std::make_shared(); - - std::string permission = "test_permission"; - int pid = 0; - int uid = 0; - EXPECT_EQ(abilityMs_->VerifyPermission(permission, pid, uid), CHECK_PERMISSION_FAILED); - - std::string permission2 = ""; - EXPECT_EQ(abilityMs_->VerifyPermission(permission2, pid, uid), CHECK_PERMISSION_FAILED); - - TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest VerifyPermission_001 end"); -} - -/* - * Feature: AbilityManagerService - * Function: AcquireShareData - * SubFunction: NA - * FunctionPoints: AbilityManagerService AcquireShareData - */ -HWTEST_F(AbilityManagerServiceThirdTest, AcquireShareData_001, TestSize.Level1) -{ - TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest AcquireShareData_001 start"); - auto abilityMs_ = std::make_shared(); - - int32_t missionId = 1; - sptr shareData = nullptr; - EXPECT_EQ(abilityMs_->AcquireShareData(missionId, shareData), ERR_INVALID_VALUE); - - TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest AcquireShareData_001 end"); -} - -/* - * Feature: AbilityManagerService - * Function: ShareDataDone - * SubFunction: NA - * FunctionPoints: AbilityManagerService ShareDataDone - */ -HWTEST_F(AbilityManagerServiceThirdTest, ShareDataDone_001, TestSize.Level1) -{ - TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest ShareDataDone_001 start"); - auto abilityMs_ = std::make_shared(); - - sptr token = nullptr; - int32_t resultCode = 1; - int32_t uniqueId = 1; - WantParams wantParam; - EXPECT_EQ(abilityMs_->ShareDataDone(token, resultCode, uniqueId, wantParam), ERR_INVALID_VALUE); - - TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest ShareDataDone_001 end"); -} - -/* - * Feature: AbilityManagerService - * Function: NotifySaveAsResult - * SubFunction: NA - * FunctionPoints: AbilityManagerService NotifySaveAsResult - */ -HWTEST_F(AbilityManagerServiceThirdTest, NotifySaveAsResult_001, TestSize.Level1) -{ - TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest NotifySaveAsResult_001 start"); - auto abilityMs_ = std::make_shared(); - - Want want; - auto result = abilityMs_->NotifySaveAsResult(want, 0, 0); - EXPECT_EQ(result, ERR_INVALID_CALLER); - - TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest NotifySaveAsResult_001 end"); -} - /* * Feature: AbilityManagerService * Function: CheckCollaboratorType @@ -1327,18 +1281,6 @@ HWTEST_F(AbilityManagerServiceThirdTest, InitInterceptor_001, TestSize.Level1) EXPECT_NE(abilityMs, nullptr); } -/* - * Feature: AbilityManagerService - * Function: InitDefaultRecoveryList - * FunctionPoints: AbilityManagerService InitDefaultRecoveryList - */ -HWTEST_F(AbilityManagerServiceThirdTest, InitDefaultRecoveryList_001, TestSize.Level1) -{ - auto abilityMs = std::make_shared(); - abilityMs->InitDefaultRecoveryList(); - EXPECT_NE(abilityMs, nullptr); -} - /* * Feature: AbilityManagerService * Function: InitPushTask @@ -1388,31 +1330,6 @@ HWTEST_F(AbilityManagerServiceThirdTest, InitStartAbilityChain_001, TestSize.Lev EXPECT_NE(abilityMs, nullptr); } -/* - * Feature: AbilityManagerService - * Function: OnStop - * FunctionPoints: AbilityManagerService OnStop - */ -HWTEST_F(AbilityManagerServiceThirdTest, OnStop_001, TestSize.Level1) -{ - auto abilityMs = std::make_shared(); - abilityMs->abilityBundleEventCallback_ = new (std::nothrow) AbilityBundleEventCallback(nullptr, nullptr); - abilityMs->OnStop(); - EXPECT_NE(abilityMs->abilityBundleEventCallback_, nullptr); -} - -/* - * Feature: AbilityManagerService - * Function: OnStop - * FunctionPoints: AbilityManagerService OnStop - */ -HWTEST_F(AbilityManagerServiceThirdTest, OnStop_002, TestSize.Level1) -{ - auto abilityMs = std::make_shared(); - abilityMs->OnStop(); - EXPECT_EQ(abilityMs->abilityBundleEventCallback_, nullptr); -} - /* * Feature: AbilityManagerService * Function: QueryServiceState @@ -1476,23 +1393,6 @@ HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityWithSpecifyTokenId_001, Tes EXPECT_EQ(result, ERR_INVALID_CONTINUATION_FLAG); } -/* - * Feature: AbilityManagerService - * Function: StartAbilityWithSpecifyTokenId - * FunctionPoints: AbilityManagerService StartAbilityWithSpecifyTokenId - */ -HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityWithSpecifyTokenId_002, TestSize.Level1) -{ - auto abilityMs = std::make_shared(); - Want want; - sptr callerToken; - uint32_t specifyTokenId = 0; - int32_t userId = 0; - int32_t requestCode = 0; - IPCSkeleton::SetCallingUid(FOUNDATION_UID); - auto result = abilityMs->StartAbilityWithSpecifyTokenId(want, callerToken, specifyTokenId, userId, requestCode); - EXPECT_NE(result, ERR_INVALID_CONTINUATION_FLAG); -} /* * Feature: AbilityManagerService * Function: StartAbilityByInsightIntent @@ -1698,9 +1598,8 @@ HWTEST_F(AbilityManagerServiceThirdTest, ImplicitStartAbilityAsCaller_001, TestS sptr asCallerSourceToken; int32_t userId = 0; int requestCode = 0; - bool isSendDialogResult = true; auto result = abilityMs->ImplicitStartAbilityAsCaller(want, callerToken, asCallerSourceToken, userId, - requestCode, isSendDialogResult); + requestCode); EXPECT_EQ(result, ERR_INVALID_VALUE); } @@ -1717,10 +1616,9 @@ HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityAsCallerDetails_001, TestSi sptr asCallerSourceToken; int32_t userId = 0; int requestCode = 0; - bool isSendDialogResult = true; bool isImplicit = true; auto result = abilityMs->StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId, - requestCode, isSendDialogResult, isImplicit); + requestCode, isImplicit); EXPECT_EQ(result, ERR_INVALID_VALUE); } @@ -1738,10 +1636,9 @@ HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityAsCallerDetails_002, TestSi sptr asCallerSourceToken; int32_t userId = 0; int requestCode = 0; - bool isSendDialogResult = true; bool isImplicit = true; auto result = abilityMs->StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId, - requestCode, isSendDialogResult, isImplicit); + requestCode, isImplicit); EXPECT_EQ(result, ERR_INVALID_CONTINUATION_FLAG); } @@ -1758,10 +1655,9 @@ HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityAsCallerDetails_003, TestSi sptr asCallerSourceToken = new AbilityManagerStubTestMock(); int32_t userId = 0; int requestCode = 0; - bool isSendDialogResult = true; bool isImplicit = true; auto result = abilityMs->StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId, - requestCode, isSendDialogResult, isImplicit); + requestCode, isImplicit); EXPECT_EQ(result, ERR_INVALID_VALUE); } @@ -1821,12 +1717,11 @@ HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityWrap_001, TestSize.Level1) 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); + specifyToken, isForegroundToRestartApp, isImplicit); EXPECT_EQ(result, ERR_INVALID_VALUE); } @@ -1937,15 +1832,6 @@ HWTEST_F(AbilityManagerServiceThirdTest, StartAbilityForOptionInner_001, TestSiz auto result = abilityMs->StartAbilityForOptionInner(want, startOptions, callerToken, userId, requestCode, isStartAsCaller, specifyTokenId, isImplicit); EXPECT_EQ(result, ERR_INVALID_VALUE); - abilityMs->interceptorExecuter_ = std::make_shared(); - result = abilityMs->StartAbilityForOptionInner(want, startOptions, callerToken, userId, requestCode, - isStartAsCaller, specifyTokenId, isImplicit); - EXPECT_NE(result, ERR_INVALID_VALUE); - - abilityMs-> implicitStartProcessor_ = std::make_shared(); - result = abilityMs->StartAbilityForOptionInner(want, startOptions, callerToken, userId, requestCode, - isStartAsCaller, specifyTokenId, isImplicit); - EXPECT_NE(result, ERR_INVALID_VALUE); } /* @@ -2021,25 +1907,6 @@ HWTEST_F(AbilityManagerServiceThirdTest, StartUIAbilityBySCB_002, TestSize.Level EXPECT_EQ(result, ERR_INVALID_VALUE); } -/* - * Feature: AbilityManagerService - * Function: StartUIAbilityBySCB - * FunctionPoints: AbilityManagerService StartUIAbilityBySCB - */ -HWTEST_F(AbilityManagerServiceThirdTest, StartUIAbilityBySCB_003, TestSize.Level1) -{ - auto abilityMs = std::make_shared(); - Rosen::SessionInfo info; - sptr sessionInfo(new SessionInfo()); - sessionInfo->sessionToken = new Rosen::Session(info); - bool isColdStart = true; - auto result = abilityMs->StartUIAbilityBySCB(sessionInfo, isColdStart); - EXPECT_EQ(result, ERR_WRONG_INTERFACE_CALL); - abilityMs->subManagersHelper_ = std::make_shared(nullptr, nullptr); - result = abilityMs->StartUIAbilityBySCB(sessionInfo, isColdStart); - EXPECT_EQ(result, ERR_WRONG_INTERFACE_CALL); -} - /* * Feature: AbilityManagerService * Function: CheckCallingTokenId @@ -2051,7 +1918,7 @@ HWTEST_F(AbilityManagerServiceThirdTest, CheckCallingTokenId_001, TestSize.Level std::string bundleName = "test"; int32_t userId = 0; auto result = abilityMs->CheckCallingTokenId(bundleName, userId); - EXPECT_EQ(result, true); + EXPECT_EQ(result, false); } /* @@ -2453,20 +2320,425 @@ HWTEST_F(AbilityManagerServiceThirdTest, AnonymizeDeviceId_002, TestSize.Level1) EXPECT_EQ(result, EMPTY_DEVICE_ID); } +/* + * Feature: AbilityManagerService + * Function: OpenLink + * FunctionPoints: AbilityManagerService OpenLink + */ +HWTEST_F(AbilityManagerServiceThirdTest, OpenLink_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + sptr token = MockToken(AbilityType::PAGE); + AAFwk::Want want; + Uri uri(""); + want.GetOperation().SetUri(uri); + + auto result = abilityMs_->OpenLink(want, token, USER_ID_U100, REQUESTCODE); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest OpenLink_001 call result %{public}d", result); +} + +/* + * Feature: AbilityManagerService + * Function: NotifySCBToHandleAtomicServiceException + * FunctionPoints: AbilityManagerService NotifySCBToHandleAtomicServiceException + */ +HWTEST_F(AbilityManagerServiceThirdTest, NotifySCBToHandleAtomicServiceException_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + int32_t errCode = 0; + std::string reason; + abilityMs_->NotifySCBToHandleAtomicServiceException(SESSIONID, errCode, reason); +} + +/* + * Feature: AbilityManagerService + * Function: StartUIAbilityByPreInstallInner + * FunctionPoints: AbilityManagerService StartUIAbilityByPreInstallInner + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartUIAbilityByPreInstallInner_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + FreeInstallInfo taskInfo; + auto result2 = abilityMs_->StartUIAbilityByPreInstall(taskInfo); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest StartUIAbilityByPreInstallInner_001 result2 %{public}d", + result2); +} + +/* + * Feature: AbilityManagerService + * Function: PreStartInner + * FunctionPoints: AbilityManagerService PreStartInner + */ +HWTEST_F(AbilityManagerServiceThirdTest, PreStartInner_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + FreeInstallInfo taskInfo; + auto result = abilityMs_->PreStartInner(taskInfo); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest PreStartInner_001 call result %{public}d", result); +} + +/* + * Feature: AbilityManagerService + * Function: PreStartMission + * FunctionPoints: PreStartMission + */ +HWTEST_F(AbilityManagerServiceThirdTest, PreStartMission_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + auto result = abilityMs_->PreStartMission("com.ix.hiservcie", "entry", "ServiceAbility", "2024-07-16 10:00:00"); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest PreStartMission_001 call result %{public}d", result); +} + +/* + * Feature: AbilityManagerService + * Function: HandleRestartResidentProcessDependedOnWeb + * FunctionPoints: HandleRestartResidentProcessDependedOnWeb + */ +HWTEST_F(AbilityManagerServiceThirdTest, HandleRestartResidentProcessDependedOnWeb_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + abilityMs_->HandleRestartResidentProcessDependedOnWeb(); +} + +/* + * Feature: AbilityManagerService + * Function: NotifyFrozenProcessByRSS + * FunctionPoints: NotifyFrozenProcessByRSS + */ +HWTEST_F(AbilityManagerServiceThirdTest, NotifyFrozenProcessByRSS_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + std::vector pidList; + int32_t UID = 1000; + abilityMs_->NotifyFrozenProcessByRSS(pidList, UID); +} + +/* + * Feature: AbilityManagerService + * Function: GetRunningMultiAppIndex + * FunctionPoints: GetRunningMultiAppIndex + */ +HWTEST_F(AbilityManagerServiceThirdTest, GetRunningMultiAppIndex_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + int32_t UID = 1000; + int32_t APPINDEX = 28; + abilityMs_->GetRunningMultiAppIndex("com.ix.hiservcie", UID, APPINDEX); +} + + /* * Feature: AbilityManagerService * Function: TransferAbilityResultForExtension - * FunctionPoints: AbilityManagerService TransferAbilityResultForExtension + * FunctionPoints: TransferAbilityResultForExtension */ HWTEST_F(AbilityManagerServiceThirdTest, TransferAbilityResultForExtension_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + AAFwk::Want want; + sptr token = MockToken(AbilityType::PAGE); + int32_t resultCode = 0; + auto result = abilityMs_->TransferAbilityResultForExtension(token, resultCode, want); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest TransferAbilityResultForExtension %{public}d", result); +} + +/* + * Feature: AbilityManagerService + * Function: StartShortcut + * FunctionPoints: StartShortcut + */ +HWTEST_F(AbilityManagerServiceThirdTest, StartShortcut_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + AAFwk::Want want; + StartOptions startOp; + auto result = abilityMs_->StartShortcut(want, startOp); + TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceThirdTest StartShortcut %{public}d", result); +} + +/* + * Feature: AbilityManagerService + * Function: ConvertFullPath + * FunctionPoints: ConvertFullPath + */ +HWTEST_F(AbilityManagerServiceThirdTest, ConvertFullPath_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + std::string partialPath = ""; + std::string fullPath; + EXPECT_EQ(abilityMs_->ConvertFullPath(partialPath, fullPath), false); + + partialPath = "hello"; + EXPECT_NE(abilityMs_->ConvertFullPath(partialPath, fullPath), true); +} + +/* + * Feature: AbilityManagerService + * Function: ParseJsonValueFromFile + * FunctionPoints: ParseJsonValueFromFile + */ +HWTEST_F(AbilityManagerServiceThirdTest, ParseJsonValueFromFile_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + std::string filePath = "hello"; + nlohmann::json value; + abilityMs_->ParseJsonValueFromFile(value, filePath); +} + +/* + * Feature: AbilityManagerService + * Function: GetConfigFileAbsolutePath + * FunctionPoints: GetConfigFileAbsolutePath + */ +HWTEST_F(AbilityManagerServiceThirdTest, GetConfigFileAbsolutePath_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + EXPECT_EQ(abilityMs_->GetConfigFileAbsolutePath(""), ""); + std::string relativePath = "hello"; + abilityMs_->GetConfigFileAbsolutePath(relativePath); +} + +/* + * Feature: AbilityManagerService + * Function: ParseJsonFromBoot + * FunctionPoints: ParseJsonFromBoot + */ +HWTEST_F(AbilityManagerServiceThirdTest, ParseJsonFromBoot_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + abilityMs_->ParseJsonFromBoot(nullptr, "", ""); +} + +/* + * Feature: AbilityManagerService + * Function: IsInWhiteList + * FunctionPoints: IsInWhiteList + */ +HWTEST_F(AbilityManagerServiceThirdTest, IsInWhiteList_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + abilityMs_->IsInWhiteList("", "", ""); +} + +/* + * Feature: AbilityManagerService + * Function: ReportPreventStartAbilityResult + * FunctionPoints: ReportPreventStartAbilityResult + */ +HWTEST_F(AbilityManagerServiceThirdTest, ReportPreventStartAbilityResult_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::AbilityInfo abilityInfo2; + abilityMs_->ReportPreventStartAbilityResult(abilityInfo, abilityInfo2); +} + +/* + * Feature: AbilityManagerService + * Function: ShouldPreventStartAbility + * FunctionPoints: ShouldPreventStartAbility + */ +HWTEST_F(AbilityManagerServiceThirdTest, ShouldPreventStartAbility_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.test.demo"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::PAGE; + + abilityMs_->ShouldPreventStartAbility(abilityRequest); +} + +/* + * Feature: AbilityManagerService + * Function: IsEmbeddedOpenAllowed + * FunctionPoints: IsEmbeddedOpenAllowed + */ +HWTEST_F(AbilityManagerServiceThirdTest, IsEmbeddedOpenAllowed_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + sptr token = MockToken(AbilityType::PAGE); + abilityMs_->IsEmbeddedOpenAllowed(token, APPID); +} + +/* + * Feature: AbilityManagerService + * Function: SignRestartAppFlag + * FunctionPoints: SignRestartAppFlag + */ +HWTEST_F(AbilityManagerServiceThirdTest, SignRestartAppFlag_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + EXPECT_NE(abilityMs_, nullptr); + + abilityMs_->SignRestartAppFlag(USER_ID_U100, "com.ix.hiservcie"); +} + +/* + * Feature: AbilityManagerService + * Function: StartUIAbilityByPreInstall + * FunctionPoints: AbilityManagerService StartUIAbilityByPreInstall free install not finished + */ +HWTEST_F(AbilityManagerServiceThirdTest, AbilityManagerServiceTest_StartUIAbilityByPreInstall_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); + FreeInstallInfo taskInfo = { + .isFreeInstallFinished = false, + }; + int32_t res = abilityMs->StartUIAbilityByPreInstall(taskInfo); EXPECT_EQ(res, ERR_INVALID_VALUE); } + +/* + * Feature: AbilityManagerService + * Function: StartUIAbilityByPreInstall + * FunctionPoints: AbilityManagerService StartUIAbilityByPreInstall free install failed + */ +HWTEST_F(AbilityManagerServiceThirdTest, AbilityManagerServiceTest_StartUIAbilityByPreInstall_002, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + EXPECT_NE(abilityMs, nullptr); + FreeInstallInfo taskInfo = { + .isInstalled = false, + }; + int32_t res = abilityMs->StartUIAbilityByPreInstall(taskInfo); + EXPECT_EQ(res, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartUIAbilityByPreInstall + * FunctionPoints: AbilityManagerService StartUIAbilityByPreInstall StartUIAbilityBySCB not called + */ +HWTEST_F(AbilityManagerServiceThirdTest, AbilityManagerServiceTest_StartUIAbilityByPreInstall_003, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + EXPECT_NE(abilityMs, nullptr); + FreeInstallInfo taskInfo = { + .isStartUIAbilityBySCBCalled = false, + }; + int32_t res = abilityMs->StartUIAbilityByPreInstall(taskInfo); + EXPECT_EQ(res, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartUIAbilityByPreInstall + * FunctionPoints: AbilityManagerService StartUIAbilityByPreInstall empty sessionId + */ +HWTEST_F(AbilityManagerServiceThirdTest, AbilityManagerServiceTest_StartUIAbilityByPreInstall_004, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + EXPECT_NE(abilityMs, nullptr); + FreeInstallInfo taskInfo = { + .isFreeInstallFinished = true, + .isInstalled = true, + .isStartUIAbilityBySCBCalled = true, + }; + int32_t res = abilityMs->StartUIAbilityByPreInstall(taskInfo); + EXPECT_EQ(res, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartUIAbilityByPreInstall + * FunctionPoints: AbilityManagerService StartUIAbilityByPreInstall session not found + */ +HWTEST_F(AbilityManagerServiceThirdTest, AbilityManagerServiceTest_StartUIAbilityByPreInstall_005, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + EXPECT_NE(abilityMs, nullptr); + Want want; + std::string sessionId = "1234567890"; + want.SetParam(KEY_SESSION_ID, sessionId); + FreeInstallInfo taskInfo = { + .want = want, + .isFreeInstallFinished = true, + .isInstalled = true, + .isStartUIAbilityBySCBCalled = true, + }; + int32_t res = abilityMs->StartUIAbilityByPreInstall(taskInfo); + EXPECT_EQ(res, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: RemovePreStartSession + * FunctionPoints: AbilityManagerService RemovePreStartSession + */ +HWTEST_F(AbilityManagerServiceThirdTest, AbilityManagerServiceTest_RemovePreStartSession_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + EXPECT_NE(abilityMs, nullptr); + sptr sessionInfo = new (std::nothrow) SessionInfo(); + std::string sessionId = "123456"; + (abilityMs->preStartSessionMap_).insert(std::make_pair(sessionId, sessionInfo)); + abilityMs->RemovePreStartSession(sessionId); + EXPECT_EQ((abilityMs->preStartSessionMap_).find(sessionId), (abilityMs->preStartSessionMap_).end()); +} + +/* + * Feature: AbilityManagerService + * Function: PreStartMission + * FunctionPoints: AbilityManagerService PreStartMission permission denied + */ +HWTEST_F(AbilityManagerServiceThirdTest, AbilityManagerServiceTest_PreStartMission_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + EXPECT_NE(abilityMs, nullptr); + int res = abilityMs->PreStartMission("bundle", "module", "ability", "startTime"); + EXPECT_EQ(res, ERR_PERMISSION_DENIED); +} + +/* + * Feature: AbilityManagerService + * Function: OpenLink + * FunctionPoints: AbilityManagerService OpenLink + */ +HWTEST_F(AbilityManagerServiceThirdTest, AbilityManagerServiceTest_OpenLink_001, TestSize.Level1) +{ + auto abilityMs = std::make_shared(); + EXPECT_NE(abilityMs, nullptr); + Want want; + sptr callerToken = nullptr; + int res = abilityMs->OpenLink(want, callerToken, 0, -1); + EXPECT_NE(res, ERR_OK); +} } // 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 d19dc278c6..ac50cdd9bc 100644 --- a/test/unittest/ability_manager_stub_test/BUILD.gn +++ b/test/unittest/ability_manager_stub_test/BUILD.gn @@ -17,13 +17,14 @@ import("//foundation/ability/ability_runtime/ability_runtime.gni") module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_manager_stub_test") { - module_out_path = module_output_path sanitize = { cfi = true cfi_cross_dso = true debug = false + blocklist = "../../cfi_blocklist.txt" } branch_protector_ret = "pac_ret" + module_out_path = module_output_path include_dirs = [ "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", diff --git a/test/unittest/ability_manager_stub_test/ability_manager_stub_impl_mock.h b/test/unittest/ability_manager_stub_test/ability_manager_stub_impl_mock.h index bf17a712a1..e390d6ebdd 100644 --- a/test/unittest/ability_manager_stub_test/ability_manager_stub_impl_mock.h +++ b/test/unittest/ability_manager_stub_test/ability_manager_stub_impl_mock.h @@ -40,8 +40,8 @@ public: int32_t userId, int requestCode)); MOCK_METHOD4(StartAbilityByInsightIntent, int32_t(const Want& want, const sptr& callerToken, uint64_t intentId, int32_t userId)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want &want, const sptr &callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want &want, const sptr &callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo& wantSenderInfo, const sptr& callerToken)); MOCK_METHOD2(SendWantSender, int(sptr target, const SenderInfo& senderInfo)); @@ -339,7 +339,8 @@ public: return 0; } - int RegisterWindowManagerServiceHandler(const sptr& handler) override + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true) override { return 0; } 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 bd799c1388..9ef2da5edb 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 @@ -14,7 +14,6 @@ */ #include -#include "ability_manager_errors.h" #include "ability_manager_stub_impl_mock.h" #include "ability_scheduler.h" #include "app_debug_listener_stub_mock.h" @@ -978,6 +977,38 @@ HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_StartUIExtensionAbilityInner EXPECT_EQ(res, NO_ERROR); } +/* + * Feature: AbilityManagerService + * Function: StartUIExtensionAbilityEmbeddedInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartUIExtensionAbilityEmbeddedInner + * EnvConditions: NA + * CaseDescription: Verify the function StartUIExtensionAbilityEmbeddedInner is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_StartUIExtensionAbilityEmbeddedInner_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + auto res = stub_->StartUIExtensionAbilityEmbeddedInner(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/* + * Feature: AbilityManagerService + * Function: StartUIExtensionConstrainedEmbeddedInner + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartUIExtensionConstrainedEmbeddedInner + * EnvConditions: NA + * CaseDescription: Verify the function StartUIExtensionConstrainedEmbeddedInner is normal flow. + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_StartUIExtensionConstrainedEmbeddedInner_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + auto res = stub_->StartUIExtensionConstrainedEmbeddedInner(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + /* * Feature: AbilityManagerService * Function: StopExtensionAbilityInner @@ -3353,7 +3384,7 @@ HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_TransferAbilityResultForExte MessageParcel data; MessageParcel reply; auto res = stub_->TransferAbilityResultForExtensionInner(data, reply); - EXPECT_EQ(res, NO_ERROR); + EXPECT_EQ(res, ERR_INVALID_VALUE); } /** diff --git a/test/unittest/ability_manager_test/ability_manager_stub_mock.h b/test/unittest/ability_manager_test/ability_manager_stub_mock.h index d703d653f8..029f0bd121 100644 --- a/test/unittest/ability_manager_test/ability_manager_stub_mock.h +++ b/test/unittest/ability_manager_test/ability_manager_stub_mock.h @@ -272,7 +272,8 @@ public: return 0; } - int RegisterWindowManagerServiceHandler(const sptr& handler) override + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true) override { return 0; } @@ -304,8 +305,8 @@ public: int32_t userId, int requestCode)); MOCK_METHOD4(StartAbilityByInsightIntent, int32_t(const Want& want, const sptr& callerToken, uint64_t intentId, int32_t userId)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo& wantSenderInfo, const sptr& callerToken)); MOCK_METHOD2(SendWantSender, int(sptr target, const SenderInfo& senderInfo)); diff --git a/test/unittest/ability_record_dump_test/ability_record_dump_test.cpp b/test/unittest/ability_record_dump_test/ability_record_dump_test.cpp index b441880a12..f429431aed 100644 --- a/test/unittest/ability_record_dump_test/ability_record_dump_test.cpp +++ b/test/unittest/ability_record_dump_test/ability_record_dump_test.cpp @@ -21,7 +21,6 @@ #undef private #undef protected #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing; using namespace testing::ext; 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 index 7e37d50cb5..a6730d6206 100644 --- a/test/unittest/ability_record_mgr_test/ability_record_mgr_test.cpp +++ b/test/unittest/ability_record_mgr_test/ability_record_mgr_test.cpp @@ -20,7 +20,6 @@ #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" diff --git a/test/unittest/ability_record_test/BUILD.gn b/test/unittest/ability_record_test/BUILD.gn index 4e675d6866..63b8f88fe2 100644 --- a/test/unittest/ability_record_test/BUILD.gn +++ b/test/unittest/ability_record_test/BUILD.gn @@ -22,6 +22,7 @@ ohos_unittest("ability_record_test") { cfi = true cfi_cross_dso = true debug = false + blocklist = "../../cfi_blocklist.txt" } branch_protector_ret = "pac_ret" include_dirs = [ @@ -52,13 +53,13 @@ ohos_unittest("ability_record_test") { } 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}/uri_permission:uri_permission_mgr", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_native_path}/ability/native:auto_startup_callback", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_services_path}/uripermmgr:libupms_static", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock", @@ -104,6 +105,7 @@ ohos_unittest("ability_record_test_call") { cfi = true cfi_cross_dso = true debug = false + blocklist = "../../cfi_blocklist.txt" } branch_protector_ret = "pac_ret" include_dirs = [ diff --git a/test/unittest/ability_record_test/ability_record_test.cpp b/test/unittest/ability_record_test/ability_record_test.cpp index c65541e6b2..9f4d65ecab 100644 --- a/test/unittest/ability_record_test/ability_record_test.cpp +++ b/test/unittest/ability_record_test/ability_record_test.cpp @@ -34,7 +34,6 @@ #include "sa_mgr_client.h" #include "system_ability_definition.h" #include "ui_extension_utils.h" -#include "hilog_wrapper.h" #include "int_wrapper.h" #ifdef SUPPORT_GRAPHICS #define private public @@ -46,6 +45,7 @@ using namespace testing::ext; using namespace OHOS::AppExecFwk; +using namespace OHOS::AbilityBase::Constants; namespace OHOS { namespace AAFwk { @@ -55,7 +55,6 @@ const std::string DLP_BUNDLE_NAME = "com.ohos.dlpmanager"; const std::string SHELL_ASSISTANT_BUNDLENAME = "com.huawei.shell_assistant"; const std::string SHOW_ON_LOCK_SCREEN = "ShowOnLockScreen"; const std::string URI_PERMISSION_TABLE_NAME = "uri_permission"; -constexpr const char* COMPRESS_PROPERTY = "compress"; } class AbilityRecordTest : public testing::TestWithParam { public: 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 index e80bb96be8..ee0410e889 100644 --- a/test/unittest/ability_running_record_test/ability_running_record_test.cpp +++ b/test/unittest/ability_running_record_test/ability_running_record_test.cpp @@ -18,7 +18,6 @@ #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; diff --git a/test/unittest/ability_runtime_error_util_test/ability_runtime_error_util_test.cpp b/test/unittest/ability_runtime_error_util_test/ability_runtime_error_util_test.cpp index 8ab8e9408f..983566b063 100644 --- a/test/unittest/ability_runtime_error_util_test/ability_runtime_error_util_test.cpp +++ b/test/unittest/ability_runtime_error_util_test/ability_runtime_error_util_test.cpp @@ -19,7 +19,6 @@ #include "ecmascript/napi/include/jsnapi.h" #include "errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "native_engine/impl/ark/ark_native_engine.h" #include "native_engine/native_engine.h" diff --git a/test/unittest/ability_scheduler_proxy_test/BUILD.gn b/test/unittest/ability_scheduler_proxy_test/BUILD.gn index 94012bc23a..56595beb00 100644 --- a/test/unittest/ability_scheduler_proxy_test/BUILD.gn +++ b/test/unittest/ability_scheduler_proxy_test/BUILD.gn @@ -18,7 +18,13 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("ability_scheduler_proxy_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", diff --git a/test/unittest/ability_service_extension_test/ability_service_extension_test.cpp b/test/unittest/ability_service_extension_test/ability_service_extension_test.cpp index 8557c9a80d..c91cf9661b 100644 --- a/test/unittest/ability_service_extension_test/ability_service_extension_test.cpp +++ b/test/unittest/ability_service_extension_test/ability_service_extension_test.cpp @@ -22,7 +22,6 @@ #include "runtime.h" #include "service_extension.h" -#include "hilog_wrapper.h" #include "iremote_object.h" using namespace testing::ext; diff --git a/test/unittest/ability_timeout_test/BUILD.gn b/test/unittest/ability_timeout_test/BUILD.gn index 2608734d77..4ac261d97a 100644 --- a/test/unittest/ability_timeout_test/BUILD.gn +++ b/test/unittest/ability_timeout_test/BUILD.gn @@ -29,6 +29,7 @@ ohos_unittest("ability_timeout_test") { "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", ] diff --git a/test/unittest/ability_timeout_test/ability_timeout_test.cpp b/test/unittest/ability_timeout_test/ability_timeout_test.cpp index 8770065dfe..db55ffd4b3 100644 --- a/test/unittest/ability_timeout_test/ability_timeout_test.cpp +++ b/test/unittest/ability_timeout_test/ability_timeout_test.cpp @@ -17,6 +17,7 @@ #define private public #define protected public #include "ability_manager_service.h" +#include "mission_list_manager.h" #undef private #undef protected @@ -69,7 +70,6 @@ void AbilityTimeoutTest::TearDown() {} HWTEST_F(AbilityTimeoutTest, GetMaxRestartNum_001, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); int maxRestart = -1; @@ -89,12 +89,13 @@ HWTEST_F(AbilityTimeoutTest, GetMaxRestartNum_001, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, OnAbilityDied_001, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto defList = abilityMs_->subManagersHelper_->currentMissionListManager_->defaultStandardList_; - EXPECT_TRUE(defList != nullptr); + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); + EXPECT_TRUE(curListManager != nullptr); + std::shared_ptr missionList = std::make_shared(); + curListManager->defaultStandardList_ = missionList; + EXPECT_TRUE(curListManager->defaultStandardList_ != nullptr); AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; @@ -106,12 +107,13 @@ HWTEST_F(AbilityTimeoutTest, OnAbilityDied_001, TestSize.Level1) std::make_shared(MOCK_MISSION_ID, abilityRecord, abilityRequest.abilityInfo.bundleName); abilityRecord->SetMissionId(mission->GetMissionId()); abilityRecord->SetOwnerMissionUserId(MOCK_MAIN_USER_ID); - defList->AddMissionToTop(mission); - EXPECT_TRUE(defList->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); + curListManager->defaultStandardList_->AddMissionToTop(mission); + EXPECT_TRUE( + curListManager->defaultStandardList_->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); abilityMs_->OnAbilityDied(abilityRecord); - - EXPECT_FALSE(defList->GetAbilityRecordByToken(abilityRecord->GetToken()) == nullptr); + EXPECT_FALSE( + curListManager->defaultStandardList_->GetAbilityRecordByToken(abilityRecord->GetToken()) == nullptr); } } @@ -126,13 +128,13 @@ HWTEST_F(AbilityTimeoutTest, OnAbilityDied_001, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, OnAbilityDied_002, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - EXPECT_TRUE(lauList != nullptr); - EXPECT_EQ((int)(abilityMs_->subManagersHelper_->currentMissionListManager_->currentMissionLists_.size()), 1); + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); + EXPECT_TRUE(curListManager != nullptr); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; @@ -146,14 +148,12 @@ HWTEST_F(AbilityTimeoutTest, OnAbilityDied_002, TestSize.Level1) abilityRecord->SetMissionId(mission->GetMissionId()); abilityRecord->SetLauncherRoot(); abilityRecord->SetOwnerMissionUserId(MOCK_MAIN_USER_ID); - lauList->AddMissionToTop(mission); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(mission); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); abilityMs_->OnAbilityDied(abilityRecord); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); - EXPECT_TRUE(abilityRecord->IsRestarting()); - EXPECT_TRUE(abilityRecord->restartCount_ < abilityRecord->restartMax_); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); } } @@ -168,13 +168,13 @@ HWTEST_F(AbilityTimeoutTest, OnAbilityDied_002, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_001, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - EXPECT_TRUE(abilityMs_->subManagersHelper_->currentMissionListManager_ != nullptr); - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - EXPECT_TRUE(lauList != nullptr); - EXPECT_EQ((int)(abilityMs_->subManagersHelper_->currentMissionListManager_->currentMissionLists_.size()), 1); + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); + EXPECT_TRUE(curListManager != nullptr); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); // root launcher ability load timeout AbilityRequest abilityRequest; @@ -190,14 +190,12 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_001, TestSize.Level1) EXPECT_TRUE(abilityRecord != nullptr); abilityRecord->SetMissionId(mission->GetMissionId()); abilityRecord->SetLauncherRoot(); - lauList->AddMissionToTop(mission); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(mission); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); abilityMs_->HandleLoadTimeOut(abilityRecord->GetAbilityRecordId()); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); - EXPECT_TRUE(abilityRecord->IsRestarting()); - EXPECT_TRUE(abilityRecord->restartCount_ < abilityRecord->restartMax_); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); } } @@ -212,14 +210,13 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_001, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_002, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); - EXPECT_EQ((int)(abilityMs_->subManagersHelper_->currentMissionListManager_->currentMissionLists_.size()), 1); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; @@ -234,8 +231,8 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_002, TestSize.Level1) EXPECT_TRUE(missionLauncher != nullptr); launcher->SetMissionId(missionLauncher->GetMissionId()); launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(missionLauncher); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); // common ability load timeout abilityRequest.appInfo.isLauncherApp = false; @@ -247,16 +244,14 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_002, TestSize.Level1) EXPECT_TRUE(abilityRecord != nullptr); abilityRecord->SetMissionId(mission->GetMissionId()); - auto missionList = std::make_shared(MissionListType::CURRENT); + missionList = std::make_shared(MissionListType::CURRENT); missionList->AddMissionToTop(mission); curListManager->MoveMissionListToTop(missionList); EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); abilityMs_->HandleLoadTimeOut(abilityRecord->GetAbilityRecordId()); - EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) == nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(launcher, topAbility); + EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); } } @@ -271,14 +266,14 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_002, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_003, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); - EXPECT_EQ((int)(abilityMs_->subManagersHelper_->currentMissionListManager_->currentMissionLists_.size()), 1); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); + AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; abilityRequest.abilityInfo.name = "com.test.rootLauncher"; @@ -290,8 +285,8 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_003, TestSize.Level1) std::make_shared(MOCK_MISSION_ID, launcher, abilityRequest.abilityInfo.bundleName); launcher->SetMissionId(missionLauncher->GetMissionId()); launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(missionLauncher); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); // common ability by caller abilityRequest.appInfo.isLauncherApp = false; abilityRequest.abilityInfo.name = "com.test.caller"; @@ -301,7 +296,7 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_003, TestSize.Level1) EXPECT_TRUE(caller != nullptr); EXPECT_TRUE(callerMission != nullptr); caller->SetMissionId(callerMission->GetMissionId()); - auto missionList = std::make_shared(MissionListType::CURRENT); + missionList = std::make_shared(MissionListType::CURRENT); missionList->AddMissionToTop(callerMission); curListManager->MoveMissionListToTop(missionList); EXPECT_TRUE(curListManager->GetAbilityRecordByToken(caller->GetToken()) != nullptr); @@ -319,9 +314,7 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_003, TestSize.Level1) EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); EXPECT_EQ(abilityRecord->GetCallerRecord(), caller); abilityMs_->HandleLoadTimeOut(abilityRecord->GetAbilityRecordId()); - EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) == nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(caller, topAbility); + EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); } } @@ -336,14 +329,13 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_003, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_004, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; @@ -358,8 +350,8 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_004, TestSize.Level1) EXPECT_TRUE(missionLauncher != nullptr); launcher->SetMissionId(missionLauncher->GetMissionId()); launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(missionLauncher); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); // common ability by caller with service ability type abilityRequest.appInfo.isLauncherApp = false; @@ -375,7 +367,7 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_004, TestSize.Level1) EXPECT_TRUE(launcher != nullptr); auto mission = std::make_shared(MOCK_MISSION_ID + 1, abilityRecord, abilityRequest.abilityInfo.bundleName); - auto missionList = std::make_shared(MissionListType::CURRENT); + missionList = std::make_shared(MissionListType::CURRENT); EXPECT_TRUE(mission != nullptr); EXPECT_TRUE(missionList != nullptr); abilityRecord->SetMissionId(mission->GetMissionId()); @@ -386,9 +378,7 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_004, TestSize.Level1) EXPECT_EQ(abilityRecord->GetCallerRecord(), caller); abilityMs_->HandleLoadTimeOut(abilityRecord->GetAbilityRecordId()); - EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) == nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(launcher, topAbility); + EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); } } @@ -403,14 +393,13 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_004, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_005, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; @@ -425,8 +414,8 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_005, TestSize.Level1) EXPECT_TRUE(missionLauncher != nullptr); launcher->SetMissionId(missionLauncher->GetMissionId()); launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(missionLauncher); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); // common ability by caller with extension ability type abilityRequest.appInfo.isLauncherApp = false; @@ -442,7 +431,7 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_005, TestSize.Level1) EXPECT_TRUE(launcher != nullptr); auto mission = std::make_shared(MOCK_MISSION_ID + 1, abilityRecord, abilityRequest.abilityInfo.bundleName); - auto missionList = std::make_shared(MissionListType::CURRENT); + missionList = std::make_shared(MissionListType::CURRENT); EXPECT_TRUE(mission != nullptr); EXPECT_TRUE(missionList != nullptr); abilityRecord->SetMissionId(mission->GetMissionId()); @@ -453,9 +442,7 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_005, TestSize.Level1) EXPECT_EQ(abilityRecord->GetCallerRecord(), caller); abilityMs_->HandleLoadTimeOut(abilityRecord->GetAbilityRecordId()); - EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) == nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(launcher, topAbility); + EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); } } @@ -470,14 +457,13 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_005, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_006, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; @@ -492,8 +478,8 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_006, TestSize.Level1) EXPECT_TRUE(missionLauncher != nullptr); launcher->SetMissionId(missionLauncher->GetMissionId()); launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(missionLauncher); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); // common ability by caller as launcher type auto caller = AbilityRecord::CreateAbilityRecord(abilityRequest); @@ -507,7 +493,7 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_006, TestSize.Level1) EXPECT_TRUE(launcher != nullptr); auto mission = std::make_shared(MOCK_MISSION_ID + 1, abilityRecord, abilityRequest.abilityInfo.bundleName); - auto missionList = std::make_shared(MissionListType::CURRENT); + missionList = std::make_shared(MissionListType::CURRENT); EXPECT_TRUE(mission != nullptr); EXPECT_TRUE(missionList != nullptr); abilityRecord->SetMissionId(mission->GetMissionId()); @@ -518,9 +504,7 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_006, TestSize.Level1) EXPECT_EQ(abilityRecord->GetCallerRecord(), caller); abilityMs_->HandleLoadTimeOut(abilityRecord->GetAbilityRecordId()); - EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) == nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(launcher, topAbility); + EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); } } @@ -535,14 +519,13 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_006, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_007, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; @@ -557,8 +540,8 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_007, TestSize.Level1) EXPECT_TRUE(missionLauncher != nullptr); launcher->SetMissionId(missionLauncher->GetMissionId()); launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(missionLauncher); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); // common ability by caller abilityRequest.appInfo.isLauncherApp = false; @@ -574,7 +557,7 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_007, TestSize.Level1) EXPECT_TRUE(launcher != nullptr); auto mission = std::make_shared(MOCK_MISSION_ID + 1, abilityRecord, abilityRequest.abilityInfo.bundleName); - auto missionList = std::make_shared(MissionListType::CURRENT); + missionList = std::make_shared(MissionListType::CURRENT); EXPECT_TRUE(mission != nullptr); EXPECT_TRUE(missionList != nullptr); abilityRecord->SetMissionId(mission->GetMissionId()); @@ -585,54 +568,7 @@ HWTEST_F(AbilityTimeoutTest, HandleLoadTimeOut_007, TestSize.Level1) EXPECT_EQ(abilityRecord->GetCallerRecord(), caller); abilityMs_->HandleLoadTimeOut(abilityRecord->GetAbilityRecordId()); - EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) == nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(launcher, topAbility); - } -} - -/* - * Feature: AbilityManagerService - * Function: HandleForgroundNewTimeout - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: Verify AbilityManagerService HandleForgroundNewTimeout success - */ -HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_001, TestSize.Level1) -{ - auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); - EXPECT_TRUE(abilityMs_ != nullptr); - if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - - EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); - - AbilityRequest abilityRequest; - abilityRequest.abilityInfo.type = AbilityType::PAGE; - abilityRequest.abilityInfo.name = "com.test.rootLauncher"; - abilityRequest.abilityInfo.bundleName = "com.test"; - abilityRequest.appInfo.isLauncherApp = true; - abilityRequest.appInfo.name = "com.test"; - auto launcher = AbilityRecord::CreateAbilityRecord(abilityRequest); - EXPECT_TRUE(launcher != nullptr); - auto missionLauncher = - std::make_shared(MOCK_MISSION_ID, launcher, abilityRequest.abilityInfo.bundleName); - EXPECT_TRUE(missionLauncher != nullptr); - launcher->SetMissionId(missionLauncher->GetMissionId()); - launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); - - // test root launcher foreground timeout. - launcher->SetAbilityState(AbilityState::FOREGROUNDING); - abilityMs_->HandleForegroundTimeOut(launcher->GetAbilityRecordId()); - EXPECT_TRUE(curListManager->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(launcher, topAbility); + EXPECT_TRUE(curListManager->GetAbilityRecordByToken(abilityRecord->GetToken()) != nullptr); } } @@ -647,14 +583,13 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_001, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_002, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; @@ -669,8 +604,8 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_002, TestSize.Level1) EXPECT_TRUE(missionLauncher != nullptr); launcher->SetMissionId(missionLauncher->GetMissionId()); launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(missionLauncher); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); // common launcher ability timeout abilityRequest.abilityInfo.name = "com.test.TimeoutForeground002"; @@ -680,16 +615,14 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_002, TestSize.Level1) std::make_shared(MOCK_MISSION_ID + 1, commonLauncher, abilityRequest.abilityInfo.bundleName); EXPECT_TRUE(commonMissionLauncher != nullptr); commonLauncher->SetMissionId(commonMissionLauncher->GetMissionId()); - lauList->AddMissionToTop(commonMissionLauncher); + curListManager->launcherList_->AddMissionToTop(commonMissionLauncher); commonLauncher->SetAbilityState(AbilityState::FOREGROUNDING); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(commonLauncher->GetToken()) != nullptr); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(commonLauncher->GetToken()) != nullptr); // test common launcher foreground timeout. abilityMs_->HandleForegroundTimeOut(commonLauncher->GetAbilityRecordId()); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(commonLauncher->GetToken()) == nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(launcher, topAbility); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(commonLauncher->GetToken()) != nullptr); } } @@ -704,13 +637,14 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_002, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_003, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); + std::shared_ptr missionList = std::make_shared(MissionListType::CURRENT); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); + AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; abilityRequest.abilityInfo.name = "com.test.rootLauncher"; @@ -724,8 +658,8 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_003, TestSize.Level1) EXPECT_TRUE(missionLauncher != nullptr); launcher->SetMissionId(missionLauncher->GetMissionId()); launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(missionLauncher); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); // common ability by caller abilityRequest.appInfo.isLauncherApp = false; abilityRequest.abilityInfo.name = "com.test.caller"; @@ -735,7 +669,6 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_003, TestSize.Level1) EXPECT_TRUE(caller != nullptr); EXPECT_TRUE(callerMission != nullptr); caller->SetMissionId(callerMission->GetMissionId()); - auto missionList = std::make_shared(MissionListType::CURRENT); missionList->AddMissionToTop(callerMission); curListManager->MoveMissionListToTop(missionList); EXPECT_TRUE(curListManager->GetAbilityRecordByToken(caller->GetToken()) != nullptr); @@ -755,8 +688,6 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_003, TestSize.Level1) // test common launcher foreground timeout. abilityMs_->HandleForegroundTimeOut(commonLauncher->GetAbilityRecordId()); EXPECT_TRUE(curListManager->GetAbilityRecordByToken(commonLauncher->GetToken()) != nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(caller, topAbility); } } @@ -771,14 +702,13 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_003, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_004, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; @@ -793,8 +723,8 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_004, TestSize.Level1) EXPECT_TRUE(missionLauncher != nullptr); launcher->SetMissionId(missionLauncher->GetMissionId()); launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(missionLauncher); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); // common ability by caller (launcher type) abilityRequest.appInfo.isLauncherApp = true; @@ -810,7 +740,7 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_004, TestSize.Level1) auto commonMissionLauncher = std::make_shared(MOCK_MISSION_ID + 1, commonLauncher, abilityRequest.abilityInfo.bundleName); EXPECT_TRUE(commonMissionLauncher != nullptr); - auto missionList = std::make_shared(MissionListType::CURRENT); + missionList = std::make_shared(MissionListType::CURRENT); commonLauncher->SetMissionId(commonMissionLauncher->GetMissionId()); commonLauncher->AddCallerRecord(caller->GetToken(), -1); missionList->AddMissionToTop(commonMissionLauncher); @@ -820,10 +750,7 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_004, TestSize.Level1) // test common launcher foreground timeout. abilityMs_->HandleForegroundTimeOut(commonLauncher->GetAbilityRecordId()); - EXPECT_TRUE(curListManager->GetAbilityRecordByToken(commonLauncher->GetToken()) != nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(launcher, topAbility); } } @@ -838,14 +765,13 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_004, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_005, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; @@ -860,8 +786,8 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_005, TestSize.Level1) EXPECT_TRUE(missionLauncher != nullptr); launcher->SetMissionId(missionLauncher->GetMissionId()); launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(missionLauncher); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); // common ability by service ability abilityRequest.appInfo.isLauncherApp = false; @@ -878,7 +804,7 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_005, TestSize.Level1) auto commonMissionLauncher = std::make_shared(MOCK_MISSION_ID + 1, commonLauncher, abilityRequest.abilityInfo.bundleName); EXPECT_TRUE(commonMissionLauncher != nullptr); - auto missionList = std::make_shared(MissionListType::CURRENT); + missionList = std::make_shared(MissionListType::CURRENT); commonLauncher->SetMissionId(commonMissionLauncher->GetMissionId()); commonLauncher->AddCallerRecord(caller->GetToken(), -1); missionList->AddMissionToTop(commonMissionLauncher); @@ -888,10 +814,7 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_005, TestSize.Level1) // test common launcher foreground timeout. abilityMs_->HandleForegroundTimeOut(commonLauncher->GetAbilityRecordId()); - EXPECT_TRUE(curListManager->GetAbilityRecordByToken(commonLauncher->GetToken()) != nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(launcher, topAbility); } } @@ -906,14 +829,13 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_005, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_006, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; @@ -928,8 +850,8 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_006, TestSize.Level1) EXPECT_TRUE(missionLauncher != nullptr); launcher->SetMissionId(missionLauncher->GetMissionId()); launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(missionLauncher); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); // common ability by service ability abilityRequest.appInfo.isLauncherApp = false; @@ -946,7 +868,7 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_006, TestSize.Level1) auto commonMissionLauncher = std::make_shared(MOCK_MISSION_ID, commonAbility, abilityRequest.abilityInfo.bundleName); EXPECT_TRUE(commonMissionLauncher != nullptr); - auto missionList = std::make_shared(MissionListType::CURRENT); + missionList = std::make_shared(MissionListType::CURRENT); commonAbility->SetMissionId(commonMissionLauncher->GetMissionId()); commonAbility->AddCallerRecord(caller->GetToken(), -1); missionList->AddMissionToTop(commonMissionLauncher); @@ -956,10 +878,7 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_006, TestSize.Level1) // test common ability foreground timeout. abilityMs_->HandleForegroundTimeOut(commonAbility->GetAbilityRecordId()); - EXPECT_TRUE(curListManager->GetAbilityRecordByToken(commonAbility->GetToken()) != nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(launcher, topAbility); } } @@ -974,14 +893,13 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_006, TestSize.Level1) HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_007, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); EXPECT_TRUE(abilityMs_ != nullptr); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { - auto curListManager = abilityMs_->subManagersHelper_->currentMissionListManager_; - auto lauList = abilityMs_->subManagersHelper_->currentMissionListManager_->launcherList_; - + auto curListManager = std::make_shared(MOCK_MAIN_USER_ID); EXPECT_TRUE(curListManager != nullptr); - EXPECT_TRUE(lauList != nullptr); + std::shared_ptr missionList = std::make_shared(); + curListManager->launcherList_ = missionList; + EXPECT_TRUE(curListManager->launcherList_ != nullptr); AbilityRequest abilityRequest; abilityRequest.abilityInfo.type = AbilityType::PAGE; @@ -996,8 +914,8 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_007, TestSize.Level1) EXPECT_TRUE(missionLauncher != nullptr); launcher->SetMissionId(missionLauncher->GetMissionId()); launcher->SetLauncherRoot(); - lauList->AddMissionToTop(missionLauncher); - EXPECT_TRUE(lauList->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); + curListManager->launcherList_->AddMissionToTop(missionLauncher); + EXPECT_TRUE(curListManager->launcherList_->GetAbilityRecordByToken(launcher->GetToken()) != nullptr); // common ability timeout without caller abilityRequest.abilityInfo.name = "com.test.TimeoutForeground007"; @@ -1006,7 +924,7 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_007, TestSize.Level1) auto commonMissionLauncher = std::make_shared(MOCK_MISSION_ID + 1, commonLauncher, abilityRequest.abilityInfo.bundleName); EXPECT_TRUE(commonMissionLauncher != nullptr); - auto missionList = std::make_shared(MissionListType::CURRENT); + missionList = std::make_shared(MissionListType::CURRENT); commonLauncher->SetMissionId(commonMissionLauncher->GetMissionId()); missionList->AddMissionToTop(commonMissionLauncher); curListManager->MoveMissionListToTop(missionList); @@ -1015,10 +933,7 @@ HWTEST_F(AbilityTimeoutTest, HandleForgroundNewTimeout_007, TestSize.Level1) // test common launcher foreground timeout. abilityMs_->HandleForegroundTimeOut(commonLauncher->GetAbilityRecordId()); - EXPECT_TRUE(curListManager->GetAbilityRecordByToken(commonLauncher->GetToken()) != nullptr); - auto topAbility = curListManager->GetCurrentTopAbilityLocked(); - EXPECT_EQ(launcher, topAbility); } } } // namespace AAFwk diff --git a/test/unittest/ams_ability_running_record_test/BUILD.gn b/test/unittest/ams_ability_running_record_test/BUILD.gn index d45c2bec41..29c0891ac0 100644 --- a/test/unittest/ams_ability_running_record_test/BUILD.gn +++ b/test/unittest/ams_ability_running_record_test/BUILD.gn @@ -88,7 +88,7 @@ ohos_unittest("AmsAbilityRunningRecordTest") { ] if (ability_runtime_graphics) { - external_deps += [ "window_manager:libwm_lite" ] + external_deps += [ "window_manager:libwm" ] } } diff --git a/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp b/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp index c84d3fb4c2..8be4b8c60f 100644 --- a/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp +++ b/test/unittest/ams_ability_running_record_test/ams_ability_running_record_test.cpp @@ -19,7 +19,6 @@ #include "app_running_record.h" #include "app_scheduler_host.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_token.h" #include "mock_application.h" diff --git a/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp b/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp index 13817ca369..7106cbfd23 100644 --- a/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp +++ b/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp @@ -20,7 +20,6 @@ #undef private #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "mock_ability_token.h" #include "mock_app_scheduler.h" diff --git a/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp b/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp index c6125e6426..1ab168eb68 100644 --- a/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp +++ b/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp @@ -594,7 +594,6 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_013, TestSize.Level1) EXPECT_CALL(*(testAppPreRecord.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_FOREGROUND); - testAppPreRecord.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppPreRecord.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppPreRecord.appRecord_->GetState()); @@ -631,7 +630,6 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_015, TestSize.Level1) EXPECT_CALL(*(testAppPreRecord.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_FOREGROUND); - testAppPreRecord.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppPreRecord.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppPreRecord.appRecord_->GetState()); @@ -685,7 +683,6 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_018, TestSize.Level1) EXPECT_CALL(*(testAppPreRecord.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_FOREGROUND); - testAppPreRecord.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(testAppPreRecord.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_FOREGROUND, testAppPreRecord.appRecord_->GetState()); @@ -805,7 +802,6 @@ HWTEST_F(AmsAppLifeCycleTest, Schedule_028, TestSize.Level1) EXPECT_CALL(*(testAppPreRecord.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); serviceInner_->UpdateAbilityState(GetMockToken(), AbilityState::ABILITY_STATE_BACKGROUND); - testAppPreRecord.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(testAppPreRecord.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, testAppPreRecord.firstAbilityRecord_->GetState()); EXPECT_EQ(ApplicationState::APP_STATE_BACKGROUND, testAppPreRecord.appRecord_->GetState()); @@ -1072,7 +1068,6 @@ HWTEST_F(AmsAppLifeCycleTest, Process_001, TestSize.Level1) int32_t appRecordId = appRecord->GetRecordId(); EXPECT_TRUE(appRecordId > 0); - appRecord->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appRecordId); auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); EXPECT_NE(nullptr, testAppRecord); @@ -1092,7 +1087,6 @@ HWTEST_F(AmsAppLifeCycleTest, Process_002, TestSize.Level1) int32_t appRecordId = appRecord->GetRecordId(); EXPECT_TRUE(appRecordId > 0); - appRecord->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appRecordId); auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); EXPECT_NE(nullptr, testAppRecord); @@ -1112,7 +1106,6 @@ HWTEST_F(AmsAppLifeCycleTest, Process_003, TestSize.Level1) int32_t appRecordId = appRecord->GetRecordId(); EXPECT_TRUE(appRecordId > 0); - appRecord->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appRecordId); auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); EXPECT_NE(nullptr, testAppRecord); @@ -1132,7 +1125,6 @@ HWTEST_F(AmsAppLifeCycleTest, Process_004, TestSize.Level1) int32_t appRecordId = appRecord->GetRecordId(); EXPECT_TRUE(appRecordId > 0); - appRecord->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appRecordId); auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); EXPECT_NE(nullptr, testAppRecord); @@ -1168,7 +1160,6 @@ HWTEST_F(AmsAppLifeCycleTest, Process_006, TestSize.Level1) int32_t appRecordId = appRecord->GetRecordId(); EXPECT_TRUE(appRecordId > 0); - appRecord->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appRecordId); auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); EXPECT_NE(nullptr, testAppRecord); @@ -1188,7 +1179,6 @@ HWTEST_F(AmsAppLifeCycleTest, Process_007, TestSize.Level1) int32_t appRecordId = appRecord->GetRecordId(); EXPECT_TRUE(appRecordId > 0); - appRecord->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appRecordId); auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecordId); EXPECT_NE(nullptr, testAppRecord); @@ -1208,7 +1198,6 @@ HWTEST_F(AmsAppLifeCycleTest, Process_008, TestSize.Level1) int32_t appRecordId = appRecord->GetRecordId(); EXPECT_TRUE(appRecordId > 0); - appRecord->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appRecord->GetRecordId()); auto testAppRecord = serviceInner_->GetAppRunningRecordByAppRecordId(appRecord->GetRecordId()); EXPECT_NE(nullptr, testAppRecord); diff --git a/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp b/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp index cedfea1c71..7ba2bb37bb 100644 --- a/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp +++ b/test/unittest/ams_app_mgr_client_test/ams_app_mgr_client_test.cpp @@ -20,7 +20,6 @@ #include "ability_info.h" #include "application_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iapp_state_callback.h" #include "mock_ability_token.h" #include "mock_ams_mgr_scheduler.h" 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 0f1460c9c2..80cfb1b45a 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 @@ -31,7 +31,6 @@ #include "bundle_mgr_interface.h" #include "event_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iremote_object.h" #include "mock_ability_token.h" @@ -146,13 +145,11 @@ void AmsAppRunningRecordTest::MockBundleInstallerAndSA() const return saMgr->GetSystemAbility(systemAbilityId); } }; - EXPECT_CALL(*mockBundleMgr, GetBundleInstaller()).WillOnce(testing::Invoke(mockGetBundleInstaller)); } void AmsAppRunningRecordTest::MockBundleInstaller() const { auto mockGetBundleInstaller = []() { return mockBundleInstaller; }; - EXPECT_CALL(*mockBundleMgr, GetBundleInstaller()).WillOnce(testing::Invoke(mockGetBundleInstaller)); } sptr AmsAppRunningRecordTest::GetMockedAppSchedulerClient() const @@ -768,11 +765,6 @@ HWTEST_F(AmsAppRunningRecordTest, DeleteAppRunningRecord_001, TestSize.Level1) HWTEST_F(AmsAppRunningRecordTest, AttachApplication_001, TestSize.Level1) { TAG_LOGI(AAFwkTag::TEST, "AmsAppRunningRecordTest AttachApplication_001 start"); - MockBundleInstallerAndSA(); - EXPECT_CALL(*mockBundleMgr, GetHapModuleInfo(testing::_, testing::_, testing::_)) - .WillOnce(testing::Return(true)) - .WillRepeatedly(testing::Return(true)); - auto abilityInfo = std::make_shared(); abilityInfo->name = GetTestAbilityName(); abilityInfo->applicationName = GetTestAppName(); @@ -799,7 +791,6 @@ HWTEST_F(AmsAppRunningRecordTest, AttachApplication_001, TestSize.Level1) HWTEST_F(AmsAppRunningRecordTest, AttachApplication_002, TestSize.Level1) { TAG_LOGI(AAFwkTag::TEST, "AmsAppRunningRecordTest AttachApplication_002 start"); - MockBundleInstaller(); auto abilityInfo = std::make_shared(); abilityInfo->name = GetTestAbilityName(); abilityInfo->applicationName = GetTestAppName(); @@ -827,7 +818,6 @@ HWTEST_F(AmsAppRunningRecordTest, AttachApplication_002, TestSize.Level1) HWTEST_F(AmsAppRunningRecordTest, AttachApplication_003, TestSize.Level1) { TAG_LOGI(AAFwkTag::TEST, "AmsAppRunningRecordTest AttachApplication_003 start"); - MockBundleInstaller(); auto abilityInfo = std::make_shared(); abilityInfo->name = GetTestAbilityName(); abilityInfo->applicationName = GetTestAppName(); @@ -855,7 +845,6 @@ HWTEST_F(AmsAppRunningRecordTest, AttachApplication_003, TestSize.Level1) HWTEST_F(AmsAppRunningRecordTest, AttachApplication_004, TestSize.Level1) { TAG_LOGI(AAFwkTag::TEST, "AmsAppRunningRecordTest AttachApplication_004 start"); - MockBundleInstaller(); auto abilityInfo = std::make_shared(); abilityInfo->name = GetTestAbilityName(); abilityInfo->applicationName = GetTestAppName(); @@ -883,7 +872,6 @@ HWTEST_F(AmsAppRunningRecordTest, AttachApplication_004, TestSize.Level1) HWTEST_F(AmsAppRunningRecordTest, AttachApplication_005, TestSize.Level1) { TAG_LOGI(AAFwkTag::TEST, "AmsAppRunningRecordTest AttachApplication_005 start"); - MockBundleInstaller(); auto abilityInfo = std::make_shared(); abilityInfo->name = GetTestAbilityName(); abilityInfo->applicationName = GetTestAppName(); @@ -912,7 +900,6 @@ HWTEST_F(AmsAppRunningRecordTest, AttachApplication_005, TestSize.Level1) HWTEST_F(AmsAppRunningRecordTest, AttachApplication_006, TestSize.Level1) { TAG_LOGI(AAFwkTag::TEST, "AmsAppRunningRecordTest AttachApplication_006 start"); - MockBundleInstaller(); auto abilityInfo = std::make_shared(); abilityInfo->name = GetTestAbilityName(); abilityInfo->applicationName = GetTestAppName(); @@ -1610,7 +1597,6 @@ HWTEST_F(AmsAppRunningRecordTest, RemoveModuleRecord_001, TestSize.Level1) moduleRecord0 = std::make_shared(appInfo, nullptr); HapModuleInfo hapModuleInfo0; hapModuleInfo0.moduleName = "module0"; - moduleRecord0->Init(hapModuleInfo0); record->RemoveModuleRecord(moduleRecord0); moduleRecordList = record->GetAllModuleRecord(); EXPECT_TRUE(moduleRecordList.size() == 2); @@ -2983,45 +2969,6 @@ HWTEST_F(AmsAppRunningRecordTest, IsAbilitytiesBackground_001, TestSize.Level1) GTEST_LOG_(INFO) << "IsAbilitytiesBackground_001 end."; } -/** - * @tc.name: AppRunningRecord_OnWindowVisibilityChanged_001 - * @tc.desc: verify that AppRunningRecord correctly handle window visibility change event - * @tc.type: FUNC - */ -HWTEST_F(AmsAppRunningRecordTest, OnWindowVisibilityChanged_001, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "OnWindowVisibilityChanged_001 start."; - // 1. create AppRunningRecord, set state and windowIds_ - auto record = GetTestAppRunningRecord(); - EXPECT_NE(record, nullptr); - uint32_t windowId = 123456; - record->windowIds_.insert(windowId); - record->curState_ = ApplicationState::APP_STATE_FOREGROUND; - - // 2. construct WindowVisibilityInfos - std::vector> windowVisibilityInfos; - auto info = new (std::nothrow) Rosen::WindowVisibilityInfo(); - EXPECT_NE(info, nullptr); - info->visibilityState_ = Rosen::WindowVisibilityState::WINDOW_VISIBILITY_STATE_TOTALLY_OCCUSION; - info->windowId_ = windowId; - windowVisibilityInfos.emplace_back(info); - - //3. verify function - record->OnWindowVisibilityChanged(windowVisibilityInfos); - EXPECT_TRUE(record->isUpdateStateFromService_); - EXPECT_TRUE(record->windowIds_.empty()); - - info->visibilityState_ = Rosen::WindowVisibilityState::WINDOW_VISIBILITY_STATE_NO_OCCLUSION; - windowVisibilityInfos.clear(); - windowVisibilityInfos.emplace_back(info); - record->isUpdateStateFromService_ = false; - record->curState_ = ApplicationState::APP_STATE_BACKGROUND; - record->OnWindowVisibilityChanged(windowVisibilityInfos); - EXPECT_FALSE(record->windowIds_.empty()); - EXPECT_TRUE(record->isUpdateStateFromService_); - GTEST_LOG_(INFO) << "OnWindowVisibilityChanged_001 end."; -} - /** * @tc.name: AppRunningRecord_SetState_001 * @tc.desc: verify that setState works. diff --git a/test/unittest/ams_app_state_callback_test/BUILD.gn b/test/unittest/ams_app_state_callback_test/BUILD.gn index 29555e5242..96cf099b43 100644 --- a/test/unittest/ams_app_state_callback_test/BUILD.gn +++ b/test/unittest/ams_app_state_callback_test/BUILD.gn @@ -19,7 +19,6 @@ module_output_path = "ability_runtime/appmgrservice" ohos_unittest("AmsAppStateCallbackTest") { module_out_path = module_output_path cflags_cc = [] - include_dirs = [ "//third_party/json/include" ] sources = [ "${ability_runtime_innerkits_path}//app_manager/src/appmgr/app_process_data.cpp", @@ -49,6 +48,7 @@ ohos_unittest("AmsAppStateCallbackTest") { "hilog:libhilog", "hitrace:hitrace_meter", "ipc:ipc_core", + "json:nlohmann_json_static", ] } diff --git a/test/unittest/ams_app_workflow_test/BUILD.gn b/test/unittest/ams_app_workflow_test/BUILD.gn index 825c9976e6..3324ddeb3d 100644 --- a/test/unittest/ams_app_workflow_test/BUILD.gn +++ b/test/unittest/ams_app_workflow_test/BUILD.gn @@ -83,7 +83,7 @@ ohos_unittest("AmsWorkFlowTest") { if (ability_runtime_graphics) { external_deps += [ - "window_manager:libwm_lite", + "window_manager:libwm", "window_manager:libwsutils", ] } diff --git a/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp b/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp index f67f4443bb..0ac1c88577 100644 --- a/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp +++ b/test/unittest/ams_app_workflow_test/ams_workflow_test.cpp @@ -22,7 +22,6 @@ #include "refbase.h" #include "app_launch_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_token.h" #include "mock_app_scheduler.h" #include "mock_app_spawn_client.h" @@ -185,10 +184,8 @@ HWTEST_F(AmsWorkFlowTest, BackKey_001, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_FOREGROUND); - appB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appB.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appB.GetAbility(tokenB)->GetState()); @@ -248,11 +245,9 @@ HWTEST_F(AmsWorkFlowTest, BackKey_003, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(2); serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); - appC.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appC.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appC.GetAbility(tokenC)->GetState()); @@ -289,12 +284,10 @@ HWTEST_F(AmsWorkFlowTest, BackKey_004, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(2); serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); - appC.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appC.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(tokenD, AbilityState::ABILITY_STATE_FOREGROUND); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appC.GetAbility(tokenC)->GetState()); @@ -331,10 +324,8 @@ HWTEST_F(AmsWorkFlowTest, BackKey_005, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleTerminateApplication(_)).Times(1); serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_FOREGROUND); - appB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appB.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(tokenA, false); serviceInner_->AbilityTerminated(tokenA); @@ -374,11 +365,9 @@ HWTEST_F(AmsWorkFlowTest, BackKey_006, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleTerminateApplication(_)).Times(1); serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); - appC.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appC.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(tokenA, false); serviceInner_->AbilityTerminated(tokenA); @@ -425,12 +414,10 @@ HWTEST_F(AmsWorkFlowTest, BackKey_007, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleTerminateApplication(_)).Times(1); serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); - appC.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appC.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(tokenD, AbilityState::ABILITY_STATE_FOREGROUND); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(tokenA, false); serviceInner_->AbilityTerminated(tokenA); @@ -463,7 +450,6 @@ HWTEST_F(AmsWorkFlowTest, ScreenOff_001, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); @@ -491,7 +477,6 @@ HWTEST_F(AmsWorkFlowTest, ScreenOff_002, TestSize.Level1) serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); @@ -519,7 +504,6 @@ HWTEST_F(AmsWorkFlowTest, ScreenOff_003, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_BACKGROUND, appA.GetAbility(tokenA)->GetState()); @@ -547,7 +531,6 @@ HWTEST_F(AmsWorkFlowTest, ScreenOff_004, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleTerminateApplication(_)).Times(1); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(tokenA, false); serviceInner_->AbilityTerminated(tokenA); @@ -581,7 +564,6 @@ HWTEST_F(AmsWorkFlowTest, ScreenOff_005, TestSize.Level1) serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(tokenA, false); serviceInner_->AbilityTerminated(tokenA); @@ -618,7 +600,6 @@ HWTEST_F(AmsWorkFlowTest, ScreenOff_006, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleTerminateApplication(_)).Times(1); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); serviceInner_->TerminateAbility(tokenA, false); serviceInner_->AbilityTerminated(tokenA); @@ -648,7 +629,6 @@ HWTEST_F(AmsWorkFlowTest, ScreenOn_001, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_FOREGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appA.GetAbility(tokenA)->GetState()); @@ -675,7 +655,6 @@ HWTEST_F(AmsWorkFlowTest, ScreenOn_002, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_FOREGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appA.appRecord_->GetRecordId()); EXPECT_EQ(AbilityState::ABILITY_STATE_FOREGROUND, appA.GetAbility(tokenA)->GetState()); @@ -703,7 +682,6 @@ HWTEST_F(AmsWorkFlowTest, ScreenOn_003, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleForegroundApplication()).Times(1); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_FOREGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appA.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_FOREGROUND); @@ -809,10 +787,8 @@ HWTEST_F(AmsWorkFlowTest, ChangeAbility_003, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(1); serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_FOREGROUND); - appB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appB.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); std::shared_ptr abilityA = appA.GetAbility(tokenA); @@ -856,12 +832,10 @@ HWTEST_F(AmsWorkFlowTest, ChangeAbility_004, TestSize.Level1) EXPECT_CALL(*(appA.mockAppScheduler_), ScheduleBackgroundApplication()).Times(2); serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); - appC.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appC.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); std::shared_ptr abilityA = appA.GetAbility(tokenA); @@ -908,11 +882,9 @@ HWTEST_F(AmsWorkFlowTest, ChangeAbility_005, TestSize.Level1) serviceInner_->UpdateAbilityState(tokenC, AbilityState::ABILITY_STATE_FOREGROUND); serviceInner_->UpdateAbilityState(tokenB, AbilityState::ABILITY_STATE_BACKGROUND); - appB.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appB.appRecord_->GetRecordId()); serviceInner_->UpdateAbilityState(tokenA, AbilityState::ABILITY_STATE_BACKGROUND); - appA.appRecord_->SetUpdateStateFromService(true); serviceInner_->ApplicationBackgrounded(appA.appRecord_->GetRecordId()); std::shared_ptr abilityB = appB.GetAbility(tokenB); diff --git a/test/unittest/ams_ipc_interface_test/ams_ipc_appmgr_interface_test.cpp b/test/unittest/ams_ipc_interface_test/ams_ipc_appmgr_interface_test.cpp index 0bc87b5133..97a9f459c1 100644 --- a/test/unittest/ams_ipc_interface_test/ams_ipc_appmgr_interface_test.cpp +++ b/test/unittest/ams_ipc_interface_test/ams_ipc_appmgr_interface_test.cpp @@ -21,7 +21,6 @@ #include "app_mgr_proxy.h" #include "app_record_id.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_application.h" #include "mock_app_mgr_service.h" #include "application_state_observer_stub.h" diff --git a/test/unittest/ams_ipc_interface_test/ams_ipc_appscheduler_interface_test.cpp b/test/unittest/ams_ipc_interface_test/ams_ipc_appscheduler_interface_test.cpp index 6f5302b72e..dce26bd268 100644 --- a/test/unittest/ams_ipc_interface_test/ams_ipc_appscheduler_interface_test.cpp +++ b/test/unittest/ams_ipc_interface_test/ams_ipc_appscheduler_interface_test.cpp @@ -17,7 +17,6 @@ #include "app_scheduler_proxy.h" #include "app_scheduler_host.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_token.h" #include "mock_application.h" diff --git a/test/unittest/ams_mgr_kill_process_test/ams_mgr_kill_process_test.cpp b/test/unittest/ams_mgr_kill_process_test/ams_mgr_kill_process_test.cpp index 8852b7954e..daf8fd7198 100644 --- a/test/unittest/ams_mgr_kill_process_test/ams_mgr_kill_process_test.cpp +++ b/test/unittest/ams_mgr_kill_process_test/ams_mgr_kill_process_test.cpp @@ -20,7 +20,6 @@ #undef private #include "app_mgr_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_bundle_manager.h" #include "mock_native_token.h" #include "mock_sa_call.h" diff --git a/test/unittest/ams_mgr_scheduler_dump_test/ams_mgr_scheduler_dump_test.cpp b/test/unittest/ams_mgr_scheduler_dump_test/ams_mgr_scheduler_dump_test.cpp index 3bb83883a4..8616c5972c 100644 --- a/test/unittest/ams_mgr_scheduler_dump_test/ams_mgr_scheduler_dump_test.cpp +++ b/test/unittest/ams_mgr_scheduler_dump_test/ams_mgr_scheduler_dump_test.cpp @@ -18,7 +18,6 @@ #define private public #include "ams_mgr_scheduler.h" #undef private -#include "hilog_wrapper.h" using namespace testing; using namespace testing::ext; 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 adac879f2d..3c730d726e 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 @@ -21,7 +21,6 @@ #include "app_state_callback_host.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_token.h" #include "mock_app_mgr_service_inner.h" #include "mock_bundle_manager.h" @@ -1279,7 +1278,7 @@ HWTEST_F(AmsMgrSchedulerTest, SetAppWaitingDebug_002, TestSize.Level0) const std::string bundleName; bool isPersist = true; auto iret = amsMgrScheduler->SetAppWaitingDebug(bundleName, isPersist); - ASSERT_EQ(iret, 22); + ASSERT_EQ(iret, ERR_PERMISSION_DENIED); } /* @@ -1347,7 +1346,7 @@ HWTEST_F(AmsMgrSchedulerTest, GetWaitingDebugApp_002, TestSize.Level0) ASSERT_NE(amsMgrScheduler, nullptr); std::vector debugInfoList; auto iret = amsMgrScheduler->GetWaitingDebugApp(debugInfoList); - ASSERT_EQ(iret, 0); + ASSERT_EQ(iret, ERR_PERMISSION_DENIED); } /* @@ -1488,5 +1487,74 @@ HWTEST_F(AmsMgrSchedulerTest, ClearProcessByToken_002, TestSize.Level0) amsMgrScheduler->ClearProcessByToken(token); } +/* + * Feature: AmsMgrScheduler + * Function: BlockProcessCacheByPids + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler BlockProcessCacheByPids + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, BlockProcessCacheByPids_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + int32_t userId = 0; + std::vector pids = {1}; + amsMgrScheduler->BlockProcessCacheByPids(pids); +} + +/* + * Feature: AmsMgrScheduler + * Function: BlockProcessCacheByPids + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler BlockProcessCacheByPids + * EnvConditions: NA + * CaseDescription: SubmitTask + */ +HWTEST_F(AmsMgrSchedulerTest, BlockProcessCacheByPids_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->BlockProcessCacheByPids(pids); +} + +/* + * Feature: AmsMgrScheduler + * Function: AttachedToStatusBar + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler AttachedToStatusBar + * EnvConditions: NA + * CaseDescription: not initial scheduler + */ +HWTEST_F(AmsMgrSchedulerTest, AttachedToStatusBar_001, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + ASSERT_NE(amsMgrScheduler, nullptr); + sptr token; + amsMgrScheduler->AttachedToStatusBar(token); +} + +/* + * Feature: AmsMgrScheduler + * Function: AttachedToStatusBar + * SubFunction: NA + * FunctionPoints: AmsMgrScheduler AttachedToStatusBar + * EnvConditions: NA + * CaseDescription: SubmitTask + */ +HWTEST_F(AmsMgrSchedulerTest, AttachedToStatusBar_002, TestSize.Level0) +{ + auto amsMgrScheduler = std::make_unique(nullptr, nullptr); + amsMgrScheduler->amsMgrServiceInner_ = GetMockAppMgrServiceInner(); + amsMgrScheduler->amsHandler_ = GetAmsTaskHandler(); + ASSERT_NE(amsMgrScheduler, nullptr); + sptr token; + amsMgrScheduler->AttachedToStatusBar(token); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/ams_mgr_scheduler_test/mock/src/mock_permission_verification.cpp b/test/unittest/ams_mgr_scheduler_test/mock/src/mock_permission_verification.cpp index 83622f9101..5539591709 100644 --- a/test/unittest/ams_mgr_scheduler_test/mock/src/mock_permission_verification.cpp +++ b/test/unittest/ams_mgr_scheduler_test/mock/src/mock_permission_verification.cpp @@ -14,7 +14,6 @@ */ #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_permission_verification.h" 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 e9ece8c44b..3af421ac51 100644 --- a/test/unittest/ams_recent_app_list_test/BUILD.gn +++ b/test/unittest/ams_recent_app_list_test/BUILD.gn @@ -100,7 +100,7 @@ ohos_unittest("AmsRecentAppListTest") { if (ability_runtime_graphics) { external_deps += [ - "window_manager:libwm_lite", + "window_manager:libwm", "window_manager:libwsutils", ] } diff --git a/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp b/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp index 0d6a758de4..f60566acf2 100644 --- a/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp +++ b/test/unittest/ams_recent_app_list_test/ams_recent_app_list_test.cpp @@ -318,7 +318,6 @@ HWTEST_F(AmsRecentAppListTest, Update_003, TestSize.Level1) for (int32_t index = INDEX_NUM_1; index <= INDEX_NUM_3; index++) { auto appRecord = GetAppRunningRecordByIndex(index); - appRecord->SetUpdateStateFromService(true); serviceInner_->ApplicationForegrounded(appRecord->GetRecordId()); auto appTaskInfo = serviceInner_->GetRecentAppList().front(); EXPECT_NE(nullptr, appTaskInfo); 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 770271f47f..38cad787fb 100644 --- a/test/unittest/ams_service_app_spawn_client_test/BUILD.gn +++ b/test/unittest/ams_service_app_spawn_client_test/BUILD.gn @@ -94,7 +94,7 @@ ohos_unittest("AmsServiceAppSpawnClientTest") { ] if (ability_runtime_graphics) { - external_deps += [ "window_manager:libwm_lite" ] + external_deps += [ "window_manager:libwm" ] } subsystem_name = "ability" diff --git a/test/unittest/ams_service_app_spawn_client_test/ams_service_app_spawn_client_test.cpp b/test/unittest/ams_service_app_spawn_client_test/ams_service_app_spawn_client_test.cpp index e555039d50..2babb6acc9 100644 --- a/test/unittest/ams_service_app_spawn_client_test/ams_service_app_spawn_client_test.cpp +++ b/test/unittest/ams_service_app_spawn_client_test/ams_service_app_spawn_client_test.cpp @@ -21,7 +21,6 @@ #include #include "securec.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_app_spawn_socket.h" using namespace testing::ext; diff --git a/test/unittest/ams_service_app_spawn_msg_wrapper_test/ams_service_app_spawn_msg_wrapper_test.cpp b/test/unittest/ams_service_app_spawn_msg_wrapper_test/ams_service_app_spawn_msg_wrapper_test.cpp index d0dc9443c6..c860f05a93 100644 --- a/test/unittest/ams_service_app_spawn_msg_wrapper_test/ams_service_app_spawn_msg_wrapper_test.cpp +++ b/test/unittest/ams_service_app_spawn_msg_wrapper_test/ams_service_app_spawn_msg_wrapper_test.cpp @@ -17,7 +17,6 @@ #include "app_spawn_msg_wrapper.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "securec.h" using namespace testing::ext; diff --git a/test/unittest/ams_service_app_spawn_socket_test/ams_service_app_spawn_socket_test.cpp b/test/unittest/ams_service_app_spawn_socket_test/ams_service_app_spawn_socket_test.cpp index 9e7fb8a4fb..1fb9f055fd 100644 --- a/test/unittest/ams_service_app_spawn_socket_test/ams_service_app_spawn_socket_test.cpp +++ b/test/unittest/ams_service_app_spawn_socket_test/ams_service_app_spawn_socket_test.cpp @@ -17,7 +17,6 @@ #include "app_spawn_socket.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_client_socket.h" #include "securec.h" diff --git a/test/unittest/ams_service_event_drive_test/BUILD.gn b/test/unittest/ams_service_event_drive_test/BUILD.gn index 73c34b8350..bd625ebb80 100644 --- a/test/unittest/ams_service_event_drive_test/BUILD.gn +++ b/test/unittest/ams_service_event_drive_test/BUILD.gn @@ -98,7 +98,7 @@ ohos_unittest("AmsServiceEventDriveTest") { ] if (ability_runtime_graphics) { - external_deps += [ "window_manager:libwm_lite" ] + external_deps += [ "window_manager:libwm" ] } } diff --git a/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp b/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp index fdc96670f2..622a7b56c7 100644 --- a/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp +++ b/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp @@ -22,7 +22,6 @@ #include #include "errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "mock_app_mgr_service_inner.h" #include "mock_native_token.h" 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 86df52e9c0..5da2d9ef83 100644 --- a/test/unittest/ams_service_load_ability_process_test/BUILD.gn +++ b/test/unittest/ams_service_load_ability_process_test/BUILD.gn @@ -103,7 +103,7 @@ ohos_unittest("AmsServiceLoadAbilityProcessTest") { if (ability_runtime_graphics) { external_deps += [ - "window_manager:libwm_lite", + "window_manager:libwm", "window_manager:libwsutils", ] } 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 e16c016f7f..444566d73d 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 @@ -27,7 +27,6 @@ #include "bundle_mgr_interface.h" #include "gtest/gtest.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_app_scheduler.h" #include "mock_ability_token.h" #include "mock_app_spawn_client.h" diff --git a/test/unittest/ams_service_startup_test/BUILD.gn b/test/unittest/ams_service_startup_test/BUILD.gn index 3e2793f67c..0c22400abd 100644 --- a/test/unittest/ams_service_startup_test/BUILD.gn +++ b/test/unittest/ams_service_startup_test/BUILD.gn @@ -93,7 +93,7 @@ ohos_unittest("AmsServiceStartupTest") { ] if (ability_runtime_graphics) { - external_deps += [ "window_manager:libwm_lite" ] + external_deps += [ "window_manager:libwm" ] } } diff --git a/test/unittest/ams_service_startup_test/ams_service_startup_test.cpp b/test/unittest/ams_service_startup_test/ams_service_startup_test.cpp index 7368921bac..a93b1ae4bf 100644 --- a/test/unittest/ams_service_startup_test/ams_service_startup_test.cpp +++ b/test/unittest/ams_service_startup_test/ams_service_startup_test.cpp @@ -21,7 +21,6 @@ #undef protected #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing; using namespace testing::ext; 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 index a0d65fe79c..1b14eba3f2 100644 --- 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 @@ -19,7 +19,6 @@ #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; 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 4d3d5e4a2d..1edb6f917c 100755 --- a/test/unittest/app_exit_reason_data_manager_test/BUILD.gn +++ b/test/unittest/app_exit_reason_data_manager_test/BUILD.gn @@ -35,6 +35,7 @@ ohos_unittest("app_exit_reason_data_manager_test") { deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_services_path}/abilitymgr:abilityms", ] diff --git a/test/unittest/app_launch_data_test/app_launch_data_test.cpp b/test/unittest/app_launch_data_test/app_launch_data_test.cpp index 94301ed240..bae6a826a3 100644 --- a/test/unittest/app_launch_data_test/app_launch_data_test.cpp +++ b/test/unittest/app_launch_data_test/app_launch_data_test.cpp @@ -20,7 +20,6 @@ #include "app_launch_data.h" #undef private #undef protected -#include "hilog_wrapper.h" using namespace testing; using namespace testing::ext; 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 5be42fec83..0ceac52c4b 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 @@ -22,7 +22,6 @@ #include "ability_record.h" #include "app_mgr_constants.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_debug_response_stub.h" #include "mock_app_debug_listener_stub.h" #include "mock_native_token.h" @@ -104,7 +103,7 @@ HWTEST_F(AppMgrClientTest, AppMgrClient_PreStartNWebSpawnProcess_001, TestSize.L EXPECT_EQ(result, AppMgrResultCode::RESULT_OK); int ret = appMgrClient->PreStartNWebSpawnProcess(); - EXPECT_EQ(ret, AppMgrResultCode::RESULT_OK); + EXPECT_EQ(ret, ERR_INVALID_VALUE); } /** @@ -297,7 +296,7 @@ HWTEST_F(AppMgrClientTest, AppMgrClient_GetRenderProcessTerminationStatus_001, T std::string abilityName = "FirstAbility"; std::string appName = "FirstApp"; std::string bundleName = "com.ix.First.Test"; - int status; + int status = ERROR_STATE; auto abilityReq = GenerateAbilityRequest(deviceName, abilityName, appName, bundleName); auto record = AbilityRecord::CreateAbilityRecord(abilityReq); auto token = record->GetToken(); @@ -427,7 +426,7 @@ HWTEST_F(AppMgrClientTest, AppMgrClient_StartUserTestProcess_001, TestSize.Level EXPECT_EQ(result, AppMgrResultCode::RESULT_OK); int ret = appMgrClient->StartUserTestProcess(want, observer, bundleInfo, userId); - EXPECT_EQ(ret, ERROR_RET); + EXPECT_EQ(ret, IPC_PROXY_ERR); } /** @@ -1382,5 +1381,81 @@ HWTEST_F(AppMgrClientTest, SaveBrowserChannel_001, TestSize.Level0) appMgrClient->SaveBrowserChannel(nullptr); EXPECT_NE(appMgrClient, nullptr); } + +/** + * @tc.name: AppMgrClient_BlockProcessCacheByPids_001 + * @tc.desc: can not block process cache by wrong user ID. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrClientTest, AppMgrClient_BlockProcessCacheByPids_001, TestSize.Level0) +{ + auto appMgrClient = std::make_unique(); + EXPECT_NE(appMgrClient, nullptr); + + auto result = appMgrClient->ConnectAppMgrService(); + EXPECT_EQ(result, AppMgrResultCode::RESULT_OK); + + std::vector pids; + appMgrClient->BlockProcessCacheByPids(pids); + EXPECT_TRUE(appMgrClient != nullptr); +} + +/** + * @tc.name: AppMgrClient_AttachedToStatusBar_001 + * @tc.desc: can not attach to status bar by wrong token. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrClientTest, AppMgrClient_AttachedToStatusBar_001, TestSize.Level0) +{ + auto appMgrClient = std::make_unique(); + EXPECT_NE(appMgrClient, nullptr); + + auto result = appMgrClient->ConnectAppMgrService(); + EXPECT_EQ(result, AppMgrResultCode::RESULT_OK); + + sptr token; + appMgrClient->AttachedToStatusBar(token); + EXPECT_TRUE(appMgrClient != nullptr); +} + +/** + * @tc.name: AppMgrClient_SetAppFreezeFilter_001 + * @tc.desc: Can not attach to status bar by wrong token. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrClientTest, AppMgrClient_SetAppFreezeFilter_001, TestSize.Level0) +{ + auto appMgrClient = std::make_unique(); + EXPECT_NE(appMgrClient, nullptr); + int32_t pid = 1; + bool ret = appMgrClient->SetAppFreezeFilter(pid); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: AppMgrClient_NotifyProcessDependedOnWeb_001 + * @tc.desc: Can not attach to status bar by wrong token. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrClientTest, AppMgrClient_NotifyProcessDependedOnWeb_001, TestSize.Level0) +{ + auto appMgrClient = std::make_unique(); + EXPECT_NE(appMgrClient, nullptr); + int32_t ret = appMgrClient->NotifyProcessDependedOnWeb(); + EXPECT_EQ(ret, ERR_INVALID_VALUE); +} + +/** + * @tc.name: AppMgrClient_KillProcessDependedOnWeb_001 + * @tc.desc: Can not attach to status bar by wrong token. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrClientTest, AppMgrClient_KillProcessDependedOnWeb_001, TestSize.Level0) +{ + auto appMgrClient = std::make_unique(); + EXPECT_NE(appMgrClient, nullptr); + appMgrClient->KillProcessDependedOnWeb(); + EXPECT_NE(appMgrClient->GetRemoteObject(), nullptr); +} } // namespace AppExecFwk } // namespace OHOS 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 82682e1ec8..dcc8e8077c 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 @@ -19,7 +19,6 @@ #include "app_foreground_state_observer_stub.h" #include "app_mgr_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_foreground_state_observer_stub.h" #include "mock_app_mgr_service.h" #include "quick_fix_callback_stub.h" @@ -333,6 +332,21 @@ HWTEST_F(AppMgrProxyTest, NotifyAppFaultBySA_001, TestSize.Level1) EXPECT_EQ(mockAppMgrService_->code_, static_cast(AppMgrInterfaceCode::NOTIFY_APP_FAULT_BY_SA)); } +/** + * @tc.name: SetAppFreezeFilter_001 + * @tc.desc: Set appfreeze filter. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrProxyTest, SetAppFreezeFilter_001, TestSize.Level1) +{ + EXPECT_CALL(*mockAppMgrService_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(mockAppMgrService_.GetRefPtr(), &MockAppMgrService::InvokeSendRequest)); + int32_t pid = 0; // test value + appMgrProxy_->SetAppFreezeFilter(pid); + EXPECT_EQ(mockAppMgrService_->code_, static_cast(AppMgrInterfaceCode::SET_APPFREEZE_FILTER)); +} + /** * @tc.name: ChangeAppGcState_001 * @tc.desc: Change app Gc state. 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 index 4dbbaedcd7..f05c3dbd43 100644 --- 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 @@ -21,7 +21,6 @@ #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" 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 590d52f0c7..295e5794b8 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 @@ -21,7 +21,6 @@ #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" diff --git a/test/unittest/app_mgr_service_dump_test/app_mgr_service_dump_test.cpp b/test/unittest/app_mgr_service_dump_test/app_mgr_service_dump_test.cpp index e8519d002a..868e379f04 100644 --- a/test/unittest/app_mgr_service_dump_test/app_mgr_service_dump_test.cpp +++ b/test/unittest/app_mgr_service_dump_test/app_mgr_service_dump_test.cpp @@ -19,7 +19,6 @@ #include "app_mgr_service.h" #undef private #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_native_token.h" #include "mock_sa_call.h" #include "app_mgr_service_dump_error_code.h" 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 05dcf4307a..4ba9bc5b9c 100644 --- a/test/unittest/app_mgr_service_event_handler_test/BUILD.gn +++ b/test/unittest/app_mgr_service_event_handler_test/BUILD.gn @@ -98,7 +98,7 @@ ohos_unittest("AMSEventHandlerTest") { if (ability_runtime_graphics) { external_deps += [ - "window_manager:libwm_lite", + "window_manager:libwm", "window_manager:libwsutils", ] } diff --git a/test/unittest/app_mgr_service_event_handler_test/app_mgr_service_event_handler_test.cpp b/test/unittest/app_mgr_service_event_handler_test/app_mgr_service_event_handler_test.cpp index 9a0d43d8ee..c9683dfce5 100644 --- a/test/unittest/app_mgr_service_event_handler_test/app_mgr_service_event_handler_test.cpp +++ b/test/unittest/app_mgr_service_event_handler_test/app_mgr_service_event_handler_test.cpp @@ -22,7 +22,6 @@ #include #include "mock_app_scheduler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "inner_event.h" #include diff --git a/test/unittest/app_mgr_service_inner_tdd_test/app_mgr_service_inner_tdd_test.cpp b/test/unittest/app_mgr_service_inner_tdd_test/app_mgr_service_inner_tdd_test.cpp index e3ba4a6035..2b94ccb033 100644 --- a/test/unittest/app_mgr_service_inner_tdd_test/app_mgr_service_inner_tdd_test.cpp +++ b/test/unittest/app_mgr_service_inner_tdd_test/app_mgr_service_inner_tdd_test.cpp @@ -24,7 +24,6 @@ #include "app_scheduler.h" #include "event_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "mock_ability_token.h" #include "mock_app_scheduler.h" @@ -595,7 +594,7 @@ HWTEST_F(AppMgrServiceInnerTest, QueryExtensionSandBox_002, TestSize.Level0) DataGroupInfo dataGroupInfo; dataGroupInfo.dataGroupId = "test3"; dataGroupInfoList.emplace_back(dataGroupInfo); - bool strictMode = false; + bool strictMode = true; appMgrServiceInner->QueryExtensionSandBox(moduleName, extensionName, bundleInfo, startMsg, dataGroupInfoList, strictMode); EXPECT_EQ(startMsg.dataGroupInfoList.size(), 0); diff --git a/test/unittest/app_mgr_service_inner_test/BUILD.gn b/test/unittest/app_mgr_service_inner_test/BUILD.gn index f4ab66da66..b70803417d 100644 --- a/test/unittest/app_mgr_service_inner_test/BUILD.gn +++ b/test/unittest/app_mgr_service_inner_test/BUILD.gn @@ -63,6 +63,7 @@ ohos_unittest("AppMgrServiceInnerTest") { "c_utils:utils", "ffrt:libffrt", "hilog:libhilog", + "hitrace:hitrace_meter", "image_framework:image_native", "init:libbeget_proxy", "init:libbegetutil", 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 abd7d678fc..20098d2cb1 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 @@ -25,7 +25,6 @@ #include "appspawn_util.h" #include "event_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_skeleton.h" #include "mock_ability_token.h" #include "mock_app_scheduler.h" @@ -677,7 +676,6 @@ HWTEST_F(AppMgrServiceInnerTest, ApplicationForegrounded_002, TestSize.Level0) BundleInfo info; std::string processName = "test_processName"; auto record = appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, info); - record->SetUpdateStateFromService(true); recordId_ += 1; appMgrServiceInner->ApplicationForegrounded(recordId_); @@ -700,7 +698,6 @@ HWTEST_F(AppMgrServiceInnerTest, ApplicationForegrounded_003, TestSize.Level0) std::string processName = "test_processName"; auto record = appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, info); recordId_ += 1; - record->SetUpdateStateFromService(true); auto record2 = appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, info); recordId_ += 1; std::shared_ptr priorityObject = std::make_shared(); @@ -2940,23 +2937,23 @@ HWTEST_F(AppMgrServiceInnerTest, NotifyAppMgrRecordExitReason_001, TestSize.Leve } /** - * @tc.name: VerifyProcessPermission_001 + * @tc.name: VerifyKillProcessPermission_001 * @tc.desc: verify process permission. * @tc.type: FUNC * @tc.require: issueI5W4S7 */ -HWTEST_F(AppMgrServiceInnerTest, VerifyProcessPermission_001, TestSize.Level0) +HWTEST_F(AppMgrServiceInnerTest, VerifyKillProcessPermission_001, TestSize.Level0) { - TAG_LOGI(AAFwkTag::TEST, "VerifyProcessPermission_001 start"); + TAG_LOGI(AAFwkTag::TEST, "VerifyKillProcessPermission_001 start"); auto appMgrServiceInner = std::make_shared(); EXPECT_NE(appMgrServiceInner, nullptr); - appMgrServiceInner->VerifyProcessPermission(""); + appMgrServiceInner->VerifyKillProcessPermission(""); appMgrServiceInner->appRunningManager_ = nullptr; - appMgrServiceInner->VerifyProcessPermission(""); + appMgrServiceInner->VerifyKillProcessPermission(""); - TAG_LOGI(AAFwkTag::TEST, "VerifyProcessPermission_001 end"); + TAG_LOGI(AAFwkTag::TEST, "VerifyKillProcessPermission_001 end"); } /** @@ -3340,7 +3337,7 @@ HWTEST_F(AppMgrServiceInnerTest, SetContinuousTaskProcess_001, TestSize.Level0) EXPECT_NE(appMgrServiceInner, nullptr); int32_t ret = appMgrServiceInner->SetContinuousTaskProcess(0, true); - EXPECT_EQ(ret, 0); + EXPECT_EQ(ret, ERR_INVALID_VALUE); BundleInfo bundleInfo; std::string processName = "test_processName"; @@ -3674,7 +3671,7 @@ HWTEST_F(AppMgrServiceInnerTest, SetAppWaitingDebug_001, TestSize.Level0) EXPECT_NE(appMgrServiceInner, nullptr); std::string bundleName("test"); auto result = appMgrServiceInner->SetAppWaitingDebug(bundleName, false); - EXPECT_EQ(result, ERR_OK); + EXPECT_EQ(result, ERR_PERMISSION_DENIED); } /** @@ -3687,7 +3684,7 @@ HWTEST_F(AppMgrServiceInnerTest, CancelAppWaitingDebug_001, TestSize.Level0) auto appMgrServiceInner = std::make_shared(); EXPECT_NE(appMgrServiceInner, nullptr); auto result = appMgrServiceInner->CancelAppWaitingDebug(); - EXPECT_EQ(result, ERR_OK); + EXPECT_EQ(result, ERR_PERMISSION_DENIED); } /** @@ -3701,7 +3698,7 @@ HWTEST_F(AppMgrServiceInnerTest, GetWaitingDebugApp_001, TestSize.Level0) EXPECT_NE(appMgrServiceInner, nullptr); std::vector debugInfoList; auto result = appMgrServiceInner->GetWaitingDebugApp(debugInfoList); - EXPECT_EQ(result, ERR_OK); + EXPECT_EQ(result, ERR_PERMISSION_DENIED); } /** @@ -3968,6 +3965,48 @@ HWTEST_F(AppMgrServiceInnerTest, IsMainProcess_001, TestSize.Level0) TAG_LOGI(AAFwkTag::TEST, "IsMainProcess_001 end"); } +/** + * @tc.name: IsApplicationRunning_001 + * @tc.desc: Obtain application running status through bundleName. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrServiceInnerTest, IsApplicationRunning_001, TestSize.Level1) +{ + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, 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"; + appMgrServiceInner->appRunningManager_->appRunningRecordMap_.emplace(recordId_, appRecord); + int32_t ret = appMgrServiceInner->IsApplicationRunning(bundleName, isRunning); + EXPECT_EQ(ret, ERR_OK); + EXPECT_TRUE(isRunning); +} + +/** + * @tc.name: IsApplicationRunning_002 + * @tc.desc: Not passing in bundleName, unable to obtain application running status. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrServiceInnerTest, IsApplicationRunning_002, TestSize.Level1) +{ + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, 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); + appMgrServiceInner->appRunningManager_->appRunningRecordMap_.emplace(recordId_, appRecord); + int32_t ret = appMgrServiceInner->IsApplicationRunning(bundleName, isRunning); + EXPECT_EQ(ret, ERR_OK); + EXPECT_FALSE(isRunning); +} + + /** * @tc.name: InitWindowVisibilityChangedListener_001 * @tc.desc: init windowVisibilityChangedListener @@ -4017,47 +4056,6 @@ HWTEST_F(AppMgrServiceInnerTest, HandleWindowVisibilityChanged_001, TestSize.Lev GTEST_LOG_(INFO) << "HandleWindowVisibilityChanged_001 end"; } -/** - * @tc.name: IsApplicationRunning_001 - * @tc.desc: Obtain application running status through bundleName. - * @tc.type: FUNC - */ -HWTEST_F(AppMgrServiceInnerTest, IsApplicationRunning_001, TestSize.Level1) -{ - auto appMgrServiceInner = std::make_shared(); - EXPECT_NE(appMgrServiceInner, 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"; - appMgrServiceInner->appRunningManager_->appRunningRecordMap_.emplace(recordId_, appRecord); - int32_t ret = appMgrServiceInner->IsApplicationRunning(bundleName, isRunning); - EXPECT_EQ(ret, ERR_OK); - EXPECT_TRUE(isRunning); -} - -/** - * @tc.name: IsApplicationRunning_002 - * @tc.desc: Not passing in bundleName, unable to obtain application running status. - * @tc.type: FUNC - */ -HWTEST_F(AppMgrServiceInnerTest, IsApplicationRunning_002, TestSize.Level1) -{ - auto appMgrServiceInner = std::make_shared(); - EXPECT_NE(appMgrServiceInner, 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); - appMgrServiceInner->appRunningManager_->appRunningRecordMap_.emplace(recordId_, appRecord); - int32_t ret = appMgrServiceInner->IsApplicationRunning(bundleName, isRunning); - EXPECT_EQ(ret, ERR_OK); - EXPECT_FALSE(isRunning); -} - /** * @tc.name: IsAppRunning_001 * @tc.desc: Obtain application running status through bundleName. @@ -4303,7 +4301,7 @@ HWTEST_F(AppMgrServiceInnerTest, SetSupportedProcessCacheSelf_001, TestSize.Leve EXPECT_NE(appMgrServiceInner, nullptr); bool isSupported = false; - EXPECT_EQ(appMgrServiceInner->SetSupportedProcessCacheSelf(isSupported), AAFwk::CHECK_PERMISSION_FAILED); + EXPECT_EQ(appMgrServiceInner->SetSupportedProcessCacheSelf(isSupported), ERR_INVALID_VALUE); appMgrServiceInner->appRunningManager_ = nullptr; EXPECT_EQ(appMgrServiceInner->SetSupportedProcessCacheSelf(isSupported), ERR_NO_INIT); @@ -4359,13 +4357,33 @@ HWTEST_F(AppMgrServiceInnerTest, GetRunningMultiAppInfoByBundleName_001, TestSiz int32_t ret = appMgrServiceInner->GetRunningMultiAppInfoByBundleName(bundleName, info); EXPECT_NE(ret, ERR_OK); - appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->remoteClientManager_ = nullptr; ret = appMgrServiceInner->GetRunningMultiAppInfoByBundleName(bundleName, info); EXPECT_EQ(ret, ERR_INVALID_VALUE); TAG_LOGI(AAFwkTag::TEST, "GetRunningMultiAppInfoByBundleName_001 end"); } +/** + * @tc.name: GetRunningMultiAppInfoByBundleName_002 + * @tc.desc: Get multiApp information list by bundleName. + * @tc.type: FUNC + * @tc.require: issueI9HMAO + */ +HWTEST_F(AppMgrServiceInnerTest, GetRunningMultiAppInfoByBundleName_002, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "GetRunningMultiAppInfoByBundleName_002 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + std::string bundleName = ""; + RunningMultiAppInfo info; + int32_t ret = appMgrServiceInner->GetRunningMultiAppInfoByBundleName(bundleName, info); + EXPECT_EQ(ret, AAFwk::INVALID_PARAMETERS_ERR); + + TAG_LOGI(AAFwkTag::TEST, "GetRunningMultiAppInfoByBundleName_002 end"); +} + /** * @tc.name: SendCreateAtomicServiceProcessEvent_001 * @tc.desc: Report event of create atomic service process. @@ -4388,5 +4406,55 @@ HWTEST_F(AppMgrServiceInnerTest, SendCreateAtomicServiceProcessEvent_001, TestSi ret = appMgrServiceInner->SendCreateAtomicServiceProcessEvent(appRecord, bundleType, moduleName, abilityName); EXPECT_EQ(ret, false); } + +/** + * @tc.name: AttachedToStatusBar_001 + * @tc.desc: Attach one ability to status bar. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrServiceInnerTest, AttachedToStatusBar_001, TestSize.Level1) +{ + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->AttachedToStatusBar(nullptr); + + OHOS::sptr token = sptr(new (std::nothrow) MockAbilityToken()); + appMgrServiceInner->AttachedToStatusBar(token); + + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + std::shared_ptr want; + std::string processName = "test_processName"; + std::shared_ptr appRecord = appMgrServiceInner->CreateAppRunningRecord(token, nullptr, + applicationInfo_, abilityInfo_, processName, bundleInfo, hapModuleInfo, want, 0); + EXPECT_NE(appRecord, nullptr); + appMgrServiceInner->AttachedToStatusBar(token); +} + +/** + * @tc.name: BlockProcessCacheByPids_001 + * @tc.desc: Block process cache feature using pids. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrServiceInnerTest, BlockProcessCacheByPids_001, TestSize.Level1) +{ + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + BundleInfo info; + std::string processName = "test_processName"; + auto record = appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, info); + std::shared_ptr priorityObject = std::make_shared(); + EXPECT_NE(priorityObject, nullptr); + std::string callerBundleName = "callerBundleName"; + priorityObject->SetPid(2); + record->priorityObject_ = priorityObject; + record->mainBundleName_ = callerBundleName; + record->SetCallerPid(1); + + std::vector pids{2}; + appMgrServiceInner->BlockProcessCacheByPids(pids); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/app_mgr_service_test/BUILD.gn b/test/unittest/app_mgr_service_test/BUILD.gn index e5b06178f1..861ad9df91 100644 --- a/test/unittest/app_mgr_service_test/BUILD.gn +++ b/test/unittest/app_mgr_service_test/BUILD.gn @@ -61,6 +61,7 @@ ohos_unittest("app_mgr_service_test") { "c_utils:utils", "ffrt:libffrt", "hilog:libhilog", + "hitrace:hitrace_meter", "init:libbeget_proxy", "init:libbegetutil", "ipc:ipc_core", 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 3130635a33..c6fa4bdcae 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 @@ -22,7 +22,6 @@ #include "ability_manager_errors.h" #include "child_main_thread.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_app_mgr_service_inner.h" #include "mock_native_token.h" #include "mock_sa_call.h" @@ -1469,11 +1468,12 @@ HWTEST_F(AppMgrServiceTest, StartChildProcess_001, TestSize.Level1) appMgrService->taskHandler_ = taskHandler_; appMgrService->eventHandler_ = eventHandler_; - EXPECT_CALL(*mockAppMgrServiceInner_, StartChildProcess(_, _, _, _, _)) + EXPECT_CALL(*mockAppMgrServiceInner_, StartChildProcess(_, _, _)) .Times(1) .WillOnce(Return(ERR_OK)); pid_t pid = 0; - int32_t res = appMgrService->StartChildProcess("./ets/AProcess.ts", pid, 1, false); + ChildProcessRequest request; + int32_t res = appMgrService->StartChildProcess(pid, request); EXPECT_EQ(res, ERR_OK); } @@ -1715,7 +1715,7 @@ HWTEST_F(AppMgrServiceTest, SetSupportedProcessCacheSelf_002, TestSize.Level0) // permission check failed int32_t res = appMgrService->SetSupportedProcessCacheSelf(false); - EXPECT_EQ(res, AAFwk::CHECK_PERMISSION_FAILED); + EXPECT_EQ(res, ERR_INVALID_VALUE); // appRecord not in AppRunningManager AAFwk::IsMockSaCall::IsMockProcessCachePermission(); @@ -1749,10 +1749,7 @@ HWTEST_F(AppMgrServiceTest, SetSupportedProcessCacheSelf_002, TestSize.Level0) 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); + EXPECT_EQ(res, AAFwk::ERR_CAPABILITY_NOT_SUPPORT); } /** 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 79ec2bf9b8..06825a8e15 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 @@ -23,7 +23,6 @@ #undef protected #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "mock_app_mgr_service.h" #include "render_state_observer_stub.h" @@ -335,6 +334,23 @@ HWTEST_F(AppMgrStubTest, HandleNotifyFaultBySA_001, TestSize.Level1) EXPECT_EQ(result, NO_ERROR); } +/** + * @tc.name: HandleSetAppFreezeFilter_001 + * @tc.desc: Handle Set AppFreeze Filter. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrStubTest, HandleSetAppFreezeFilter_001, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + WriteInterfaceToken(data); + data.WriteInt32(0); + auto result = mockAppMgrService_->OnRemoteRequest( + static_cast(AppMgrInterfaceCode::SET_APPFREEZE_FILTER), data, reply, option); + EXPECT_EQ(result, NO_ERROR); +} + /** * @tc.name: HandleChangeAppGcState_001 * @tc.desc: Handle change app Gc state. diff --git a/test/unittest/app_running_manager_test/app_running_manager_test.cpp b/test/unittest/app_running_manager_test/app_running_manager_test.cpp index 9f101774a7..9bdec73907 100644 --- a/test/unittest/app_running_manager_test/app_running_manager_test.cpp +++ b/test/unittest/app_running_manager_test/app_running_manager_test.cpp @@ -21,7 +21,6 @@ #include "child_process_record.h" #undef private #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "window_visibility_info.h" using namespace testing; @@ -166,7 +165,7 @@ HWTEST_F(AppRunningManagerTest, AppRunningManager_GetAbilityTokensByBundleName_0 /** * @tc.name: AppRunningManager_OnWindowVisibilityChanged_0100 - * @tc.desc: verify the function of OnWindowVisibilityChanged : set windowIds and isUpdateStateFromService_ + * @tc.desc: verify the function of OnWindowVisibilityChanged : set windowIds * @tc.type: FUNC */ HWTEST_F(AppRunningManagerTest, AppRunningManager_OnWindowVisibilityChanged_0100, TestSize.Level1) @@ -184,7 +183,6 @@ HWTEST_F(AppRunningManagerTest, AppRunningManager_OnWindowVisibilityChanged_0100 auto appRunningRecord = std::make_shared(appInfo, recordId, processName); EXPECT_NE(appRunningRecord, nullptr); appRunningRecord->curState_ = ApplicationState::APP_STATE_BACKGROUND; - appRunningRecord->isUpdateStateFromService_ = false; appRunningRecord->GetPriorityObject()->SetPid(PID); appRunningManager->appRunningRecordMap_.emplace(recordId, appRunningRecord); @@ -201,7 +199,6 @@ HWTEST_F(AppRunningManagerTest, AppRunningManager_OnWindowVisibilityChanged_0100 appRunningManager->OnWindowVisibilityChanged(windowVisibilityInfos); EXPECT_FALSE(appRunningManager->appRunningRecordMap_.empty()); EXPECT_FALSE(appRunningManager->appRunningRecordMap_.at(1)->windowIds_.empty()); - EXPECT_TRUE(appRunningManager->appRunningRecordMap_.at(1)->isUpdateStateFromService_); } /** @@ -217,7 +214,9 @@ HWTEST_F(AppRunningManagerTest, AppRunningManager_GetAppRunningRecordByChildProc auto appInfo = std::make_shared(); auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); - auto childRecord = ChildProcessRecord::CreateChildProcessRecord(PID, "./ets/AProcess.ts", appRecord, 1, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = ChildProcessRecord::CreateChildProcessRecord(PID, request, appRecord); pid_t childPid = 201; childRecord->pid_ = childPid; appRecord->AddChildProcessRecord(childPid, childRecord); @@ -256,6 +255,48 @@ HWTEST_F(AppRunningManagerTest, AppRunningManager_UpdateConfiguration_0100, Test EXPECT_EQ(ret, ERR_OK); } +/** + * @tc.name: AppRunningManager_UpdateConfiguration_0200 + * @tc.desc: Test UpdateConfiguration config storage + * @tc.type: FUNC + */ +HWTEST_F(AppRunningManagerTest, AppRunningManager_UpdateConfiguration_0200, TestSize.Level1) +{ + auto appRunningManager = std::make_shared(); + EXPECT_NE(appRunningManager, nullptr); + Configuration config; + config.AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, ConfigurationInner::COLOR_MODE_LIGHT); + auto ret = appRunningManager->UpdateConfiguration(config); + EXPECT_EQ(ret, ERR_OK); + EXPECT_NE(appRunningManager->configuration_, nullptr); + EXPECT_EQ(appRunningManager->configuration_->GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE), + ConfigurationInner::COLOR_MODE_LIGHT); +} + +/** + * @tc.name: AppRunningManager_UpdateConfiguration_0300 + * @tc.desc: Test UpdateConfiguration delayed + * @tc.type: FUNC + */ +HWTEST_F(AppRunningManagerTest, AppRunningManager_UpdateConfiguration_0300, TestSize.Level1) +{ + auto appRunningManager = std::make_shared(); + EXPECT_NE(appRunningManager, nullptr); + std::shared_ptr appInfo = std::make_shared(); + int32_t recordId = 1; + std::string processName; + Configuration config; + auto appRunningRecord = std::make_shared(appInfo, recordId, processName); + appRunningManager->appRunningRecordMap_.emplace(recordId, appRunningRecord); + appRunningRecord = std::make_shared(appInfo, recordId, processName); + appRunningRecord->SetState(ApplicationState::APP_STATE_BACKGROUND); + appRunningManager->appRunningRecordMap_.emplace(++recordId, appRunningRecord); + auto ret = appRunningManager->UpdateConfiguration(config); + EXPECT_EQ(ret, ERR_OK); + EXPECT_EQ(appRunningManager->updateConfigurationDelayedMap_[0], false); + EXPECT_EQ(appRunningManager->updateConfigurationDelayedMap_[1], true); +} + /** * @tc.name: RemoveAppRunningRecordById_0100 * @tc.desc: Remove app running record by id. @@ -631,8 +672,10 @@ HWTEST_F(AppRunningManagerTest, IsAppProcessesAllCached_0100, TestSize.Level1) std::string processName = "com.tdd.cacheprocesstest"; auto appRunningRecord1 = std::make_shared(appInfo, recordId1, processName); appRunningRecord1->SetUid(appInfo->uid); + appRunningRecord1->SetSupportedProcessCache(true); auto appRunningRecord2 = std::make_shared(appInfo, recordId2, processName); appRunningRecord2->SetUid(appInfo->uid); + appRunningRecord2->SetSupportedProcessCache(true); appRunningManager->appRunningRecordMap_.insert(make_pair(recordId1, appRunningRecord1)); std::set> cachedSet; diff --git a/test/unittest/app_running_processes_info_test/app_running_processes_info_test.cpp b/test/unittest/app_running_processes_info_test/app_running_processes_info_test.cpp index ab9d0d9c26..87eae5a54a 100644 --- a/test/unittest/app_running_processes_info_test/app_running_processes_info_test.cpp +++ b/test/unittest/app_running_processes_info_test/app_running_processes_info_test.cpp @@ -25,7 +25,6 @@ #include "app_record_id.h" #include "app_scheduler_host.h" #include "bundle_mgr_interface.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "iservice_registry.h" #include "mock_ability_token.h" diff --git a/test/unittest/app_running_record_test/app_running_record_test.cpp b/test/unittest/app_running_record_test/app_running_record_test.cpp index cf18cfa99f..3b7959d2d0 100644 --- a/test/unittest/app_running_record_test/app_running_record_test.cpp +++ b/test/unittest/app_running_record_test/app_running_record_test.cpp @@ -28,7 +28,6 @@ #undef private #undef protected #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_token.h" using namespace testing; @@ -201,7 +200,9 @@ HWTEST_F(AppRunningRecordTest, AppRunningRecord_AddChildProcessRecord_0100, Test auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); EXPECT_NE(appRecord, nullptr); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", appRecord, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, appRecord); pid_t childPid = 201; childRecord->SetPid(childPid); appRecord->AddChildProcessRecord(childPid, childRecord); @@ -223,7 +224,9 @@ HWTEST_F(AppRunningRecordTest, AppRunningRecord_RemoveChildProcessRecord_0100, T auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); EXPECT_NE(appRecord, nullptr); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", appRecord, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, appRecord); pid_t childPid = 201; childRecord->SetPid(childPid); appRecord->childProcessRecordMap_.emplace(childPid, childRecord); @@ -246,7 +249,9 @@ HWTEST_F(AppRunningRecordTest, AppRunningRecord_GetChildProcessRecordByPid_0100, auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); EXPECT_NE(appRecord, nullptr); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", appRecord, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, appRecord); pid_t childPid = 201; childRecord->SetPid(childPid); appRecord->childProcessRecordMap_.emplace(childPid, childRecord); diff --git a/test/unittest/app_running_record_test/child_process_record_test.cpp b/test/unittest/app_running_record_test/child_process_record_test.cpp index 5461f04c03..0384efe58c 100644 --- a/test/unittest/app_running_record_test/child_process_record_test.cpp +++ b/test/unittest/app_running_record_test/child_process_record_test.cpp @@ -58,7 +58,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0100, TestSize.Level1) auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); EXPECT_NE(appRecord, nullptr); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", appRecord, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, appRecord); auto hostPid = childRecord->GetHostPid(); EXPECT_EQ(hostPid, 101); } @@ -75,7 +77,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0200, TestSize.Level1) auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); EXPECT_NE(appRecord, nullptr); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", appRecord, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, appRecord); childRecord->SetUid(100); auto uid = childRecord->GetUid(); EXPECT_EQ(uid, 100); @@ -90,7 +94,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0300, TestSize.Level1) { TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_0300 called."); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", nullptr, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, nullptr); auto record = childRecord->GetHostRecord(); EXPECT_EQ(record, nullptr); } @@ -107,7 +113,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0400, TestSize.Level1) auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); EXPECT_NE(appRecord, nullptr); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", appRecord, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, appRecord); auto processName = childRecord->GetProcessName(); EXPECT_TRUE(processName.length() > 0); } @@ -121,7 +129,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0500, TestSize.Level1) { TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_0500 called."); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", nullptr, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, nullptr); auto processName = childRecord->GetProcessName(); EXPECT_TRUE(processName.length() <= 0); } @@ -138,7 +148,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0600, TestSize.Level1) auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); EXPECT_NE(appRecord, nullptr); - auto childRecord = std::make_shared(101, "", appRecord, 0, false); + ChildProcessRequest request; + request.srcEntry = ""; + auto childRecord = std::make_shared(101, request, appRecord); auto processName = childRecord->GetProcessName(); EXPECT_TRUE(processName.length() <= 0); } @@ -155,7 +167,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0700, TestSize.Level1) auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); EXPECT_NE(appRecord, nullptr); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", appRecord, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, appRecord); auto srcEntry = childRecord->GetSrcEntry(); EXPECT_EQ(srcEntry, "./ets/AProcess.ts"); } @@ -169,7 +183,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0800, TestSize.Level1) { TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_0800 called."); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", nullptr, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, nullptr); sptr scheduler; childRecord->SetScheduler(scheduler); EXPECT_NE(childRecord, nullptr); @@ -184,7 +200,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0900, TestSize.Level1) { TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_0900 called."); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", nullptr, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, nullptr); sptr scheduler; childRecord->SetScheduler(scheduler); EXPECT_EQ(childRecord->GetScheduler(), scheduler); @@ -199,7 +217,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_1000, TestSize.Level1) { TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_1000 called."); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", nullptr, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, nullptr); sptr recipient; childRecord->SetDeathRecipient(recipient); EXPECT_NE(childRecord, nullptr); @@ -214,7 +234,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_1100, TestSize.Level1) { TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_1100 called."); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", nullptr, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, nullptr); sptr scheduler; childRecord->SetScheduler(scheduler); sptr recipient; @@ -232,7 +254,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_1200, TestSize.Level1) { TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_1200 called."); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", nullptr, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, nullptr); childRecord->RemoveDeathRecipient(); EXPECT_NE(childRecord, nullptr); } @@ -246,7 +270,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_1300, TestSize.Level1) { TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_1300 called."); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", nullptr, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, nullptr); sptr scheduler; childRecord->SetScheduler(scheduler); childRecord->RemoveDeathRecipient(); @@ -262,7 +288,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_1400, TestSize.Level1) { TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_1400 called."); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", nullptr, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, nullptr); sptr scheduler; childRecord->SetScheduler(scheduler); childRecord->ScheduleExitProcessSafely(); @@ -278,7 +306,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_1500, TestSize.Level1) { TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_1500 called."); - auto childRecord = std::make_shared(101, "./ets/AProcess.ts", nullptr, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = std::make_shared(101, request, nullptr); childRecord->ScheduleExitProcessSafely(); EXPECT_NE(childRecord, nullptr); } @@ -295,7 +325,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_1600, TestSize.Level1) auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); EXPECT_NE(appRecord, nullptr); - auto childRecord = ChildProcessRecord::CreateChildProcessRecord(0, "./ets/AProcess.ts", appRecord, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = ChildProcessRecord::CreateChildProcessRecord(0, request, appRecord); EXPECT_EQ(childRecord, nullptr); } @@ -311,7 +343,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_1700, TestSize.Level1) auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); EXPECT_NE(appRecord, nullptr); - auto childRecord = ChildProcessRecord::CreateChildProcessRecord(101, "", appRecord, 0, false); + ChildProcessRequest request; + request.srcEntry = ""; + auto childRecord = ChildProcessRecord::CreateChildProcessRecord(101, request, appRecord); EXPECT_EQ(childRecord, nullptr); } @@ -323,7 +357,9 @@ HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_1700, TestSize.Level1) HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_1800, TestSize.Level1) { TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_1800 called."); - auto childRecord = ChildProcessRecord::CreateChildProcessRecord(101, "./ets/AProcess.ts", nullptr, 0, false); + ChildProcessRequest request; + request.srcEntry = "./ets/AProcess.ts"; + auto childRecord = ChildProcessRecord::CreateChildProcessRecord(101, request, nullptr); EXPECT_EQ(childRecord, nullptr); } } // namespace AppExecFwk diff --git a/test/unittest/app_utils_test/app_utils_test.cpp b/test/unittest/app_utils_test/app_utils_test.cpp index d5b2eb4679..c1a33afd3c 100644 --- a/test/unittest/app_utils_test/app_utils_test.cpp +++ b/test/unittest/app_utils_test/app_utils_test.cpp @@ -17,7 +17,6 @@ #include "app_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "parameters.h" using namespace testing; diff --git a/test/unittest/appkit/BUILD.gn b/test/unittest/appkit/BUILD.gn index 79faaaed47..fb2c75472f 100644 --- a/test/unittest/appkit/BUILD.gn +++ b/test/unittest/appkit/BUILD.gn @@ -14,5 +14,8 @@ group("unittest") { testonly = true - deps = [ "child_main_thread_test:unittest" ] + deps = [ + "child_main_thread_test:unittest", + "main_thread_test:unittest", + ] } 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 9bfcea64c4..f37749eb88 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 @@ -22,7 +22,6 @@ #include "child_process_info.h" #include "event_handler.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_app_mgr_service.h" #include "mock_bundle_manager.h" #include "sys_mgr_client.h" @@ -113,6 +112,7 @@ HWTEST_F(ChildMainThreadTest, ScheduleLoadJs_0100, TestSize.Level0) std::shared_ptr runner = EventRunner::GetMainEventRunner(); std::shared_ptr handler = std::make_shared(runner); thread->mainHandler_ = handler; + thread->processInfo_ = std::make_shared(); auto ret = thread->ScheduleLoadJs(); EXPECT_TRUE(ret); @@ -152,6 +152,41 @@ HWTEST_F(ChildMainThreadTest, HandleLoadJs_0100, TestSize.Level0) ASSERT_NE(thread->runtime_, nullptr); } +/** + * @tc.number: HandleLoadArkTs_0100 + * @tc.desc: Test HandleLoadArkTs works + * @tc.type: FUNC + */ +HWTEST_F(ChildMainThreadTest, HandleLoadArkTs_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "HandleLoadArkTs_0100 called."); + sptr thread = sptr(new (std::nothrow) ChildMainThread()); + ASSERT_NE(thread, nullptr); + + BundleInfo bundleInfo; + std::vector hapModuleInfos; + HapModuleInfo moduleInfo; + moduleInfo.name = "entry"; + moduleInfo.moduleName = "entry"; + moduleInfo.moduleType = ModuleType::ENTRY; + moduleInfo.hapPath = "/data/app/el1/bundle/public/com.ohos.demoprocess/entry"; + moduleInfo.compileMode = CompileMode::ES_MODULE; + moduleInfo.isStageBasedModel = true; + hapModuleInfos.push_back(moduleInfo); + bundleInfo.hapModuleInfos = hapModuleInfos; + + ApplicationInfo applicationInfo; + applicationInfo.uid = 2001; + bundleInfo.applicationInfo = applicationInfo; + + thread->bundleInfo_ = std::make_shared(bundleInfo); + thread->processInfo_ = std::make_shared(); + thread->processInfo_->srcEntry = "entry/./ets/process/AProcess.ets"; + thread->appMgr_ = sptr(new (std::nothrow) MockAppMgrService()); + thread->HandleLoadArkTs(); + ASSERT_NE(thread->runtime_, nullptr); +} + /** * @tc.number: ScheduleExitProcessSafely_0100 * @tc.desc: Test ScheduleExitProcessSafely works diff --git a/test/unittest/appkit/main_thread_test/main_thread_by_mock_bms_test.cpp b/test/unittest/appkit/main_thread_test/main_thread_by_mock_bms_test.cpp index 1b3e2577c0..89e6fcd846 100644 --- a/test/unittest/appkit/main_thread_test/main_thread_by_mock_bms_test.cpp +++ b/test/unittest/appkit/main_thread_test/main_thread_by_mock_bms_test.cpp @@ -18,7 +18,6 @@ #define private public #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "main_thread.h" 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 50af33d0d2..006e98ab0b 100644 --- a/test/unittest/appkit/main_thread_test/main_thread_test.cpp +++ b/test/unittest/appkit/main_thread_test/main_thread_test.cpp @@ -21,7 +21,6 @@ #include "app_mgr_stub.h" #include "main_thread.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "mock_bundle_manager.h" @@ -514,12 +513,14 @@ HWTEST_F(MainThreadTest, InitResourceManager_0100, TestSize.Level1) std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); EXPECT_TRUE(resourceManager != nullptr); HapModuleInfo info; + ApplicationInfo appInfo; Configuration config; - bool multiProjects = true; - mainThread_->InitResourceManager(resourceManager, info, info.bundleName, multiProjects, config); + appInfo.multiProjects = true; + appInfo.debug = false; + mainThread_->InitResourceManager(resourceManager, info, info.bundleName, config, appInfo); EXPECT_TRUE(resourceManager != nullptr); - multiProjects = false; - mainThread_->InitResourceManager(resourceManager, info, info.bundleName, multiProjects, config); + appInfo.multiProjects = false; + mainThread_->InitResourceManager(resourceManager, info, info.bundleName, config, appInfo); EXPECT_TRUE(resourceManager != nullptr); info.name = "com.ohos.contactsdataability"; @@ -528,25 +529,25 @@ HWTEST_F(MainThreadTest, InitResourceManager_0100, TestSize.Level1) info.iconPath = "$media:icon"; info.deviceTypes = { "smartVision" }; info.bundleName = "com.ohos.contactsdataability"; - multiProjects = true; - mainThread_->InitResourceManager(resourceManager, info, info.bundleName, multiProjects, config); + appInfo.multiProjects = true; + mainThread_->InitResourceManager(resourceManager, info, info.bundleName, config, appInfo); EXPECT_TRUE(resourceManager != nullptr); - multiProjects = false; - mainThread_->InitResourceManager(resourceManager, info, info.bundleName, multiProjects, config); + appInfo.multiProjects = false; + mainThread_->InitResourceManager(resourceManager, info, info.bundleName, config, appInfo); EXPECT_TRUE(resourceManager != nullptr); info.resourcePath = "/data/app/el1/budle/public/com.ohos.contactsdataability"\ "/com.ohos.contactsdataability/assets/entry/resources.index"; - mainThread_->InitResourceManager(resourceManager, info, info.bundleName, multiProjects, config); + mainThread_->InitResourceManager(resourceManager, info, info.bundleName, config, appInfo); EXPECT_TRUE(resourceManager != nullptr); info.hapPath = "/system/app/com.ohos.contactsdataability/Contacts_DataAbility.hap"; - mainThread_->InitResourceManager(resourceManager, info, info.bundleName, multiProjects, config); + mainThread_->InitResourceManager(resourceManager, info, info.bundleName, config, appInfo); EXPECT_TRUE(resourceManager != nullptr); info.resourcePath = ""; - mainThread_->InitResourceManager(resourceManager, info, info.bundleName, multiProjects, config); + mainThread_->InitResourceManager(resourceManager, info, info.bundleName, config, appInfo); EXPECT_TRUE(resourceManager != nullptr); } @@ -1646,11 +1647,13 @@ HWTEST_F(MainThreadTest, InitResourceManager_0200, TestSize.Level1) std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); EXPECT_TRUE(resourceManager != nullptr); Configuration config; + ApplicationInfo appInfo; HapModuleInfo hapModuleInfo = {}; hapModuleInfo.isStageBasedModel = true; const std::string bundleName = "bundleName"; - bool multiProjects = true; - mainThread_->InitResourceManager(resourceManager, hapModuleInfo, bundleName, multiProjects, config); + appInfo.multiProjects = true; + appInfo.debug = false; + mainThread_->InitResourceManager(resourceManager, hapModuleInfo, bundleName, config, appInfo); EXPECT_TRUE(resourceManager != nullptr); } diff --git a/test/unittest/appkit/ohos_application_test/ohos_application_test.cpp b/test/unittest/appkit/ohos_application_test/ohos_application_test.cpp index 224f3efac9..257f537eb9 100644 --- a/test/unittest/appkit/ohos_application_test/ohos_application_test.cpp +++ b/test/unittest/appkit/ohos_application_test/ohos_application_test.cpp @@ -25,7 +25,6 @@ #include "context_impl.h" #include "fa_ability_thread.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_lifecycle_callbacks.h" #include "mock_element_callback.h" #include "mock_i_remote_object.h" diff --git a/test/unittest/application_context_test/application_context_test.cpp b/test/unittest/application_context_test/application_context_test.cpp index 1c82a5896a..7e2e5004f8 100644 --- a/test/unittest/application_context_test/application_context_test.cpp +++ b/test/unittest/application_context_test/application_context_test.cpp @@ -1316,5 +1316,208 @@ HWTEST_F(ApplicationContextTest, SetCurrentAppMode_0100, TestSize.Level1) int32_t res = context_->GetCurrentAppMode(); EXPECT_EQ(res, appMode); } + +/** + * @tc.number:DispatchOnAbilityWillContinue_0100 + * @tc.name: DispatchOnAbilityWillContinue + * @tc.desc: DispatchOnAbilityWillContinue fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnAbilityWillContinue_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnAbilityWillContinue_0100 start"; + std::shared_ptr ability = nullptr; + context_->DispatchOnAbilityWillContinue(ability); + GTEST_LOG_(INFO) << "DispatchOnAbilityWillContinue_0100 end"; +} + +/** + * @tc.number:DispatchOnWindowStageWillRestore_0100 + * @tc.name: DispatchOnWindowStageWillRestore + * @tc.desc: DispatchOnWindowStageWillRestore fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnWindowStageWillRestore_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnWindowStageWillRestore_0100 start"; + std::shared_ptr ability = nullptr; + std::shared_ptr winstage = nullptr; + context_->DispatchOnWindowStageWillRestore(ability, winstage); + GTEST_LOG_(INFO) << "DispatchOnWindowStageWillRestore_0100 end"; +} + +/** + * @tc.number:DispatchOnWindowStageRestore_0100 + * @tc.name: DispatchOnWindowStageRestore + * @tc.desc: DispatchOnWindowStageRestore fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnWindowStageRestore_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnWindowStageRestore_0100 start"; + std::shared_ptr ability = nullptr; + std::shared_ptr winstage = nullptr; + context_->DispatchOnWindowStageRestore(ability, winstage); + GTEST_LOG_(INFO) << "DispatchOnWindowStageRestore_0100 end"; +} + +/** + * @tc.number:DispatchOnAbilityWillSaveState_0100 + * @tc.name: DispatchOnAbilityWillSaveState + * @tc.desc: DispatchOnAbilityWillSaveState fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnAbilityWillSaveState_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnAbilityWillSaveState_0100 start"; + std::shared_ptr ability = nullptr; + context_->DispatchOnAbilityWillSaveState(ability); + GTEST_LOG_(INFO) << "DispatchOnAbilityWillSaveState_0100 end"; +} + +/** + * @tc.number:DispatchOnAbilitySaveState_0100 + * @tc.name: DispatchOnAbilitySaveState + * @tc.desc: DispatchOnAbilitySaveState fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnAbilitySaveState_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnAbilitySaveState_0100 start"; + std::shared_ptr ability = nullptr; + context_->DispatchOnAbilitySaveState(ability); + GTEST_LOG_(INFO) << "DispatchOnAbilitySaveState_0100 end"; +} + +/** + * @tc.number:DispatchOnWillNewWant_0100 + * @tc.name: DispatchOnWillNewWant + * @tc.desc: DispatchOnWillNewWant fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnWillNewWant_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnWillNewWant_0100 start"; + std::shared_ptr ability = nullptr; + context_->DispatchOnWillNewWant(ability); + GTEST_LOG_(INFO) << "DispatchOnWillNewWant_0100 end"; +} + +/** + * @tc.number:DispatchOnNewWant_0100 + * @tc.name: DispatchOnNewWant + * @tc.desc: DispatchOnNewWant fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnNewWant_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnNewWant_0100 start"; + std::shared_ptr ability = nullptr; + context_->DispatchOnNewWant(ability); + GTEST_LOG_(INFO) << "DispatchOnNewWant_0100 end"; +} + +/** + * @tc.number:DispatchOnAbilityWillCreate_0100 + * @tc.name: DispatchOnAbilityWillCreate + * @tc.desc: DispatchOnAbilityWillCreate fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnAbilityWillCreate_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnAbilityWillCreate_0100 start"; + std::shared_ptr ability = nullptr; + context_->DispatchOnAbilityWillCreate(ability); + GTEST_LOG_(INFO) << "DispatchOnAbilityWillCreate_0100 end"; +} + +/** + * @tc.number:DispatchOnWindowStageWillCreate_0100 + * @tc.name: DispatchOnWindowStageWillCreate + * @tc.desc: DispatchOnWindowStageWillCreate fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnWindowStageWillCreate_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnWindowStageWillCreate_0100 start"; + std::shared_ptr ability = nullptr; + std::shared_ptr winstage = nullptr; + context_->DispatchOnWindowStageWillCreate(ability, winstage); + GTEST_LOG_(INFO) << "DispatchOnWindowStageWillCreate_0100 end"; +} + +/** + * @tc.number:DispatchOnWindowStageWillDestroy_0100 + * @tc.name: DispatchOnWindowStageWillDestroy + * @tc.desc: DispatchOnWindowStageWillDestroy fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnWindowStageWillDestroy_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnWindowStageWillDestroy_0100 start"; + std::shared_ptr ability = nullptr; + std::shared_ptr winstage = nullptr; + context_->DispatchOnWindowStageWillDestroy(ability, winstage); + GTEST_LOG_(INFO) << "DispatchOnWindowStageWillDestroy_0100 end"; +} + +/** + * @tc.number:DispatchOnAbilityWillDestroy_0100 + * @tc.name: DispatchOnAbilityWillDestroy + * @tc.desc: DispatchOnAbilityWillDestroy fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnAbilityWillDestroy_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnAbilityWillDestroy_0100 start"; + std::shared_ptr ability = nullptr; + context_->DispatchOnAbilityWillDestroy(ability); + GTEST_LOG_(INFO) << "DispatchOnAbilityWillDestroy_0100 end"; +} + +/** + * @tc.number:DispatchOnAbilityWillForeground_0100 + * @tc.name: DispatchOnAbilityWillForeground + * @tc.desc: DispatchOnAbilityWillForeground fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnAbilityWillForeground_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnAbilityWillForeground_0100 start"; + std::shared_ptr ability = nullptr; + context_->DispatchOnAbilityWillForeground(ability); + GTEST_LOG_(INFO) << "DispatchOnAbilityWillForeground_0100 end"; +} + +/** + * @tc.number:DispatchOnAbilityWillBackground_0100 + * @tc.name: DispatchOnAbilityWillBackground + * @tc.desc: DispatchOnAbilityWillBackground fail with no permission + */ +HWTEST_F(ApplicationContextTest, DispatchOnAbilityWillBackground_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "DispatchOnAbilityWillBackground_0100 start"; + std::shared_ptr ability = nullptr; + context_->DispatchOnAbilityWillBackground(ability); + GTEST_LOG_(INFO) << "DispatchOnAbilityWillBackground_0100 end"; +} + +/** + * @tc.number:SetFont_0100 + * @tc.name: SetFont + * @tc.desc: SetFont fail with no permission + */ +HWTEST_F(ApplicationContextTest, SetFont_0100, TestSize.Level1) +{ + context_->SetFont("awk"); +} + +/** + * @tc.number:SetMcc_0100 + * @tc.name: SetMcc + * @tc.desc: SetMcc fail with no permission + */ +HWTEST_F(ApplicationContextTest, SetMcc_0100, TestSize.Level1) +{ + context_->SetMcc("mcc"); +} + +/** + * @tc.number:SetMnc_0100 + * @tc.name: SetMnc + * @tc.desc: SetMnc fail with no permission + */ +HWTEST_F(ApplicationContextTest, SetMnc_0100, TestSize.Level1) +{ + context_->SetMnc("mnc"); +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/auto_fill_manager_test/auto_fill_manager_test.cpp b/test/unittest/auto_fill_manager_test/auto_fill_manager_test.cpp index 026ea6ead2..07c0c2c881 100644 --- a/test/unittest/auto_fill_manager_test/auto_fill_manager_test.cpp +++ b/test/unittest/auto_fill_manager_test/auto_fill_manager_test.cpp @@ -20,7 +20,6 @@ #include "auto_fill_error.h" #include "auto_fill_extension_callback.h" #include "extension_ability_info.h" -#include "hilog_wrapper.h" #include "mock_ui_content.h" #undef private @@ -42,9 +41,6 @@ public: { return nullptr; } - - std::shared_ptr autoFillManager_ = - std::make_shared(); }; class MockModalUIExtensionProxy : public Ace::ModalUIExtensionProxy { @@ -64,19 +60,6 @@ void AutoFillManagerTest::SetUp() void AutoFillManagerTest::TearDown() {} -/** - * @tc.name: ReloadInModal_0100 - * @tc.desc: Js auto fill extension ReloadInModal. - * @tc.type: FUNC - */ -HWTEST_F(AutoFillManagerTest, ReloadInModal_0100, TestSize.Level1) -{ - AbilityRuntime::AutoFill::ReloadInModalRequest request; - ASSERT_NE(autoFillManager_, nullptr); - auto ret = autoFillManager_->ReloadInModal(request); - EXPECT_EQ(ret, AbilityRuntime::AutoFill::AUTO_FILL_OBJECT_IS_NULL); -} - /* * Feature: AutoFillManager * Function: RequestAutoFill @@ -91,9 +74,9 @@ HWTEST_F(AutoFillManagerTest, RequestAutoFill_0100, TestSize.Level1) auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); const AbilityRuntime::AutoFill::AutoFillRequest autoFillRequest; const std::shared_ptr fillCallback = nullptr; - bool isPopup = false; - int32_t result = manager.RequestAutoFill(GetUIContent(), autoFillRequest, fillCallback, isPopup); - EXPECT_EQ(result, AbilityRuntime::AutoFill::AUTO_FILL_OBJECT_IS_NULL); + AbilityRuntime::AutoFill::AutoFillResult result; + int32_t ret = manager.RequestAutoFill(GetUIContent(), autoFillRequest, fillCallback, result); + EXPECT_EQ(ret, AbilityRuntime::AutoFill::AUTO_FILL_OBJECT_IS_NULL); } /* @@ -110,8 +93,9 @@ HWTEST_F(AutoFillManagerTest, RequestAutoSave_0100, TestSize.Level1) auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); const AbilityRuntime::AutoFill::AutoFillRequest autoFillRequest; const std::shared_ptr saveCallback = nullptr; - int32_t result = manager.RequestAutoSave(GetUIContent(), autoFillRequest, saveCallback); - EXPECT_EQ(result, AbilityRuntime::AutoFill::AUTO_FILL_OBJECT_IS_NULL); + AbilityRuntime::AutoFill::AutoFillResult result; + int32_t ret = manager.RequestAutoSave(GetUIContent(), autoFillRequest, saveCallback, result); + EXPECT_EQ(ret, AbilityRuntime::AutoFill::AUTO_FILL_OBJECT_IS_NULL); } /* @@ -130,10 +114,10 @@ HWTEST_F(AutoFillManagerTest, HandleRequestExecuteInner_0100, TestSize.Level1) const AbilityRuntime::AutoFill::AutoFillRequest autoFillRequest; const std::shared_ptr fillCallback = nullptr; const std::shared_ptr saveCallback = nullptr; - bool isPopup = false; - int32_t result = - manager.HandleRequestExecuteInner(GetUIContent(), autoFillRequest, fillCallback, saveCallback, isPopup); - EXPECT_EQ(result, AbilityRuntime::AutoFill::AUTO_FILL_OBJECT_IS_NULL); + AbilityRuntime::AutoFill::AutoFillResult result; + int32_t ret = + manager.HandleRequestExecuteInner(GetUIContent(), autoFillRequest, fillCallback, saveCallback, result); + EXPECT_EQ(ret, AbilityRuntime::AutoFill::AUTO_FILL_OBJECT_IS_NULL); } /* @@ -148,12 +132,8 @@ HWTEST_F(AutoFillManagerTest, SetTimeOutEvent_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AutoFillManagerTest, SetTimeOutEvent_0100, TestSize.Level1"; auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); - EXPECT_EQ(manager.eventHandler_, nullptr); manager.SetTimeOutEvent(EVENT_ID); EXPECT_NE(manager.eventHandler_, nullptr); - if (manager.eventHandler_ != nullptr) { - manager.eventHandler_.reset(); - } } /* @@ -168,14 +148,10 @@ HWTEST_F(AutoFillManagerTest, RemoveEvent_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AutoFillManagerTest, SetTimeOutEvent_0100, TestSize.Level1"; auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); - EXPECT_EQ(manager.eventHandler_, nullptr); manager.SetTimeOutEvent(EVENT_ID); EXPECT_NE(manager.eventHandler_, nullptr); manager.RemoveEvent(EVENT_ID); EXPECT_NE(manager.eventHandler_, nullptr); - if (manager.eventHandler_ != nullptr) { - manager.eventHandler_.reset(); - } } /* @@ -190,9 +166,8 @@ HWTEST_F(AutoFillManagerTest, RemoveEvent_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AutoFillManagerTest, RemoveEvent_0200, TestSize.Level1"; auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); - EXPECT_EQ(manager.eventHandler_, nullptr); manager.RemoveEvent(EVENT_ID); - EXPECT_EQ(manager.eventHandler_, nullptr); + EXPECT_NE(manager.eventHandler_, nullptr); } /* @@ -207,76 +182,9 @@ HWTEST_F(AutoFillManagerTest, UpdateCustomPopupUIExtension_0100, TestSize.Level1 { GTEST_LOG_(INFO) << "AutoFillManagerTest, UpdateCustomPopupUIExtension_0100, TestSize.Level1"; auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); - EXPECT_EQ(manager.modalUIExtensionProxyMap_.size(), 0); - auto modalUIExtensionProxy = std::make_shared(); - auto uiContent = Ace::UIContent::Create(nullptr, nullptr); - manager.modalUIExtensionProxyMap_.emplace(uiContent->GetInstanceId(), modalUIExtensionProxy); + EXPECT_EQ(manager.extensionCallbacks_.size(), 0); const AbilityBase::ViewData viewdata; - EXPECT_CALL(*modalUIExtensionProxy, SendData(_)).Times(1); - manager.UpdateCustomPopupUIExtension(uiContent.get(), viewdata); - manager.modalUIExtensionProxyMap_.clear(); -} - -/* - * Feature: AutoFillManager - * Function: UpdateCustomPopupConfig - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: Verify if the UpdateCustomPopupConfig is valid. - */ -HWTEST_F(AutoFillManagerTest, UpdateCustomPopupConfig_0100, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "AutoFillManagerTest, UpdateCustomPopupConfig_0100, TestSize.Level1"; - auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); - Ace::CustomPopupUIExtensionConfig customPopupUIExtensionConfig; - int32_t result = manager.UpdateCustomPopupConfig(-1, customPopupUIExtensionConfig); - EXPECT_EQ(result, AbilityRuntime::AutoFill::AUTO_FILL_OBJECT_IS_NULL); - - auto uiContent = Ace::UIContent::Create(nullptr, nullptr); - result = manager.UpdateCustomPopupConfig(uiContent->GetInstanceId(), customPopupUIExtensionConfig); - EXPECT_EQ(result, AbilityRuntime::AutoFill::AUTO_FILL_SUCCESS); -} - -/* - * Feature: AutoFillManager - * Function: SetAutoFillExtensionProxy - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: Verify if the SetAutoFillExtensionProxy is valid. - */ -HWTEST_F(AutoFillManagerTest, SetAutoFillExtensionProxy_0100, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "AutoFillManagerTest, SetAutoFillExtensionProxy_0100, TestSize.Level1"; - auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); - EXPECT_EQ(manager.modalUIExtensionProxyMap_.size(), 0); - auto modalUIExtensionProxy = std::make_shared(); - auto uiContent = Ace::UIContent::Create(nullptr, nullptr); - manager.SetAutoFillExtensionProxy(uiContent->GetInstanceId(), modalUIExtensionProxy); - EXPECT_EQ(manager.modalUIExtensionProxyMap_.size(), 1); - manager.modalUIExtensionProxyMap_.clear(); -} - -/* - * Feature: AutoFillManager - * Function: RemoveAutoFillExtensionProxy - * SubFunction: NA - * FunctionPoints: NA - * EnvConditions: NA - * CaseDescription: Verify if the RemoveAutoFillExtensionProxy is valid. - */ -HWTEST_F(AutoFillManagerTest, RemoveAutoFillExtensionProxy_0100, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "AutoFillManagerTest, RemoveAutoFillExtensionProxy_0100, TestSize.Level1"; - auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); - EXPECT_EQ(manager.modalUIExtensionProxyMap_.size(), 0); - auto modalUIExtensionProxy = std::make_shared(); - auto uiContent = Ace::UIContent::Create(nullptr, nullptr); - manager.modalUIExtensionProxyMap_.emplace(uiContent->GetInstanceId(), modalUIExtensionProxy); - manager.RemoveAutoFillExtensionProxy(uiContent->GetInstanceId()); - EXPECT_EQ(manager.modalUIExtensionProxyMap_.size(), 0); - manager.modalUIExtensionProxyMap_.clear(); + manager.UpdateCustomPopupUIExtension(1, viewdata); } /* @@ -293,9 +201,8 @@ HWTEST_F(AutoFillManagerTest, HandleTimeOut_0100, TestSize.Level1) auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); EXPECT_EQ(manager.extensionCallbacks_.size(), 0); auto extensionCallback = std::make_shared(); - uint32_t eventId = 0; - manager.extensionCallbacks_.emplace(eventId, extensionCallback); - manager.HandleTimeOut(eventId); + manager.extensionCallbacks_.emplace(extensionCallback->GetCallbackId(), extensionCallback); + manager.HandleTimeOut(extensionCallback->GetCallbackId()); EXPECT_EQ(manager.extensionCallbacks_.size(), 0); manager.extensionCallbacks_.clear(); } @@ -328,5 +235,75 @@ HWTEST_F(AutoFillManagerTest, ConvertAutoFillWindowType_0100, TestSize.Level1) EXPECT_EQ(isSmartAutoFill, true); EXPECT_EQ(autoFillWindowType, AbilityRuntime::AutoFill::AutoFillWindowType::MODAL_WINDOW); } + +/* + * Feature: AutoFillManager + * Function: IsNeedToCreatePopupWindow + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: pull up the windowType and extension types. + */ +HWTEST_F(AutoFillManagerTest, IsNeedToCreatePopupWindow_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AutoFillManagerTest, IsNeedToCreatePopupWindow_0100, TestSize.Level1"; + auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); + bool isPopupAutoFill = false; + + isPopupAutoFill = manager.IsNeedToCreatePopupWindow(AbilityBase::AutoFillType::PERSON_FULL_NAME); + EXPECT_EQ(isPopupAutoFill, true); +} + +/* + * Feature: AutoFillManager + * Function: CloseUIExtension + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: test when extensionCallback is not nullptr. + */ +HWTEST_F(AutoFillManagerTest, CloseUIExtension_0100, TestSize.Level1) +{ + auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); + EXPECT_EQ(manager.extensionCallbacks_.size(), 0); + uint32_t autoFillSessionId = 0; + auto extensionCallback = std::make_shared(); + manager.extensionCallbacks_.emplace(autoFillSessionId, extensionCallback); + manager.CloseUIExtension(autoFillSessionId); + manager.extensionCallbacks_.clear(); +} + +/* + * Feature: AutoFillManager + * Function: CloseUIExtension + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: test when extensionCallback is nullptr. + */ +HWTEST_F(AutoFillManagerTest, CloseUIExtension_0200, TestSize.Level1) +{ + auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); + EXPECT_EQ(manager.extensionCallbacks_.size(), 0); + uint32_t autoFillSessionId = 0; + manager.CloseUIExtension(autoFillSessionId); +} + +/* + * Feature: AutoFillManager + * Function: BindModalUIExtensionCallback + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: test BindModalUIExtensionCallback. + */ +HWTEST_F(AutoFillManagerTest, BindModalUIExtensionCallback_0100, TestSize.Level1) +{ + std::shared_ptr extensionCallback; + Ace::ModalUIExtensionCallbacks callback; + auto &manager = AbilityRuntime::AutoFillManager::GetInstance(); + EXPECT_EQ(manager.extensionCallbacks_.size(), 0); + manager.BindModalUIExtensionCallback(extensionCallback, callback); +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/auto_startup_callback_proxy_test/auto_startup_callback_proxy_test.cpp b/test/unittest/auto_startup_callback_proxy_test/auto_startup_callback_proxy_test.cpp index 577bfc7205..e893989217 100644 --- a/test/unittest/auto_startup_callback_proxy_test/auto_startup_callback_proxy_test.cpp +++ b/test/unittest/auto_startup_callback_proxy_test/auto_startup_callback_proxy_test.cpp @@ -20,7 +20,6 @@ #undef private #include "ability_manager_errors.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/test/unittest/auto_startup_callback_stub_test/auto_startup_callback_stub_test.cpp b/test/unittest/auto_startup_callback_stub_test/auto_startup_callback_stub_test.cpp index 0b67d38aa0..1faef8449a 100644 --- a/test/unittest/auto_startup_callback_stub_test/auto_startup_callback_stub_test.cpp +++ b/test/unittest/auto_startup_callback_stub_test/auto_startup_callback_stub_test.cpp @@ -18,7 +18,6 @@ #include "ability_manager_ipc_interface_code.h" #include "auto_startup_info.h" #include "event_handler.h" -#include "hilog_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" #define private public diff --git a/test/unittest/auto_startup_info_test/auto_startup_info_test.cpp b/test/unittest/auto_startup_info_test/auto_startup_info_test.cpp index 4689e0e3c6..1538d83a63 100644 --- a/test/unittest/auto_startup_info_test/auto_startup_info_test.cpp +++ b/test/unittest/auto_startup_info_test/auto_startup_info_test.cpp @@ -21,7 +21,6 @@ #undef private #undef protected -#include "hilog_wrapper.h" #include "string_ex.h" #include "types.h" 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 192921f910..1dfb8464fa 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 @@ -232,7 +232,9 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_ImplicitQueryInfos_001, TestSi bool withDefault = false; std::vector abilityInfos; std::vector extensionInfos; - auto ret = bundleMgrHelper->ImplicitQueryInfos(want, flags, userId, withDefault, abilityInfos, extensionInfos); + bool findDefaultApp = false; + auto ret = bundleMgrHelper->ImplicitQueryInfos(want, flags, userId, withDefault, abilityInfos, extensionInfos, + findDefaultApp); EXPECT_EQ(ret, false); } @@ -263,20 +265,6 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_QueryDataGroupInfos_001, TestS EXPECT_EQ(ret, false); } -/** - * @tc.name: BundleMgrHelperTest_GetBundleGidsByUid_001 - * @tc.desc: GetBundleGidsByUid - * @tc.type: FUNC - */ -HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetBundleGidsByUid_001, TestSize.Level1) -{ - std::string bundleName; - int32_t uid = DEFAULT_USERID; - std::vector gids; - auto ret = bundleMgrHelper->GetBundleGidsByUid(bundleName, uid, gids); - EXPECT_EQ(ret, true); -} - /** * @tc.name: BundleMgrHelperTest_RegisterBundleEventCallback_001 * @tc.desc: RegisterBundleEventCallback 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 80b09876a9..d131fa2ac4 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 @@ -266,7 +266,7 @@ HWTEST_F(CacheProcessManagerTest, CacheProcessManager_IsAppSupportProcessCache_0 // different supportState auto appRecord3 = MockAppRecord(12); EXPECT_NE(appRecord3, nullptr); - EXPECT_EQ(cacheProcMgr->IsAppSupportProcessCache(appRecord3), true); + EXPECT_EQ(cacheProcMgr->IsAppSupportProcessCache(appRecord3), false); appRecord3->SetSupportedProcessCache(true); EXPECT_EQ(cacheProcMgr->IsAppSupportProcessCache(appRecord3), true); appRecord3->procCacheSupportState_ = SupportProcessCacheState::NOT_SUPPORT; @@ -474,5 +474,38 @@ HWTEST_F(CacheProcessManagerTest, CacheProcessManager_RemoveFromApplicationSet_0 cacheProcMgr->RemoveFromApplicationSet(appRecord1); EXPECT_TRUE(cacheProcMgr->sameAppSet.find(DEFAULT_BUNDLE_NAME) == cacheProcMgr->sameAppSet.end()); } + +/** + * @tc.name: CacheProcessManager_RemoveFromApplicationSet_0100 + * @tc.desc: Test the state of RemoveFromApplicationSet + * @tc.type: FUNC + */ +HWTEST_F(CacheProcessManagerTest, CacheProcessManager_IsAppContainsSrvExt_0100, TestSize.Level1) +{ + auto cacheProcMgr = std::make_shared(); + EXPECT_NE(cacheProcMgr, nullptr); + cacheProcMgr->maxProcCacheNum_ = 2; + + auto abilityInfo = std::make_shared(); + abilityInfo->name = "test_ability_name1"; + auto appInfo = std::make_shared(); + appInfo->name = "test_app_name1"; + std::string processName = "com.ohos.test.helloworld"; + auto appRunningRecord = std::make_shared(appInfo, AppRecordId::Create(), processName); + EXPECT_TRUE(appRunningRecord != nullptr); + sptr token = new MockAbilityToken(); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = "module789"; + abilityInfo->type = AppExecFwk::AbilityType::EXTENSION; + abilityInfo->extensionAbilityType = AppExecFwk::ExtensionAbilityType::SERVICE; + hapModuleInfo.abilityInfos.push_back(*abilityInfo); + appRunningRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, nullptr, 0); + auto moduleRecord = appRunningRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName); + EXPECT_TRUE(moduleRecord != nullptr); + auto abilityRunningRecord = moduleRecord->GetAbilityRunningRecordByToken(token); + EXPECT_TRUE(abilityRunningRecord != nullptr); + + EXPECT_EQ(cacheProcMgr->IsAppContainsSrvExt(appRunningRecord), true); +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/call_container_test/BUILD.gn b/test/unittest/call_container_test/BUILD.gn index f41a49ffb8..e83238c0a0 100644 --- a/test/unittest/call_container_test/BUILD.gn +++ b/test/unittest/call_container_test/BUILD.gn @@ -45,6 +45,7 @@ ohos_unittest("call_container_test") { "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock", "//third_party/googletest:gmock_main", diff --git a/test/unittest/call_container_test/call_container_test.cpp b/test/unittest/call_container_test/call_container_test.cpp index df0794abb3..e8c4f232a1 100644 --- a/test/unittest/call_container_test/call_container_test.cpp +++ b/test/unittest/call_container_test/call_container_test.cpp @@ -19,6 +19,7 @@ #include "call_container.h" #include "ability_record.h" #include "ability_manager_service.h" +#include "mission_list_manager.h" #undef private #undef protected #include "ability_scheduler_mock.h" 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 da364c8298..ca5c502049 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 @@ -26,7 +26,6 @@ #include "sys_mgr_client.h" #include "system_ability_definition.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing; using namespace testing::ext; @@ -153,7 +152,24 @@ HWTEST_F(ChildProcessManagerTest, GetHapModuleInfo_0100, TestSize.Level0) EXPECT_TRUE(ret); AppExecFwk::HapModuleInfo hapModuleInfo; - ret = ChildProcessManager::GetInstance().GetHapModuleInfo(bundleInfo, hapModuleInfo); + ret = ChildProcessManager::GetInstance().GetHapModuleInfo(bundleInfo, "entry", hapModuleInfo); + EXPECT_TRUE(ret); +} + +/** + * @tc.number: GetEntryHapModuleInfo_0100 + * @tc.desc: Test GetEntryHapModuleInfo works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessManagerTest, GetEntryHapModuleInfo_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "GetEntryHapModuleInfo_0100 called."); + AppExecFwk::BundleInfo bundleInfo; + auto ret = ChildProcessManager::GetInstance().GetBundleInfo(bundleInfo); + EXPECT_TRUE(ret); + + AppExecFwk::HapModuleInfo hapModuleInfo; + ret = ChildProcessManager::GetInstance().GetEntryHapModuleInfo(bundleInfo, hapModuleInfo); EXPECT_TRUE(ret); } @@ -172,7 +188,7 @@ HWTEST_F(ChildProcessManagerTest, CreateRuntime_0100, TestSize.Level0) EXPECT_TRUE(ret); AppExecFwk::HapModuleInfo hapModuleInfo; - ret = ChildProcessManager::GetInstance().GetHapModuleInfo(bundleInfo, hapModuleInfo); + ret = ChildProcessManager::GetInstance().GetEntryHapModuleInfo(bundleInfo, hapModuleInfo); EXPECT_TRUE(ret); auto runtime = ChildProcessManager::GetInstance().CreateRuntime(bundleInfo, hapModuleInfo, false, false); @@ -218,6 +234,21 @@ HWTEST_F(ChildProcessManagerTest, LoadJsFile_0100, TestSize.Level0) EXPECT_TRUE(ret); } +/** + * @tc.number: LoadJsFile_0200 + * @tc.desc: Test LoadJsFile works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessManagerTest, LoadJsFile_0200, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "LoadJsFile_0200 called."); + std::unique_ptr runtime; + AppExecFwk::HapModuleInfo hapModuleInfo; + auto args = std::make_shared(); + auto ret = ChildProcessManager::GetInstance().LoadJsFile("./ets/process/AProcess.ts", hapModuleInfo, runtime, args); + EXPECT_TRUE(ret); +} + /** * @tc.number: SetForkProcessDebugOption_0100 * @tc.desc: Test SetForkProcessDebugOption. @@ -244,5 +275,72 @@ HWTEST_F(ChildProcessManagerTest, StartNativeChildProcessByAppSpawnFork_0100, Te EXPECT_NE(ret, ChildProcessManagerErrorCode::ERR_FORK_FAILED); } +/** + * @tc.number: GetModuleNameFromSrcEntry_0100 + * @tc.desc: Test GetModuleNameFromSrcEntry works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessManagerTest, GetModuleNameFromSrcEntry_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "GetModuleNameFromSrcEntry_0100 called."); + std::string srcEntry = "entry/./ets/process/AProcess.ts"; + auto moduleName = ChildProcessManager::GetInstance().GetModuleNameFromSrcEntry(srcEntry); + EXPECT_EQ(moduleName, "entry"); +} + +/** + * @tc.number: GetModuleNameFromSrcEntry_0200 + * @tc.desc: Test GetModuleNameFromSrcEntry works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessManagerTest, GetModuleNameFromSrcEntry_0200, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "GetModuleNameFromSrcEntry_0200 called."); + std::string srcEntry = "AProcess.ts"; + auto moduleName = ChildProcessManager::GetInstance().GetModuleNameFromSrcEntry(srcEntry); + EXPECT_EQ(moduleName, ""); +} + +/** + * @tc.number: GetModuleNameFromSrcEntry_0300 + * @tc.desc: Test GetModuleNameFromSrcEntry works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessManagerTest, GetModuleNameFromSrcEntry_0300, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "GetModuleNameFromSrcEntry_0300 called."); + std::string srcEntry = "./ets/process/AProcess.ts"; + auto moduleName = ChildProcessManager::GetInstance().GetModuleNameFromSrcEntry(srcEntry); + EXPECT_EQ(moduleName, ""); +} + +/** + * @tc.number: SetAppSpawnForkDebugOption_0100 + * @tc.desc: Test SetAppSpawnForkDebugOption works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessManagerTest, SetAppSpawnForkDebugOption_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "SetAppSpawnForkDebugOption_0100 called."); + Runtime::DebugOption debugOption; + ChildProcessManager::GetInstance().SetAppSpawnForkDebugOption(debugOption, nullptr); + EXPECT_EQ(debugOption.processName, ""); +} + +/** + * @tc.number: SetAppSpawnForkDebugOption_0200 + * @tc.desc: Test SetAppSpawnForkDebugOption works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessManagerTest, SetAppSpawnForkDebugOption_0200, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "SetAppSpawnForkDebugOption_0200 called."); + Runtime::DebugOption debugOption; + auto processInfo = std::make_shared(); + auto processName = "com.test.abc"; + processInfo->processName = processName; + ChildProcessManager::GetInstance().SetAppSpawnForkDebugOption(debugOption, processInfo); + EXPECT_EQ(debugOption.processName, processName); +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/child_process_manager_test/child_process_test.cpp b/test/unittest/child_process_manager_test/child_process_test.cpp index 259f8b6e64..55993cf7e0 100644 --- a/test/unittest/child_process_manager_test/child_process_test.cpp +++ b/test/unittest/child_process_manager_test/child_process_test.cpp @@ -17,7 +17,6 @@ #include "child_process.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "runtime.h" using namespace testing; diff --git a/test/unittest/child_process_manager_test/js_child_process_test.cpp b/test/unittest/child_process_manager_test/js_child_process_test.cpp index b229760c48..958cb9eb29 100644 --- a/test/unittest/child_process_manager_test/js_child_process_test.cpp +++ b/test/unittest/child_process_manager_test/js_child_process_test.cpp @@ -19,7 +19,6 @@ #include "js_child_process.h" #undef protected #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" using namespace testing; @@ -74,7 +73,7 @@ HWTEST_F(JsChildProcessTest, JsChildProcessInit_0100, TestSize.Level0) std::shared_ptr info = std::make_shared(); info->name = "AProcess"; - info->srcEntry = "./ets/process/AProcess.ts"; + info->srcEntry = "entry/./ets/process/AProcess.ts"; info->moduleName = "entry"; process->Init(info); @@ -132,12 +131,35 @@ HWTEST_F(JsChildProcessTest, JsChildProcessOnStart_0100, TestSize.Level0) std::shared_ptr info = std::make_shared(); info->name = "AProcess"; - info->srcEntry = "./ets/process/AProcess.ts"; + info->srcEntry = "entry/./ets/process/AProcess.ts"; info->moduleName = "entry"; process->Init(info); process->OnStart(); EXPECT_TRUE(process->processStartInfo_ != nullptr); } + +/** + * @tc.number: JsChildProcessOnStart_0200 + * @tc.desc: Test JsChildProcess OnStart works + * @tc.type: FUNC + */ +HWTEST_F(JsChildProcessTest, JsChildProcessOnStart_0200, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "JsChildProcessOnStart_0200 called."); + std::unique_ptr runtime = std::make_unique(); + auto process = JsChildProcess::Create(runtime); + EXPECT_TRUE(process != nullptr); + + std::shared_ptr info = std::make_shared(); + info->name = "AProcess"; + info->srcEntry = "entry/./ets/process/AProcess.ts"; + info->moduleName = "entry"; + + process->Init(info); + auto args = std::make_shared(); + process->OnStart(args); + EXPECT_TRUE(process->processStartInfo_ != nullptr); +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/cj_ability_connect_callback_object_test/BUILD.gn b/test/unittest/cj_ability_connect_callback_object_test/BUILD.gn new file mode 100644 index 0000000000..c2534e9853 --- /dev/null +++ b/test/unittest/cj_ability_connect_callback_object_test/BUILD.gn @@ -0,0 +1,70 @@ +# 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") + +ohos_unittest("cj_ability_connect_callback_object_test") { + module_out_path = "ability_runtime/cj_ability_connect_callback_object_test" + + include_dirs = [ + "${ability_runtime_path}/frameworks/cj/ffi", + "${ability_runtime_path}/interfaces/kits/native/ability/native/ability_runtime", + "${ability_base_path}/interfaces/kits/native/want/include", + "${ability_runtime_services_path}/common/include", + "${ability_runtime_path}/interfaces/kits/native/ability/ability_runtime", + "${ability_runtime_path}/interfaces/inner_api/ability_manager/include", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ + "${ability_runtime_path}/frameworks/native/ability/native/ability_runtime/cj_ability_connect_callback_object.cpp", + "cj_ability_connect_callback_object_test.cpp", + ] + + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_innerkits_path}/runtime:runtime", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "hilog:libhilog", + "init:libbeget_proxy", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "napi:cj_bind_native", + "relational_store:native_appdatafwk", + "relational_store:native_dataability", + "relational_store:native_rdb", + ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_ability_connect_callback_object_test" ] +} diff --git a/test/unittest/cj_ability_connect_callback_object_test/cj_ability_connect_callback_object_test.cpp b/test/unittest/cj_ability_connect_callback_object_test/cj_ability_connect_callback_object_test.cpp new file mode 100644 index 0000000000..c05750c1bb --- /dev/null +++ b/test/unittest/cj_ability_connect_callback_object_test/cj_ability_connect_callback_object_test.cpp @@ -0,0 +1,101 @@ +/* + * 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 "cj_ability_connect_callback_object.h" +#include "mock_ability_connect_callback_stub.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AAFwk; + +namespace OHOS { +namespace AbilityRuntime { +class CjAbilityConnectCallbackProxyTest : public testing::Test { +public: + CjAbilityConnectCallbackProxyTest() + {} + ~CjAbilityConnectCallbackProxyTest() + {} + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; + + std::shared_ptr proxy_{nullptr}; +}; + +int g_cjRet = 0; +void (*g_registerFunc)(CJAbilityConnectCallbackFuncs *result) = [](CJAbilityConnectCallbackFuncs *result) { + if (result != nullptr) { + g_cjRet += 1; + } + result->onConnect = + [](int64_t id, ElementNameHandle elementNameHandle, int64_t remoteObjectId, int32_t resultCode) {}; + result->onDisconnect = [](int64_t id, ElementNameHandle elementNameHandle, int32_t resultCode) {}; + result->release = [](int64_t id) { id++; }; +}; + +void CjAbilityConnectCallbackProxyTest::SetUpTestCase() +{} + +void CjAbilityConnectCallbackProxyTest::TearDownTestCase() +{} + +void CjAbilityConnectCallbackProxyTest::SetUp() +{} + +void CjAbilityConnectCallbackProxyTest::TearDown() +{} + +HWTEST_F(CjAbilityConnectCallbackProxyTest, OnAbilityConnectDone_0100, TestSize.Level1) +{ + sptr mockAbilityConnectStub(new MockAbilityConnectCallback()); + sptr callback(new CJAbilityConnectCallback(0)); + AppExecFwk::ElementName element; + EXPECT_CALL(*mockAbilityConnectStub, OnAbilityConnectDone(_, _, _)).Times(0); + callback->OnAbilityConnectDone(element, mockAbilityConnectStub, 0); + mockAbilityConnectStub->Wait(); +} + +HWTEST_F(CjAbilityConnectCallbackProxyTest, OnAbilityDisconnectDone_0100, TestSize.Level1) +{ + sptr mockAbilityConnectStub(new MockAbilityConnectCallback()); + sptr callback(new CJAbilityConnectCallback(0)); + AppExecFwk::ElementName element; + EXPECT_CALL(*mockAbilityConnectStub, OnAbilityDisconnectDone(_, _)).Times(0); + callback->OnAbilityDisconnectDone(element, 0); + mockAbilityConnectStub->Wait(); +} + +HWTEST_F(CjAbilityConnectCallbackProxyTest, RegisterCJAbilityConnectCallbackFuncs_0100, TestSize.Level1) +{ + RegisterCJAbilityConnectCallbackFuncs(g_registerFunc); + EXPECT_EQ(g_cjRet, 1); + + RegisterCJAbilityConnectCallbackFuncs(g_registerFunc); + EXPECT_EQ(g_cjRet, 1); + + sptr remoteObject = nullptr; + sptr callback(new CJAbilityConnectCallback(0)); + AppExecFwk::ElementName element; + + callback->OnAbilityConnectDone(element, remoteObject, 0); + callback->OnAbilityDisconnectDone(element, 0); +} + +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/cj_ability_connect_callback_object_test/mock_ability_connect_callback_stub.h b/test/unittest/cj_ability_connect_callback_object_test/mock_ability_connect_callback_stub.h new file mode 100644 index 0000000000..563c1b50cb --- /dev/null +++ b/test/unittest/cj_ability_connect_callback_object_test/mock_ability_connect_callback_stub.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 UNITTEST_OHOS_ABILITY_RUNTIME_MOCK_ABILITY_CONNECT_CALLBACK_STUB_H +#define UNITTEST_OHOS_ABILITY_RUNTIME_MOCK_ABILITY_CONNECT_CALLBACK_STUB_H + +#include +#include "ability_connect_callback_stub.h" +#include "semaphore_ex.h" + +namespace OHOS { +namespace AAFwk { +class MockAbilityConnectCallback : public AbilityConnectionStub { +public: + MOCK_METHOD3(OnAbilityConnectDone, + void(const AppExecFwk::ElementName& element, const sptr& remoteObject, int resultCode)); + MOCK_METHOD2(OnAbilityDisconnectDone, void(const AppExecFwk::ElementName& element, int resultCode)); + + void Wait() + { + sem_.Wait(); + } + + int Post() + { + sem_.Post(); + return 0; + } + + void PostVoid() + { + sem_.Post(); + } + +private: + Semaphore sem_; +}; +} // namespace AAFwk +} // namespace OHOS + +#endif // UNITTEST_OHOS_ABILITY_RUNTIME_MOCK_ABILITY_CONNECT_CALLBACK_STUB_H diff --git a/test/unittest/cj_ability_context_object_test/BUILD.gn b/test/unittest/cj_ability_context_object_test/BUILD.gn new file mode 100644 index 0000000000..d968243d19 --- /dev/null +++ b/test/unittest/cj_ability_context_object_test/BUILD.gn @@ -0,0 +1,102 @@ +# 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") + +ohos_unittest("cj_ability_context_object_test") { + module_out_path = "ability_runtime/cj_ability_context_object_test" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/ability/native/ability_runtime", + "${ability_runtime_path}/frameworks/cj/ffi", + "${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", + "${ability_runtime_napi_path}/inner/napi_common", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ + "${ability_runtime_path}/frameworks/native/ability/native/ability_runtime/cj_ability_context_object.cpp", + "cj_ability_context_object_test.cpp", + ] + + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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}/dataobs_manager:dataobs_manager", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_innerkits_path}/napi_base_context:napi_base_context", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_innerkits_path}/wantagent:wantagent_innerkits", + "${ability_runtime_native_path}/ability:ability_context_native", + "${ability_runtime_native_path}/ability/native:ability_business_error", + "${ability_runtime_native_path}/appkit:app_context", + "${ability_runtime_native_path}/appkit:app_context_utils", + "${ability_runtime_native_path}/appkit:appkit_delegator", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_path}/frameworks/native/ability/native:continuation_ipc", + "${ability_runtime_path}/frameworks/native/ability/native:extension_blocklist_config", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_services_path}/common:app_util", + "${ability_runtime_services_path}/common:event_report", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "input:libmmi-client", + "ipc:ipc_core", + "ipc:ipc_napi", + "ipc:rpc", + "napi:ace_napi", + "napi:cj_bind_ffi", + "napi:cj_bind_native", + "relational_store:native_rdb", + "resource_management:global_resmgr", + "samgr:samgr_proxy", + "window_manager:libwsutils", + ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_ability_context_object_test" ] +} diff --git a/test/unittest/cj_ability_context_object_test/cj_ability_context_object_test.cpp b/test/unittest/cj_ability_context_object_test/cj_ability_context_object_test.cpp new file mode 100644 index 0000000000..a91b45e237 --- /dev/null +++ b/test/unittest/cj_ability_context_object_test/cj_ability_context_object_test.cpp @@ -0,0 +1,48 @@ +/* + * 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 "cj_ability_context_object.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AbilityRuntime { +class CjAbilityContextProxyTest : public testing::Test { +}; + +int g_result = 0; + +HWTEST_F(CjAbilityContextProxyTest, RegisterCJAbilityCallbacks_0100, TestSize.Level1) +{ + RegisterCJAbilityCallbacks(nullptr); + void (*registerFunc)(CJAbilityCallbacks*) = [](CJAbilityCallbacks* cjAbilityCallbacks) + { + if (cjAbilityCallbacks != nullptr) g_result += 1; + cjAbilityCallbacks->invokeAbilityResultCallback = [](int64_t id, int32_t error, + CJAbilityResult* cjAbilityResult) {}; + cjAbilityCallbacks->invokePermissionRequestResultCallback = + [](int64_t id, int32_t error, CJPermissionRequestResult* cjPermissionRequestResult) {}; + cjAbilityCallbacks->invokeDialogRequestResultCallback = [](int64_t id, int32_t error, + CJDialogRequestResult* cjDialogRequestResult) {}; + }; + RegisterCJAbilityCallbacks(registerFunc); + RegisterCJAbilityCallbacks(registerFunc); + EXPECT_EQ(g_result, 1); +} +} +} \ No newline at end of file diff --git a/test/unittest/cj_ability_delegator_test/BUILD.gn b/test/unittest/cj_ability_delegator_test/BUILD.gn new file mode 100644 index 0000000000..6a80d649b9 --- /dev/null +++ b/test/unittest/cj_ability_delegator_test/BUILD.gn @@ -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. + +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +ohos_unittest("cj_ability_delegator_test") { + module_out_path = "ability_runtime/cj_ability_delegator_test" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_delegator", + "${ability_runtime_path}/interfaces/kits/native/appkit/app", + "${bundlefwk_path}/interfaces/inner_api/appexecfwk_base/include", + "${ability_runtime_path}/interfaces/inner_api/ability_manager/include", + "${common_event_service_path}/interfaces/inner_api", + "${ability_runtime_path}/interfaces/inner_api/app_manager/include/appmgr", + "${ability_base_path}/interfaces/kits/native/session_info/include", + "${arkui_path}/ace_engine", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/frameworks/cj/ffi", + "${ace_engine_path}/frameworks", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ + "${ability_runtime_path}/frameworks/cj/ffi/cj_ability_delegator.cpp", + "cj_ability_delegator_test.cpp", + ] + + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/ability_manager:mission_info", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/ability:ability_context_native", + "${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:appkit_delegator", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_path}/frameworks/cj/ffi:cj_ability_ffi", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "${global_path}/resource_management/frameworks/resmgr:global_resmgr", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:session_info", + "ability_base:want", + "ability_runtime:ability_context_native", + "ability_runtime:runtime", + "ability_runtime:wantagent_innerkits", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "napi:cj_bind_native", + "window_manager:libwsutils", + "window_manager:scene_session", + ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_ability_delegator_test" ] +} diff --git a/test/unittest/cj_ability_delegator_test/cj_ability_delegator_test.cpp b/test/unittest/cj_ability_delegator_test/cj_ability_delegator_test.cpp new file mode 100644 index 0000000000..9a215b1980 --- /dev/null +++ b/test/unittest/cj_ability_delegator_test/cj_ability_delegator_test.cpp @@ -0,0 +1,299 @@ +/* + * 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 "gtest/gtest.h" +#include "cj_ability_delegator.h" +#include "ability_delegator_registry.h" +#include "cj_application_context.h" +#include "application_context.h" +#include "runner_runtime/cj_test_runner.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::FFI; +using namespace OHOS::AbilityRuntime; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +using namespace OHOS::RunnerRuntime; + +namespace OHOS { +namespace AbilityDelegatorCJ { +namespace { +const std::string KEY_TEST_BUNDLE_NAME = "-p"; +const std::string VALUE_TEST_BUNDLE_NAME = "com.example.myapplication"; +const std::string CHANGE_VALUE_TEST_BUNDLE_NAME = "com.example.myapplication1"; +const std::string KEY_TEST_RUNNER_CLASS = "-s unittest"; +const std::string VALUE_TEST_RUNNER_CLASS = "JSUserTestRunner"; +const std::string CHANGE_VALUE_TEST_RUNNER_CLASS = "JSUserTestRunner1"; +const std::string KEY_TEST_CASE = "-s class"; +const std::string VALUE_TEST_CASE = "ohos.acts.aafwk.ability.test.ConstructorTest#testDataAbilityOtherFunction0010"; +const std::string CHANGE_VALUE_TEST_CASE = + "ohos.acts.aafwk.ability.test.ConstructorTest#testDataAbilityOtherFunction00101"; +const std::string KEY_TEST_WAIT_TIMEOUT = "-w"; +const std::string VALUE_TEST_WAIT_TIMEOUT = "50"; +const std::string CHANGE_VALUE_TEST_WAIT_TIMEOUT = "80"; +const std::string SET_VALUE_TEST_BUNDLE_NAME = "com.example.myapplicationset"; +const std::string ABILITY_NAME = "com.example.myapplication.MainAbility"; +const std::string FINISH_MSG = "finish message"; +const int32_t FINISH_RESULT_CODE = 144; +const std::string PRINT_MSG = "print aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const int ZERO = 0; +const int ONE = 1; +const int TWO = 2; +const int64_t TIMEOUT = 50; +const std::string CMD = "ls -l"; +const std::string KEY_TEST_DEBUG {"-D"}; +const std::string VALUE_TEST_DEBUG {"true"}; +const std::string ABILITY_STAGE_MONITOR_MODULE_NAME {"entry"}; +const std::string ABILITY_STAGE_MONITOR_SRC_ENTRANCE {"MainAbility"}; +} // namespace + +class CjAbilityDelegatorTest : public testing::Test { +public: + CjAbilityDelegatorTest() + {} + ~CjAbilityDelegatorTest() + {} + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +protected: + static std::shared_ptr cjDelegator; + static std::shared_ptr commonDelegator_; + static std::shared_ptr delegatorArgs_; +}; + +std::shared_ptr CjAbilityDelegatorTest::cjDelegator = nullptr; +std::shared_ptr CjAbilityDelegatorTest::commonDelegator_ = nullptr; +std::shared_ptr CjAbilityDelegatorTest::delegatorArgs_ = nullptr; + +void CjAbilityDelegatorTest::SetUpTestCase() +{ + // Construct a common ability delegator firstly. + std::map paras; + paras.emplace(KEY_TEST_BUNDLE_NAME, VALUE_TEST_BUNDLE_NAME); + paras.emplace(KEY_TEST_RUNNER_CLASS, VALUE_TEST_RUNNER_CLASS); + paras.emplace(KEY_TEST_CASE, VALUE_TEST_CASE); + paras.emplace(KEY_TEST_WAIT_TIMEOUT, VALUE_TEST_WAIT_TIMEOUT); + paras.emplace(KEY_TEST_DEBUG, VALUE_TEST_DEBUG); + + Want want; + for (auto para : paras) { + want.SetParam(para.first, para.second); + } + + delegatorArgs_ = std::make_shared(want); + AbilityRuntime::Runtime::Options options; + BundleInfo bundleInfo; + auto testRunner = CJTestRunner::Create(AbilityRuntime::Runtime::Create(options), delegatorArgs_, bundleInfo); + commonDelegator_ = std::make_shared(std::make_shared(), + std::move(testRunner), nullptr); + + // 创建一个 CJAbilityDelegator 对象 + cjDelegator = std::make_shared(commonDelegator_); +} + +void CjAbilityDelegatorTest::TearDownTestCase() +{} + +void CjAbilityDelegatorTest::SetUp() +{} + +void CjAbilityDelegatorTest::TearDown() +{} + +/** + * @tc.name: CjAbilityDelegatorTestStartAbility_001 + * @tc.desc: CjAbilityDelegatorTest test for FFICJWantAddEntity. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, CjAbilityDelegatorTestStartAbility_001, TestSize.Level1) +{ + EXPECT_NE(commonDelegator_, nullptr); + AbilityDelegatorRegistry::RegisterInstance(commonDelegator_, delegatorArgs_); + + AAFwk::Want want; + want.SetElementName(VALUE_TEST_BUNDLE_NAME, ABILITY_NAME); + auto result = cjDelegator->StartAbility(want); +} + +/** + * @tc.name: CjAbilityDelegatorTestExecuteShellCommand_001 + * @tc.desc: CjAbilityDelegatorTest test for ExecuteShellCommand. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, CjAbilityDelegatorTestExecuteShellCommand_001, TestSize.Level1) +{ + const char* cmd = "ls"; + int64_t timeoutSec = 10; + auto shellCmdResult = cjDelegator->ExecuteShellCommand(cmd, timeoutSec); + EXPECT_EQ(shellCmdResult, nullptr); +} + +/** + * @tc.name: CjAbilityDelegatorTestGetAppContext_001 + * @tc.desc: CjAbilityDelegatorTest test for GetAppContext. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, CjAbilityDelegatorTestGetAppContext_001, TestSize.Level1) +{ + auto appContext = cjDelegator->GetAppContext(); + EXPECT_EQ(appContext, nullptr); +} + +/** + * @tc.name: CjAbilityDelegatorTestGetExitCode_001 + * @tc.desc: CjAbilityDelegatorTest test for GetExitCode. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, CjAbilityDelegatorTestGetExitCode_001, TestSize.Level1) +{ + auto shellResult = std::make_shared(); + CJShellCmdResult shellCmdResult(shellResult); + int32_t exitCode = shellCmdResult.GetExitCode(); + EXPECT_GE(exitCode, -1); +} + +/** + * @tc.name: CjAbilityDelegatorTestGetStdResult_001 + * @tc.desc: CjAbilityDelegatorTest test for GetStdResult. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, CjAbilityDelegatorTestGetStdResult_001, TestSize.Level1) +{ + auto shellResult = std::make_shared(); + CJShellCmdResult shellCmdResult(shellResult); + std::string stdResult = shellCmdResult.GetStdResult(); + EXPECT_TRUE(stdResult.empty()); +} + +/** + * @tc.name: CjAbilityDelegatorTestDump_001 + * @tc.desc: CjAbilityDelegatorTest test for Dump. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, CjAbilityDelegatorTestDump_001, TestSize.Level1) +{ + auto shellResult = std::make_shared(); + CJShellCmdResult shellCmdResult(shellResult); + shellCmdResult.Dump(); +} + +/** + * @tc.name: CJAbilityDelegatorTestFFIAbilityDelegatorRegistryGetAbilityDelegator_001 + * @tc.desc: CjAbilityDelegatorTest test for FFIAbilityDelegatorRegistryGetAbilityDelegator. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, + CJAbilityDelegatorTestFFIAbilityDelegatorRegistryGetAbilityDelegator_001, TestSize.Level1) +{ + FFIAbilityDelegatorRegistryGetAbilityDelegator(); +} + +/** + * @tc.name: CJAbilityDelegatorTestFFIAbilityDelegatorStartAbility_001 + * @tc.desc: CjAbilityDelegatorTest test for FFIAbilityDelegatorStartAbility. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, CJAbilityDelegatorTestFFIAbilityDelegatorStartAbility_001, TestSize.Level1) +{ + Want want; + WantHandle wantHandle = const_cast(&want); + auto delegator = OHOS::AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator(); + auto cjDelegator = FFI::FFIData::Create(delegator); + int64_t id = cjDelegator->GetID(); + int64_t ret = FFIAbilityDelegatorStartAbility(id, wantHandle); + EXPECT_NE(ret, 1); +} + +/** + * @tc.name: CJAbilityDelegatorTestFFIAbilityDelegatorExecuteShellCommand_001 + * @tc.desc: CjAbilityDelegatorTest test for FFIAbilityDelegatorExecuteShellCommand. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, CJAbilityDelegatorTestFFIAbilityDelegatorExecuteShellCommand_001, TestSize.Level1) +{ + const char* cmd = "test"; + int64_t timeoutSec = 1000; + auto delegator = OHOS::AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator(); + auto cjDelegator = FFI::FFIData::Create(delegator); + int64_t id = cjDelegator->GetID(); + FFIAbilityDelegatorExecuteShellCommand(id, cmd, timeoutSec); +} + +/** + * @tc.name: CJAbilityDelegatorTestFFIGetExitCode_001 + * @tc.desc: CjAbilityDelegatorTest test for FFIGetExitCode. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, CJAbilityDelegatorTestFFIGetExitCode_001, TestSize.Level1) +{ + int64_t timeoutSec = 1000; + const char* cmd = "ls"; + + auto shellResult = std::make_shared(); + auto cJShellCmdResult = FFI::FFIData::Create(shellResult); + int64_t id = cJShellCmdResult->GetID(); + FFIGetExitCode(id); +} + +/** + * @tc.name: CJAbilityDelegatorTestFFIGetStdResult_001 + * @tc.desc: CjAbilityDelegatorTest test for FFIGetStdResult. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, CJAbilityDelegatorTestFFIGetStdResult_001, TestSize.Level1) +{ + int64_t timeoutSec = 1000; + const char* cmd = "ls"; + auto shellResult = std::make_shared(); + auto cJShellCmdResult = FFI::FFIData::Create(shellResult); + int64_t id = cJShellCmdResult->GetID(); + FFIGetStdResult(id); +} + +/** + * @tc.name: CJAbilityDelegatorTestFFIDump_001 + * @tc.desc: CjAbilityDelegatorTest test for FFIDump. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, CJAbilityDelegatorTestFFIDump_001, TestSize.Level1) +{ + int64_t timeoutSec = 1000; + const char* cmd = "ls"; + auto shellResult = std::make_shared(); + auto cJShellCmdResult = FFI::FFIData::Create(shellResult); + int64_t id = cJShellCmdResult->GetID(); + FFIDump(id); +} + +/** + * @tc.name: CJAbilityDelegatorTestFFIAbilityDelegatorApplicationContext_001 + * @tc.desc: CjAbilityDelegatorTest test for FFIAbilityDelegatorApplicationContext. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityDelegatorTest, CJAbilityDelegatorTestFFIAbilityDelegatorApplicationContext_001, TestSize.Level1) +{ + auto delegator = OHOS::AppExecFwk::AbilityDelegatorRegistry::GetAbilityDelegator(); + auto cjDelegator = FFI::FFIData::Create(delegator); + int64_t id = cjDelegator->GetID(); + FFIAbilityDelegatorApplicationContext(id); +} + +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/cj_ability_ffi_mock_test/BUILD.gn b/test/unittest/cj_ability_ffi_mock_test/BUILD.gn new file mode 100644 index 0000000000..8335d216ef --- /dev/null +++ b/test/unittest/cj_ability_ffi_mock_test/BUILD.gn @@ -0,0 +1,90 @@ +# 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") + +ohos_unittest("cj_ability_ffi_mock_test") { + module_out_path = "ability_runtime/cj_ability_ffi_mock_test" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_delegator", + "${ability_runtime_path}/interfaces/kits/native/appkit/app", + "${bundlefwk_path}/interfaces/inner_api/appexecfwk_base/include", + "${ability_runtime_path}/interfaces/inner_api/ability_manager/include", + "${common_event_service_path}/interfaces/inner_api", + "${ability_runtime_path}/interfaces/inner_api/app_manager/include/appmgr", + "${ability_base_path}/interfaces/kits/native/session_info/include", + "${arkui_path}/ace_engine", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/frameworks/cj/ffi", + "${ability_runtime_path}/frameworks/cj/mock", + "${ace_engine_path}/frameworks", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ "cj_ability_ffi_mock_test.cpp" ] + + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/ability_manager:mission_info", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/ability:ability_context_native", + "${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:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "${global_path}/resource_management/frameworks/resmgr:global_resmgr", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:session_info", + "ability_base:want", + "ability_runtime:ability_context_native", + "ability_runtime:runtime", + "ability_runtime:wantagent_innerkits", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "napi:cj_bind_native", + "window_manager:libwsutils", + "window_manager:scene_session", + ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_ability_ffi_mock_test" ] +} diff --git a/test/unittest/cj_ability_ffi_mock_test/cj_ability_ffi_mock_test.cpp b/test/unittest/cj_ability_ffi_mock_test/cj_ability_ffi_mock_test.cpp new file mode 100644 index 0000000000..880992dee4 --- /dev/null +++ b/test/unittest/cj_ability_ffi_mock_test/cj_ability_ffi_mock_test.cpp @@ -0,0 +1,164 @@ +/* + * 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 "foundation/ability/ability_runtime/frameworks/cj/mock/cj_ability_ffi.cpp" +#include + +using namespace testing; +using namespace testing::ext; + +class CjAbilityFfiMockTest : public testing::Test { +public: + CjAbilityFfiMockTest() + {} + ~CjAbilityFfiMockTest() + {} + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; + +void CjAbilityFfiMockTest::SetUpTestCase() +{} + +void CjAbilityFfiMockTest::TearDownTestCase() +{} + +void CjAbilityFfiMockTest::SetUp() +{} + +void CjAbilityFfiMockTest::TearDown() +{} + +/** + * @tc.name: CjAbilityFfiMockTestGlobalVariables_0100 + * @tc.desc: CjAbilityFfiMockTest test for GlobalVariables. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityFfiMockTest, CjAbilityFfiMockTestGlobalVariables_0100, TestSize.Level1) +{ + EXPECT_NE(nullptr, FFICJWantDelete); + EXPECT_NE(nullptr, FFICJWantGetWantInfo); + EXPECT_NE(nullptr, FFICJWantParamsDelete); + EXPECT_NE(nullptr, FFICJWantCreateWithWantInfo); + EXPECT_NE(nullptr, FFICJWantParseUri); + EXPECT_NE(nullptr, FFICJWantAddEntity); + EXPECT_NE(nullptr, FFICJElementNameCreateWithContent); + EXPECT_NE(nullptr, FFICJElementNameDelete); + EXPECT_NE(nullptr, FFICJElementNameGetElementNameInfo); + EXPECT_NE(nullptr, FFICJElementNameParamsDelete); + EXPECT_NE(nullptr, FFIAbilityGetAbilityContext); + EXPECT_NE(nullptr, FFIAbilityContextGetFilesDir); + EXPECT_NE(nullptr, FFIGetContext); + EXPECT_NE(nullptr, FFICreateNapiValue); + EXPECT_NE(nullptr, FFIGetArea); + EXPECT_NE(nullptr, FFICJApplicationInfo); + EXPECT_NE(nullptr, FFIAbilityDelegatorRegistryGetAbilityDelegator); + EXPECT_NE(nullptr, FFIAbilityDelegatorStartAbility); + EXPECT_NE(nullptr, FFIAbilityDelegatorExecuteShellCommand); + EXPECT_NE(nullptr, FFIGetExitCode); + EXPECT_NE(nullptr, FFIGetStdResult); + EXPECT_NE(nullptr, FFIDump); + EXPECT_NE(nullptr, FFIAbilityDelegatorApplicationContext); +} + + +/** + * @tc.name: CjAbilityFfiMockTestGetBroker_0100 + * @tc.desc: CjAbilityFfiMockTest test for GetBroker. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityFfiMockTest, CjAbilityFfiMockTestGetBroker_0100, TestSize.Level1) +{ + AbilityContextBroker* broker = FFIAbilityContextGetBroker(); + EXPECT_NE(nullptr, broker); + EXPECT_EQ(1, broker->isAbilityContextExisted); + EXPECT_EQ(1, broker->getSizeOfStartOptions); + EXPECT_EQ(1, broker->getAbilityInfo); + EXPECT_EQ(1, broker->getHapModuleInfo); + EXPECT_EQ(1, broker->getConfiguration); + EXPECT_EQ(1, broker->startAbility); + EXPECT_EQ(1, broker->startAbilityWithOption); + EXPECT_EQ(1, broker->startAbilityWithAccount); + EXPECT_EQ(1, broker->startAbilityWithAccountAndOption); + EXPECT_EQ(1, broker->startServiceExtensionAbility); + EXPECT_EQ(1, broker->startServiceExtensionAbilityWithAccount); + EXPECT_EQ(1, broker->stopServiceExtensionAbility); + EXPECT_EQ(1, broker->stopServiceExtensionAbilityWithAccount); + EXPECT_EQ(1, broker->terminateSelf); + EXPECT_EQ(1, broker->terminateSelfWithResult); + EXPECT_EQ(1, broker->isTerminating); + EXPECT_EQ(1, broker->connectAbility); + EXPECT_EQ(1, broker->connectAbilityWithAccount); + EXPECT_EQ(1, broker->disconnectAbility); + EXPECT_EQ(1, broker->startAbilityForResult); + EXPECT_EQ(1, broker->startAbilityForResultWithOption); + EXPECT_EQ(1, broker->startAbilityForResultWithAccount); + EXPECT_EQ(1, broker->startAbilityForResultWithAccountAndOption); + EXPECT_EQ(1, broker->requestPermissionsFromUser); + EXPECT_EQ(1, broker->setMissionLabel); + EXPECT_EQ(1, broker->setMissionIcon); +} + +/** + * @tc.name: CjAbilityFfiMockTestRegisterCJAbilityStageFuncs_0100 + * @tc.desc: CjAbilityFfiMockTest test for RegisterCJAbilityStageFuncs. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityFfiMockTest, CjAbilityFfiMockTestRegisterCJAbilityStageFuncs_0100, TestSize.Level1) +{ + RegisterCJAbilityStageFuncs(); // 实际执行函数 +} + +/** + * @tc.name: CjAbilityFfiMockTestRegisterCJAbilityConnectCallbackFuncs_0100 + * @tc.desc: CjAbilityFfiMockTest test for RegisterCJAbilityConnectCallbackFuncs. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityFfiMockTest, CjAbilityFfiMockTestRegisterCJAbilityConnectCallbackFuncs_0100, TestSize.Level1) +{ + RegisterCJAbilityConnectCallbackFuncs(); +} + +/** + * @tc.name: CjAbilityFfiMockTestRegisterCJAbilityCallbacks_0100 + * @tc.desc: CjAbilityFfiMockTest test for RegisterCJAbilityCallbacks. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityFfiMockTest, CjAbilityFfiMockTestRegisterCJAbilityCallbacks_0100, TestSize.Level1) +{ + RegisterCJAbilityCallbacks(); +} + +/** + * @tc.name: CjAbilityFfiMockTestRegisterCJAbilityFuncs_0100 + * @tc.desc: CjAbilityFfiMockTest test for RegisterCJAbilityFuncs. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityFfiMockTest, CjAbilityFfiMockTestRegisterCJAbilityFuncs_0100, TestSize.Level1) +{ + RegisterCJAbilityFuncs(); +} + +/** + * @tc.name: CjAbilityFfiMockTestRequestDialogService_0100 + * @tc.desc: CjAbilityFfiMockTest test for FFIAbilityContextRequestDialogService. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityFfiMockTest, CjAbilityFfiMockTestRequestDialogService_0100, TestSize.Level1) +{ + FFIAbilityContextRequestDialogService(); +} \ No newline at end of file diff --git a/test/unittest/cj_ability_object_test/BUILD.gn b/test/unittest/cj_ability_object_test/BUILD.gn new file mode 100644 index 0000000000..3dd7ef763b --- /dev/null +++ b/test/unittest/cj_ability_object_test/BUILD.gn @@ -0,0 +1,82 @@ +# 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") + +ohos_unittest("cj_ability_object_test") { + module_out_path = "ability_runtime/cj_ability_object_test" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/ability/native/ability_runtime/", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime", + "${ability_base_kits_path}/configuration/include", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ "cj_ability_object_test.cpp" ] + + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_native_path}/ability:ability_context_native", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:continuation_ipc", + "${ability_runtime_native_path}/ability/native:insight_intent_executor", + "${ability_runtime_native_path}/ability/native:uiabilitykit_native", + "${ability_runtime_native_path}/appkit:app_context", + "${ability_runtime_native_path}/appkit:appkit_delegator", + "${ability_runtime_native_path}/insight_intent/insight_intent_context:insightintentcontext", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_services_path}/common:event_report", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:want", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ets_runtime:libark_jsruntime", + "eventhandler:libeventhandler", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "ipc:ipc_napi", + "napi:ace_napi", + "napi:cj_bind_native", + "resource_management:global_resmgr", + "window_manager:cj_window_ffi", + "window_manager:libwm", + "window_manager:libwsutils", + "window_manager:windowstage_kit", + ] + + defines = [ "CONFIG_HILOG" ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_ability_object_test" ] +} diff --git a/test/unittest/cj_ability_object_test/cj_ability_object_test.cpp b/test/unittest/cj_ability_object_test/cj_ability_object_test.cpp new file mode 100644 index 0000000000..5c15187172 --- /dev/null +++ b/test/unittest/cj_ability_object_test/cj_ability_object_test.cpp @@ -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. + */ + +#include + +#include "ability.h" +#include "cj_ability_object.h" +#include "cj_runtime.h" +#include "configuration.h" +#include "window_stage_impl.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AbilityRuntime; + +class CjAbilityObjectTest : public testing::Test { +}; + +void ProxyCall() +{ + CJAbilityObject::LoadModule("0"); + CJAbilityObject::LoadModule("1"); + Want want; + auto proxy = CJAbilityObject(0); + proxy.Init(nullptr); + proxy.OnStart(want, AAFwk::LaunchParam()); + auto win = std::make_shared(); + auto winStage = new Rosen::CJWindowStageImpl(win); + proxy.OnSceneCreated(winStage); + proxy.OnSceneRestored(winStage); + proxy.OnForeground(want); + proxy.OnBackground(); + auto config = std::make_shared(); + proxy.OnConfigurationUpdated(config); + proxy.OnNewWant(want, AAFwk::LaunchParam()); + std::vector params = {"123"}; + std::vector infos = {"123"}; + AAFwk::WantParams wantParams = AAFwk::WantParams(); + proxy.OnContinue(wantParams); + proxy.Dump(params, infos); + proxy.OnSceneDestroyed(); + proxy.OnStop(); +} + +HWTEST_F(CjAbilityObjectTest, CJAbilityObject001, TestSize.Level1) +{ + ProxyCall(); +} + +HWTEST_F(CjAbilityObjectTest, CJAbilityObject002, TestSize.Level1) +{ + auto registerFunc = [](CJAbilityFuncs* funcs) { + funcs->cjAbilityCreate = [](const char* name) -> int64_t { return name[0] == '0' ? 0 : 1; }; + funcs->cjAbilityRelease = [](int64_t id) {}; + funcs->cjAbilityOnStart = [](int64_t id, WantHandle want, CJLaunchParam launchParam) {}; + funcs->cjAbilityOnStop = [](int64_t id) {}; + funcs->cjAbilityOnSceneCreated = [](int64_t id, WindowStagePtr cjWindowStage) {}; + funcs->cjAbilityOnSceneRestored = [](int64_t id, WindowStagePtr cjWindowStage) {}; + funcs->cjAbilityOnSceneDestroyed = [](int64_t id) {}; + funcs->cjAbilityOnForeground = [](int64_t id, WantHandle want) {}; + funcs->cjAbilityOnBackground = [](int64_t id) {}; + funcs->cjAbilityOnConfigurationUpdated = [](int64_t id, CJConfiguration configuration) {}; + funcs->cjAbilityOnNewWant = [](int64_t id, WantHandle want, CJLaunchParam launchParam) {}; + funcs->cjAbilityDump = [](int64_t id, VectorStringHandle params) { return VectorStringHandle(); }; + funcs->cjAbilityOnContinue = [](int64_t id, const char* params) { return 0; }; + funcs->cjAbilityInit = [](int64_t id, void* ability) {}; + }; + RegisterCJAbilityFuncs(registerFunc); + ProxyCall(); + RegisterCJAbilityFuncs(nullptr); +} diff --git a/test/unittest/cj_ability_stage_object_test/BUILD.gn b/test/unittest/cj_ability_stage_object_test/BUILD.gn new file mode 100644 index 0000000000..d2b3754015 --- /dev/null +++ b/test/unittest/cj_ability_stage_object_test/BUILD.gn @@ -0,0 +1,95 @@ +# 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") + +ohos_unittest("cj_ability_stage_object_test") { + module_out_path = "ability_runtime/cj_ability_stage_object_test" + include_dirs = [ + "${ability_runtime_test_path}/mock/common/include", + "${resource_management_path}/frameworks/resmgr/include", + "${ability_base_kits_path}/configuration/include", + "${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/ability/native", + "${ability_runtime_path}/interfaces/inner_api/runtime/include", + "${ability_runtime_native_path}/runtime", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ + "${ability_runtime_native_path}/appkit/app/app_context.cpp", + "${ability_runtime_native_path}/appkit/app/app_loader.cpp", + "${ability_runtime_native_path}/appkit/app/application_cleaner.cpp", + "${ability_runtime_native_path}/appkit/app/ohos_application.cpp", + "${ability_runtime_path}/frameworks/native/appkit/ability_runtime/app/cj_ability_stage_object.cpp", + "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include/mock_bundle_manager.cpp", + "${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", + "cj_ability_stage_object_test.cpp", + ] + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + 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}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${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:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:want", + "ability_runtime:runtime", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "resource_management:global_resmgr", + ] + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } + + defines = [ "CONFIG_HILOG" ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_ability_stage_object_test" ] +} diff --git a/test/unittest/cj_ability_stage_object_test/cj_ability_stage_object_test.cpp b/test/unittest/cj_ability_stage_object_test/cj_ability_stage_object_test.cpp new file mode 100644 index 0000000000..d30c9d5005 --- /dev/null +++ b/test/unittest/cj_ability_stage_object_test/cj_ability_stage_object_test.cpp @@ -0,0 +1,101 @@ +/* + * 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 "cj_ability_stage_object.h" +#include "cj_runtime.h" +#include "hilog_wrapper.h" +#include "runtime.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AbilityRuntime { +class CjAbilityStageObjectTest : public testing::Test { +public: + CjAbilityStageObjectTest() + {} + ~CjAbilityStageObjectTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override; + void TearDown() override; +}; + +void CjAbilityStageObjectTest::SetUpTestCase(void) +{} + +void CjAbilityStageObjectTest::TearDownTestCase(void) +{} + +void CjAbilityStageObjectTest::SetUp(void) +{} + +void CjAbilityStageObjectTest::TearDown(void) +{} + +HWTEST_F(CjAbilityStageObjectTest, CjAbilityNoInit_001, TestSize.Level0) +{ + std::shared_ptr cjAbilityStageObject = CJAbilityStageObject::LoadModule("test"); + cjAbilityStageObject->OnCreate(); + + AAFwk::Want want; + cjAbilityStageObject->OnAcceptWant(want); + + std::shared_ptr configuration = std::make_shared(); + cjAbilityStageObject->OnConfigurationUpdated(configuration); + + int32_t level = 1; + cjAbilityStageObject->OnMemoryLevel(level); +} + +HWTEST_F(CjAbilityStageObjectTest, CjAbilityNoInit_002, TestSize.Level0) +{ + RegisterCJAbilityStageFuncs(nullptr); + auto registerFunc = [](CJAbilityStageFuncs *funcs) { + funcs->LoadAbilityStage = [](const char *moduleName) -> int64_t { return moduleName[0] == '0' ? 0 : 1; }; + funcs->ReleaseAbilityStage = [](int64_t handle) {}; + funcs->AbilityStageOnCreate = [](int64_t handle) {}; + funcs->AbilityStageOnAcceptWant = [](int64_t handle, OHOS::AAFwk::Want *want) -> char* { + std::string str = "Hello, world!"; + char *cstr = new char[str.length() + 1]; + memcpy_s(cstr, str.length() + 1, str.c_str(), str.size()); + return cstr; + }; + funcs->AbilityStageOnConfigurationUpdated = [](int64_t id, CJConfiguration configuration) {}; + funcs->AbilityStageOnMemoryLevel = [](int64_t id, int32_t level) {}; + }; + RegisterCJAbilityStageFuncs(registerFunc); + RegisterCJAbilityStageFuncs(registerFunc); + std::shared_ptr cjAbilityStageObject = CJAbilityStageObject::LoadModule("1"); + cjAbilityStageObject->OnCreate(); + std::shared_ptr cjAbilityStageObjectAnother = CJAbilityStageObject::LoadModule("0"); + + AAFwk::Want want; + cjAbilityStageObject->OnAcceptWant(want); + + std::shared_ptr configuration = std::make_shared(); + cjAbilityStageObject->OnConfigurationUpdated(configuration); + + int32_t level = 1; + cjAbilityStageObject->OnMemoryLevel(level); +} + +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/test/unittest/cj_ability_stage_test/BUILD.gn b/test/unittest/cj_ability_stage_test/BUILD.gn new file mode 100644 index 0000000000..b659e389ba --- /dev/null +++ b/test/unittest/cj_ability_stage_test/BUILD.gn @@ -0,0 +1,100 @@ +# 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") + +ohos_unittest("cj_ability_stage_test") { + module_out_path = "ability_runtime/cj_ability_stage_test" + include_dirs = [ + "${ability_runtime_test_path}/mock/common/include", + "${ability_base_kits_path}/configuration/include", + "${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/ability/native", + "${ability_runtime_path}/interfaces/inner_api/runtime/include", + "${ability_runtime_native_path}/runtime", + "${ability_runtime_path}/frameworks/cj/ffi", + "${windowmanager_path}/interfaces/kits/cangjie_ffi/window_runtime/ffi", + "${windowmanager_path}/interfaces/kits/cangjie_ffi/window_runtime/native", + "${ability_runtime_services_path}/common/include", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ + "${ability_runtime_native_path}/appkit/app/app_context.cpp", + "${ability_runtime_native_path}/appkit/app/app_loader.cpp", + "${ability_runtime_native_path}/appkit/app/application_cleaner.cpp", + "${ability_runtime_native_path}/appkit/app/ohos_application.cpp", + "${ability_runtime_path}/frameworks/native/appkit/ability_runtime/app/cj_ability_stage.cpp", + "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include/mock_bundle_manager.cpp", + "${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", + "cj_ability_stage_test.cpp", + ] + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + 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}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${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:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_path}/cj_environment/frameworks/cj_environment:cj_environment", + "${ability_runtime_path}/frameworks/cj/ffi:cj_ability_ffi", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:want", + "ability_runtime:runtime", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "napi:cj_bind_ffi", + "napi:cj_bind_native", + "resource_management:global_resmgr", + ] + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +group("unittest") { + testonly = true + deps = [ ":cj_ability_stage_test" ] +} diff --git a/test/unittest/cj_ability_stage_test/cj_ability_stage_test.cpp b/test/unittest/cj_ability_stage_test/cj_ability_stage_test.cpp new file mode 100644 index 0000000000..ccc8bc2dcb --- /dev/null +++ b/test/unittest/cj_ability_stage_test/cj_ability_stage_test.cpp @@ -0,0 +1,135 @@ +/* + * 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 "cj_ability_stage.h" +#include "cj_runtime.h" +#include "hilog_wrapper.h" +#include "runtime.h" +#include "cj_ability_stage_object.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AbilityRuntime { +class CjAbilityStageTest : public testing::Test { +public: + CjAbilityStageTest() + {} + ~CjAbilityStageTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override; + void TearDown() override; + std::unique_ptr cjAbilityStage_ = nullptr; + std::unique_ptr initCjAbilityStage_ = nullptr; +}; + +void (*g_registerFunc)(CJAbilityStageFuncs* result) = [](CJAbilityStageFuncs *result) { + result->LoadAbilityStage = [](const char *moduleName) -> int64_t { return moduleName[0] == '0' ? 0 : 1; }; + result->ReleaseAbilityStage = [](int64_t handle) {}; + result->AbilityStageOnCreate = [](int64_t handle) {}; + result->AbilityStageOnAcceptWant = [](int64_t handle, OHOS::AAFwk::Want *want) -> char* { + std::string str = "Hello, world!"; + char* cstr = new char[str.length() + 1]; + if (memcpy_s(cstr, str.length() + 1, str.c_str(), str.size()) != EOK) { + delete[] cstr; + return nullptr; + } + return cstr; + }; + result->AbilityStageOnConfigurationUpdated = [](int64_t id, CJConfiguration configuration) {}; + result->AbilityStageOnMemoryLevel = [](int64_t id, int32_t level) {}; + }; +void CjAbilityStageTest::SetUpTestCase(void) +{} + +void CjAbilityStageTest::TearDownTestCase(void) +{} + +void CjAbilityStageTest::SetUp(void) +{ + RegisterCJAbilityStageFuncs(g_registerFunc); + std::string moduleName = "0"; + auto proxy = CJAbilityStageObject::LoadModule(moduleName); + cjAbilityStage_ = std::make_unique(proxy); + auto cjProxy = CJAbilityStageObject::LoadModule("1"); + initCjAbilityStage_ = std::make_unique(cjProxy); +} + +void CjAbilityStageTest::TearDown(void) +{} + +/** + * @tc.name: CjAbilityStageTestCreate_001 + * @tc.desc: CjAbilityStageTest test for Create. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityStageTest, CjAbilityStageTestCreate_001, TestSize.Level0) +{ + AppExecFwk::HapModuleInfo hapModuleInfo; + std::unique_ptr nullRuntime = nullptr; + auto cjStage = CJAbilityStage::Create(nullRuntime, hapModuleInfo); + Runtime::Options options; + auto runtime = Runtime::Create(options); + EXPECT_TRUE(runtime != nullptr); + auto cjAbilityStage = CJAbilityStage::Create(runtime, hapModuleInfo); + EXPECT_TRUE(cjAbilityStage == nullptr); +} + +/** + * @tc.name: CjAbilityStageTestOnCreate_001 + * @tc.desc: CjAbilityStageTest test for OnCreate. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityStageTest, CjAbilityStageTestOnCreate_001, TestSize.Level0) +{ + AAFwk::Want want; + cjAbilityStage_->OnCreate(want); + initCjAbilityStage_->OnCreate(want); +} + +/** + * @tc.name: CjAbilityStageTestOnAcceptWant_001 + * @tc.desc: CjAbilityStageTest test for OnAcceptWant. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityStageTest, CjAbilityStageTestOnAcceptWant_001, TestSize.Level0) +{ + AAFwk::Want want; + auto info = cjAbilityStage_->OnAcceptWant(want); + EXPECT_TRUE(info == ""); + auto ret = initCjAbilityStage_->OnAcceptWant(want); + EXPECT_TRUE(ret != ""); +} + +/** + * @tc.name: CjAbilityStageTestOnMemoryLevel_001 + * @tc.desc: CjAbilityStageTest test for OnMemoryLevel. + * @tc.type: FUNC + */ +HWTEST_F(CjAbilityStageTest, CjAbilityStageTestOnMemoryLevel_001, TestSize.Level0) +{ + int level = 1; + cjAbilityStage_->OnMemoryLevel(level); + initCjAbilityStage_->OnMemoryLevel(level); +} + +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/test/unittest/cj_application_context_test/BUILD.gn b/test/unittest/cj_application_context_test/BUILD.gn new file mode 100644 index 0000000000..620f61ee53 --- /dev/null +++ b/test/unittest/cj_application_context_test/BUILD.gn @@ -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. + +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +ohos_unittest("cj_application_context_test") { + module_out_path = "ability_runtime/cj_application_context_test" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_delegator", + "${ability_runtime_path}/interfaces/kits/native/appkit/app", + "${bundlefwk_path}/interfaces/inner_api/appexecfwk_base/include", + "${ability_runtime_path}/interfaces/inner_api/ability_manager/include", + "${common_event_service_path}/interfaces/inner_api", + "${ability_runtime_path}/interfaces/inner_api/app_manager/include/appmgr", + "${ability_base_path}/interfaces/kits/native/session_info/include", + "${arkui_path}/ace_engine", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/frameworks/cj/ffi", + "${ace_engine_path}/frameworks", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ + "${ability_runtime_path}/frameworks/cj/ffi/cj_application_context.cpp", + "cj_application_context_test.cpp", + ] + + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/ability_manager:mission_info", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/ability:ability_context_native", + "${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:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_path}/frameworks/cj/ffi:cj_ability_ffi", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "${global_path}/resource_management/frameworks/resmgr:global_resmgr", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:session_info", + "ability_base:want", + "ability_runtime:ability_context_native", + "ability_runtime:runtime", + "ability_runtime:wantagent_innerkits", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "napi:cj_bind_native", + "window_manager:libwsutils", + "window_manager:scene_session", + ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_application_context_test" ] +} diff --git a/test/unittest/cj_application_context_test/cj_application_context_test.cpp b/test/unittest/cj_application_context_test/cj_application_context_test.cpp new file mode 100644 index 0000000000..4d8d2b0ad0 --- /dev/null +++ b/test/unittest/cj_application_context_test/cj_application_context_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 "cj_ability_delegator.h" +#include "cj_application_context.h" +#include "ability_delegator_registry.h" +#include "application_context.h" +#include "cj_utils_ffi.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::FFI; +using namespace OHOS::AbilityRuntime; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace ApplicationContextCJ { + +class CjApplicationContextTest : public testing::Test { +public: + CjApplicationContextTest() + {} + ~CjApplicationContextTest() + {} + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +protected: + std::shared_ptr appContext_; + std::shared_ptr cjAppContext_; +}; + +void CjApplicationContextTest::SetUpTestCase() +{} + +void CjApplicationContextTest::TearDownTestCase() +{} + +void CjApplicationContextTest::SetUp() +{ +} + +void CjApplicationContextTest::TearDown() +{} + +/** + * @tc.name: CJApplicationContextTestGetArea_001 + * @tc.desc: CjApplicationContextTest test for GetArea. + * @tc.type: FUNC + */ +HWTEST_F(CjApplicationContextTest, CJApplicationContextTestGetArea_001, TestSize.Level1) +{ + // 创建一个 ApplicationContext 对象 + auto appInfo = std::make_shared(); + appInfo->name = "TestApp"; + appInfo->bundleName = "com.example.testapp"; + appContext_ = std::make_shared(); + appContext_->SetApplicationInfo(appInfo); + + // 创建一个 CJApplicationContext 对象 + cjAppContext_ = std::make_shared(appContext_); + // 测试 GetArea 函数 + int area = cjAppContext_->GetArea(); + EXPECT_EQ(area, 1); +} + +/** + * @tc.name: CJApplicationContextTestGetApplicationInfo_001 + * @tc.desc: CjApplicationContextTest test for GetApplicationInfo. + * @tc.type: FUNC + */ +HWTEST_F(CjApplicationContextTest, CJApplicationContextTestGetApplicationInfo_001, TestSize.Level1) +{ + // 创建一个 ApplicationContext 对象 + auto appInfo = std::make_shared(); + appInfo->name = "TestApp"; + appInfo->bundleName = "com.example.testapp"; + appContext_ = std::make_shared(); + appContext_->SetApplicationInfo(appInfo); + + // 创建一个 CJApplicationContext 对象 + cjAppContext_ = std::make_shared(appContext_); + + // 测试 GetApplicationInfo 函数 + auto appInfoResult = cjAppContext_->GetApplicationInfo(); +} + +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/cj_delegator_ffi_mock_test/BUILD.gn b/test/unittest/cj_delegator_ffi_mock_test/BUILD.gn new file mode 100644 index 0000000000..5fe3c5465b --- /dev/null +++ b/test/unittest/cj_delegator_ffi_mock_test/BUILD.gn @@ -0,0 +1,90 @@ +# 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") + +ohos_unittest("cj_delegator_ffi_mock_test") { + module_out_path = "ability_runtime/cj_delegator_ffi_mock_test" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_delegator", + "${ability_runtime_path}/interfaces/kits/native/appkit/app", + "${bundlefwk_path}/interfaces/inner_api/appexecfwk_base/include", + "${ability_runtime_path}/interfaces/inner_api/ability_manager/include", + "${common_event_service_path}/interfaces/inner_api", + "${ability_runtime_path}/interfaces/inner_api/app_manager/include/appmgr", + "${ability_base_path}/interfaces/kits/native/session_info/include", + "${arkui_path}/ace_engine", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/frameworks/cj/ffi", + "${ability_runtime_path}/frameworks/cj/mock", + "${ace_engine_path}/frameworks", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ "cj_delegator_ffi_mock_test.cpp" ] + + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/ability_manager:mission_info", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/ability:ability_context_native", + "${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:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "${global_path}/resource_management/frameworks/resmgr:global_resmgr", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:session_info", + "ability_base:want", + "ability_runtime:ability_context_native", + "ability_runtime:runtime", + "ability_runtime:wantagent_innerkits", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "napi:cj_bind_native", + "window_manager:libwsutils", + "window_manager:scene_session", + ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_delegator_ffi_mock_test" ] +} diff --git a/test/unittest/cj_delegator_ffi_mock_test/cj_delegator_ffi_mock_test.cpp b/test/unittest/cj_delegator_ffi_mock_test/cj_delegator_ffi_mock_test.cpp new file mode 100644 index 0000000000..305cd75751 --- /dev/null +++ b/test/unittest/cj_delegator_ffi_mock_test/cj_delegator_ffi_mock_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 "foundation/ability/ability_runtime/frameworks/cj/mock/cj_delegator_ffi.cpp" + +using namespace testing; +using namespace testing::ext; + +class CjDelegatorFfiMockTest : public testing::Test { +public: + CjDelegatorFfiMockTest() + {} + ~CjDelegatorFfiMockTest() + {} + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; + +void CjDelegatorFfiMockTest::SetUpTestCase() +{} + +void CjDelegatorFfiMockTest::TearDownTestCase() +{} + +void CjDelegatorFfiMockTest::SetUp() +{} + +void CjDelegatorFfiMockTest::TearDown() +{} + +/** + * @tc.name: CjDelegatorFfiMockTestRegisterCJTestRunnerFuncs_0100 + * @tc.desc: CjDelegatorFfiMockTest test for RegisterCJTestRunnerFuncs. + * @tc.type: FUNC + */ +HWTEST_F(CjDelegatorFfiMockTest, CjDelegatorFfiMockTestRegisterCJTestRunnerFuncs_0100, TestSize.Level1) +{ + RegisterCJTestRunnerFuncs(); +} \ No newline at end of file diff --git a/test/unittest/cj_element_name_ffi_test/BUILD.gn b/test/unittest/cj_element_name_ffi_test/BUILD.gn new file mode 100644 index 0000000000..93e5b50592 --- /dev/null +++ b/test/unittest/cj_element_name_ffi_test/BUILD.gn @@ -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. + +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +ohos_unittest("cj_element_name_ffi_test") { + module_out_path = "ability_runtime/cj_element_name_ffi_test" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_delegator", + "${ability_runtime_path}/interfaces/kits/native/appkit/app", + "${bundlefwk_path}/interfaces/inner_api/appexecfwk_base/include", + "${ability_runtime_path}/interfaces/inner_api/ability_manager/include", + "${common_event_service_path}/interfaces/inner_api", + "${ability_runtime_path}/interfaces/inner_api/app_manager/include/appmgr", + "${ability_base_path}/interfaces/kits/native/session_info/include", + "${arkui_path}/ace_engine", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/frameworks/cj/ffi", + "${ace_engine_path}/frameworks", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ + "${ability_runtime_path}/frameworks/cj/ffi/cj_element_name_ffi.cpp", + "cj_element_name_ffi_test.cpp", + ] + + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/ability_manager:mission_info", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/ability:ability_context_native", + "${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:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_path}/frameworks/cj/ffi:cj_ability_ffi", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "${global_path}/resource_management/frameworks/resmgr:global_resmgr", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:session_info", + "ability_base:want", + "ability_runtime:ability_context_native", + "ability_runtime:runtime", + "ability_runtime:wantagent_innerkits", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "napi:cj_bind_native", + "window_manager:libwsutils", + "window_manager:scene_session", + ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_element_name_ffi_test" ] +} diff --git a/test/unittest/cj_element_name_ffi_test/cj_element_name_ffi_test.cpp b/test/unittest/cj_element_name_ffi_test/cj_element_name_ffi_test.cpp new file mode 100644 index 0000000000..dd99ba9ae9 --- /dev/null +++ b/test/unittest/cj_element_name_ffi_test/cj_element_name_ffi_test.cpp @@ -0,0 +1,165 @@ +/* + * 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 "cj_element_name_ffi.h" +#include "cj_utils_ffi.h" +#include "element_name.h" +#include "securec.h" + +using namespace testing; +using namespace testing::ext; +using OHOS::AppExecFwk::ElementName; + +class CjElementNameFfiTest : public testing::Test { +public: + CjElementNameFfiTest() + {} + ~CjElementNameFfiTest() + {} + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; + +void CjElementNameFfiTest::SetUpTestCase() +{} + +void CjElementNameFfiTest::TearDownTestCase() +{} + +void CjElementNameFfiTest::SetUp() +{} + +void CjElementNameFfiTest::TearDown() +{} + +/** + * @tc.name: CJElementNameFFITestFFICJElementNameCreateWithContent_0100 + * @tc.desc: CjElementNameFfiTest test for FFICJElementNameCreateWithContent. + * @tc.type: FUNC + */ +HWTEST_F(CjElementNameFfiTest, CJElementNameFFITestFFICJElementNameCreateWithContent_0100, TestSize.Level1) +{ + char* deviceId = new char[9]; + strcpy_s(deviceId, 9, "deviceId"); + + char* bundleName = new char[11]; + strcpy_s(bundleName, 11, "bundleName"); + + char* abilityName = new char[12]; + strcpy_s(abilityName, 12, "abilityName"); + + char* moduleName = new char[11]; + strcpy_s(moduleName, 11, "moduleName"); + + ElementNameHandle elementNameHandle = + FFICJElementNameCreateWithContent(deviceId, bundleName, abilityName, moduleName); + auto actualElementName = reinterpret_cast(elementNameHandle); + + EXPECT_EQ(actualElementName->GetDeviceID(), deviceId); + EXPECT_EQ(actualElementName->GetBundleName(), bundleName); + EXPECT_EQ(actualElementName->GetAbilityName(), abilityName); + EXPECT_EQ(actualElementName->GetModuleName(), moduleName); + + FFICJElementNameDelete(elementNameHandle); +} + +/** + * @tc.name: CJElementNameFFITestFFICJElementNameDelete_0100 + * @tc.desc: CjElementNameFfiTest test for FFICJElementNameDelete. + * @tc.type: FUNC + */ +HWTEST_F(CjElementNameFfiTest, CJElementNameFFITestFFICJElementNameDelete_0100, TestSize.Level1) +{ + char* deviceId = new char[9]; + strcpy_s(deviceId, 9, "deviceId"); + + char* bundleName = new char[11]; + strcpy_s(bundleName, 11, "bundleName"); + + char* abilityName = new char[12]; + strcpy_s(abilityName, 12, "abilityName"); + + char* moduleName = new char[11]; + strcpy_s(moduleName, 11, "moduleName"); + + ElementNameHandle elementNameHandle = + FFICJElementNameCreateWithContent(deviceId, bundleName, abilityName, moduleName); + FFICJElementNameDelete(elementNameHandle); +} + +/** + * @tc.name: CjElementNameFfiTestContext_0100 + * @tc.desc: CjElementNameFfiTest test for FFICJElementNameGetElementNameInfo. + * @tc.type: FUNC + */ +HWTEST_F(CjElementNameFfiTest, CJElementNameFFITestFFICJElementNameGetElementNameInfo_0100, TestSize.Level1) +{ + char* deviceId = new char[9]; + strcpy_s(deviceId, 9, "deviceId"); + + char* bundleName = new char[11]; + strcpy_s(bundleName, 11, "bundleName"); + + char* abilityName = new char[12]; + strcpy_s(abilityName, 12, "abilityName"); + + char* moduleName = new char[11]; + strcpy_s(moduleName, 11, "moduleName"); + + ElementNameHandle elementNameHandle = + FFICJElementNameCreateWithContent(deviceId, bundleName, abilityName, moduleName); + ElementNameParams* elementNameParams = FFICJElementNameGetElementNameInfo(elementNameHandle); + + auto actualElementName = reinterpret_cast(elementNameHandle); + EXPECT_STREQ(elementNameParams->deviceId, CreateCStringFromString(actualElementName->GetDeviceID())); + EXPECT_STREQ(elementNameParams->bundleName, CreateCStringFromString(actualElementName->GetBundleName())); + EXPECT_STREQ(elementNameParams->abilityName, CreateCStringFromString(actualElementName->GetAbilityName())); + EXPECT_STREQ(elementNameParams->moduleName, CreateCStringFromString(actualElementName->GetModuleName())); + + FFICJElementNameParamsDelete(elementNameParams); + FFICJElementNameDelete(elementNameHandle); +} + +/** + * @tc.name: CjElementNameFfiTestContext_0100 + * @tc.desc: CjElementNameFfiTest test for FFICJElementNameParamsDelete. + * @tc.type: FUNC + */ +HWTEST_F(CjElementNameFfiTest, CJElementNameFFITestFFICJElementNameParamsDelete_0100, TestSize.Level1) +{ + char* deviceId = new char[9]; + strcpy_s(deviceId, 9, "deviceId"); + + char* bundleName = new char[11]; + strcpy_s(bundleName, 11, "bundleName"); + + char* abilityName = new char[12]; + strcpy_s(abilityName, 12, "abilityName"); + + char* moduleName = new char[11]; + strcpy_s(moduleName, 11, "moduleName"); + + ElementNameParams* elementNameParams = static_cast(malloc(sizeof(ElementNameParams))); + elementNameParams->deviceId = CreateCStringFromString(deviceId); + elementNameParams->bundleName = CreateCStringFromString(bundleName); + elementNameParams->abilityName = CreateCStringFromString(abilityName); + elementNameParams->moduleName = CreateCStringFromString(moduleName); + + FFICJElementNameParamsDelete(elementNameParams); +} \ No newline at end of file diff --git a/test/unittest/cj_environment_test/BUILD.gn b/test/unittest/cj_environment_test/BUILD.gn new file mode 100644 index 0000000000..99ecd9626e --- /dev/null +++ b/test/unittest/cj_environment_test/BUILD.gn @@ -0,0 +1,95 @@ +# 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") +import("//foundation/ability/ability_runtime/cj_environment/cj_environment.gni") + +ohos_unittest("cj_environment_test") { + module_out_path = "ability_runtime/cj_environment_test" + include_dirs = [ + "${ability_runtime_test_path}/mock/common/include", + "${resource_management_path}/frameworks/resmgr/include", + "${ability_base_kits_path}/configuration/include", + "${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/ability/native", + "${ability_runtime_path}/interfaces/inner_api/runtime/include", + "${ability_runtime_path}/cj_environment/frameworks/cj_environment", + "${ability_runtime_path}/cj_environment/frameworks/cj_environment/src", + "${ability_runtime_path}/cj_environment/interfaces", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + "${ability_runtime_path}/cj_environment/frameworks/cj_environment/include", + "${ability_runtime_native_path}/runtime", + ] + + sources = [ + "${ability_runtime_path}/cj_environment/frameworks/cj_environment/src/cj_environment.cpp", + "${ability_runtime_path}/cj_environment/frameworks/cj_environment/src/dynamic_loader_ohos.cpp", + "cj_environment_test.cpp", + ] + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + 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}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${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:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:want", + "ability_runtime:runtime", + "bounds_checking_function:libsec_shared", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "resource_management:global_resmgr", + ] + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } + + defines = [ "CONFIG_HILOG" ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_environment_test" ] +} diff --git a/test/unittest/cj_environment_test/cj_environment_test.cpp b/test/unittest/cj_environment_test/cj_environment_test.cpp new file mode 100644 index 0000000000..98026e302b --- /dev/null +++ b/test/unittest/cj_environment_test/cj_environment_test.cpp @@ -0,0 +1,197 @@ +/* + * 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 "cj_environment.h" +#include "dynamic_loader.h" + +#include + +#include "cj_invoker.h" +#ifdef __OHOS__ +#include +#endif +#include "dynamic_loader.h" +#ifdef WITH_EVENT_HANDLER +#include "event_handler.h" +#endif + +using namespace OHOS; +using namespace testing; +using namespace testing::ext; + + +class CjEnvironmentTest : public testing::Test { +public: + CjEnvironmentTest() + {} + ~CjEnvironmentTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override; + void TearDown() override; +}; + +void CjEnvironmentTest::SetUpTestCase(void) +{} + +void CjEnvironmentTest::TearDownTestCase(void) +{} + +void CjEnvironmentTest::SetUp(void) +{} + +void CjEnvironmentTest::TearDown(void) +{} + +void TestFunc() +{} + +/** + * @tc.name: CjEnvironmentTestPostTask_001 + * @tc.desc: CjEnvironmentTest test for PostTask. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestPostTask_001, TestSize.Level0) +{ + CJEnvironment::GetInstance()->PostTask(nullptr); + void (*func)() = TestFunc; + CJEnvironment::GetInstance()->PostTask(func); +} + +/** + * @tc.name: CjEnvironmentTestHasHigherPriorityTask_001 + * @tc.desc: CjEnvironmentTest test for HasHigherPriorityTask. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestHasHigherPriorityTask_001, TestSize.Level0) +{ + CJEnvironment::GetInstance()->HasHigherPriorityTask(); +} + +/** + * @tc.name: CjEnvironmentTestInitCJChipSDKNS_001 + * @tc.desc: CjEnvironmentTest test for InitCJChipSDKNS. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestInitCJChipSDKNS_001, TestSize.Level0) +{ + CJEnvironment::GetInstance()->InitCJChipSDKNS("path/to/hap"); +} + +/** + * @tc.name: CjEnvironmentTestInitCJAppNS_001 + * @tc.desc: CjEnvironmentTest test for InitCJAppNS. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestInitCJAppNS_001, TestSize.Level0) +{ + CJEnvironment::GetInstance()->InitCJAppNS("path/to/hap"); +} + +/** + * @tc.name: CjEnvironmentTestInitCJSDKNS_001 + * @tc.desc: CjEnvironmentTest test for InitCJSDKNS. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestInitCJSDKNS_001, TestSize.Level0) +{ + CJEnvironment::GetInstance()->InitCJSDKNS("path/to/hap"); +} + +/** + * @tc.name: CjEnvironmentTestInitCJSysNS_001 + * @tc.desc: CjEnvironmentTest test for InitCJSysNS. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestInitCJSysNS_001, TestSize.Level0) +{ + CJEnvironment::GetInstance()->InitCJSysNS("path/to/hap"); +} + +/** + * @tc.name: CjEnvironmentTestStartRuntime_001 + * @tc.desc: CjEnvironmentTest test for StartRuntime. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestStartRuntime_001, TestSize.Level0) +{ + CJEnvironment::GetInstance()->StartRuntime(); + CJEnvironment::GetInstance()->StartRuntime(); +} + +/** + * @tc.name: CjEnvironmentTestStopRuntime_001 + * @tc.desc: CjEnvironmentTest test for StopRuntime. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestStopRuntime_001, TestSize.Level0) +{ + CJEnvironment::GetInstance()->StopRuntime(); + CJEnvironment::GetInstance()->StopRuntime(); +} + +/** + * @tc.name: CjEnvironmentTestStopUIScheduler_001 + * @tc.desc: CjEnvironmentTest test for StopUIScheduler. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestStopUIScheduler_001, TestSize.Level0) +{ + CJEnvironment::GetInstance()->StopUIScheduler(); +} + +/** + * @tc.name: CjEnvironmentTestLoadCJLibrary_001 + * @tc.desc: CjEnvironmentTest test for LoadCJLibrary. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestLoadCJLibrary_001, TestSize.Level0) +{ + CJEnvironment::GetInstance()->LoadCJLibrary("dlName"); +} + +/** + * @tc.name: CjEnvironmentTestLoadCJLibrary_001 + * @tc.desc: CjEnvironmentTest test for LoadCJLibrary. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestLoadCJLibrary_002, TestSize.Level0) +{ + CJEnvironment::GetInstance()->LoadCJLibrary(CJEnvironment::GetInstance()->LibraryKind::APP, "dlName"); + CJEnvironment::GetInstance()->LoadCJLibrary(CJEnvironment::GetInstance()->LibraryKind::SYSTEM, "dlName"); + CJEnvironment::GetInstance()->LoadCJLibrary(CJEnvironment::GetInstance()->LibraryKind::SDK, "dlName"); +} + +/** + * @tc.name: CjEnvironmentTestStartDebugger_001 + * @tc.desc: CjEnvironmentTest test for StartDebugger. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestStartDebugger_001, TestSize.Level0) +{ + CJEnvironment::GetInstance()->StartDebugger(); +} + +/** + * @tc.name: CjEnvironmentTestGetSymbol_001 + * @tc.desc: CjEnvironmentTest test for GetSymbol. + * @tc.type: FUNC + */ +HWTEST_F(CjEnvironmentTest, CjEnvironmentTestGetSymbol_001, TestSize.Level0) +{ + CJEnvironment::GetInstance()->GetSymbol(nullptr, "dlName"); +} diff --git a/test/unittest/cj_runtime_test/BUILD.gn b/test/unittest/cj_runtime_test/BUILD.gn new file mode 100644 index 0000000000..4e591e918f --- /dev/null +++ b/test/unittest/cj_runtime_test/BUILD.gn @@ -0,0 +1,49 @@ +# 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") + +ohos_unittest("cj_runtime_test") { + module_out_path = "ability_runtime/cj_runtime_test" + include_dirs = [ + "${ability_runtime_path}/interfaces/inner_api/runtime/include", + "${ability_runtime_path}/test/unittest/cj_runtime_test", + "${ability_runtime_native_path}/runtime", + "${ability_runtime_native_path}/runtime/utils/include", + "${ability_base_kits_path}/extractortool/include", + "//third_party/zlib/contrib/minizip", + "//third_party/zlib", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ "cj_runtime_test.cpp" ] + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_innerkits_path}/runtime:runtime", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ "eventhandler:libeventhandler" ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_runtime_test" ] +} diff --git a/test/unittest/cj_runtime_test/cj_mock_runtime.h b/test/unittest/cj_runtime_test/cj_mock_runtime.h new file mode 100644 index 0000000000..6053d522f0 --- /dev/null +++ b/test/unittest/cj_runtime_test/cj_mock_runtime.h @@ -0,0 +1,113 @@ +/* + * 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_RUNTIME_H +#define MOCK_RUNTIME_H + +#include + +#include "cj_runtime.h" + +namespace OHOS { +namespace AbilityRuntime { +class cjMockRuntime : public CJRuntime { +public: + cjMockRuntime() = default; + ~cjMockRuntime() = default; + + Language GetLanguage() const override + { + return Language::CJ; + } + + void StartDebugMode(const DebugOption debugOption) override {} + + void FinishPreload() override {} + bool LoadRepairPatch(const std::string& patchFile, const std::string& baseFile) override + { + return true; + } + bool NotifyHotReloadPage() override + { + return true; + } + bool SuspendVM(uint32_t tid) override + { + return true; + } + void ResumeVM(uint32_t tid) override {} + bool UnLoadRepairPatch(const std::string& patchFile) override + { + return true; + } + void DumpHeapSnapshot(bool isPrivate) override + { + return; + } + void DestroyHeapProfiler() override + { + return; + } + void ForceFullGC() override + { + return; + } + void AllowCrossThreadExecution() override + { + return; + } + void GetHeapPrepare() override + { + return; + } + void NotifyApplicationState(bool isBackground) override + { + return; + } + void PreloadSystemModule(const std::string& moduleName) override + { + return; + } + bool RunScript(const std::string& path, const std::string& hapPath, bool useCommonChunk = false) + { + return true; + } + bool Initialize(const Options& options) + { + return true; + } + void Deinitialize() {} + bool LoadScript(const std::string& path, std::vector* buffer = nullptr, bool isBundle = false) + { + return true; + } + void RegisterQuickFixQueryFunc(const std::map& moduleAndPath) override + { + return; + } + void SetDeviceDisconnectCallback(const std::function &cb) override + { + return; + } + + void StartProfiler(const DebugOption debugOption) override {} + + void DoCleanWorkAfterStageCleaned() override {} +public: + Language language; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // MOCK_RUNTIME_H diff --git a/test/unittest/cj_runtime_test/cj_runtime_test.cpp b/test/unittest/cj_runtime_test/cj_runtime_test.cpp new file mode 100644 index 0000000000..d3b4639046 --- /dev/null +++ b/test/unittest/cj_runtime_test/cj_runtime_test.cpp @@ -0,0 +1,161 @@ +/* + * 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 "cj_runtime.h" +#include "runtime.h" +#include "cj_mock_runtime.h" + +#include "event_runner.h" +#include "hilog_wrapper.h" +#include "cj_runtime.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AbilityRuntime { +namespace { +const std::string TEST_BUNDLE_NAME = "com.ohos.contactsdataability"; +const std::string TEST_MODULE_NAME = ".ContactsDataAbility"; +const std::string TEST_ABILITY_NAME = "ContactsDataAbility"; +const std::string TEST_CODE_PATH = "/data/storage/el1/bundle"; +const std::string TEST_HAP_PATH = "/system/app/com.ohos.contactsdataability/Contacts_DataAbility.hap"; +const std::string TEST_LIB_PATH = "/data/storage/el1/bundle/lib/"; +const std::string TEST_MODULE_PATH = "/data/storage/el1/bundle/curCJModulePath"; +} // namespace +class CjRuntimeTest : public testing::Test { +public: + CjRuntimeTest() + {} + ~CjRuntimeTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override; + void TearDown() override; + Runtime::Options options_; +}; + +void CjRuntimeTest::SetUpTestCase(void) +{} + +void CjRuntimeTest::TearDownTestCase(void) +{} + +void CjRuntimeTest::SetUp(void) +{ + options_.bundleName = TEST_BUNDLE_NAME; + options_.codePath = TEST_CODE_PATH; + options_.loadAce = false; + options_.isBundle = true; + options_.preload = false; + std::shared_ptr eventRunner = AppExecFwk::EventRunner::Create(TEST_ABILITY_NAME); + options_.eventRunner = eventRunner; +} + +void CjRuntimeTest::TearDown(void) +{} + +/** + * @tc.name: CjRuntimeCreate_001 + * @tc.desc: Interface Create Test + * @tc.type: FUNC + */ +HWTEST_F(CjRuntimeTest, CjRuntimeCreate_001, TestSize.Level1) +{ + options_.preload = true; + options_.lang = CJRuntime::Language::CJ; + std::unique_ptr runtime = std::make_unique(); + AppLibPathMap appLibPaths{}; + CJRuntime::SetAppLibPath(appLibPaths); + auto cjRuntime = runtime->Create(options_); + EXPECT_EQ(cjRuntime, nullptr); + std::vector paths = {"/data/test/"}; + appLibPaths.emplace("", paths); + CJRuntime::SetAppLibPath(appLibPaths); + cjRuntime = runtime->Create(options_); +} + +/** + * @tc.name: CjRuntimeCreate_002 + * @tc.desc: Interface Create Test for Fail Situation + * @tc.type: FUNC + */ +HWTEST_F(CjRuntimeTest, CjRuntimeCreate_002, TestSize.Level1) +{ + options_.preload = true; + options_.lang = CJRuntime::Language::JS; + std::unique_ptr runtime = std::make_unique(); + auto cjRuntime = runtime->Create(options_); + EXPECT_TRUE(cjRuntime == nullptr); +} + +/** + * @tc.name: CjRuntimeSetAppLibPath_001 + * @tc.desc: Interface SetAppLibPath Test + * @tc.type: FUNC + */ +HWTEST_F(CjRuntimeTest, CjRuntimeSetAppLibPath_001, TestSize.Level0) +{ + std::string appLibPathKey = TEST_BUNDLE_NAME + TEST_MODULE_NAME; + std::string libPath = TEST_LIB_PATH; + + AppLibPathMap appLibPaths{}; + CJRuntime::SetAppLibPath(appLibPaths); + + appLibPaths[appLibPathKey].emplace_back(libPath); + EXPECT_NE(appLibPaths.size(), 0); + CJRuntime::SetAppLibPath(appLibPaths); +} + +/** + * @tc.name: CjRuntimeGetLanguageTest_001 + * @tc.desc: CjRuntime Test for GetLanguage + * @tc.type: FUNC + */ +HWTEST_F(CjRuntimeTest, CjRuntimeGetLanguageTest_001, TestSize.Level0) +{ + auto instance = std::make_unique(); + + CJRuntime::Language language = instance->GetLanguage(); + EXPECT_TRUE(language == CJRuntime::Language::CJ); + instance->UnLoadCJAppLibrary(); +} + +/** + * @tc.name: CjRuntimeStartDebuggerMode_001 + * @tc.desc: CjRuntime test for StartDebuggerMode. + * @tc.type: FUNC + */ +HWTEST_F(CjRuntimeTest, CjRuntimeStartDebuggerMode_001, TestSize.Level0) +{ + auto instance = std::make_unique(); + + bool needBreakPoint = true; + bool debugApp = true; + const std::string processName = "test"; + + CJRuntime::DebugOption debugOption; + debugOption.isStartWithDebug = needBreakPoint; + debugOption.isDebugApp = debugApp; + debugOption.processName = processName; + + instance->StartDebugMode(debugOption); + instance->StartDebugMode(debugOption); +} + +} // namespace Runtime +} // namespace OHOS diff --git a/test/unittest/cj_test_runner_object_test/BUILD.gn b/test/unittest/cj_test_runner_object_test/BUILD.gn new file mode 100644 index 0000000000..3b82681734 --- /dev/null +++ b/test/unittest/cj_test_runner_object_test/BUILD.gn @@ -0,0 +1,75 @@ +# 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") + +ohos_unittest("cj_test_runner_object_test") { + module_out_path = "ability_runtime/cj_test_runner_object_test" + include_dirs = [ + "${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/ability_runtime/ability_delegator/include", + "${ability_runtime_services_path}/common/include", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/frameworks/native", + "${ability_runtime_path}/interfaces/kits/native/appkit/app", + "${ability_runtime_path}/interfaces/kits/native/appkit/dfr", + "//third_party/json/include", + "${ability_base_kits_path}/configuration/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_delegator", + "${global_path}/resource_management/interfaces/inner_api/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ + "${ability_runtime_path}/frameworks/native/appkit/ability_delegator/runner_runtime/cj_test_runner_object.cpp", + "cj_test_runner_object_test.cpp", + ] + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + 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", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:want", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "hilog:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + ] + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +group("unittest") { + testonly = true + deps = [ ":cj_test_runner_object_test" ] +} diff --git a/test/unittest/cj_test_runner_object_test/cj_test_runner_object_test.cpp b/test/unittest/cj_test_runner_object_test/cj_test_runner_object_test.cpp new file mode 100644 index 0000000000..03c907adb4 --- /dev/null +++ b/test/unittest/cj_test_runner_object_test/cj_test_runner_object_test.cpp @@ -0,0 +1,170 @@ +/* + * 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 "gtest/gtest.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace RunnerRuntime { +class CjTestRunnerObjectTest : public ::testing::Test { +public: + CjTestRunnerObjectTest() + {} + ~CjTestRunnerObjectTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override; + void TearDown() override; +}; + +void CjTestRunnerObjectTest::SetUpTestCase() +{} + +void CjTestRunnerObjectTest::TearDownTestCase() +{} + +int64_t create(const char* name) +{ + return 1; +} + +void release(int64_t id) {} + +void onRun(int64_t id) {} + +void onPrepare(int64_t id) {} + +// 模拟 Cangjie 侧的函数注册函数 +void RegisterCangjieFuncs(CJTestRunnerFuncs* funcs) +{ + funcs->cjTestRunnerCreate = create; + funcs->cjTestRunnerRelease = release; + funcs->cjTestRunnerOnRun = onRun; + funcs->cjTestRunnerOnPrepare = onPrepare; +} + +void CjTestRunnerObjectTest::SetUp() +{ +} + +void CjTestRunnerObjectTest::TearDown() +{ +} + +/** + * @tc.name: CjTestRunnerObjectTestLoadModule_Success_001 + * @tc.desc: CjTestRunnerObjectTest test for LoadModule. + * @tc.type: FUNC + */ +HWTEST_F(CjTestRunnerObjectTest, CjTestRunnerObjectTestLoadModule_Success_001, TestSize.Level0) +{ + RegisterCJTestRunnerFuncs(nullptr); + RegisterCJTestRunnerFuncs(RegisterCangjieFuncs); + std::shared_ptr proxy = CJTestRunnerObject::LoadModule("test_ability"); + EXPECT_NE(nullptr, proxy); + proxy->OnPrepare(); + proxy->OnRun(); + + proxy.reset(); +} + +/** + * @tc.name: CjTestRunnerObjectTestLoadModule_Failed_NoRegistration_001 + * @tc.desc: CjTestRunnerObjectTest test for LoadModule. + * @tc.type: FUNC + */ +HWTEST_F(CjTestRunnerObjectTest, CjTestRunnerObjectTestLoadModule_Failed_NoRegistration_001, TestSize.Level0) +{ + auto proxy = CJTestRunnerObject::LoadModule("test_ability"); + EXPECT_NE(nullptr, proxy); +} + +/** + * @tc.name: CjAbilityStageTestOnMemoryLevel_001 + * @tc.desc: CjTestRunnerObjectTest test for OnMemoryLevel. + * @tc.type: FUNC + */ +HWTEST_F(CjTestRunnerObjectTest, CjTestRunnerObjectTestLoadModule_Failed_CangjieCreateFailed_001, TestSize.Level0) +{ + RegisterCJTestRunnerFuncs(RegisterCangjieFuncs); + auto proxy = CJTestRunnerObject::LoadModule("test_ability"); + EXPECT_NE(nullptr, proxy); +} + +/** + * @tc.name: CjTestRunnerObjectTestOnRun_Success_001 + * @tc.desc: CjTestRunnerObjectTest test for OnRun. + * @tc.type: FUNC + */ +HWTEST_F(CjTestRunnerObjectTest, CjTestRunnerObjectTestOnRun_Success_001, TestSize.Level0) +{ + RegisterCJTestRunnerFuncs(RegisterCangjieFuncs); + auto proxy = CJTestRunnerObject::LoadModule("test_ability"); + proxy->OnRun(); + proxy.reset(); +} + +/** + * @tc.name: CjTestRunnerObjectTestOnRun_Failed_NoRegistration_001 + * @tc.desc: CjTestRunnerObjectTest test for OnRun. + * @tc.type: FUNC + */ +HWTEST_F(CjTestRunnerObjectTest, CjTestRunnerObjectTestOnRun_Failed_NoRegistration_001, TestSize.Level0) +{ + auto proxy = CJTestRunnerObject::LoadModule("test_ability"); + proxy->OnRun(); +} + +/** + * @tc.name: CjTestRunnerObjectTestOnPrepare_Success_001 + * @tc.desc: CjTestRunnerObjectTest test for OnPrepare. + * @tc.type: FUNC + */ +HWTEST_F(CjTestRunnerObjectTest, CjTestRunnerObjectTestOnPrepare_Success_001, TestSize.Level0) +{ + RegisterCJTestRunnerFuncs(RegisterCangjieFuncs); + auto proxy = CJTestRunnerObject::LoadModule("test_ability"); + proxy->OnPrepare(); +} + +/** + * @tc.name: CjTestRunnerObjectTestOnPrepare_Failed_NoRegistration_001 + * @tc.desc: CjTestRunnerObjectTest test for OnPrepare. + * @tc.type: FUNC + */ +HWTEST_F(CjTestRunnerObjectTest, CjTestRunnerObjectTestOnPrepare_Failed_NoRegistration_001, TestSize.Level0) +{ + auto proxy = CJTestRunnerObject::LoadModule("test_ability"); + proxy->OnPrepare(); +} + +/** + * @tc.name: CjTestRunnerObjectTestDestructor_Success_001 + * @tc.desc: CjTestRunnerObjectTest test for reset. + * @tc.type: FUNC + */ +HWTEST_F(CjTestRunnerObjectTest, CjTestRunnerObjectTestDestructor_Success_001, TestSize.Level0) +{ + RegisterCJTestRunnerFuncs(RegisterCangjieFuncs); + auto proxy = CJTestRunnerObject::LoadModule("test_ability"); + proxy.reset(); +} +} // namespace RunnerRuntime +} // namespace OHOS diff --git a/test/unittest/cj_test_runner_test/BUILD.gn b/test/unittest/cj_test_runner_test/BUILD.gn new file mode 100644 index 0000000000..bbc7128ba4 --- /dev/null +++ b/test/unittest/cj_test_runner_test/BUILD.gn @@ -0,0 +1,110 @@ +# 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("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +ohos_unittest("cj_test_runner_test") { + module_out_path = "ability_runtime/cj_test_runner_test" + include_dirs = [ + "native", + "${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/ability_runtime/ability_delegator/include", + "${ability_runtime_services_path}/common/include", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/interfaces/kits/native/appkit/app", + "${ability_runtime_path}/interfaces/kits/native/appkit/dfr", + "//third_party/json/include", + "${ability_base_kits_path}/configuration/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_delegator", + "${global_path}/resource_management/interfaces/inner_api/include", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_path}/frameworks/native/appkit/ability_delegator", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ + "${ability_runtime_native_path}/appkit/ability_delegator/ability_delegator.cpp", + "${ability_runtime_native_path}/appkit/ability_delegator/ability_delegator_args.cpp", + "${ability_runtime_native_path}/appkit/ability_delegator/ability_delegator_registry.cpp", + "${ability_runtime_native_path}/appkit/ability_delegator/delegator_thread.cpp", + "${ability_runtime_native_path}/appkit/ability_delegator/iability_monitor.cpp", + "${ability_runtime_native_path}/appkit/ability_delegator/iability_stage_monitor.cpp", + "${ability_runtime_native_path}/appkit/ability_delegator/runner_runtime/cj_test_runner_object.cpp", + "${ability_runtime_native_path}/appkit/ability_delegator/runner_runtime/js_test_runner.cpp", + "${ability_runtime_native_path}/appkit/ability_delegator/shell_cmd_result.cpp", + "${ability_runtime_native_path}/appkit/ability_delegator/test_runner.cpp", + "${ability_runtime_path}/frameworks/native/appkit/ability_delegator/runner_runtime/cj_test_runner.cpp", + "${ability_runtime_path}/tools/aa/src/shell_command_result.cpp", + "${ability_runtime_path}/tools/aa/src/test_observer_proxy.cpp", + "cj_test_runner_test.cpp", + ] + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + 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}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${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:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_native_path}/appkit:delegator_mgmt", + "${ability_runtime_path}/frameworks/cj/ffi:cj_ability_ffi", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:extractortool", + "ability_base:want", + "ability_runtime:runtime", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ets_runtime:libark_jsruntime", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "napi:cj_bind_native", + "resource_management:global_resmgr", + ] + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +group("unittest") { + testonly = true + deps = [ ":cj_test_runner_test" ] +} diff --git a/test/unittest/cj_test_runner_test/cj_mock_runtime.h b/test/unittest/cj_test_runner_test/cj_mock_runtime.h new file mode 100644 index 0000000000..626d20740f --- /dev/null +++ b/test/unittest/cj_test_runner_test/cj_mock_runtime.h @@ -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. + */ + +#ifndef MOCK_RUNTIME_H +#define MOCK_RUNTIME_H + +#include + +#include "cj_runtime.h" + +namespace OHOS { +namespace AbilityRuntime { +class cjMockRuntime : public CJRuntime { +public: + cjMockRuntime() = default; + ~cjMockRuntime() = default; + + Language GetLanguage() const override + { + return Language::CJ; + } + + void FinishPreload() override {} + bool LoadRepairPatch(const std::string& patchFile, const std::string& baseFile) override + { + return true; + } + bool NotifyHotReloadPage() override + { + return true; + } + bool SuspendVM(uint32_t tid) override + { + return true; + } + void ResumeVM(uint32_t tid) override {} + bool UnLoadRepairPatch(const std::string& patchFile) override + { + return true; + } + void DumpHeapSnapshot(bool isPrivate) override + { + return; + } + void DestroyHeapProfiler() override + { + return; + } + void ForceFullGC() override + { + return; + } + void AllowCrossThreadExecution() override + { + return; + } + void GetHeapPrepare() override + { + return; + } + void NotifyApplicationState(bool isBackground) override + { + return; + } + void PreloadSystemModule(const std::string& moduleName) override + { + return; + } + bool RunScript(const std::string& path, const std::string& hapPath, bool useCommonChunk = false) + { + return true; + } + bool Initialize(const Options& options) + { + return true; + } + void Deinitialize() {} + bool LoadScript(const std::string& path, std::vector* buffer = nullptr, bool isBundle = false) + { + return true; + } + void RegisterQuickFixQueryFunc(const std::map& moduleAndPath) override + { + return; + } + void SetDeviceDisconnectCallback(const std::function &cb) override + { + return; + } + + void DoCleanWorkAfterStageCleaned() override {} +public: + Language language; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // MOCK_RUNTIME_H diff --git a/test/unittest/cj_test_runner_test/cj_test_runner_test.cpp b/test/unittest/cj_test_runner_test/cj_test_runner_test.cpp new file mode 100644 index 0000000000..bf66f6df73 --- /dev/null +++ b/test/unittest/cj_test_runner_test/cj_test_runner_test.cpp @@ -0,0 +1,135 @@ +/* + * 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 +#include + +#include "ability_delegator_registry.h" +#include "hilog_wrapper.h" +#include "cj_runtime.h" +#include "runner_runtime/cj_test_runner.h" +#include "runner_runtime/cj_test_runner_object.h" + +#include "cj_mock_runtime.h" +#include "constants.h" +#include "app_loader.h" +#include "event_runner.h" +#include "hilog_tag_wrapper.h" +#include "napi/native_common.h" +#include "ohos_application.h" + +using namespace OHOS; +using namespace RunnerRuntime; +using namespace OHOS::AppExecFwk; +using namespace OHOS::AAFwk; +using namespace OHOS::AbilityBase::Constants; +using namespace testing; +using namespace testing::ext; + +namespace { +const std::string KEY_TEST_BUNDLE_NAME = "-p"; +const std::string VALUE_TEST_BUNDLE_NAME = "com.example.myapplicationjs"; +const std::string KEY_TEST_RUNNER_CLASS = "-s unittest"; +const std::string VALUE_TEST_RUNNER_CLASS = "CjUserTestRunnerCj"; +const std::string KEY_TEST_CASE = "-s class"; +const std::string VALUE_TEST_CASE = +"ohos.acts.aafwk.ability.test.ConstructorTest#testDataAbilityOtherFunction0010_js"; +const std::string KEY_TEST_WAIT_TIMEOUT = "-w"; +const std::string VALUE_TEST_WAIT_TIMEOUT = "35"; +const std::string REPORT_FINISH_MSG = "report finish message"; +const std::string TEST_BUNDLE_NAME = "com.ohos.contactsdataability"; +const std::string TEST_MODULE_NAME = ".ContactsDataAbility"; +const std::string TEST_ABILITY_NAME = "ContactsDataAbility"; +const std::string TEST_CODE_PATH = "/data/storage/el1/bundle"; +const std::string TEST_HAP_PATH = "/system/app/com.ohos.contactsdataability/Contacts_DataAbility.hap"; +const std::string TEST_LIB_PATH = "/data/storage/el1/bundle/lib/"; +const std::string TEST_MODULE_PATH = "/data/storage/el1/bundle/curCJModulePath"; +} + +class CjTestRunnerTest : public Test { +public: + CjTestRunnerTest() + {} + ~CjTestRunnerTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override; + void TearDown() override; + Runtime::Options options_; + +protected: + std::unique_ptr testRunner_; + std::shared_ptr delegator_; + std::unique_ptr runtime_; + AppExecFwk::BundleInfo bundleInfo_; +}; + +void CjTestRunnerTest::SetUpTestCase() +{} + +void CjTestRunnerTest::TearDownTestCase() +{} + +void CjTestRunnerTest::SetUp() +{ + options_.bundleName = TEST_BUNDLE_NAME; + options_.codePath = TEST_CODE_PATH; + options_.loadAce = false; + options_.isBundle = true; + options_.preload = false; + std::shared_ptr eventRunner = AppExecFwk::EventRunner::Create(TEST_ABILITY_NAME); + options_.eventRunner = eventRunner; + options_.preload = true; + options_.lang = CJRuntime::Language::CJ; + std::unique_ptr runtime = std::make_unique(); + AppLibPathMap appLibPaths{}; + std::vector paths = {"/data/test/"}; + appLibPaths.emplace("", paths); + CJRuntime::SetAppLibPath(appLibPaths); + runtime_ = runtime->Create(options_); +} + +void CjTestRunnerTest::TearDown() +{ +} + +/** + * @tc.name: CjTestRunnerTestCreate_Failed_RuntimeNull_001 + * @tc.desc: CjTestRunnerTest test for OnMemoryLevel. + * @tc.type: FUNC + */ +HWTEST_F(CjTestRunnerTest, CjTestRunnerTestCreate_Failed_RuntimeNull_001, TestSize.Level0) +{ + TAG_LOGI(AAFwkTag::TEST, "CjTestRunnerTestInitialize_Success_001 is called"); + std::map paras; + paras.emplace(KEY_TEST_BUNDLE_NAME, VALUE_TEST_BUNDLE_NAME); + paras.emplace(KEY_TEST_RUNNER_CLASS, VALUE_TEST_RUNNER_CLASS); + paras.emplace(KEY_TEST_CASE, VALUE_TEST_CASE); + paras.emplace(KEY_TEST_WAIT_TIMEOUT, VALUE_TEST_WAIT_TIMEOUT); + + Want want; + for (auto para : paras) { + want.SetParam(para.first, para.second); + } + std::shared_ptr abilityArgs = std::make_shared(want); + + std::unique_ptr runtime = static_cast>(std::move(runtime_)); + std::unique_ptr testRunner = TestRunner::Create( + runtime, + abilityArgs, + true); +} diff --git a/test/unittest/cj_ui_ability_test/BUILD.gn b/test/unittest/cj_ui_ability_test/BUILD.gn new file mode 100644 index 0000000000..01f6d2b5ef --- /dev/null +++ b/test/unittest/cj_ui_ability_test/BUILD.gn @@ -0,0 +1,113 @@ +# 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") + +ohos_unittest("cj_ui_ability_test") { + module_out_path = "ability_runtime/cj_ui_ability_test" + include_dirs = [ + "${ability_runtime_test_path}/mock/common/include", + "${resource_management_path}/frameworks/resmgr/include", + "${ability_runtime_path}/utils/global/freeze", + "${ability_runtime_path}/utils/global/freeze/include/freeze_util.h", + "${ability_runtime_path}/interfaces/kits/native/ability/native/ability_runtime", + "${ability_base_kits_path}/configuration/include", + "${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/ability/native", + "${ability_runtime_path}/interfaces/inner_api/runtime/include", + "${ability_runtime_native_path}/runtime", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + sources = [ + "${ability_runtime_native_path}/appkit/app/ability_record_mgr.cpp", + "${ability_runtime_native_path}/appkit/app/app_context.cpp", + "${ability_runtime_native_path}/appkit/app/app_loader.cpp", + "${ability_runtime_native_path}/appkit/app/application_cleaner.cpp", + "${ability_runtime_native_path}/appkit/app/ohos_application.cpp", + "cj_ui_ability_test.cpp", + "mock_lifecycle_observer.cpp", + "mock_lifecycle_observer.h", + ] + + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${ability_runtime_native_path}/ability:ability_context_native", + "${ability_runtime_native_path}/ability/native:ability_thread", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:insight_intent_executor", + "${ability_runtime_native_path}/ability/native:uiabilitykit_native", + "${ability_runtime_native_path}/appkit:app_context", + "${ability_runtime_native_path}/appkit:appkit_delegator", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_native_path}/insight_intent/insight_intent_context:insightintentcontext", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_services_path}/common:event_report", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "${global_path}/resource_management/frameworks/resmgr:global_resmgr", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:session_info", + "ability_base:want", + "ability_runtime:ability_context_native", + "ability_runtime:runtime", + "ability_runtime:wantagent_innerkits", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "napi:cj_bind_ffi", + "napi:cj_bind_native", + "window_manager:cj_window_ffi", + "window_manager:scene_session", + ] + + if (ability_runtime_graphics) { + external_deps += [ + "image_framework:image_native", + "input:libmmi-client", + "window_manager:libwm", + ] + } + + defines = [ "CONFIG_HILOG" ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_ui_ability_test" ] +} diff --git a/test/unittest/cj_ui_ability_test/cj_ui_ability_test.cpp b/test/unittest/cj_ui_ability_test/cj_ui_ability_test.cpp new file mode 100644 index 0000000000..c2b39dac2e --- /dev/null +++ b/test/unittest/cj_ui_ability_test/cj_ui_ability_test.cpp @@ -0,0 +1,827 @@ +/* + * 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 "cj_ui_ability.h" +#include "ui_ability.h" + +#include "insight_intent_executor_info.h" +#include "ability_context_impl.h" +#include "ability_handler.h" +#include "ability_recovery.h" +#include "ability_local_record.h" +#include "cj_ability_object.h" +#include "cj_runtime.h" +#include "hilog_wrapper.h" +#include "int_wrapper.h" +#include "mock_lifecycle_observer.h" +#include "ohos_application.h" +#include "runtime.h" +#include "string_wrapper.h" +#include "ability_context_impl.h" + +using namespace testing; +using namespace testing::ext; + +namespace { +const std::string TEST_BUNDLE_NANE = "test.bundleName"; +const std::string TEST_MODULE_NANE = "test.entry"; +const std::string TEST_ABILITY_NANE = "test.abilityName"; +const std::string TEST_CALLER_BUNDLE_NANE = "test.callerBundleName"; +const std::string TEST_PLAY_MUSIC = "PlayMusic"; +const std::string ABILITY_STAGE_MONITOR_SRC_ENTRANCE = "MainAbility"; +const std::string KEY_TEST_BUNDLE_NAME = "-p"; +const std::string VALUE_TEST_BUNDLE_NAME = "com.example.myapplication"; +const std::string CHANGE_VALUE_TEST_BUNDLE_NAME = "com.example.myapplication1"; +const std::string KEY_TEST_RUNNER_CLASS = "-s unittest"; +const std::string VALUE_TEST_RUNNER_CLASS = "JSUserTestRunner"; +const std::string CHANGE_VALUE_TEST_RUNNER_CLASS = "JSUserTestRunner1"; +const std::string KEY_TEST_CASE = "-s class"; +const std::string VALUE_TEST_CASE = "ohos.acts.aafwk.ability.test.ConstructorTest#testDataAbilityOtherFunction0010"; +const std::string CHANGE_VALUE_TEST_CASE = + "ohos.acts.aafwk.ability.test.ConstructorTest#testDataAbilityOtherFunction00101"; +const std::string KEY_TEST_WAIT_TIMEOUT = "-w"; +const std::string VALUE_TEST_WAIT_TIMEOUT = "50"; +const std::string CHANGE_VALUE_TEST_WAIT_TIMEOUT = "80"; +const std::string SET_VALUE_TEST_BUNDLE_NAME = "com.example.myapplicationset"; +const std::string ABILITY_NAME = "com.example.myapplication.MainAbility"; +const std::string FINISH_MSG = "finish message"; +const int32_t FINISH_RESULT_CODE = 144; +const std::string PRINT_MSG = "print aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const int ZERO = 0; +const int ONE = 1; +const int TWO = 2; +const int64_t TIMEOUT = 50; +const std::string CMD = "ls -l"; +const std::string KEY_TEST_DEBUG{"-D"}; +const std::string VALUE_TEST_DEBUG{"true"}; +const std::string ABILITY_STAGE_MONITOR_MODULE_NAME{"entry"}; +} // namespace + +namespace OHOS { +namespace AppExecFwk { +namespace { +constexpr char CJ_UI_ABILITY[] = "cjUIAbility"; +constexpr char DEFAULT_LANGUAGE[] = "zh_CN"; +} // namespace +class CjUIAbilityTest : public testing::Test { +public: + CjUIAbilityTest() + {} + ~CjUIAbilityTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override; + void TearDown() override; + std::shared_ptr cjAbility_ = nullptr; +}; + +void PreSetCJAbilityStageFuncs() +{ + auto registerFunc = [](CJAbilityFuncs *funcs) { + funcs->cjAbilityCreate = [](const char *name) -> int64_t { return 1; }; + funcs->cjAbilityRelease = [](int64_t id) {}; + funcs->cjAbilityOnStart = [](int64_t id, WantHandle want, CJLaunchParam launchParam) {}; + funcs->cjAbilityOnStop = [](int64_t id) {}; + funcs->cjAbilityOnSceneCreated = [](int64_t id, WindowStagePtr cjWindowStage) {}; + funcs->cjAbilityOnSceneRestored = [](int64_t id, WindowStagePtr cjWindowStage) {}; + funcs->cjAbilityOnSceneDestroyed = [](int64_t id) {}; + funcs->cjAbilityOnForeground = [](int64_t id, WantHandle want) {}; + funcs->cjAbilityOnBackground = [](int64_t id) {}; + funcs->cjAbilityOnConfigurationUpdated = [](int64_t id, CJConfiguration configuration) {}; + funcs->cjAbilityOnNewWant = [](int64_t id, WantHandle want, CJLaunchParam launchParam) {}; + funcs->cjAbilityDump = [](int64_t id, VectorStringHandle params) { return VectorStringHandle(); }; + funcs->cjAbilityOnContinue = [](int64_t id, const char *params) { return 0; }; + funcs->cjAbilityInit = [](int64_t id, void *ability) {}; + }; + RegisterCJAbilityFuncs(registerFunc); +} + +void CjUIAbilityTest::SetUpTestCase(void) +{} + +void CjUIAbilityTest::TearDownTestCase(void) +{} + +void CjUIAbilityTest::SetUp(void) +{ + auto cjAbilityRuntime = std::make_unique(); + cjAbility_ = std::make_shared(*(cjAbilityRuntime.get())); +} + +void CjUIAbilityTest::TearDown(void) +{} + +/** + * @tc.number: CJRuntime_Init_0100 + */ +HWTEST_F(CjUIAbilityTest, CJRuntime_Init_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "CJRuntime_Init_0100 start"; + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "CJUIability"; + std::shared_ptr application = std::make_shared(); + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + std::shared_ptr handler = std::make_shared(eventRunner); + sptr token = nullptr; + cjAbility_->Init(nullptr, application, handler, token); + + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + cjAbility_->Init(abilityLocalRecord, application, handler, token); + + abilityInfo->isModuleJson = true; + abilityLocalRecord = std::make_shared(abilityInfo, token); + cjAbility_->Init(abilityLocalRecord, application, handler, token); + + GTEST_LOG_(INFO) << "CJRuntime_Init_0100 end"; +} + +/** + * @tc.number: CJUIAbility_Create_0100 + * @tc.name: CJUIAbility_Create_0100 + */ +HWTEST_F(CjUIAbilityTest, CJUIAbility_Create_0100, TestSize.Level1) +{ + AbilityRuntime::Runtime::Options options; + options.lang = AbilityRuntime::Runtime::Language::CJ; + auto runtime = AbilityRuntime::Runtime::Create(options); + auto ability = AbilityRuntime::CJUIAbility::Create(runtime); + EXPECT_NE(ability, nullptr); +} + +/** + * @tc.number: CJUIAbility_Create_0200 + * @tc.name: CJUIAbility_Create_0200 + */ +HWTEST_F(CjUIAbilityTest, CJUIAbility_Create_0200, TestSize.Level1) +{ + auto ability = AbilityRuntime::CJUIAbility::Create(nullptr); + EXPECT_NE(ability, nullptr); +} + +/** + * @tc.number: CJRuntime_OnNewWant_0100 + * @tc.name: OnNewWant + * @tc.desc: Test whether onnewwant can be called normally. + */ +HWTEST_F(CjUIAbilityTest, CJRuntime_OnNewWant_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "CJRuntime_OnNewWant_0100 start"; + std::shared_ptr abilityInfo = std::make_shared(); + std::shared_ptr application = std::make_shared(); + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + std::shared_ptr handler = std::make_shared(eventRunner); + sptr token = nullptr; + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + cjAbility_->Init(abilityLocalRecord, application, handler, token); + Want want; + cjAbility_->OnNewWant(want); + GTEST_LOG_(INFO) << "CJRuntime_OnNewWant_0100 end"; +} + +HWTEST_F(CjUIAbilityTest, CJRuntime_OnStart_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "CJRuntime_OnStart_0100 start"; + std::shared_ptr abilityInfo = std::make_shared(); + AbilityType type = AbilityType::PAGE; + abilityInfo->type = type; + abilityInfo->isStageBasedModel = true; + std::shared_ptr application = nullptr; + std::shared_ptr handler = nullptr; + sptr token = nullptr; + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + cjAbility_->Init(abilityLocalRecord, application, handler, token); + Want want; + cjAbility_->OnStart(want); + GTEST_LOG_(INFO) << "CJRuntime_OnStart_0100 end"; +} + +/** + * @tc.number: CJRuntime_OnStart_0300 + * @tc.name: OnStart + * @tc.desc: Test the OnStart exception. + */ +HWTEST_F(CjUIAbilityTest, CJRuntime_OnStart_0300, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "CJRuntime_OnStart_0300 start"; + Want want; + cjAbility_->OnStart(want); + AbilityLifecycleExecutor::LifecycleState state = cjAbility_->GetState(); + std::shared_ptr lifeCycle = cjAbility_->GetLifecycle(); + EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED, state); + EXPECT_EQ(nullptr, lifeCycle); + GTEST_LOG_(INFO) << "CJRuntime_OnStart_0300 end"; +} + +/** + * @tc.number: CJRuntime_OnStop_0100 + * @tc.name: OnStop + * @tc.desc: Test whether onstop is called normally and verify whether the members are correct. + */ +HWTEST_F(CjUIAbilityTest, CJRuntime_OnStop_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "CJRuntime_OnStop_0100 start"; + std::shared_ptr abilityInfo = std::make_shared(); + AbilityType type = AbilityType::PAGE; + abilityInfo->type = type; + std::shared_ptr application = nullptr; + std::shared_ptr handler = nullptr; + sptr token = nullptr; + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + cjAbility_->Init(abilityLocalRecord, application, handler, token); + cjAbility_->OnStop(); + AbilityLifecycleExecutor::LifecycleState state = cjAbility_->GetState(); + std::shared_ptr lifeCycle = cjAbility_->GetLifecycle(); + LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState(); + EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::INITIAL, state); + EXPECT_EQ(LifeCycle::Event::ON_STOP, lifeCycleState); + GTEST_LOG_(INFO) << "CJRuntime_OnStop_0100 end"; +} + +/** + * @tc.number: CJRuntime_OnBackground_0300 + * @tc.name: OnBackground + * @tc.desc: Test the OnBackground exception. + */ +HWTEST_F(CjUIAbilityTest, CJRuntime_OnBackground_0300, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "CJRuntime_OnBackground_0300 start"; + std::shared_ptr abilityInfo = std::make_shared(); + AbilityType type = AbilityType::PAGE; + abilityInfo->type = type; + abilityInfo->isStageBasedModel = true; + std::shared_ptr application = nullptr; + std::shared_ptr handler = nullptr; + sptr token = nullptr; + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + cjAbility_->Init(abilityLocalRecord, application, handler, token); + cjAbility_->OnBackground(); + AbilityLifecycleExecutor::LifecycleState state = cjAbility_->GetState(); + std::shared_ptr lifeCycle = cjAbility_->GetLifecycle(); + LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState(); + // Sence is nullptr, so lifecycle schedule failed. + EXPECT_NE(AbilityLifecycleExecutor::LifecycleState::INITIAL, state); + EXPECT_NE(LifeCycle::Event::UNDEFINED, lifeCycleState); + GTEST_LOG_(INFO) << "CJRuntime_OnBackground_0300 end"; +} + +/** + * @tc.name: cjUIAbilityCreate_0100 + * @tc.desc: UIAbility create test. + * @tc.type: FUNC + */ +HWTEST_F(CjUIAbilityTest, cjUIAbilityCreate_0100, TestSize.Level1) +{ + AbilityRuntime::Runtime::Options options; + auto runtime = AbilityRuntime::Runtime::Create(options); + auto ability = AbilityRuntime::CJUIAbility::Create(runtime); + EXPECT_NE(ability, nullptr); + AbilityRuntime::Runtime::Options anotherOptions; + anotherOptions.lang = static_cast(100); // invalid Runtime::Language + auto anotherRuntime = AbilityRuntime::Runtime::Create(anotherOptions); + auto anotherAbility = AbilityRuntime::CJUIAbility::Create(anotherRuntime); + EXPECT_NE(anotherAbility, nullptr); +} + +/** + * @tc.name: CJUIAbilityOnStop_0100 + * @tc.desc: CJUIAbility onStop test. + * @tc.type: FUNC + */ +HWTEST_F(CjUIAbilityTest, CJUIAbilityOnStop_0100, TestSize.Level1) +{ + bool isAsyncCallback = true; + cjAbility_->OnStop(nullptr, isAsyncCallback); + cjAbility_->OnStopCallback(); + EXPECT_EQ(isAsyncCallback, false); +} + +/** + * @tc.name: CJUIAbilityOnMemoryLevel_0100 + * @tc.desc: CJUIAbility OnMemoryLevel test. + * @tc.type: FUNC + */ +HWTEST_F(CjUIAbilityTest, CJUIAbilityOnMemoryLevel_0100, TestSize.Level1) +{ + int level = 0; + cjAbility_->OnMemoryLevel(level); + auto contentInfo = cjAbility_->GetContentInfo(); + EXPECT_EQ(contentInfo, ""); +} + +/** + * @tc.number: CJUIAbility_OnStop_AsyncCallback_0100 + * @tc.name: OnStop_AsyncCallback + * @tc.desc: Verify OnStop with AsyncCallback. + */ +HWTEST_F(CjUIAbilityTest, CJUIAbility_OnStop_AsyncCallback_0100, TestSize.Level1) +{ + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->type = AbilityType::PAGE; + std::shared_ptr application = nullptr; + std::shared_ptr handler = nullptr; + sptr token = nullptr; + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + cjAbility_->Init(abilityLocalRecord, application, handler, token); + bool isAsyncCallback = false; + cjAbility_->OnStop(nullptr, isAsyncCallback); + AbilityLifecycleExecutor::LifecycleState state = cjAbility_->GetState(); + std::shared_ptr lifeCycle = cjAbility_->GetLifecycle(); + LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState(); + auto *callbackInfo = AbilityTransactionCallbackInfo<>::Create(); + cjAbility_->OnStop(callbackInfo, isAsyncCallback); + EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::INITIAL, state); + EXPECT_EQ(LifeCycle::Event::ON_STOP, lifeCycleState); +} + +/** + * @tc.number: CJUIAbility_GetCJAbility_0100 + * @tc.name: GetCJAbility + */ +HWTEST_F(CjUIAbilityTest, CJUIAbility_GetCJAbility_0100, TestSize.Level1) +{ + std::shared_ptr ptr = cjAbility_->GetCJAbility(); + EXPECT_EQ(ptr, nullptr); +} + +/** + * @tc.number: CJUIAbility_OnShare_0100 + * @tc.name: OnShare + */ +HWTEST_F(CjUIAbilityTest, CJUIAbility_OnShare_0100, TestSize.Level1) +{ + WantParams data; + int32_t ret = cjAbility_->OnShare(data); + EXPECT_EQ(ERR_OK, ret); +} + +#ifdef SUPPORT_GRAPHICS +/** + * @tc.name: CJUIAbilityScene_0100 + * @tc.desc: CJUIAbility Scene test + * @tc.type: FUNC + */ +HWTEST_F(CjUIAbilityTest, CJUIAbilityScene_0100, TestSize.Level1) +{ + ASSERT_NE(cjAbility_, nullptr); + cjAbility_->OnSceneCreated(); + cjAbility_->OnSceneRestored(); + cjAbility_->onSceneDestroyed(); + auto scene = cjAbility_->GetScene(); + EXPECT_EQ(scene, nullptr); +} + +/** + * @tc.number: CJRuntime_OnForeground_0100 + * @tc.name: OnForeground + * @tc.desc: Test whether onforegroup is called normally, and verify whether the member is correct. + */ +HWTEST_F(CjUIAbilityTest, CJRuntime_OnForeground_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "CJRuntime_OnForeground_0100 start"; + std::shared_ptr abilityInfo = std::make_shared(); + AbilityType type = AbilityType::PAGE; + abilityInfo->type = type; + std::shared_ptr application = nullptr; + std::shared_ptr handler = nullptr; + sptr token = nullptr; + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + cjAbility_->Init(abilityLocalRecord, application, handler, token); + Want want; + cjAbility_->OnForeground(want); + AbilityLifecycleExecutor::LifecycleState state = cjAbility_->GetState(); + std::shared_ptr lifeCycle = cjAbility_->GetLifecycle(); + LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState(); + EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::FOREGROUND_NEW, state); + EXPECT_EQ(LifeCycle::Event::ON_FOREGROUND, lifeCycleState); + GTEST_LOG_(INFO) << "CJRuntime_OnForeground_0100 end"; +} + +/** + * @tc.number: CJRuntime_OnForeground_0200 + * @tc.name: OnForeground + * @tc.desc: Test the OnInactive exception. + */ +HWTEST_F(CjUIAbilityTest, CJRuntime_OnForeground_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "CJRuntime_OnForeground_0200 start"; + Want want; + cjAbility_->OnForeground(want); + AbilityLifecycleExecutor::LifecycleState state = cjAbility_->GetState(); + std::shared_ptr lifeCycle = cjAbility_->GetLifecycle(); + EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::UNINITIALIZED, state); + EXPECT_EQ(nullptr, lifeCycle); + GTEST_LOG_(INFO) << "CJRuntime_OnForeground_0200 end"; +} + +/** + * @tc.number: CJRuntime_OnForeground_0300 + * @tc.name: OnForeground + * @tc.desc: Test the OnForeground exception. + */ +HWTEST_F(CjUIAbilityTest, CJRuntime_OnForeground_0300, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "CJRuntime_OnForeground_0300 start"; + std::shared_ptr abilityInfo = std::make_shared(); + AbilityType type = AbilityType::PAGE; + abilityInfo->type = type; + abilityInfo->isStageBasedModel = true; + std::shared_ptr application = nullptr; + std::shared_ptr handler = nullptr; + sptr token = nullptr; + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + cjAbility_->Init(abilityLocalRecord, application, handler, token); + Want want; + cjAbility_->OnForeground(want); + AbilityLifecycleExecutor::LifecycleState state = cjAbility_->GetState(); + std::shared_ptr lifeCycle = cjAbility_->GetLifecycle(); + LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState(); + EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::FOREGROUND_NEW, state); + EXPECT_EQ(LifeCycle::Event::ON_FOREGROUND, lifeCycleState); + GTEST_LOG_(INFO) << "CJRuntime_OnForeground_0300 end"; +} + +/** + * @tc.name: CJUIAbilityVirtualFunc_0100 + * @tc.desc: CJUIAbility virtual function test, such as OnAbilityResult, IsTerminating and so on. + * @tc.type: FUNC + */ +HWTEST_F(CjUIAbilityTest, CJUIAbilityVirtualFunc_0100, TestSize.Level1) +{ + // ability window is nullptr + Want want; + cjAbility_->RequestFocus(want); + std::shared_ptr pageAbilityInfo = std::make_shared(); + pageAbilityInfo->type = AppExecFwk::AbilityType::PAGE; + pageAbilityInfo->isStageBasedModel = true; + auto eventRunner = EventRunner::Create(pageAbilityInfo->name); + auto handler = std::make_shared(eventRunner); + std::shared_ptr abilityLocalRecord = + std::make_shared(pageAbilityInfo, nullptr); + cjAbility_->Init(abilityLocalRecord, nullptr, handler, nullptr); + cjAbility_->UpdateContextConfiguration(); + int requestCode = 0; + int resultCode = 0; + cjAbility_->OnAbilityResult(requestCode, resultCode, want); + std::vector params; + std::vector info; + cjAbility_->Dump(params, info); +} + +/** + * @tc.name: CJUIAbilityVirtualFunc_0200 + * @tc.desc: CJUIAbility virtual function test, such as OnStartContinuation, OnSaveData and so on. + * @tc.type: FUNC + */ +HWTEST_F(CjUIAbilityTest, CJUIAbilityVirtualFunc_0200, TestSize.Level1) +{ + bool ret = cjAbility_->OnStartContinuation(); + EXPECT_EQ(ret, false); + WantParams data; + ret = cjAbility_->OnSaveData(data); + EXPECT_EQ(ret, false); + ret = cjAbility_->OnRestoreData(data); + EXPECT_EQ(ret, false); + int onContinueRet = cjAbility_->OnContinue(data); + int32_t reason = 0; + EXPECT_EQ(cjAbility_->OnSaveState(reason, data), 0); + int result = 0; + cjAbility_->OnCompleteContinuation(result); + cjAbility_->OnRemoteTerminated(); + sptr ptr = cjAbility_->CallRequest(); + EXPECT_EQ(ptr, nullptr); +} + +/** + * @tc.name: CJUIAbilityRequestFocus_0100 + * @tc.desc: CJUIAbility RequestFocus test + * @tc.type: FUNC + */ +HWTEST_F(CjUIAbilityTest, CJUIAbilityRequestFocus_0100, TestSize.Level1) +{ + // ability window is nullptr + Want want; + cjAbility_->RequestFocus(want); + std::shared_ptr pageAbilityInfo = std::make_shared(); + pageAbilityInfo->type = AppExecFwk::AbilityType::PAGE; + pageAbilityInfo->isStageBasedModel = true; + auto eventRunner = EventRunner::Create(pageAbilityInfo->name); + auto handler = std::make_shared(eventRunner); + std::shared_ptr abilityLocalRecord = + std::make_shared(pageAbilityInfo, nullptr); + cjAbility_->Init(abilityLocalRecord, nullptr, handler, nullptr); + + // window is nullptr + cjAbility_->RequestFocus(want); + int32_t displayId = 0; + sptr option = new Rosen::WindowOption(); + cjAbility_->InitWindow(displayId, option); + cjAbility_->RequestFocus(want); +} + +/** + * @tc.number: CJRuntime_OnBackground_0100 + * @tc.name: OnBackground + * @tc.desc: Test whether onbackground is called normally and verify whether the members are correct. + */ +HWTEST_F(CjUIAbilityTest, CJRuntime_OnBackground_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "CJRuntime_OnBackground_0100 start"; + std::shared_ptr abilityInfo = std::make_shared(); + AbilityType type = AbilityType::PAGE; + abilityInfo->type = type; + std::shared_ptr application = nullptr; + std::shared_ptr handler = nullptr; + sptr token = nullptr; + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + cjAbility_->Init(abilityLocalRecord, application, handler, token); + cjAbility_->OnBackground(); + AbilityLifecycleExecutor::LifecycleState state = cjAbility_->GetState(); + std::shared_ptr lifeCycle = cjAbility_->GetLifecycle(); + LifeCycle::Event lifeCycleState = lifeCycle->GetLifecycleState(); + EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::BACKGROUND_NEW, state); + EXPECT_EQ(LifeCycle::Event::ON_BACKGROUND, lifeCycleState); + GTEST_LOG_(INFO) << "CJRuntime_OnBackground_0100 end"; +} + +/** + * @tc.number: CJRuntime_OnBackground_0200 + * @tc.name: OnBackground + * @tc.desc: Test the OnBackground exception. + */ +HWTEST_F(CjUIAbilityTest, CJRuntime_OnBackground_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "CJRuntime_OnBackground_0200 start"; + std::shared_ptr abilityInfo = std::make_shared(); + std::shared_ptr application = nullptr; + std::shared_ptr handler = nullptr; + sptr token = nullptr; + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + cjAbility_->Init(abilityLocalRecord, application, handler, token); + cjAbility_->OnBackground(); + AbilityLifecycleExecutor::LifecycleState state = cjAbility_->GetState(); + std::shared_ptr lifeCycle = cjAbility_->GetLifecycle(); + EXPECT_EQ(AbilityLifecycleExecutor::LifecycleState::BACKGROUND_NEW, state); + EXPECT_TRUE(lifeCycle); + GTEST_LOG_(INFO) << "CJRuntime_OnBackground_0200 end"; +} + +/** + * @tc.number: CJUIAbility_OnBackPress_0100 + * @tc.name: OnBackPress + */ +HWTEST_F(CjUIAbilityTest, CJUIAbility_OnBackPress_0100, TestSize.Level1) +{ + bool ret = cjAbility_->OnBackPress(); + EXPECT_TRUE(ret); +} + +/** + * @tc.number: CJUIAbility_OnPrepareTerminate_0100 + * @tc.name: OnPrepareTerminate + */ +HWTEST_F(CjUIAbilityTest, CJUIAbility_OnPrepareTerminate_0100, TestSize.Level1) +{ + bool ret = cjAbility_->OnPrepareTerminate(); + EXPECT_TRUE(ret); +} + +HWTEST_F(CjUIAbilityTest, InitedCJUIAbilityTest_0100, TestSize.Level1) +{ + auto abilityRuntime = std::make_unique(); + std::shared_ptr initedCJUIAbility_ = + std::make_shared(*(abilityRuntime.get())); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "CJUIability"; + std::shared_ptr application = std::make_shared(); + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + std::shared_ptr handler = std::make_shared(eventRunner); + sptr token = nullptr; + abilityInfo->isModuleJson = false; + PreSetCJAbilityStageFuncs(); + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + initedCJUIAbility_->Init(abilityLocalRecord, application, handler, token); + + Want want; + initedCJUIAbility_->OnStart(want); + initedCJUIAbility_->OnStop(); +} + +HWTEST_F(CjUIAbilityTest, InitedCJUIAbilityTest_0200, TestSize.Level1) +{ + auto abilityRuntime = std::make_unique(); + std::shared_ptr initedCJUIAbility_ = + std::make_shared(*(abilityRuntime.get())); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "CJUIability"; + std::shared_ptr application = std::make_shared(); + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + std::shared_ptr handler = std::make_shared(eventRunner); + sptr token = nullptr; + abilityInfo->isModuleJson = false; + PreSetCJAbilityStageFuncs(); + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + initedCJUIAbility_->Init(abilityLocalRecord, application, handler, token); + + Want want; + + std::shared_ptr initedPtr = initedCJUIAbility_->GetCJAbility(); + EXPECT_NE(initedPtr, nullptr); + + initedCJUIAbility_->OnSceneCreated(); + initedCJUIAbility_->OnSceneRestored(); + initedCJUIAbility_->onSceneDestroyed(); + + initedCJUIAbility_->OnForeground(want); +} + +HWTEST_F(CjUIAbilityTest, InitedCJUIAbilityTest_0300, TestSize.Level1) +{ + auto abilityRuntime = std::make_unique(); + std::shared_ptr initedCJUIAbility_ = + std::make_shared(*(abilityRuntime.get())); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "CJUIability"; + std::shared_ptr application = std::make_shared(); + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + std::shared_ptr handler = std::make_shared(eventRunner); + sptr token = nullptr; + abilityInfo->isModuleJson = false; + PreSetCJAbilityStageFuncs(); + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + initedCJUIAbility_->Init(abilityLocalRecord, application, handler, token); + + Want want; + int requestCode = 0; + int resultCode = 0; + initedCJUIAbility_->OnAbilityResult(requestCode, resultCode, want); + std::vector params; + std::vector info; + initedCJUIAbility_->Dump(params, info); +} + +HWTEST_F(CjUIAbilityTest, InitedCJUIAbilityTest_0400, TestSize.Level1) +{ + auto abilityRuntime = std::make_unique(); + std::shared_ptr initedCJUIAbility_ = + std::make_shared(*(abilityRuntime.get())); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "CJUIability"; + std::shared_ptr application = std::make_shared(); + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + std::shared_ptr handler = std::make_shared(eventRunner); + sptr token = nullptr; + abilityInfo->isModuleJson = false; + PreSetCJAbilityStageFuncs(); + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + initedCJUIAbility_->Init(abilityLocalRecord, application, handler, token); + + Want want; + WantParams data; + int continueRet = initedCJUIAbility_->OnContinue(data); + + initedCJUIAbility_->OnBackground(); + + std::map paras; + paras.emplace(KEY_TEST_BUNDLE_NAME, VALUE_TEST_BUNDLE_NAME); + paras.emplace(KEY_TEST_RUNNER_CLASS, VALUE_TEST_RUNNER_CLASS); + paras.emplace(KEY_TEST_CASE, VALUE_TEST_CASE); + paras.emplace(KEY_TEST_WAIT_TIMEOUT, VALUE_TEST_WAIT_TIMEOUT); + + for (auto para : paras) { + want.SetParam(para.first, para.second); + } + + initedCJUIAbility_->GetCJRuntime(); + initedCJUIAbility_->RequestFocus(want); +} + +HWTEST_F(CjUIAbilityTest, InitedCJUIAbilityTest_0500, TestSize.Level1) +{ + auto abilityRuntime = std::make_unique(); + std::shared_ptr initedCJUIAbility_ = + std::make_shared(*(abilityRuntime.get())); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "CJUIability"; + std::shared_ptr application = std::make_shared(); + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + std::shared_ptr handler = std::make_shared(eventRunner); + sptr token = nullptr; + abilityInfo->isModuleJson = false; + PreSetCJAbilityStageFuncs(); + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + initedCJUIAbility_->Init(abilityLocalRecord, application, handler, token); + + Want want; + + WantParams data; + int continueRet = initedCJUIAbility_->OnContinue(data); + + initedCJUIAbility_->OnBackground(); + + std::map paras; + paras.emplace(KEY_TEST_BUNDLE_NAME, VALUE_TEST_BUNDLE_NAME); + paras.emplace(KEY_TEST_RUNNER_CLASS, VALUE_TEST_RUNNER_CLASS); + paras.emplace(KEY_TEST_CASE, VALUE_TEST_CASE); + paras.emplace(KEY_TEST_WAIT_TIMEOUT, VALUE_TEST_WAIT_TIMEOUT); + + for (auto para : paras) { + want.SetParam(para.first, para.second); + } + + std::string test = "test"; + auto callback = std::make_unique(); + initedCJUIAbility_->ExecuteInsightIntentRepeateForeground(want, nullptr, std::move(callback)); +} + +HWTEST_F(CjUIAbilityTest, InitedCJUIAbilityTest_0600, TestSize.Level1) +{ + auto abilityRuntime = std::make_unique(); + std::shared_ptr initedCJUIAbility_ = + std::make_shared(*(abilityRuntime.get())); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "CJUIability"; + std::shared_ptr application = std::make_shared(); + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + std::shared_ptr handler = std::make_shared(eventRunner); + sptr token = nullptr; + abilityInfo->isModuleJson = false; + PreSetCJAbilityStageFuncs(); + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + initedCJUIAbility_->Init(abilityLocalRecord, application, handler, token); + + Want want; + + std::map paras; + paras.emplace(KEY_TEST_BUNDLE_NAME, VALUE_TEST_BUNDLE_NAME); + paras.emplace(KEY_TEST_RUNNER_CLASS, VALUE_TEST_RUNNER_CLASS); + paras.emplace(KEY_TEST_CASE, VALUE_TEST_CASE); + paras.emplace(KEY_TEST_WAIT_TIMEOUT, VALUE_TEST_WAIT_TIMEOUT); + + for (auto para : paras) { + want.SetParam(para.first, para.second); + } + + initedCJUIAbility_->OnSceneCreated(); + initedCJUIAbility_->OnSceneRestored(); + initedCJUIAbility_->OnSceneDestroyed(); +} + +HWTEST_F(CjUIAbilityTest, InitedCJUIAbilityTest_0700, TestSize.Level1) +{ + auto abilityRuntime = std::make_unique(); + std::shared_ptr initedCJUIAbility_ = + std::make_shared(*(abilityRuntime.get())); + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "CJUIability"; + std::shared_ptr application = std::make_shared(); + std::shared_ptr eventRunner = EventRunner::Create(abilityInfo->name); + std::shared_ptr handler = std::make_shared(eventRunner); + sptr token = nullptr; + abilityInfo->isModuleJson = false; + PreSetCJAbilityStageFuncs(); + std::shared_ptr abilityLocalRecord = std::make_shared(abilityInfo, token); + initedCJUIAbility_->Init(abilityLocalRecord, application, handler, token); + + Want want; + + std::map paras; + paras.emplace(KEY_TEST_BUNDLE_NAME, VALUE_TEST_BUNDLE_NAME); + paras.emplace(KEY_TEST_RUNNER_CLASS, VALUE_TEST_RUNNER_CLASS); + paras.emplace(KEY_TEST_CASE, VALUE_TEST_CASE); + paras.emplace(KEY_TEST_WAIT_TIMEOUT, VALUE_TEST_WAIT_TIMEOUT); + + for (auto para : paras) { + want.SetParam(para.first, para.second); + } + + initedCJUIAbility_->RequestFocus(want); + + std::shared_ptr abilityContextImpl = + std::make_shared(); + initedCJUIAbility_->AttachAbilityContext(abilityContextImpl); + std::shared_ptr abilityContextRet = initedCJUIAbility_->GetAbilityContext(); + EXPECT_TRUE(abilityContextRet != nullptr); + int requestCode = 0; + int resultCode = 0; + initedCJUIAbility_->OnAbilityResult(requestCode, resultCode, want); + initedCJUIAbility_->OnStop(); +} + +#endif + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/unittest/cj_ui_ability_test/mock_lifecycle_observer.cpp b/test/unittest/cj_ui_ability_test/mock_lifecycle_observer.cpp new file mode 100644 index 0000000000..fd5212cb80 --- /dev/null +++ b/test/unittest/cj_ui_ability_test/mock_lifecycle_observer.cpp @@ -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. + */ + +#include "mock_lifecycle_observer.h" +#include + +namespace OHOS { +namespace AppExecFwk { +void MockLifecycleObserver::OnActive() +{ + GTEST_LOG_(INFO) << "MockLifecycleObserver::OnActive called"; +} + +void MockLifecycleObserver::OnBackground() +{ + GTEST_LOG_(INFO) << "MockLifecycleObserver::OnBackground called"; +} + +void MockLifecycleObserver::OnForeground(const Want& want) +{ + GTEST_LOG_(INFO) << "MockLifecycleObserver::OnForeground called"; +} + +void MockLifecycleObserver::OnInactive() +{ + GTEST_LOG_(INFO) << "MockLifecycleObserver::OnInactive called"; +} + +void MockLifecycleObserver::OnStart(const Want& want) +{ + GTEST_LOG_(INFO) << "MockLifecycleObserver::OnStart called"; +} + +void MockLifecycleObserver::OnStop() +{ + GTEST_LOG_(INFO) << "MockLifecycleObserver::OnStop called"; +} + +void MockLifecycleObserver::OnStateChanged(LifeCycle::Event event, const Want& want) +{ + GTEST_LOG_(INFO) << "MockLifecycleObserver::OnStateChanged called"; +} + +void MockLifecycleObserver::OnStateChanged(LifeCycle::Event event) +{ + GTEST_LOG_(INFO) << "MockLifecycleObserver::OnStateChanged called"; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/unittest/cj_ui_ability_test/mock_lifecycle_observer.h b/test/unittest/cj_ui_ability_test/mock_lifecycle_observer.h new file mode 100644 index 0000000000..11d51f7dba --- /dev/null +++ b/test/unittest/cj_ui_ability_test/mock_lifecycle_observer.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 MOCK_OHOS_ABILITY_RUNTIME_MOCK_LIFECYCLE_OBSERVER_H +#define MOCK_OHOS_ABILITY_RUNTIME_MOCK_LIFECYCLE_OBSERVER_H + +#include "ability_lifecycle_observer_interface.h" +#include "ability_lifecycle.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; + +class MockLifecycleObserver : public ILifecycleObserver { +public: + MockLifecycleObserver() = default; + virtual ~MockLifecycleObserver() = default; + + void OnActive() override; + + void OnBackground() override; + + void OnForeground(const Want& want) override; + + void OnInactive() override; + + void OnStart(const Want& want) override; + + void OnStop() override; + + void OnStateChanged(LifeCycle::Event event, const Want& want) override; + + void OnStateChanged(LifeCycle::Event event) override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // MOCK_OHOS_ABILITY_RUNTIME_MOCK_LIFECYCLE_OBSERVER_H diff --git a/test/unittest/cj_utils_ffi_test/BUILD.gn b/test/unittest/cj_utils_ffi_test/BUILD.gn new file mode 100644 index 0000000000..f9f305de94 --- /dev/null +++ b/test/unittest/cj_utils_ffi_test/BUILD.gn @@ -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. + +import("//build/ohos.gni") +import("//build/test.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") + +ohos_unittest("cj_utils_ffi_test") { + module_out_path = "ability_runtime/cj_utils_ffi_test" + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_delegator", + "${ability_runtime_path}/interfaces/kits/native/appkit/app", + "${bundlefwk_path}/interfaces/inner_api/appexecfwk_base/include", + "${ability_runtime_path}/interfaces/inner_api/ability_manager/include", + "${common_event_service_path}/interfaces/inner_api", + "${ability_runtime_path}/interfaces/inner_api/app_manager/include/appmgr", + "${ability_base_path}/interfaces/kits/native/session_info/include", + "${arkui_path}/ace_engine", + "${ability_runtime_path}/interfaces/kits/native/ability/native", + "${ability_runtime_path}/frameworks/cj/ffi", + "${ace_engine_path}/frameworks", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + ] + + sources = [ + "${ability_runtime_path}/frameworks/cj/ffi/cj_utils_ffi.cpp", + "cj_utils_ffi_test.cpp", + ] + + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/ability_manager:mission_info", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/ability:ability_context_native", + "${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:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_path}/frameworks/cj/ffi:cj_ability_ffi", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "${global_path}/resource_management/frameworks/resmgr:global_resmgr", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:session_info", + "ability_base:want", + "ability_runtime:ability_context_native", + "ability_runtime:runtime", + "ability_runtime:wantagent_innerkits", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "napi:cj_bind_native", + "window_manager:libwsutils", + "window_manager:scene_session", + ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_utils_ffi_test" ] +} diff --git a/test/unittest/cj_utils_ffi_test/cj_utils_ffi_test.cpp b/test/unittest/cj_utils_ffi_test/cj_utils_ffi_test.cpp new file mode 100644 index 0000000000..6c805fdb23 --- /dev/null +++ b/test/unittest/cj_utils_ffi_test/cj_utils_ffi_test.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 + +#include "cj_utils_ffi.h" + +#include "securec.h" +#include + +using namespace testing; +using namespace testing::ext; + +class CjUtilsFfiTest : public testing::Test { +public: + CjUtilsFfiTest() + {} + ~CjUtilsFfiTest() + {} + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; + +void CjUtilsFfiTest::SetUpTestCase() +{} + +void CjUtilsFfiTest::TearDownTestCase() +{} + +void CjUtilsFfiTest::SetUp() +{} + +void CjUtilsFfiTest::TearDown() +{} + +/** + * @tc.name: CjElementNameFfiTestContext_0100 + * @tc.desc: CjUtilsFfiTest test for CreateCStringFromString. + * @tc.type: FUNC + */ +HWTEST_F(CjUtilsFfiTest, CjUtilsFfiTestCreateCStringFromString_0100, TestSize.Level1) +{ + // 测试用例1:空字符串 + std::string emptyStr = ""; + const char* result1 = CreateCStringFromString(emptyStr); + EXPECT_TRUE(result1 == nullptr); + + // 测试用例2:正常字符串 + std::string normalStr = "Hello, world!"; + const char* result2 = CreateCStringFromString(normalStr); + EXPECT_TRUE(result2 != nullptr); + + // 测试用例3:包含特殊字符的字符串 + std::string specialStr = "Hello, \0world!"; + const char* result3 = CreateCStringFromString(specialStr); + EXPECT_TRUE(result3 != nullptr); +} \ No newline at end of file diff --git a/test/unittest/cj_want_ffi_test/BUILD.gn b/test/unittest/cj_want_ffi_test/BUILD.gn new file mode 100644 index 0000000000..ac58d3c664 --- /dev/null +++ b/test/unittest/cj_want_ffi_test/BUILD.gn @@ -0,0 +1,80 @@ +# 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") + +ohos_unittest("cj_want_ffi_test") { + module_out_path = "ability_runtime/cj_want_ffi_test" + include_dirs = [ "${ability_runtime_path}/frameworks/cj/ffi" ] + + sources = [ + "${ability_runtime_path}/frameworks/cj/ffi/cj_want_ffi.cpp", + "cj_want_ffi_test.cpp", + ] + + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/ability_manager:mission_info", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/ability:ability_context_native", + "${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:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_path}/frameworks/cj/ffi:cj_ability_ffi", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "${global_path}/resource_management/frameworks/resmgr:global_resmgr", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:session_info", + "ability_base:want", + "ability_runtime:ability_context_native", + "ability_runtime:runtime", + "ability_runtime:wantagent_innerkits", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "napi:cj_bind_native", + "window_manager:libwsutils", + "window_manager:scene_session", + ] +} + +group("unittest") { + testonly = true + deps = [ ":cj_want_ffi_test" ] +} diff --git a/test/unittest/cj_want_ffi_test/cj_want_ffi_test.cpp b/test/unittest/cj_want_ffi_test/cj_want_ffi_test.cpp new file mode 100644 index 0000000000..2184cf85e0 --- /dev/null +++ b/test/unittest/cj_want_ffi_test/cj_want_ffi_test.cpp @@ -0,0 +1,202 @@ +/* + * 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_want_ffi.h" +#include + +#include +#include +#include +#include + +#include "cj_utils_ffi.h" +#include "want.h" +#include "want_params_wrapper.h" +#include "securec.h" + +using namespace testing; +using namespace testing::ext; +using OHOS::AAFwk::Want; +using OHOS::AppExecFwk::ElementName; + +class CjWantFfiTest : public testing::Test { +public: + CjWantFfiTest() + {} + ~CjWantFfiTest() + {} + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; + +void CjWantFfiTest::SetUpTestCase() +{} + +void CjWantFfiTest::TearDownTestCase() +{} + +void CjWantFfiTest::SetUp() +{} + +void CjWantFfiTest::TearDown() +{} + +/** + * @tc.name: CjWantFfiTestFFICJWantCreateWithWantInfo_0100 + * @tc.desc: CjWantFfiTest test for FFICJWantCreateWithWantInfo. + * @tc.type: FUNC + */ +HWTEST_F(CjWantFfiTest, CjWantFfiTestFFICJWantCreateWithWantInfo_0100, TestSize.Level1) +{ + const char* deviceId = "deviceId"; + const char* bundleName = "bundleName"; + const char* abilityName = "abilityName"; + const char* moduleName = "moduleName"; + ElementNameHandle elementNameHandle = new ElementName(deviceId, bundleName, abilityName, moduleName); + + CJWantParams params; + params.elementName = elementNameHandle; + params.flags = 123; + + params.uri = new char[9]; + strcpy_s(params.uri, 9, "deviceId"); + + params.action = new char[11]; + strcpy_s(params.action, 11, "bundleName"); + + params.wantType = new char[12]; + strcpy_s(params.wantType, 12, "abilityName"); + + params.parameters = new char[11]; + strcpy_s(params.parameters, 11, "moduleName"); + + WantHandle want = FFICJWantCreateWithWantInfo(params); + EXPECT_NE(want, nullptr); +} + +/** + * @tc.name: CjWantFfiTestFFICJWantDelete_0100 + * @tc.desc: CjWantFfiTest test for FFICJWantDelete. + * @tc.type: FUNC + */ +HWTEST_F(CjWantFfiTest, CjWantFfiTestFFICJWantDelete_0100, TestSize.Level1) +{ + const char* deviceId = "deviceId"; + const char* bundleName = "bundleName"; + const char* abilityName = "abilityName"; + const char* moduleName = "moduleName"; + ElementNameHandle elementNameHandle = new ElementName(deviceId, bundleName, abilityName, moduleName); + + CJWantParams params; + params.elementName = elementNameHandle; + params.flags = 123; + + params.uri = new char[9]; + strcpy_s(params.uri, 9, "deviceId"); + + params.action = new char[11]; + strcpy_s(params.action, 11, "bundleName"); + + params.wantType = new char[12]; + strcpy_s(params.wantType, 12, "abilityName"); + + params.parameters = new char[11]; + strcpy_s(params.parameters, 11, "moduleName"); + WantHandle want = FFICJWantCreateWithWantInfo(params); + FFICJWantDelete(want); +} + +/** + * @tc.name: CjWantFfiTestFFICJWantGetWantInfo_0100 + * @tc.desc: CjWantFfiTest test for OnCreate. + * @tc.type: FUNC + */ +HWTEST_F(CjWantFfiTest, CjWantFfiTestFFICJWantGetWantInfo_0100, TestSize.Level1) +{ + const char* deviceId = "deviceId"; + const char* bundleName = "bundleName"; + const char* abilityName = "abilityName"; + const char* moduleName = "moduleName"; + ElementNameHandle elementNameHandle = new ElementName(deviceId, bundleName, abilityName, moduleName); + + CJWantParams params; + params.elementName = elementNameHandle; + params.flags = 123; + + params.uri = new char[9]; + strcpy_s(params.uri, 9, "deviceId"); + + params.action = new char[11]; + strcpy_s(params.action, 11, "bundleName"); + + params.wantType = new char[12]; + strcpy_s(params.wantType, 12, "abilityName"); + + params.parameters = new char[11]; + strcpy_s(params.parameters, 11, "moduleName"); + WantHandle want = FFICJWantCreateWithWantInfo(params); + + CJWantParams* paramsResult = FFICJWantGetWantInfo(want); + EXPECT_NE(paramsResult, nullptr); + FFICJWantParamsDelete(paramsResult); + FFICJWantDelete(reinterpret_cast(want)); +} + +/** + * @tc.name: CjWantFfiTestFFICJWantAddEntity_0100 + * @tc.desc: CjWantFfiTest test for FFICJWantAddEntity. + * @tc.type: FUNC + */ +HWTEST_F(CjWantFfiTest, CjWantFfiTestFFICJWantAddEntity_0100, TestSize.Level1) +{ + const char* deviceId = "deviceId"; + const char* bundleName = "bundleName"; + const char* abilityName = "abilityName"; + const char* moduleName = "moduleName"; + ElementNameHandle elementNameHandle = new ElementName(deviceId, bundleName, abilityName, moduleName); + + CJWantParams params; + params.elementName = elementNameHandle; + params.flags = 123; + + params.uri = new char[9]; + strcpy_s(params.uri, 9, "deviceId"); + + params.action = new char[11]; + strcpy_s(params.action, 11, "bundleName"); + + params.wantType = new char[12]; + strcpy_s(params.wantType, 12, "abilityName"); + + params.parameters = new char[11]; + strcpy_s(params.parameters, 11, "moduleName"); + WantHandle want = FFICJWantCreateWithWantInfo(params); + + const char* entity = "test_entity"; + FFICJWantAddEntity(want, entity); +} + +/** + * @tc.name: CjWantFfiTestFFICJWantParseUri_0100 + * @tc.desc: CjWantFfiTest test for FFICJWantParseUri. + * @tc.type: FUNC + */ +HWTEST_F(CjWantFfiTest, CjWantFfiTestFFICJWantParseUri_0100, TestSize.Level1) +{ + const char* uri = "test_uri"; + WantHandle want = FFICJWantParseUri(uri); +} \ No newline at end of file diff --git a/test/unittest/connect_server_manager_test/connect_server_manager_test.cpp b/test/unittest/connect_server_manager_test/connect_server_manager_test.cpp index 5a3da6ce1e..23caff1356 100644 --- a/test/unittest/connect_server_manager_test/connect_server_manager_test.cpp +++ b/test/unittest/connect_server_manager_test/connect_server_manager_test.cpp @@ -23,7 +23,6 @@ #undef private #undef protected #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing::ext; using namespace testing; using namespace OHOS::AbilityRuntime; diff --git a/test/unittest/connection_observer_test/connection_observer_test.cpp b/test/unittest/connection_observer_test/connection_observer_test.cpp index c01c1400e7..58623fe0cc 100644 --- a/test/unittest/connection_observer_test/connection_observer_test.cpp +++ b/test/unittest/connection_observer_test/connection_observer_test.cpp @@ -25,7 +25,6 @@ #include "connection_observer_client_impl.h" #include "dlp_state_data.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_native_token.h" #include "parcel.h" diff --git a/test/unittest/connection_record_test/BUILD.gn b/test/unittest/connection_record_test/BUILD.gn index fb97ed0533..28436f5122 100644 --- a/test/unittest/connection_record_test/BUILD.gn +++ b/test/unittest/connection_record_test/BUILD.gn @@ -18,7 +18,12 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("connection_record_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", diff --git a/test/unittest/connection_state_item_test/BUILD.gn b/test/unittest/connection_state_item_test/BUILD.gn index 7d77735f25..bc458b9384 100755 --- a/test/unittest/connection_state_item_test/BUILD.gn +++ b/test/unittest/connection_state_item_test/BUILD.gn @@ -18,7 +18,12 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("connection_state_item_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", diff --git a/test/unittest/connection_state_manager_test/BUILD.gn b/test/unittest/connection_state_manager_test/BUILD.gn index f27228ff04..7f8c8e2973 100755 --- a/test/unittest/connection_state_manager_test/BUILD.gn +++ b/test/unittest/connection_state_manager_test/BUILD.gn @@ -18,7 +18,12 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("connection_state_manager_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", diff --git a/test/unittest/continuation_test/remote_register_service_test/connect_callback_stub_test/connect_callback_stub_test.cpp b/test/unittest/continuation_test/remote_register_service_test/connect_callback_stub_test/connect_callback_stub_test.cpp index 30060629d0..28f7ea9187 100644 --- a/test/unittest/continuation_test/remote_register_service_test/connect_callback_stub_test/connect_callback_stub_test.cpp +++ b/test/unittest/continuation_test/remote_register_service_test/connect_callback_stub_test/connect_callback_stub_test.cpp @@ -183,25 +183,5 @@ HWTEST_F(ConnectCallbackStubTest, AppExecFwk_ConnectCallbackStub_OnRemoteRequest OHOS::IPC_STUB_UNKNOW_TRANS_ERR); GTEST_LOG_(INFO) << "AppExecFwk_ConnectCallbackStub_OnRemoteRequest_004 end."; } - -/** - * @tc.number: AppExecFwk_ConnectCallbackStub_OnRemoteRequest_005 - * @tc.name: OnRemoteRequest - * @tc.desc: The input parameter code is null ptr, and the test program executes as expected without exception - */ -HWTEST_F(ConnectCallbackStubTest, AppExecFwk_ConnectCallbackStub_OnRemoteRequest_005, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "AppExecFwk_ConnectCallbackStub_OnRemoteRequest_005 start."; - sptr object = new (std::nothrow) MockConnectCallback(); - EXPECT_TRUE(object != nullptr); - MessageParcel data = {}; - MessageParcel reply = {}; - MessageOption option = {}; - EXPECT_TRUE(data.WriteInterfaceToken(u"ohos.appexecfwk.iconnectcallback")); - object->memberFuncMap_[MockConnectCallback::COMMAND_DISCONNECT + 1] = nullptr; - EXPECT_EQ(object->OnRemoteRequest(MockConnectCallback::COMMAND_DISCONNECT + 1, data, reply, option), - IPC_STUB_UNKNOW_TRANS_ERR); - GTEST_LOG_(INFO) << "AppExecFwk_ConnectCallbackStub_OnRemoteRequest_005 end."; -} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/continuation_test/remote_register_service_test/remote_register_service_stub_test/remote_register_service_stub_test.cpp b/test/unittest/continuation_test/remote_register_service_test/remote_register_service_stub_test/remote_register_service_stub_test.cpp index df97a8992c..81f4394d39 100644 --- a/test/unittest/continuation_test/remote_register_service_test/remote_register_service_stub_test/remote_register_service_stub_test.cpp +++ b/test/unittest/continuation_test/remote_register_service_test/remote_register_service_stub_test/remote_register_service_stub_test.cpp @@ -281,33 +281,6 @@ HWTEST_F(RemoteRegisterServiceStubTest, AppExecFwk_RemoteRegisterServiceStub_OnR GTEST_LOG_(INFO) << "AppExecFwk_RemoteRegisterServiceStub_OnRemoteRequest_006 end."; } -/* - * Feature: AbilityManager - * Function: RemoteRegisterServiceStub - * SubFunction: OnRemoteRequest - * FunctionPoints: The parameter of function OnRemoteRequest. - * EnvConditions: Can run ohos test framework - * CaseDescription: Verify function OnRemoteRequest parameter emptry funciton cmd - */ -HWTEST_F(RemoteRegisterServiceStubTest, AppExecFwk_RemoteRegisterServiceStub_OnRemoteRequest_007, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "AppExecFwk_RemoteRegisterServiceStub_OnRemoteRequest_007 start."; - sptr object = new (std::nothrow) MockRegisterService(); - EXPECT_TRUE(object != nullptr); - - MessageParcel data; - MessageParcel reply; - MessageOption option; - - EXPECT_TRUE(data.WriteInterfaceToken(IRemoteRegisterService::GetDescriptor())); - - object->requestFuncMap_[MockRegisterService::COMMAND_SHOW_DEVICE_LIST + 1] = nullptr; - - EXPECT_EQ( - object->OnRemoteRequest( - MockRegisterService::COMMAND_SHOW_DEVICE_LIST + 1, data, reply, option), IPC_STUB_UNKNOW_TRANS_ERR); - GTEST_LOG_(INFO) << "AppExecFwk_RemoteRegisterServiceStub_OnRemoteRequest_007 end."; -} /* * Feature: AbilityManager diff --git a/test/unittest/data_ability_record_test/BUILD.gn b/test/unittest/data_ability_record_test/BUILD.gn index fbb5d2e1e0..229e712f82 100644 --- a/test/unittest/data_ability_record_test/BUILD.gn +++ b/test/unittest/data_ability_record_test/BUILD.gn @@ -18,7 +18,13 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("data_ability_record_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/ability_scheduler_mock", diff --git a/test/unittest/dataobs_mgr_service_dump_test/dataobs_mgr_service_dump_test.cpp b/test/unittest/dataobs_mgr_service_dump_test/dataobs_mgr_service_dump_test.cpp index c459014b4f..a2b3761a47 100755 --- a/test/unittest/dataobs_mgr_service_dump_test/dataobs_mgr_service_dump_test.cpp +++ b/test/unittest/dataobs_mgr_service_dump_test/dataobs_mgr_service_dump_test.cpp @@ -20,7 +20,6 @@ #include "app_mgr_service.h" #undef private #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing; using namespace testing::ext; 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 504b7f1257..c04d6efabc 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 @@ -62,26 +62,6 @@ HWTEST_F(DataObsMgrServiceTest, AaFwk_DataObsMgrServiceTest_QueryServiceState_01 GTEST_LOG_(INFO) << "AaFwk_DataObsMgrServiceTest_QueryServiceState_0100 end"; } -/* - * Feature: DataObsMgrService - * Function: OnStart - * SubFunction: NA - * FunctionPoints: DataObsMgrService OnStart - * EnvConditions: NA - * CaseDescription: Verify that the DataObsMgrService OnStart is normal. - */ -HWTEST_F(DataObsMgrServiceTest, AaFwk_DataObsMgrServiceTest_OnStart_0100, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_DataObsMgrServiceTest_OnStart_0100 start"; - const DataObsServiceRunningState testValue = DataObsServiceRunningState::STATE_RUNNING; - auto dataObsMgrServer = DelayedSingleton::GetInstance(); - - dataObsMgrServer->OnStart(); - EXPECT_EQ(testValue, dataObsMgrServer->QueryServiceState()); - - GTEST_LOG_(INFO) << "AaFwk_DataObsMgrServiceTest_OnStart_0100 end"; -} - /* * Feature: DataObsMgrService * Function: RegisterObserver @@ -230,7 +210,7 @@ HWTEST_F(DataObsMgrServiceTest, AaFwk_DataObsMgrServiceTest_UnregisterObserver_0 HWTEST_F(DataObsMgrServiceTest, AaFwk_DataObsMgrServiceTest_NotifyChange_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AaFwk_DataObsMgrServiceTest_NotifyChange_0100 start"; - const int testVal = static_cast(NO_ERROR); + const int testVal = static_cast(DATAOBS_SERVICE_HANDLER_IS_NULL); std::shared_ptr uri = std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); auto dataObsMgrServer = DelayedSingleton::GetInstance(); @@ -258,7 +238,6 @@ HWTEST_F(DataObsMgrServiceTest, AaFwk_DataObsMgrServiceTest_NotifyChange_0200, T dataObsMgrServer->OnStop(); EXPECT_EQ(testVal, dataObsMgrServer->NotifyChange(*uri)); - dataObsMgrServer->OnStart(); GTEST_LOG_(INFO) << "AaFwk_DataObsMgrServiceTest_NotifyChange_0200 end"; } @@ -274,7 +253,7 @@ HWTEST_F(DataObsMgrServiceTest, AaFwk_DataObsMgrServiceTest_NotifyChange_0200, T HWTEST_F(DataObsMgrServiceTest, AaFwk_DataObsMgrServiceTest_NotifyChange_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "AaFwk_DataObsMgrServiceTest_NotifyChange_0300 start"; - const int testVal = static_cast(DATAOBS_SERVICE_INNER_IS_NULL); + const int testVal = static_cast(DATAOBS_SERVICE_HANDLER_IS_NULL); std::shared_ptr uri = std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); auto dataObsMgrServer = DelayedSingleton::GetInstance(); @@ -297,7 +276,7 @@ HWTEST_F(DataObsMgrServiceTest, AaFwk_DataObsMgrServiceTest_NotifyChange_0300, T HWTEST_F(DataObsMgrServiceTest, AaFwk_DataObsMgrServiceTest_NotifyChange_0400, TestSize.Level1) { GTEST_LOG_(INFO) << "AaFwk_DataObsMgrServiceTest_NotifyChange_0400 start"; - const int testVal = static_cast(DATAOBS_SERVICE_TASK_LIMMIT); + const int testVal = static_cast(DATAOBS_SERVICE_HANDLER_IS_NULL); std::shared_ptr uri = std::make_shared("dataability://device_id/com.domainname.dataability.persondata/person/10"); auto dataObsMgrServer = DelayedSingleton::GetInstance(); @@ -515,7 +494,7 @@ HWTEST_F(DataObsMgrServiceTest, DataObsMgrServiceTest_UnregisterObserverExt_0600 HWTEST_F(DataObsMgrServiceTest, DataObsMgrServiceTest_NotifyChangeExt_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "DataObsMgrServiceTest_NotifyChangeExt_0100 start"; - const int testVal = static_cast(NO_ERROR); + const int testVal = static_cast(DATAOBS_SERVICE_HANDLER_IS_NULL); Uri uri("dataobs://authority/com.domainname.dataability.persondata/ person/10"); auto dataObsMgrServer = DelayedSingleton::GetInstance(); @@ -540,7 +519,6 @@ HWTEST_F(DataObsMgrServiceTest, DataObsMgrServiceTest_NotifyChangeExt_0200, Test dataObsMgrServer->OnStop(); EXPECT_EQ(testVal, dataObsMgrServer->NotifyChangeExt({ ChangeInfo::ChangeType::UPDATE, { uri } })); - dataObsMgrServer->OnStart(); GTEST_LOG_(INFO) << "DataObsMgrServiceTest_NotifyChangeExt_0200 end"; } @@ -555,7 +533,7 @@ HWTEST_F(DataObsMgrServiceTest, DataObsMgrServiceTest_NotifyChangeExt_0200, Test HWTEST_F(DataObsMgrServiceTest, DataObsMgrServiceTest_NotifyChangeExt_0300, TestSize.Level1) { GTEST_LOG_(INFO) << "DataObsMgrServiceTest_NotifyChangeExt_0300 start"; - const int testVal = static_cast(DATAOBS_SERVICE_INNER_IS_NULL); + const int testVal = static_cast(DATAOBS_SERVICE_HANDLER_IS_NULL); Uri uri("dataobs://authority/com.domainname.dataability.persondata/ person/10"); auto dataObsMgrServer = DelayedSingleton::GetInstance(); diff --git a/test/unittest/dfr_test/appfreeze_inner_test/BUILD.gn b/test/unittest/dfr_test/appfreeze_inner_test/BUILD.gn index f9cc437dd8..d4818c5bbd 100644 --- a/test/unittest/dfr_test/appfreeze_inner_test/BUILD.gn +++ b/test/unittest/dfr_test/appfreeze_inner_test/BUILD.gn @@ -50,7 +50,6 @@ ohos_unittest("appfreeze_inner_test") { include_dirs = [ "${ability_runtime_path}/interfaces/kits/native/appkit/dfr", "${ability_runtime_path}/utils/global/time/include", - "//third_party/json/include", ] configs = [ @@ -104,6 +103,7 @@ ohos_unittest("appfreeze_inner_test") { "init:libbegetutil", "input:libmmi-client", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", "resource_management:global_resmgr", "safwk:system_ability_fwk", 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 0eae9e539c..8c2aefc3f5 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 @@ -130,12 +130,12 @@ HWTEST_F(AppfreezeInnerTest, AppfreezeInner_IsNeedIgnoreFreezeEvent_001, TestSiz int32_t pid = static_cast(getprocpid()); std::shared_ptr listener = std::make_shared(); - listener->OnAnr(pid); + listener->OnAnr(pid, 0); int left = 61; // over 1min while (left > 0) { left = sleep(left); } - listener->OnAnr(pid); + listener->OnAnr(pid, 0); } /** diff --git a/test/unittest/dfr_test/appfreeze_manager_test/BUILD.gn b/test/unittest/dfr_test/appfreeze_manager_test/BUILD.gn index e0452c3154..ca35c2db20 100644 --- a/test/unittest/dfr_test/appfreeze_manager_test/BUILD.gn +++ b/test/unittest/dfr_test/appfreeze_manager_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") @@ -52,7 +52,6 @@ ohos_unittest("appfreeze_manager_test") { "${ability_runtime_services_path}/appdfr/include", "${ability_runtime_services_path}/appmgr/include", "${ability_runtime_services_path}/common/include", - "//third_party/json/include", ] configs = [ @@ -87,10 +86,11 @@ ohos_unittest("appfreeze_manager_test") { "hilog:libhilog", "init:libbeget_proxy", "ipc:ipc_core", + "json:nlohmann_json_static", ] } -############################################################################### +############################################################################### group("unittest") { testonly = true diff --git a/test/unittest/dfr_test/appfreeze_state_test/BUILD.gn b/test/unittest/dfr_test/appfreeze_state_test/BUILD.gn index 57c1669ea6..422a69dcb9 100644 --- a/test/unittest/dfr_test/appfreeze_state_test/BUILD.gn +++ b/test/unittest/dfr_test/appfreeze_state_test/BUILD.gn @@ -50,7 +50,6 @@ ohos_unittest("appfreeze_state_test") { include_dirs = [ "${ability_runtime_path}/interfaces/kits/native/appkit/dfr", "${ability_runtime_path}/utils/global/time/include", - "//third_party/json/include", ] configs = [ @@ -101,6 +100,7 @@ ohos_unittest("appfreeze_state_test") { "hitrace:hitrace_meter", "init:libbegetutil", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", ] } diff --git a/test/unittest/dfr_test/watchdog_test/BUILD.gn b/test/unittest/dfr_test/watchdog_test/BUILD.gn index 1825d44c40..0c9afbb19d 100644 --- a/test/unittest/dfr_test/watchdog_test/BUILD.gn +++ b/test/unittest/dfr_test/watchdog_test/BUILD.gn @@ -52,7 +52,6 @@ ohos_unittest("watchdog_test") { "${ability_runtime_path}/interfaces/kits/native/appkit/dfr", "${ability_runtime_test_path}/mock/frameworks_kits_appkit_test/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/app", - "//third_party/json/include", ] configs = [ @@ -80,6 +79,7 @@ ohos_unittest("watchdog_test") { "hilog:libhilog", "image_framework:image_native", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", ] } diff --git a/test/unittest/dummy_values_bucket_test/dummy_values_bucket_test.cpp b/test/unittest/dummy_values_bucket_test/dummy_values_bucket_test.cpp index 083fa8f653..ce0bfbc49d 100644 --- a/test/unittest/dummy_values_bucket_test/dummy_values_bucket_test.cpp +++ b/test/unittest/dummy_values_bucket_test/dummy_values_bucket_test.cpp @@ -21,7 +21,6 @@ #undef private #undef protected #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing::ext; using namespace testing; using namespace OHOS::AppExecFwk; diff --git a/test/unittest/dynamic_loader_ohos_test/BUILD.gn b/test/unittest/dynamic_loader_ohos_test/BUILD.gn new file mode 100644 index 0000000000..e344cf3c1e --- /dev/null +++ b/test/unittest/dynamic_loader_ohos_test/BUILD.gn @@ -0,0 +1,92 @@ +# 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") + +ohos_unittest("dynamic_loader_ohos_test") { + module_out_path = "ability_runtime/dynamic_loader_ohos_test" + include_dirs = [ + "${ability_runtime_test_path}/mock/common/include", + "${resource_management_path}/frameworks/resmgr/include", + "${ability_base_kits_path}/configuration/include", + "${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/ability/native", + "${ability_runtime_path}/interfaces/inner_api/runtime/include", + "${ability_runtime_path}/cj_environment/interfaces/inner_api", + "${ability_runtime_path}/cj_environment/frameworks/cj_environment/include", + "${ability_runtime_native_path}/runtime", + ] + + sources = [ + "${ability_runtime_path}/cj_environment/frameworks/cj_environment/src/dynamic_loader_ohos.cpp", + "dynamic_loader_ohos_test.cpp", + ] + configs = [ "${c_utils_base_path}:utils_config" ] + cflags = [] + if (target_cpu == "arm") { + 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}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_innerkits_path}/runtime:runtime", + "${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:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:want", + "ability_runtime:runtime", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "resource_management:global_resmgr", + ] + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } + + defines = [ + "CONFIG_HILOG", + "__OHOS__", + ] +} + +group("unittest") { + testonly = true + deps = [ ":dynamic_loader_ohos_test" ] +} diff --git a/test/unittest/dynamic_loader_ohos_test/dynamic_loader_ohos_test.cpp b/test/unittest/dynamic_loader_ohos_test/dynamic_loader_ohos_test.cpp new file mode 100644 index 0000000000..9804833224 --- /dev/null +++ b/test/unittest/dynamic_loader_ohos_test/dynamic_loader_ohos_test.cpp @@ -0,0 +1,106 @@ +/* + * 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 "dynamic_loader.h" +#include // For dlerror + +using namespace testing; +using namespace testing::ext; + +class DynamicLoaderOhosTest : public testing::Test { +public: + DynamicLoaderOhosTest() + {} + ~DynamicLoaderOhosTest() + {} + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override; + void TearDown() override; +}; + +void DynamicLoaderOhosTest::SetUpTestCase(void) +{} + +void DynamicLoaderOhosTest::TearDownTestCase(void) +{} + +void DynamicLoaderOhosTest::SetUp(void) +{} + +void DynamicLoaderOhosTest::TearDown(void) +{} + +/** + * @tc.name: DynamicLoaderOhosTestInitNamespace_0100 + * @tc.desc: DynamicLoaderOhosTest test for dynamic_init_namespace. + * @tc.type: FUNC + */ +HWTEST_F(DynamicLoaderOhosTest, DynamicLoaderOhosTestInitNamespace_0100, TestSize.Level1) +{ + Dl_namespace ns; + const char* name = "test_namespace"; + + // Test success + DynamicInitNamespace(&ns, nullptr, "test_entries", name); + EXPECT_STREQ(DynamicGetError(), ""); + + // Test duplicate init + DynamicInitNamespace(&ns, nullptr, "test_entries", name); + EXPECT_STREQ(DynamicGetError(), ""); +} + +/** + * @tc.name: DynamicLoaderOhosTestLoadLibrary_0100 + * @tc.desc: DynamicLoaderOhosTest test for dynamic_load_library. + * @tc.type: FUNC + */ +HWTEST_F(DynamicLoaderOhosTest, DynamicLoaderOhosTestLoadLibrary_0100, TestSize.Level1) +{ + Dl_namespace ns; + + // Test success + auto handle = DynamicLoadLibrary(&ns, "test_library.so", RTLD_LAZY); + const char* dlerror = DynamicGetError(); + DynamicLoadLibrary(nullptr, "test_library.so", RTLD_LAZY); + EXPECT_NE(dlerror, nullptr); +} + +/** + * @tc.name: DynamicLoaderOhosTestFindSymbol_0100 + * @tc.desc: DynamicLoaderOhosTest test for dynamic_find_symbol. + * @tc.type: FUNC + */ +HWTEST_F(DynamicLoaderOhosTest, DynamicLoaderOhosTestFindSymbol_0100, TestSize.Level1) +{ + void* so = reinterpret_cast(1); + const char* symbol = "test_symbol"; + + // Test success + void* result = DynamicFindSymbol(so, symbol); + EXPECT_EQ(result, dlsym(so, symbol)); +} + +/** + * @tc.name: DynamicLoaderOhosTestGetError_0100 + * @tc.desc: DynamicLoaderOhosTest test for dynamic_get_error. + * @tc.type: FUNC + */ +HWTEST_F(DynamicLoaderOhosTest, DynamicLoaderOhosTestGetError_0100, TestSize.Level1) +{ + // Test dlerror with an error message + DynamicLoadLibrary(nullptr, "test_library.so", RTLD_LAZY); +} \ No newline at end of file diff --git a/test/unittest/extension_manager_client_test/extension_manager_client_test.cpp b/test/unittest/extension_manager_client_test/extension_manager_client_test.cpp index 659dfa4584..828947a8a3 100644 --- a/test/unittest/extension_manager_client_test/extension_manager_client_test.cpp +++ b/test/unittest/extension_manager_client_test/extension_manager_client_test.cpp @@ -20,7 +20,6 @@ #undef private #include "ability_manager_client.h" #include "appexecfwk_errors.h" -#include "hilog_wrapper.h" using namespace testing::ext; using namespace OHOS::AppExecFwk; 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 6f0f8660ca..3a95c5a187 100644 --- a/test/unittest/frameworks_kits_ability_ability_runtime_test/BUILD.gn +++ b/test/unittest/frameworks_kits_ability_ability_runtime_test/BUILD.gn @@ -41,7 +41,6 @@ ohos_unittest("ability_context_impl_test") { 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_native_path}/ability:ability_context_native", "${ability_runtime_native_path}/ability/native:abilitykit_native", 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 5c2002ca8c..380f9b7fcc 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 @@ -235,6 +235,29 @@ HWTEST_F(AbilityContextImplTest, Ability_Context_Impl_SetMissionContinueState_01 } } +/** + * @tc.name: Ability_Context_Impl_SetMissionContinueState_0200 + * @tc.desc: test set mission continue state. + * @tc.type: FUNC + */ +HWTEST_F(AbilityContextImplTest, Ability_Context_Impl_SetMissionContinueState_0200, Function | MediumTest | Level1) +{ + ASSERT_TRUE(g_mockAbilityMs != nullptr); + ASSERT_TRUE(context_ != nullptr); + AAFwk::AbilityManagerClient::GetInstance()->proxy_ = g_mockAbilityMs; + g_mockAbilityMs->SetCommonMockResult(false); + + AAFwk::ContinueState state = AAFwk::ContinueState::CONTINUESTATE_INACTIVE; + auto ret = context_->SetMissionContinueState(state); + EXPECT_NE(ret, 0); + + g_mockAbilityMs->SetCommonMockResult(true); + ret = context_->SetMissionContinueState(state); + if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { + EXPECT_EQ(ret, 0); + } +} + /** * @tc.name: Ability_Context_Impl_SetMissionLabel_0100 * @tc.desc: test set mission label. @@ -1484,9 +1507,10 @@ HWTEST_F(AbilityContextImplTest, Ability_Context_Impl_SetMissionIcon_0300, Funct auto ret = context_->SetMissionLabel(TEST_LABEL); if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { EXPECT_EQ(ret, 0); + auto ret1 = context_->SetMissionIcon(nullptr); + EXPECT_TRUE(ret1 == ERR_OK); } - auto ret1 = context_->SetMissionIcon(nullptr); - EXPECT_TRUE(ret1 == ERR_OK); + EXPECT_TRUE(context_ != nullptr); } /** diff --git a/test/unittest/frameworks_kits_ability_native_test/BUILD.gn b/test/unittest/frameworks_kits_ability_native_test/BUILD.gn index bdfd558403..ae99cbd360 100644 --- a/test/unittest/frameworks_kits_ability_native_test/BUILD.gn +++ b/test/unittest/frameworks_kits_ability_native_test/BUILD.gn @@ -399,6 +399,13 @@ ohos_unittest("scene_created_test") { ohos_unittest("data_ability_helper_test") { module_out_path = module_output_path + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_services_path}/abilitymgr/include", "${ability_runtime_path}/interfaces/kits/native/ability/native", @@ -706,7 +713,13 @@ ohos_unittest("ui_ability_impl_test") { ohos_unittest("ability_thread_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/unittest/dataobs_mgr_stub_test", "${ability_runtime_services_path}/dataobsmgr/include/", @@ -778,7 +791,13 @@ ohos_unittest("ability_thread_test") { ohos_unittest("fa_ability_thread_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/unittest/dataobs_mgr_stub_test", "${ability_runtime_services_path}/dataobsmgr/include/", @@ -891,6 +910,13 @@ ohos_unittest("extension_ability_thread_test") { ohos_unittest("ui_ability_thread_test") { module_out_path = module_output_path + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" sources = [ "${ability_runtime_innerkits_path}/app_manager/src/appmgr/process_info.cpp", "${ability_runtime_native_path}/appkit/app/app_context.cpp", @@ -2014,7 +2040,7 @@ ohos_unittest("reserse_continuation_scheduler_primary_proxy_test") { ohos_unittest("distributed_client_test") { module_out_path = module_output_path sources = [ - "${ability_runtime_services_path}/abilitymgr/src/distributed_client.cpp", + "${ability_runtime_native_path}/ability/native/distributed_ability_runtime/distributed_client.cpp", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit/src/mock_ability_connect_callback.cpp", "distributed_client_test.cpp", ] @@ -2339,6 +2365,7 @@ ohos_unittest("reverse_continuation_scheduler_replica_stub_test") { ohos_unittest("ability_connection_manager_test") { module_out_path = module_output_path + include_dirs = [ "${ability_runtime_path}/interfaces/kits/native/ability/native/ui_service_extension_ability/connection" ] sources = [ "${ability_runtime_native_path}/ability/ability_runtime/connection_manager.cpp", "${ability_runtime_native_path}/appkit/app/ability_record_mgr.cpp", @@ -2777,6 +2804,7 @@ ohos_unittest("dialog_request_callback_test") { defines = [] include_dirs = [ "${ability_runtime_path}/interfaces/kits/native/ability/ability_runtime", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", "${ability_runtime_path}/frameworks/simulator/common/include", "${ability_runtime_path}/interfaces/kits/native/ability/native/dialog_request_callback", ] diff --git a/test/unittest/frameworks_kits_ability_native_test/ability_connection_manager_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ability_connection_manager_test.cpp index f1ec9c42bd..4d2faf6fb4 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ability_connection_manager_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ability_connection_manager_test.cpp @@ -22,7 +22,6 @@ #include "ability_manager_client.h" #include "ability_manager_errors.h" #include "connection_manager.h" -#include "hilog_wrapper.h" #undef protected #undef private diff --git a/test/unittest/frameworks_kits_ability_native_test/ability_impl_active_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ability_impl_active_test.cpp index 03ed1b5a8f..c6e3c79e0f 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ability_impl_active_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ability_impl_active_test.cpp @@ -19,7 +19,6 @@ #include "ability.h" #include "ability_impl.h" #include "context_deal.h" -#include "hilog_wrapper.h" #include "mock_ability_token.h" #include "ohos_application.h" #include "page_ability_impl.h" diff --git a/test/unittest/frameworks_kits_ability_native_test/ability_impl_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ability_impl_test.cpp index 256ff56c44..856c517aee 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ability_impl_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ability_impl_test.cpp @@ -22,7 +22,6 @@ #undef protected #undef private #include "context_deal.h" -#include "hilog_wrapper.h" #include "mock_ability_token.h" #include "mock_page_ability.h" #include "mock_ability_impl.h" diff --git a/test/unittest/frameworks_kits_ability_native_test/ability_loader_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ability_loader_test.cpp index 3404595363..ecbb940dc7 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ability_loader_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ability_loader_test.cpp @@ -17,7 +17,6 @@ #define private public #define protected public #include "ability_loader.h" -#include "hilog_wrapper.h" #include "iservice_registry.h" #include "iremote_object.h" #undef protected diff --git a/test/unittest/frameworks_kits_ability_native_test/ability_runtime_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ability_runtime_test.cpp index 4f71c6b056..e77a07bedd 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ability_runtime_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ability_runtime_test.cpp @@ -16,7 +16,6 @@ #include #define private public #define protected public -#include "hilog_wrapper.h" #include "iremote_object.h" #include "iservice_registry.h" #include "js_runtime.h" 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 0836b5812c..c40139cc34 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ability_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ability_test.cpp @@ -34,7 +34,6 @@ #include "data_ability_predicates.h" #include "data_ability_result.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "key_event.h" #include "mock_lifecycle_observer.h" #include "mock_page_ability.h" @@ -3183,12 +3182,12 @@ HWTEST_F(AbilityBaseTest, Ability_RegisterAbilityLifecycleObserver_0100, Functio */ HWTEST_F(AbilityBaseTest, Ability_GetModuleName_0100, TestSize.Level1) { - HILOG_INFO("%{public}s start.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); auto ret = ability_->GetModuleName(); ASSERT_EQ(ret, ""); - HILOG_INFO("%{public}s end.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); } /** @@ -3198,7 +3197,7 @@ HWTEST_F(AbilityBaseTest, Ability_GetModuleName_0100, TestSize.Level1) */ HWTEST_F(AbilityBaseTest, RegisterAbilityLifecycleObserver_0100, TestSize.Level1) { - HILOG_INFO("%{public}s start.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); ability_->RegisterAbilityLifecycleObserver(nullptr); std::shared_ptr observer = std::make_shared(); @@ -3207,7 +3206,7 @@ HWTEST_F(AbilityBaseTest, RegisterAbilityLifecycleObserver_0100, TestSize.Level1 ability_->RegisterAbilityLifecycleObserver(observer); EXPECT_EQ(ability_->GetLifecycle(), nullptr); - HILOG_INFO("%{public}s end.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); } /** @@ -3217,7 +3216,7 @@ HWTEST_F(AbilityBaseTest, RegisterAbilityLifecycleObserver_0100, TestSize.Level1 */ HWTEST_F(AbilityBaseTest, UnregisterAbilityLifecycleObserver_0100, TestSize.Level1) { - HILOG_INFO("%{public}s start.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); ability_->UnregisterAbilityLifecycleObserver(nullptr); std::shared_ptr observer = std::make_shared(); @@ -3226,7 +3225,7 @@ HWTEST_F(AbilityBaseTest, UnregisterAbilityLifecycleObserver_0100, TestSize.Leve ability_->UnregisterAbilityLifecycleObserver(observer); EXPECT_EQ(ability_->GetLifecycle(), nullptr); - HILOG_INFO("%{public}s end.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); } /** @@ -3237,7 +3236,7 @@ HWTEST_F(AbilityBaseTest, UnregisterAbilityLifecycleObserver_0100, TestSize.Leve */ HWTEST_F(AbilityBaseTest, ExecuteOperation_0100, TestSize.Level1) { - HILOG_INFO("%{public}s start.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); std::shared_ptr ability = std::make_shared(); ASSERT_NE(ability, nullptr); @@ -3260,7 +3259,7 @@ HWTEST_F(AbilityBaseTest, ExecuteOperation_0100, TestSize.Level1) auto ret = result.size(); EXPECT_EQ(ret, 0); - HILOG_INFO("%{public}s end.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); } /** @@ -3271,7 +3270,7 @@ HWTEST_F(AbilityBaseTest, ExecuteOperation_0100, TestSize.Level1) */ HWTEST_F(AbilityBaseTest, AbilityCheckAssertQueryResult_0200, TestSize.Level1) { - HILOG_INFO("%{public}s start.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); std::shared_ptr ability = std::make_shared(); ASSERT_NE(ability, nullptr); @@ -3289,7 +3288,7 @@ HWTEST_F(AbilityBaseTest, AbilityCheckAssertQueryResult_0200, TestSize.Level1) bool ret = ability->CheckAssertQueryResult(queryResult, nullptr); EXPECT_EQ(ret, true); - HILOG_INFO("%{public}s end.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); } /** @@ -3300,7 +3299,7 @@ HWTEST_F(AbilityBaseTest, AbilityCheckAssertQueryResult_0200, TestSize.Level1) */ HWTEST_F(AbilityBaseTest, AbilityCheckAssertQueryResult_0300, TestSize.Level1) { - HILOG_INFO("%{public}s start.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); std::shared_ptr ability = std::make_shared(); ASSERT_NE(ability, nullptr); @@ -3310,7 +3309,7 @@ HWTEST_F(AbilityBaseTest, AbilityCheckAssertQueryResult_0300, TestSize.Level1) bool ret = ability->CheckAssertQueryResult(queryResult, operation->GetValuesBucket()); EXPECT_EQ(ret, true); - HILOG_INFO("%{public}s end.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); } /** @@ -3321,7 +3320,7 @@ HWTEST_F(AbilityBaseTest, AbilityCheckAssertQueryResult_0300, TestSize.Level1) */ HWTEST_F(AbilityBaseTest, OnShare_0100, TestSize.Level1) { - HILOG_INFO("%{public}s start.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); std::shared_ptr ability = std::make_shared(); ASSERT_NE(ability, nullptr); @@ -3338,7 +3337,7 @@ HWTEST_F(AbilityBaseTest, OnShare_0100, TestSize.Level1) int32_t height = 1; ability->GetWindowRect(left, top, width, height); EXPECT_EQ(left, top); - HILOG_INFO("%{public}s end.", __func__); + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); } } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/frameworks_kits_ability_native_test/ability_thread_dataability_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ability_thread_dataability_test.cpp index 21dcb9c8aa..81d4d452e5 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ability_thread_dataability_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ability_thread_dataability_test.cpp @@ -24,7 +24,6 @@ #include "context_deal.h" #include "data_ability_predicates.h" #include "fa_ability_thread.h" -#include "hilog_wrapper.h" #include "mock_ability_impl.h" #include "mock_ability_lifecycle_callbacks.h" #include "mock_ability_thread.h" diff --git a/test/unittest/frameworks_kits_ability_native_test/ability_thread_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ability_thread_test.cpp index fa9c1efe46..3886d50713 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ability_thread_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ability_thread_test.cpp @@ -25,7 +25,6 @@ #include "ability_impl.h" #include "ability_impl_factory.h" #include "context_deal.h" -#include "hilog_wrapper.h" #include "mock_ability_impl.h" #include "mock_ability_lifecycle_callbacks.h" #include "mock_ability_thread.h" 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 index 71108ea063..2e15755e55 100644 --- 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 @@ -19,7 +19,6 @@ #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" diff --git a/test/unittest/frameworks_kits_ability_native_test/continuation_test.cpp b/test/unittest/frameworks_kits_ability_native_test/continuation_test.cpp index 7c0b68c9ee..890d29b38b 100644 --- a/test/unittest/frameworks_kits_ability_native_test/continuation_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/continuation_test.cpp @@ -22,7 +22,6 @@ #include "ability_impl.h" #include "abs_shared_result_set.h" #include "bool_wrapper.h" -#include "hilog_wrapper.h" #include "context_deal.h" #include "continuation_manager.h" #include "continuation_handler.h" diff --git a/test/unittest/frameworks_kits_ability_native_test/data_ability_impl_file_secondpart_test.cpp b/test/unittest/frameworks_kits_ability_native_test/data_ability_impl_file_secondpart_test.cpp index 1de5eeadb5..d2973c6ccf 100644 --- a/test/unittest/frameworks_kits_ability_native_test/data_ability_impl_file_secondpart_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/data_ability_impl_file_secondpart_test.cpp @@ -16,7 +16,6 @@ #include #include "ability_loader.h" #include "data_ability_impl.h" -#include "hilog_wrapper.h" #include "mock_ability_token.h" #include "mock_data_ability.h" diff --git a/test/unittest/frameworks_kits_ability_native_test/data_ability_impl_file_test.cpp b/test/unittest/frameworks_kits_ability_native_test/data_ability_impl_file_test.cpp index 2820a84108..33fa440111 100644 --- a/test/unittest/frameworks_kits_ability_native_test/data_ability_impl_file_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/data_ability_impl_file_test.cpp @@ -16,7 +16,6 @@ #include #include "ability_loader.h" #include "data_ability_impl.h" -#include "hilog_wrapper.h" #include "mock_ability_token.h" #include "mock_data_ability.h" diff --git a/test/unittest/frameworks_kits_ability_native_test/data_ability_impl_test.cpp b/test/unittest/frameworks_kits_ability_native_test/data_ability_impl_test.cpp index 428a22c852..f1e1d4bebf 100644 --- a/test/unittest/frameworks_kits_ability_native_test/data_ability_impl_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/data_ability_impl_test.cpp @@ -17,12 +17,11 @@ #define private public #define protected public #include "ability_loader.h" +#include "base/account/os_account/services/accountmgr/test/mock/app_account/accesstoken_kit.h" #include "data_ability_impl.h" -#include "hilog_wrapper.h" +#include "data_ability_operation.h" #include "mock_ability_token.h" #include "mock_data_ability.h" -#include "base/account/os_account/services/accountmgr/test/mock/app_account/accesstoken_kit.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/ability/native/data_ability_operation.h" #undef private #undef protected namespace OHOS { diff --git a/test/unittest/frameworks_kits_ability_native_test/distributed_client_test.cpp b/test/unittest/frameworks_kits_ability_native_test/distributed_client_test.cpp index de5a775741..8d33f5e91c 100644 --- a/test/unittest/frameworks_kits_ability_native_test/distributed_client_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/distributed_client_test.cpp @@ -385,7 +385,8 @@ HWTEST_F(DistributedClientTest, NotifyCompleteContinuation_0100, TestSize.Level3 std::u16string devId = to_utf16("deviceId"); int32_t sessionId = 0; bool isSuccess = true; - auto result = client->NotifyCompleteContinuation(devId, sessionId, isSuccess); + std::string callerBundleName; + auto result = client->NotifyCompleteContinuation(devId, sessionId, isSuccess, callerBundleName); if (client->GetDmsProxy() != nullptr) { EXPECT_EQ(result, OHOS::AAFwk::DMS_PERMISSION_DENIED); } else { @@ -406,8 +407,9 @@ HWTEST_F(DistributedClientTest, NotifyCompleteContinuation_0200, TestSize.Level3 std::u16string devId = to_utf16("deviceId"); int32_t sessionId = 0; bool isSuccess = true; + std::string callerBundleName; SystemAbilityManagerClient::GetInstance().systemAbilityManager_ = nullptr; - auto result = client->NotifyCompleteContinuation(devId, sessionId, isSuccess); + auto result = client->NotifyCompleteContinuation(devId, sessionId, isSuccess, callerBundleName); EXPECT_EQ(result, OHOS::AAFwk::INVALID_PARAMETERS_ERR); GTEST_LOG_(INFO) << "DistributedClientTest NotifyCompleteContinuation_0200 end"; diff --git a/test/unittest/frameworks_kits_ability_native_test/fa_ability_thread_test.cpp b/test/unittest/frameworks_kits_ability_native_test/fa_ability_thread_test.cpp index d262a2155f..f603abeb18 100644 --- a/test/unittest/frameworks_kits_ability_native_test/fa_ability_thread_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/fa_ability_thread_test.cpp @@ -25,7 +25,6 @@ #include "ability_impl.h" #include "ability_impl_factory.h" #include "context_deal.h" -#include "hilog_wrapper.h" #include "mock_ability_impl.h" #include "mock_ability_lifecycle_callbacks.h" #include "mock_ability_thread.h" diff --git a/test/unittest/frameworks_kits_ability_native_test/form_extension_module_loader_test.cpp b/test/unittest/frameworks_kits_ability_native_test/form_extension_module_loader_test.cpp index fd9a4ffff5..cc1acabd65 100644 --- a/test/unittest/frameworks_kits_ability_native_test/form_extension_module_loader_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/form_extension_module_loader_test.cpp @@ -17,7 +17,6 @@ #include #include "form_extension_module_loader.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing; using namespace testing::ext; 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 index f6c312360c..1bc0fb51f6 100644 --- 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 @@ -19,7 +19,6 @@ #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" diff --git a/test/unittest/frameworks_kits_ability_native_test/mock_ability_runtime_context.h b/test/unittest/frameworks_kits_ability_native_test/mock_ability_runtime_context.h index 9672c0fa13..be4fa4379c 100644 --- a/test/unittest/frameworks_kits_ability_native_test/mock_ability_runtime_context.h +++ b/test/unittest/frameworks_kits_ability_native_test/mock_ability_runtime_context.h @@ -20,7 +20,7 @@ #define private public #define protected public -#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/context.h" +#include "context.h" #undef private #undef protected diff --git a/test/unittest/frameworks_kits_ability_native_test/reserse_continuation_scheduler_primary_stub_test.cpp b/test/unittest/frameworks_kits_ability_native_test/reserse_continuation_scheduler_primary_stub_test.cpp index 3161552a3e..8b14765593 100644 --- a/test/unittest/frameworks_kits_ability_native_test/reserse_continuation_scheduler_primary_stub_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/reserse_continuation_scheduler_primary_stub_test.cpp @@ -58,65 +58,6 @@ void ReverseContinuationSchedulerPrimaryStubTest::TearDown(void) primaryStub_ = nullptr; } -/** - * @tc.number: OnRemoteRequest_0100 - * @tc.name: OnRemoteRequest - * @tc.desc: Verify that function OnRemoteRequest - */ -HWTEST_F(ReverseContinuationSchedulerPrimaryStubTest, OnRemoteRequest_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "OnRemoteRequest_0100 start"; - uint32_t code = 1; - MessageParcel data; - MessageParcel reply; - MessageOption option; - auto result = primaryStub_->OnRemoteRequest(code, data, reply, option); - - EXPECT_EQ(result, INVALID_FD); - GTEST_LOG_(INFO) << "OnRemoteRequest_0100 end"; -} - -/** - * @tc.number: OnRemoteRequest_0200 - * @tc.name: OnRemoteRequest - * @tc.desc: Verify that function OnRemoteRequest - */ -HWTEST_F(ReverseContinuationSchedulerPrimaryStubTest, OnRemoteRequest_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "OnRemoteRequest_0200 start"; - uint32_t code = 1; - MessageParcel data; - MessageParcel reply; - MessageOption option; - std::u16string name = u"ohos.abilityshell.ReverseContinuationSchedulerMaster"; - data.WriteInterfaceToken(name); - auto result = primaryStub_->OnRemoteRequest(code, data, reply, option); - - EXPECT_EQ(result, ERR_NONE); - GTEST_LOG_(INFO) << "OnRemoteRequest_0200 end"; -} - -/** - * @tc.number: OnRemoteRequest_0300 - * @tc.name: OnRemoteRequest - * @tc.desc: Verify that function OnRemoteRequest - */ -HWTEST_F(ReverseContinuationSchedulerPrimaryStubTest, OnRemoteRequest_0300, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "OnRemoteRequest_0300 start"; - uint32_t code = 3; - MessageParcel data; - MessageParcel reply; - MessageOption option; - std::u16string name = u"ohos.abilityshell.ReverseContinuationSchedulerMaster"; - data.WriteInterfaceToken(name); - primaryStub_->requestFuncMap_[3] = nullptr; - auto result = primaryStub_->OnRemoteRequest(code, data, reply, option); - - EXPECT_EQ(result, IPC_STUB_UNKNOW_TRANS_ERR); - GTEST_LOG_(INFO) << "OnRemoteRequest_0300 end"; -} - /** * @tc.number: NotifyReplicaTerminatedInner_0100 * @tc.name: NotifyReplicaTerminatedInner diff --git a/test/unittest/frameworks_kits_ability_native_test/reverse_continuation_scheduler_replica_proxy_test.cpp b/test/unittest/frameworks_kits_ability_native_test/reverse_continuation_scheduler_replica_proxy_test.cpp index e007cfc0b0..9f7f680d80 100644 --- a/test/unittest/frameworks_kits_ability_native_test/reverse_continuation_scheduler_replica_proxy_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/reverse_continuation_scheduler_replica_proxy_test.cpp @@ -18,7 +18,6 @@ #include "continuation_handler.h" #include "continuation_manager.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_new_ability.h" #include "mock_reverse_continuation_scheduler_replica_stub.h" #include "reverse_continuation_scheduler_primary.h" diff --git a/test/unittest/frameworks_kits_ability_native_test/reverse_continuation_scheduler_replica_stub_test.cpp b/test/unittest/frameworks_kits_ability_native_test/reverse_continuation_scheduler_replica_stub_test.cpp index 97f3d02386..9582b811ab 100644 --- a/test/unittest/frameworks_kits_ability_native_test/reverse_continuation_scheduler_replica_stub_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/reverse_continuation_scheduler_replica_stub_test.cpp @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_reverse_continuation_scheduler_replica_stub.h" #include "reverse_continuation_scheduler_replica_stub.h" diff --git a/test/unittest/frameworks_kits_ability_native_test/service_ability_impl_test.cpp b/test/unittest/frameworks_kits_ability_native_test/service_ability_impl_test.cpp index 8f04723848..e2d3be03be 100644 --- a/test/unittest/frameworks_kits_ability_native_test/service_ability_impl_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/service_ability_impl_test.cpp @@ -17,7 +17,6 @@ #include "context_deal.h" #include "fa_ability_thread.h" -#include "hilog_wrapper.h" #include "mock_ability_token.h" #include "mock_service_ability.h" #include "service_ability_impl.h" diff --git a/test/unittest/frameworks_kits_ability_native_test/task_handler_client_test.cpp b/test/unittest/frameworks_kits_ability_native_test/task_handler_client_test.cpp index 50cefa9c90..37495c283c 100644 --- a/test/unittest/frameworks_kits_ability_native_test/task_handler_client_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/task_handler_client_test.cpp @@ -16,7 +16,6 @@ #include #include "task_handler_client.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { 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 04f087b76c..1bff5bc100 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 @@ -22,7 +22,6 @@ #undef private #include "ability_handler.h" #include "context_deal.h" -#include "hilog_wrapper.h" #include "locale_config.h" #include "mock_ability_impl.h" #include "mock_ability_token.h" @@ -106,7 +105,7 @@ HWTEST_F(UIAbilityImplTest, AbilityRuntime_ScheduleUpdateConfiguration_001, Test EXPECT_EQ(testNotify1, 0); mockUIAbilityimpl->ScheduleUpdateConfiguration(config); auto testNotify2 = pMocKUIAbility->OnConfigurationUpdated_; - EXPECT_EQ(testNotify2, 0); + EXPECT_EQ(testNotify2, 1); } } GTEST_LOG_(INFO) << "AbilityRuntime_ScheduleUpdateConfiguration_001 end"; @@ -154,14 +153,14 @@ HWTEST_F(UIAbilityImplTest, AbilityRuntime_ScheduleUpdateConfiguration_002, Test Configuration config; mockUIAbilityimpl->ScheduleUpdateConfiguration(config); auto testNotify2 = pMocKUIAbility->OnConfigurationUpdated_; - EXPECT_EQ(testNotify2, 0); + EXPECT_EQ(testNotify2, 1); auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage(); GTEST_LOG_(INFO) << "AbilityRuntime_ScheduleUpdateConfiguration_002 : " << language; config.AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE, language); mockUIAbilityimpl->SetlifecycleState(AAFwk::ABILITY_STATE_ACTIVE); mockUIAbilityimpl->ScheduleUpdateConfiguration(config); auto testNotify3 = pMocKUIAbility->OnConfigurationUpdated_; - EXPECT_EQ(testNotify3, 1); + EXPECT_EQ(testNotify3, 2); } } GTEST_LOG_(INFO) << "AbilityRuntime_ScheduleUpdateConfiguration_002 end"; @@ -212,17 +211,17 @@ HWTEST_F(UIAbilityImplTest, AbilityRuntime_ScheduleUpdateConfiguration_003, Test EXPECT_EQ(testNotify1, 0); mockUIAbilityimpl->ScheduleUpdateConfiguration(config); auto testNotify2 = pMocKUIAbility->OnConfigurationUpdated_; - EXPECT_EQ(testNotify2, 0); + EXPECT_EQ(testNotify2, 1); auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage(); GTEST_LOG_(INFO) << "AbilityRuntime_ScheduleUpdateConfiguration_003 : " << language; config.AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE, language); mockUIAbilityimpl->SetlifecycleState(AAFwk::ABILITY_STATE_ACTIVE); mockUIAbilityimpl->ScheduleUpdateConfiguration(config); auto testNotify3 = pMocKUIAbility->OnConfigurationUpdated_; - EXPECT_EQ(testNotify3, 1); + EXPECT_EQ(testNotify3, 2); mockUIAbilityimpl->ScheduleUpdateConfiguration(config); auto testNotify4 = pMocKUIAbility->OnConfigurationUpdated_; - EXPECT_EQ(testNotify4, 2); + EXPECT_EQ(testNotify4, 3); } } GTEST_LOG_(INFO) << "AbilityRuntime_ScheduleUpdateConfiguration_003 end"; diff --git a/test/unittest/frameworks_kits_ability_native_test/ui_ability_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ui_ability_test.cpp index 0792a35927..5c3acf9a63 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ui_ability_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ui_ability_test.cpp @@ -25,7 +25,6 @@ #include "ability_recovery.h" #include "fa_ability_thread.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_lifecycle_observer.h" #include "ohos_application.h" #include "runtime.h" diff --git a/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn b/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn index 1765794194..14a73f3961 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn +++ b/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn @@ -104,10 +104,65 @@ ohos_unittest("application_test") { "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include/mock_bundle_manager.cpp", "${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", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${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_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:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:configuration", + "ability_base:extractortool", + "ability_base:want", + "ability_runtime:runtime", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_core", + "napi:ace_napi", + "resource_management:global_resmgr", + ] + + if (ability_runtime_graphics) { + external_deps += [ "window_manager:libwm" ] + } +} + +ohos_unittest("context_impl_test") { + module_out_path = module_output_path + + include_dirs = [ + "${ability_runtime_services_path}/common/include", + "${ability_runtime_test_path}/mock/common/include", + "${resource_management_path}/frameworks/resmgr/include", + ] + + sources = [ + "${ability_runtime_native_path}/appkit/app/app_context.cpp", + "${ability_runtime_native_path}/appkit/app/app_loader.cpp", + "${ability_runtime_native_path}/appkit/app/application_cleaner.cpp", + "${ability_runtime_native_path}/appkit/app/ohos_application.cpp", + "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include/mock_bundle_manager.cpp", "context_impl_test.cpp", ] @@ -301,6 +356,7 @@ ohos_unittest("application_impl_test") { "ability_base:configuration", "ability_base:want", "ability_runtime:runtime", + "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", @@ -351,18 +407,20 @@ ohos_unittest("ability_start_setting_test") { ohos_unittest("ability_stage_test") { module_out_path = module_output_path + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" + sources = [ - "${ability_runtime_native_path}/appkit/app/app_context.cpp", - "${ability_runtime_native_path}/appkit/app/app_loader.cpp", - "${ability_runtime_native_path}/appkit/app/application_cleaner.cpp", - "${ability_runtime_native_path}/appkit/app/ohos_application.cpp", "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include/mock_bundle_manager.cpp", "${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_data_manager_test.cpp", - "application_test.cpp", - "context_impl_test.cpp", ] configs = [ ":module_private_config" ] @@ -457,20 +515,20 @@ ohos_unittest("form_extension_context_test") { ohos_unittest("bms_context_impl_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_services_path}/common/include", "${resource_management_path}/frameworks/resmgr/include", "${ability_runtime_test_path}/mock/common/include", ] - sources = [ - "${ability_runtime_native_path}/appkit/app/app_context.cpp", - "${ability_runtime_native_path}/appkit/app/app_loader.cpp", - "${ability_runtime_native_path}/appkit/app/application_cleaner.cpp", - "${ability_runtime_native_path}/appkit/app/ohos_application.cpp", - "bms_context_impl_test.cpp", - ] + sources = [ "bms_context_impl_test.cpp" ] configs = [ ":module_private_config" ] diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_args_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_args_test.cpp index 457bd4e89d..795ee8c2b1 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_args_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_args_test.cpp @@ -22,7 +22,6 @@ #undef private #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "want.h" using namespace testing::ext; diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_registry_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_registry_test.cpp index 487de349dd..46e6d35f18 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_registry_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_registry_test.cpp @@ -26,7 +26,6 @@ #include "app_loader.h" #include "event_runner.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "mock_ability_delegator_stub.h" #include "ohos_application.h" diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_test.cpp index abfb21377b..0be170a4d0 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_test.cpp @@ -22,25 +22,24 @@ #define private public #include "ability_delegator.h" #include "ability_manager_client.h" -#include "foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context/context_impl.h" +#include "context_impl.h" #undef private #include "ability_delegator_infos.h" #include "ability_delegator_registry.h" #include "app_loader.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "mock_ability_delegator_stub.h" #include "mock_iability_monitor.h" #include "mock_test_observer_stub.h" #include "mock_test_runner.h" #include "ohos_application.h" +#include "scene_board_judgement.h" #include "test_observer_stub.h" #include "test_observer.h" #include "test_runner.h" #include "want.h" -#include "scene_board_judgement.h" using namespace testing; using namespace testing::ext; diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/delegator_thread_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/delegator_thread_test.cpp index ae96fa3434..98b10b783c 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/delegator_thread_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/delegator_thread_test.cpp @@ -20,7 +20,6 @@ #undef private #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing::ext; using namespace OHOS; diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/iability_monitor_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/iability_monitor_test.cpp index e0278e9724..516a62a1a7 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/iability_monitor_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/iability_monitor_test.cpp @@ -29,7 +29,6 @@ #undef private #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_delegator_stub.h" #include "native_engine/native_reference.h" diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/js_test_runner_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/js_test_runner_test.cpp index ad0795b859..1528289697 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/js_test_runner_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/js_test_runner_test.cpp @@ -27,7 +27,6 @@ #include "app_loader.h" #include "event_runner.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "napi/native_common.h" #include "mock_ability_delegator_stub.h" #include "mock_test_observer_stub.h" diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/shell_cmd_result_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/shell_cmd_result_test.cpp index ded5cd7507..e5060e0e66 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/shell_cmd_result_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/shell_cmd_result_test.cpp @@ -17,7 +17,6 @@ #include "shell_cmd_result.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing::ext; using namespace OHOS; diff --git a/test/unittest/frameworks_kits_appkit_native_test/bms_context_impl_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/bms_context_impl_test.cpp index d83c739971..7af46a5edf 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/bms_context_impl_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/bms_context_impl_test.cpp @@ -23,7 +23,6 @@ #include "ability_local_record.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "mock_bundle_installer_service.h" #include "mock_bundle_manager_service.h" diff --git a/test/unittest/frameworks_kits_appkit_native_test/context_container_by_mock_bms_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/context_container_by_mock_bms_test.cpp index 4c8882e6ad..d1eb14311d 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/context_container_by_mock_bms_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/context_container_by_mock_bms_test.cpp @@ -20,7 +20,6 @@ #include "ability_context.h" #include "context_container.h" #include "context_deal.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "mock_bundle_installer_service.h" 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 6e553396b8..51b33fa10f 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 @@ -26,7 +26,6 @@ #include "context.h" #include "hap_module_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "mock_ability_token.h" #include "mock_bundle_manager.h" @@ -653,7 +652,7 @@ HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetApplicationInfo_001, Functio HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetApplicationContext_001, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationContext_001 start"; - EXPECT_FALSE(contextImpl_->GetApplicationContext() == nullptr); + EXPECT_TRUE(contextImpl_->GetApplicationContext() == nullptr); auto contextImpl = std::make_shared(); EXPECT_NE(contextImpl, nullptr); @@ -678,7 +677,7 @@ HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_SetParentContext_001, Function GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetParentContext_001 start"; std::shared_ptr contextImpl_ = std::make_shared(); contextImpl_->SetParentContext(contextImpl_); - EXPECT_FALSE(contextImpl_->GetApplicationContext() == nullptr); + EXPECT_TRUE(contextImpl_->GetApplicationContext() == nullptr); GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetParentContext_001 end"; } diff --git a/test/unittest/free_install_manager_test/free_install_manager_test.cpp b/test/unittest/free_install_manager_test/free_install_manager_test.cpp index fad2764103..fc0aea65a7 100644 --- a/test/unittest/free_install_manager_test/free_install_manager_test.cpp +++ b/test/unittest/free_install_manager_test/free_install_manager_test.cpp @@ -98,7 +98,7 @@ HWTEST_F(FreeInstallTest, FreeInstall_StartFreeInstall_001, TestSize.Level1) break; } } - freeInstallManager_->OnInstallFinished(0, want, userId, false); + freeInstallManager_->OnInstallFinished(-1, 0, want, userId, false); EXPECT_EQ(res, 0); } @@ -153,7 +153,7 @@ HWTEST_F(FreeInstallTest, FreeInstall_StartFreeInstall_003, TestSize.Level1) break; } } - freeInstallManager_->OnInstallFinished(1, want, userId, false); + freeInstallManager_->OnInstallFinished(-1, 1, want, userId, false); EXPECT_EQ(res, 0); } @@ -177,7 +177,7 @@ HWTEST_F(FreeInstallTest, FreeInstall_OnInstallFinished_001, TestSize.Level1) FreeInstallInfo info = freeInstallManager_->BuildFreeInstallInfo(want, userId, requestCode, nullptr, false); freeInstallManager_->freeInstallList_.resize(0); freeInstallManager_->freeInstallList_.emplace_back(info); - freeInstallManager_->OnInstallFinished(0, want, userId, false); + freeInstallManager_->OnInstallFinished(-1, 0, want, userId, false); for (auto it = freeInstallManager_->freeInstallList_.begin(); it != freeInstallManager_->freeInstallList_.end(); it++) { @@ -211,7 +211,7 @@ HWTEST_F(FreeInstallTest, FreeInstall_OnInstallFinished_002, TestSize.Level1) FreeInstallInfo info = freeInstallManager_->BuildFreeInstallInfo(want, userId, requestCode, nullptr, false); freeInstallManager_->freeInstallList_.resize(0); freeInstallManager_->freeInstallList_.emplace_back(info); - freeInstallManager_->OnInstallFinished(1, want, userId, false); + freeInstallManager_->OnInstallFinished(-1, 1, want, userId, false); for (auto it = freeInstallManager_->freeInstallList_.begin(); it != freeInstallManager_->freeInstallList_.end(); it++) { @@ -247,7 +247,7 @@ HWTEST_F(FreeInstallTest, FreeInstall_OnInstallFinished_003, TestSize.Level1) freeInstallManager_->freeInstallList_.resize(0); info.promise.reset(); freeInstallManager_->freeInstallList_.emplace_back(info); - freeInstallManager_->OnInstallFinished(0, want, userId, false); + freeInstallManager_->OnInstallFinished(-1, 0, want, userId, false); int size = freeInstallManager_->freeInstallList_.size(); EXPECT_EQ(size, 1); @@ -291,7 +291,7 @@ HWTEST_F(FreeInstallTest, FreeInstall_OnRemoteInstallFinished_001, TestSize.Leve FreeInstallInfo info = freeInstallManager_->BuildFreeInstallInfo(want, userId, requestCode, nullptr, false); freeInstallManager_->freeInstallList_.resize(0); freeInstallManager_->freeInstallList_.emplace_back(info); - freeInstallManager_->OnRemoteInstallFinished(0, want, userId); + freeInstallManager_->OnRemoteInstallFinished(-1, 0, want, userId); for (auto it = freeInstallManager_->freeInstallList_.begin(); it != freeInstallManager_->freeInstallList_.end(); it++) { @@ -323,5 +323,181 @@ HWTEST_F(FreeInstallTest, FreeInstall_ConnectFreeInstall_001, TestSize.Level1) int res = freeInstallManager_->ConnectFreeInstall(want, userId, nullptr, ""); EXPECT_NE(res, 0); } + + +/** + * @tc.number: FreeInstall_UpdateElementName_001 + * @tc.name: UpdateElementName + * @tc.desc: Test UpdateElementName. + */ +HWTEST_F(FreeInstallTest, FreeInstall_UpdateElementName_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + freeInstallManager_ = std::make_shared(abilityMs_); + Want want; + const int32_t userId = 1; + freeInstallManager_->UpdateElementName(want, userId); + freeInstallManager_->GetTimeStamp(); +} + +/** + * @tc.number: FreeInstall_AddFreeInstallObserver_001 + * @tc.name: AddFreeInstallObserver + * @tc.desc: Test AddFreeInstallObserver. + */ +HWTEST_F(FreeInstallTest, FreeInstall_AddFreeInstallObserver_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + freeInstallManager_ = std::make_shared(abilityMs_); + + const sptr callerToken = MockToken(); + freeInstallManager_->AddFreeInstallObserver(nullptr, nullptr); + + freeInstallManager_->AddFreeInstallObserver(callerToken, nullptr); +} + +/** + * @tc.number: FreeInstall_RemoveFreeInstallInfo_001 + * @tc.name: RemoveFreeInstallInfo + * @tc.desc: Test RemoveFreeInstallInfo. + */ +HWTEST_F(FreeInstallTest, FreeInstall_RemoveFreeInstallInfo_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + freeInstallManager_ = std::make_shared(abilityMs_); + + freeInstallManager_->RemoveFreeInstallInfo("com.ix.hiservcie", "ServiceAbility", "2024-7-17 00:00:00"); +} + +/** + * @tc.number: FreeInstall_GetFreeInstallTaskInfo_001 + * @tc.name: GetFreeInstallTaskInfo + * @tc.desc: Test GetFreeInstallTaskInfo. + */ +HWTEST_F(FreeInstallTest, FreeInstall_GetFreeInstallTaskInfo_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + freeInstallManager_ = std::make_shared(abilityMs_); + + FreeInstallInfo freeInstallInfo; + freeInstallManager_->GetFreeInstallTaskInfo("sessionId", freeInstallInfo); +} + +/** + * @tc.number: FreeInstall_SetSCBCallStatus_001 + * @tc.name: SetSCBCallStatus + * @tc.desc: Test SetSCBCallStatus. + */ +HWTEST_F(FreeInstallTest, FreeInstall_SetSCBCallStatus_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + freeInstallManager_ = std::make_shared(abilityMs_); + + freeInstallManager_->SetSCBCallStatus("com.ix.hiservcie", "ServiceAbility", "2024-7-17 00:00:00", false); +} + +/** + * @tc.number: FreeInstall_SetPreStartMissionCallStatus_001 + * @tc.name: SetPreStartMissionCallStatus + * @tc.desc: Test SetPreStartMissionCallStatus. + */ +HWTEST_F(FreeInstallTest, FreeInstall_SetPreStartMissionCallStatus_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + freeInstallManager_ = std::make_shared(abilityMs_); + + freeInstallManager_->SetPreStartMissionCallStatus("com.ix.hiservcie", "ServiceAbility", + "2024-7-17 00:00:00", false); +} + +/** + * @tc.number: FreeInstall_SetFreeInstallTaskSessionId_001 + * @tc.name: SetFreeInstallTaskSessionId + * @tc.desc: Test SetFreeInstallTaskSessionId. + */ +HWTEST_F(FreeInstallTest, FreeInstall_SetFreeInstallTaskSessionId_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + freeInstallManager_ = std::make_shared(abilityMs_); + + freeInstallManager_->SetFreeInstallTaskSessionId("com.ix.hiservcie", "ServiceAbility", + "2024-7-17 00:00:00", "sessionId"); +} + +/** + * @tc.number: FreeInstall_VerifyStartFreeInstallPermission_001 + * @tc.name: VerifyStartFreeInstallPermission + * @tc.desc: Test VerifyStartFreeInstallPermission. + */ +HWTEST_F(FreeInstallTest, FreeInstall_VerifyStartFreeInstallPermission_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + freeInstallManager_ = std::make_shared(abilityMs_); + + const sptr callerToken = MockToken(); + freeInstallManager_->VerifyStartFreeInstallPermission(callerToken); + freeInstallManager_->GetRecordIdByToken(callerToken); +} + +/** + * @tc.number: FreeInstall_SetAppRunningState_001 + * @tc.name: SetAppRunningState + * @tc.desc: Test SetAppRunningState. + */ +HWTEST_F(FreeInstallTest, FreeInstall_SetAppRunningState_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + freeInstallManager_ = std::make_shared(abilityMs_); + + Want want; + freeInstallManager_->SetAppRunningState(want); +} + +/** + * @tc.number: FreeInstall_PostUpgradeAtomicServiceTask_001 + * @tc.name: PostUpgradeAtomicServiceTask + * @tc.desc: Test PostUpgradeAtomicServiceTask. + */ +HWTEST_F(FreeInstallTest, FreeInstall_PostUpgradeAtomicServiceTask_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + freeInstallManager_ = std::make_shared(abilityMs_); + + Want want; + ElementName element("", "com.test.demo", "MainAbility"); + want.SetElement(element); + const int32_t userId = 100; + int resultCode = 0; + freeInstallManager_->PostUpgradeAtomicServiceTask(resultCode, want, userId); +} + +/** + * @tc.number: FreeInstall_StartAbilityByOriginalWant_001 + * @tc.name: StartAbilityByOriginalWant + * @tc.desc: Test StartAbilityByOriginalWant. + */ +HWTEST_F(FreeInstallTest, FreeInstall_StartAbilityByOriginalWant_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + freeInstallManager_ = std::make_shared(abilityMs_); + + FreeInstallInfo freeInstallInfo; + freeInstallManager_->StartAbilityByOriginalWant(freeInstallInfo, "2024-07-17 00:00:00"); +} + +/** + * @tc.number: FreeInstall_StartAbilityByConvertedWant_001 + * @tc.name: StartAbilityByConvertedWant + * @tc.desc: Test StartAbilityByConvertedWant. + */ +HWTEST_F(FreeInstallTest, FreeInstall_StartAbilityByConvertedWant_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + freeInstallManager_ = std::make_shared(abilityMs_); + + FreeInstallInfo freeInstallInfo; + freeInstallManager_->StartAbilityByConvertedWant(freeInstallInfo, "2024-07-17 00:00:00"); +} + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/freeze_util_test/freeze_util_test.cpp b/test/unittest/freeze_util_test/freeze_util_test.cpp index 66d651ef40..1eb37ae5a2 100644 --- a/test/unittest/freeze_util_test/freeze_util_test.cpp +++ b/test/unittest/freeze_util_test/freeze_util_test.cpp @@ -17,7 +17,6 @@ #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; diff --git a/test/unittest/implicit_start_processor_test/BUILD.gn b/test/unittest/implicit_start_processor_test/BUILD.gn index 6b137d8243..36a75fd373 100755 --- a/test/unittest/implicit_start_processor_test/BUILD.gn +++ b/test/unittest/implicit_start_processor_test/BUILD.gn @@ -20,7 +20,12 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("implicit_start_processor_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", diff --git a/test/unittest/insight_intent/insight_intent_execute_manager_test/insight_intent_execute_manager_test.cpp b/test/unittest/insight_intent/insight_intent_execute_manager_test/insight_intent_execute_manager_test.cpp index 7dbe1a6b6d..6fddaaa1ce 100644 --- a/test/unittest/insight_intent/insight_intent_execute_manager_test/insight_intent_execute_manager_test.cpp +++ b/test/unittest/insight_intent/insight_intent_execute_manager_test/insight_intent_execute_manager_test.cpp @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "want.h" #include "insight_intent_execute_param.h" #include "insight_intent_execute_manager.h" diff --git a/test/unittest/insight_intent/insight_intent_execute_param_test/insight_intent_execute_param_test.cpp b/test/unittest/insight_intent/insight_intent_execute_param_test/insight_intent_execute_param_test.cpp index c038622947..ccbeccb269 100644 --- a/test/unittest/insight_intent/insight_intent_execute_param_test/insight_intent_execute_param_test.cpp +++ b/test/unittest/insight_intent/insight_intent_execute_param_test/insight_intent_execute_param_test.cpp @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "want.h" #include "want_params_wrapper.h" #include "insight_intent_execute_param.h" diff --git a/test/unittest/js_auto_fill_extension_test/BUILD.gn b/test/unittest/js_auto_fill_extension_test/BUILD.gn index 11e750bfd5..6a919c7e81 100644 --- a/test/unittest/js_auto_fill_extension_test/BUILD.gn +++ b/test/unittest/js_auto_fill_extension_test/BUILD.gn @@ -28,7 +28,6 @@ ohos_unittest("js_auto_fill_extension_test") { "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include", "//third_party/jsoncpp/include", - "//third_party/json/include", ] sources = [ "js_auto_fill_extension_test.cpp" ] @@ -62,6 +61,7 @@ ohos_unittest("js_auto_fill_extension_test") { "i18n:intl_util", "init:libbegetutil", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", "resource_management:global_resmgr", ] diff --git a/test/unittest/js_auto_fill_extension_test/js_auto_fill_extension_test.cpp b/test/unittest/js_auto_fill_extension_test/js_auto_fill_extension_test.cpp index 36dc809187..41358a9fd5 100644 --- a/test/unittest/js_auto_fill_extension_test/js_auto_fill_extension_test.cpp +++ b/test/unittest/js_auto_fill_extension_test/js_auto_fill_extension_test.cpp @@ -26,7 +26,6 @@ #undef private #undef protected #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #define private public #define protected public diff --git a/test/unittest/js_service_extension_test/BUILD.gn b/test/unittest/js_service_extension_test/BUILD.gn index e69761f716..202ea65685 100644 --- a/test/unittest/js_service_extension_test/BUILD.gn +++ b/test/unittest/js_service_extension_test/BUILD.gn @@ -27,7 +27,6 @@ ohos_unittest("js_service_extension_test") { "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include", "//third_party/jsoncpp/include", - "//third_party/json/include", ] sources = [ @@ -63,6 +62,7 @@ ohos_unittest("js_service_extension_test") { "i18n:intl_util", "init:libbegetutil", "ipc:ipc_core", + "json:nlohmann_json_static", "napi:ace_napi", "resource_management:global_resmgr", ] diff --git a/test/unittest/js_service_extension_test/js_service_extension_test.cpp b/test/unittest/js_service_extension_test/js_service_extension_test.cpp index 1b60045927..943437a609 100644 --- a/test/unittest/js_service_extension_test/js_service_extension_test.cpp +++ b/test/unittest/js_service_extension_test/js_service_extension_test.cpp @@ -25,7 +25,6 @@ #undef private #undef protected #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_object.h" #include "js_runtime.h" #define private public diff --git a/test/unittest/mission_data_storage_test/BUILD.gn b/test/unittest/mission_data_storage_test/BUILD.gn index ed04925f22..4e3cb6a194 100755 --- a/test/unittest/mission_data_storage_test/BUILD.gn +++ b/test/unittest/mission_data_storage_test/BUILD.gn @@ -41,6 +41,7 @@ ohos_unittest("mission_data_storage_test") { "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${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/mission_info_mgr_test/BUILD.gn b/test/unittest/mission_info_mgr_test/BUILD.gn index cef4142f08..058082a4a1 100755 --- a/test/unittest/mission_info_mgr_test/BUILD.gn +++ b/test/unittest/mission_info_mgr_test/BUILD.gn @@ -42,6 +42,7 @@ ohos_unittest("mission_info_mgr_test") { "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_appmgr_mock", diff --git a/test/unittest/mission_list_dump_test/BUILD.gn b/test/unittest/mission_list_dump_test/BUILD.gn index 6dd615ff90..aa6decb2df 100644 --- a/test/unittest/mission_list_dump_test/BUILD.gn +++ b/test/unittest/mission_list_dump_test/BUILD.gn @@ -23,7 +23,10 @@ ohos_unittest("mission_list_dump_test") { configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] - deps = [ "${ability_runtime_services_path}/abilitymgr:abilityms" ] + deps = [ + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", + ] external_deps = [ "ability_base:session_info", diff --git a/test/unittest/mission_list_dump_test/mission_list_dump_test.cpp b/test/unittest/mission_list_dump_test/mission_list_dump_test.cpp index b6b95274da..6639f87e02 100644 --- a/test/unittest/mission_list_dump_test/mission_list_dump_test.cpp +++ b/test/unittest/mission_list_dump_test/mission_list_dump_test.cpp @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #define private public #include "mission_list.h" #undef private diff --git a/test/unittest/mission_list_manager_dump_test/BUILD.gn b/test/unittest/mission_list_manager_dump_test/BUILD.gn index 732b0537b4..b5519e87dd 100644 --- a/test/unittest/mission_list_manager_dump_test/BUILD.gn +++ b/test/unittest/mission_list_manager_dump_test/BUILD.gn @@ -25,6 +25,7 @@ ohos_unittest("mission_list_manager_dump_test") { deps = [ "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "//third_party/googletest:gtest_main", ] diff --git a/test/unittest/mission_list_manager_dump_test/mission_list_manager_dump_test.cpp b/test/unittest/mission_list_manager_dump_test/mission_list_manager_dump_test.cpp index d743862bf4..edc851b409 100644 --- a/test/unittest/mission_list_manager_dump_test/mission_list_manager_dump_test.cpp +++ b/test/unittest/mission_list_manager_dump_test/mission_list_manager_dump_test.cpp @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #define private public #include "mission_list_manager.h" #undef private diff --git a/test/unittest/mission_list_manager_test/BUILD.gn b/test/unittest/mission_list_manager_test/BUILD.gn index 7a38e81a5b..c1a147b6d7 100644 --- a/test/unittest/mission_list_manager_test/BUILD.gn +++ b/test/unittest/mission_list_manager_test/BUILD.gn @@ -50,6 +50,7 @@ ohos_unittest("mission_list_manager_test") { "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_appmgr_mock", diff --git a/test/unittest/mission_list_manager_test/mission_list_manager_test.cpp b/test/unittest/mission_list_manager_test/mission_list_manager_test.cpp index c9c8f1a12e..1927179832 100644 --- a/test/unittest/mission_list_manager_test/mission_list_manager_test.cpp +++ b/test/unittest/mission_list_manager_test/mission_list_manager_test.cpp @@ -20,7 +20,6 @@ #include "ability_info.h" #include "ability_manager_errors.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mission.h" #include "mission_info_mgr.h" #include "mission_list_manager.h" diff --git a/test/unittest/mission_list_manager_ut_test/BUILD.gn b/test/unittest/mission_list_manager_ut_test/BUILD.gn index f96461b545..fef373f8bc 100644 --- a/test/unittest/mission_list_manager_ut_test/BUILD.gn +++ b/test/unittest/mission_list_manager_ut_test/BUILD.gn @@ -18,7 +18,12 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("mission_list_manager_ut_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", @@ -40,6 +45,7 @@ ohos_unittest("mission_list_manager_ut_test") { "${ability_runtime_native_path}/ability/native:ability_thread", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_appmgr_mock", diff --git a/test/unittest/mission_list_test/BUILD.gn b/test/unittest/mission_list_test/BUILD.gn index 937d6618f3..dacb1e581e 100644 --- a/test/unittest/mission_list_test/BUILD.gn +++ b/test/unittest/mission_list_test/BUILD.gn @@ -40,6 +40,7 @@ ohos_unittest("mission_list_test") { deps = [ "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_appmgr_mock", @@ -86,6 +87,7 @@ ohos_unittest("mission_list_test_call") { deps = [ "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "//third_party/googletest:gtest_main", ] diff --git a/test/unittest/mission_listener_proxy_test/BUILD.gn b/test/unittest/mission_listener_proxy_test/BUILD.gn index 56f2ef0983..a301cdf7ce 100755 --- a/test/unittest/mission_listener_proxy_test/BUILD.gn +++ b/test/unittest/mission_listener_proxy_test/BUILD.gn @@ -18,7 +18,13 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("mission_listener_proxy_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", diff --git a/test/unittest/mission_listener_test/BUILD.gn b/test/unittest/mission_listener_test/BUILD.gn index 53ae6f859c..84807a8561 100644 --- a/test/unittest/mission_listener_test/BUILD.gn +++ b/test/unittest/mission_listener_test/BUILD.gn @@ -18,7 +18,12 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("mission_listener_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core", diff --git a/test/unittest/mission_listener_test/mission_listener_test.cpp b/test/unittest/mission_listener_test/mission_listener_test.cpp index 1e96d699dc..208d252ceb 100644 --- a/test/unittest/mission_listener_test/mission_listener_test.cpp +++ b/test/unittest/mission_listener_test/mission_listener_test.cpp @@ -17,7 +17,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mission_listener_controller.h" #include "mission_listener_stub.h" diff --git a/test/unittest/mission_test/BUILD.gn b/test/unittest/mission_test/BUILD.gn index 10f1ad977e..906486680b 100644 --- a/test/unittest/mission_test/BUILD.gn +++ b/test/unittest/mission_test/BUILD.gn @@ -40,6 +40,7 @@ ohos_unittest("mission_test") { deps = [ "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_appmgr_mock", diff --git a/test/unittest/napi_base_context_test/napi_base_context_test.cpp b/test/unittest/napi_base_context_test/napi_base_context_test.cpp index e162873cdd..4e7ae97973 100644 --- a/test/unittest/napi_base_context_test/napi_base_context_test.cpp +++ b/test/unittest/napi_base_context_test/napi_base_context_test.cpp @@ -17,7 +17,6 @@ #include "napi_base_context.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing::ext; diff --git a/test/unittest/native_runtime_test/native_runtime_test.cpp b/test/unittest/native_runtime_test/native_runtime_test.cpp index 7f46aee1ef..b9e79bae58 100644 --- a/test/unittest/native_runtime_test/native_runtime_test.cpp +++ b/test/unittest/native_runtime_test/native_runtime_test.cpp @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" #include "js_environment.h" #include "native_runtime_impl.h" diff --git a/test/unittest/pending_want_manager_dump_test/pending_want_manager_dump_test.cpp b/test/unittest/pending_want_manager_dump_test/pending_want_manager_dump_test.cpp index 0eea8401b4..c432d7b90d 100644 --- a/test/unittest/pending_want_manager_dump_test/pending_want_manager_dump_test.cpp +++ b/test/unittest/pending_want_manager_dump_test/pending_want_manager_dump_test.cpp @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #define private public #include "pending_want_manager.h" #undef private diff --git a/test/unittest/pending_want_record_test/BUILD.gn b/test/unittest/pending_want_record_test/BUILD.gn index 81def2a390..986ce5c0d5 100644 --- a/test/unittest/pending_want_record_test/BUILD.gn +++ b/test/unittest/pending_want_record_test/BUILD.gn @@ -18,7 +18,13 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("pending_want_record_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", @@ -39,7 +45,6 @@ ohos_unittest("pending_want_record_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${ability_runtime_innerkits_path}/wantagent:wantagent_innerkits", "${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/pending_want_test/pending_want_test.cpp b/test/unittest/pending_want_test/pending_want_test.cpp index e3d7b2922e..58a974938f 100644 --- a/test/unittest/pending_want_test/pending_want_test.cpp +++ b/test/unittest/pending_want_test/pending_want_test.cpp @@ -54,7 +54,6 @@ #include "string_wrapper.h" #include "array_wrapper.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing::ext; using namespace OHOS::AAFwk; diff --git a/test/unittest/quick_fix/mock/src/mock_quick_fix_util.cpp b/test/unittest/quick_fix/mock/src/mock_quick_fix_util.cpp index 2026e418e5..0a14c48fcc 100644 --- a/test/unittest/quick_fix/mock/src/mock_quick_fix_util.cpp +++ b/test/unittest/quick_fix/mock/src/mock_quick_fix_util.cpp @@ -16,7 +16,6 @@ #include "mock_quick_fix_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "system_ability_definition.h" diff --git a/test/unittest/quick_fix/quick_fix_callback_proxy_test/quick_fix_callback_proxy_test.cpp b/test/unittest/quick_fix/quick_fix_callback_proxy_test/quick_fix_callback_proxy_test.cpp index edb449d2fa..6c96b8d56c 100644 --- a/test/unittest/quick_fix/quick_fix_callback_proxy_test/quick_fix_callback_proxy_test.cpp +++ b/test/unittest/quick_fix/quick_fix_callback_proxy_test/quick_fix_callback_proxy_test.cpp @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #define private public #include "mock_quick_fix_callback_stub.h" #include "quick_fix_callback_proxy.h" diff --git a/test/unittest/quick_fix/quick_fix_callback_stub_test/quick_fix_callback_stub_test.cpp b/test/unittest/quick_fix/quick_fix_callback_stub_test/quick_fix_callback_stub_test.cpp index 2f14c3d560..85ffb70f70 100644 --- a/test/unittest/quick_fix/quick_fix_callback_stub_test/quick_fix_callback_stub_test.cpp +++ b/test/unittest/quick_fix/quick_fix_callback_stub_test/quick_fix_callback_stub_test.cpp @@ -20,7 +20,6 @@ #include "mock_quick_fix_callback_stub.h" #undef private #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing; using namespace testing::ext; diff --git a/test/unittest/quick_fix/quick_fix_callback_with_record_test/quick_fix_callback_with_record_test.cpp b/test/unittest/quick_fix/quick_fix_callback_with_record_test/quick_fix_callback_with_record_test.cpp index 45df28b33b..54aba74a68 100644 --- a/test/unittest/quick_fix/quick_fix_callback_with_record_test/quick_fix_callback_with_record_test.cpp +++ b/test/unittest/quick_fix/quick_fix_callback_with_record_test/quick_fix_callback_with_record_test.cpp @@ -17,7 +17,6 @@ #include "quick_fix_callback_with_record.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing; using namespace testing::ext; diff --git a/test/unittest/quick_fix/quick_fix_error_utils_test/quick_fix_error_utils_test.cpp b/test/unittest/quick_fix/quick_fix_error_utils_test/quick_fix_error_utils_test.cpp index 4ff70f40e3..c0fdaf2787 100644 --- a/test/unittest/quick_fix/quick_fix_error_utils_test/quick_fix_error_utils_test.cpp +++ b/test/unittest/quick_fix/quick_fix_error_utils_test/quick_fix_error_utils_test.cpp @@ -17,7 +17,6 @@ #include "quick_fix_error_utils.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing; using namespace testing::ext; diff --git a/test/unittest/quick_fix/quick_fix_manager_client_test/quick_fix_manager_client_test.cpp b/test/unittest/quick_fix/quick_fix_manager_client_test/quick_fix_manager_client_test.cpp index a6725566a1..7681b8304e 100644 --- a/test/unittest/quick_fix/quick_fix_manager_client_test/quick_fix_manager_client_test.cpp +++ b/test/unittest/quick_fix/quick_fix_manager_client_test/quick_fix_manager_client_test.cpp @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_bundle_manager.h" #include "mock_quick_fix_manager_stub.h" #include "mock_quick_fix_util.h" 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 bae12e9412..254e47f43b 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 @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "mock_bundle_manager.h" 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 f5dcb5304f..a3b2265461 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 @@ -17,7 +17,6 @@ #include "bundle_mgr_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "if_system_ability_manager.h" #include "mock_bundle_installer_service.h" #include "mock_bundle_manager.h" diff --git a/test/unittest/remote_mission_listener_proxy_test/BUILD.gn b/test/unittest/remote_mission_listener_proxy_test/BUILD.gn index 9be3156731..661f9d8ddb 100755 --- a/test/unittest/remote_mission_listener_proxy_test/BUILD.gn +++ b/test/unittest/remote_mission_listener_proxy_test/BUILD.gn @@ -18,7 +18,13 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("remote_mission_listener_proxy_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", diff --git a/test/unittest/res_sched_util_test/res_sched_util_test.cpp b/test/unittest/res_sched_util_test/res_sched_util_test.cpp index e0784f294a..43818deff3 100644 --- a/test/unittest/res_sched_util_test/res_sched_util_test.cpp +++ b/test/unittest/res_sched_util_test/res_sched_util_test.cpp @@ -17,7 +17,6 @@ #include "ability_info.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #define private public #include "res_sched_util.h" #undef private diff --git a/test/unittest/running_infos_test/BUILD.gn b/test/unittest/running_infos_test/BUILD.gn index 3e7675edd8..0f3f3357a7 100644 --- a/test/unittest/running_infos_test/BUILD.gn +++ b/test/unittest/running_infos_test/BUILD.gn @@ -29,6 +29,7 @@ ohos_unittest("running_infos_test") { "${ability_runtime_innerkits_path}/app_manager:app_manager", "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", ] diff --git a/test/unittest/running_infos_test/running_infos_test.cpp b/test/unittest/running_infos_test/running_infos_test.cpp index ce25a097e5..af4a842327 100644 --- a/test/unittest/running_infos_test/running_infos_test.cpp +++ b/test/unittest/running_infos_test/running_infos_test.cpp @@ -17,6 +17,7 @@ #define private public #define protected public #include "ability_manager_service.h" +#include "mission_list_manager.h" #undef private #undef protected #include "ability_manager_errors.h" @@ -148,7 +149,8 @@ HWTEST_F(RunningInfosTest, GetAbilityRunningInfos_004, TestSize.Level1) auto result = abilityMs_->StartAbility(want); if (result == OHOS::ERR_OK) { - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get())->GetCurrentTopAbilityLocked(); EXPECT_TRUE(topAbility); topAbility->SetAbilityState(AbilityState::FOREGROUND); } @@ -223,7 +225,8 @@ HWTEST_F(RunningInfosTest, GetAbilityRunningInfos_006, TestSize.Level1) auto result = abilityMs_->StartAbility(want); if (result == OHOS::ERR_OK) { - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get())->GetCurrentTopAbilityLocked(); EXPECT_TRUE(topAbility); topAbility->SetAbilityState(AbilityState::FOREGROUND); } @@ -262,7 +265,8 @@ HWTEST_F(RunningInfosTest, GetAbilityRunningInfos_007, TestSize.Level1) auto result = abilityMs_->StartAbility(want); if (result == OHOS::ERR_OK) { - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get())->GetCurrentTopAbilityLocked(); EXPECT_TRUE(topAbility); topAbility->SetAbilityState(AbilityState::ACTIVE); @@ -535,7 +539,8 @@ HWTEST_F(RunningInfosTest, MissionGetAbilityRunningInfos_002, TestSize.Level1) auto result = abilityMs_->StartAbility(want); if (result == OHOS::ERR_OK) { - auto topAbility = abilityMs_->subManagersHelper_->currentMissionListManager_->GetCurrentTopAbilityLocked(); + auto topAbility = reinterpret_cast(abilityMs_->subManagersHelper_-> + currentMissionListManager_.get())->GetCurrentTopAbilityLocked(); EXPECT_TRUE(topAbility); topAbility->SetAbilityState(AbilityState::FOREGROUND); } @@ -570,7 +575,6 @@ HWTEST_F(RunningInfosTest, MissionGetAbilityRunningInfos_002, TestSize.Level1) HWTEST_F(RunningInfosTest, DataGetAbilityRunningInfos_001, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); Want want; ElementName element("device", "com.ix.hiMusic", "MusicAbility"); want.SetElement(element); @@ -586,11 +590,12 @@ HWTEST_F(RunningInfosTest, DataGetAbilityRunningInfos_001, TestSize.Level1) abilityRequest.requestCode); dataAbilityRecord->ability_ = abilityRecord; const std::string dataAbilityName(abilityRequest.abilityInfo.bundleName + '.' + abilityRequest.abilityInfo.name); - abilityMs_->subManagersHelper_->currentDataAbilityManager_->dataAbilityRecordsLoading_.insert( + auto manager = std::make_shared(); + manager->dataAbilityRecordsLoading_.insert( std::pair>(dataAbilityName, dataAbilityRecord)); std::vector infos; - abilityMs_->subManagersHelper_->currentDataAbilityManager_->GetAbilityRunningInfos(infos, true); + manager->GetAbilityRunningInfos(infos, true); size_t infoCount{ 1 }; EXPECT_TRUE(infos.size() == infoCount); if (infos.size() == infoCount) { @@ -610,7 +615,6 @@ HWTEST_F(RunningInfosTest, DataGetAbilityRunningInfos_001, TestSize.Level1) HWTEST_F(RunningInfosTest, DataGetAbilityRunningInfos_002, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); Want want; ElementName element("device", "com.ix.hiMusic", "MusicAbility"); want.SetElement(element); @@ -626,11 +630,12 @@ HWTEST_F(RunningInfosTest, DataGetAbilityRunningInfos_002, TestSize.Level1) abilityRequest.requestCode); dataAbilityRecord->ability_ = abilityRecord; const std::string dataAbilityName(abilityRequest.abilityInfo.bundleName + '.' + abilityRequest.abilityInfo.name); - abilityMs_->subManagersHelper_->currentDataAbilityManager_->dataAbilityRecordsLoaded_.insert( + auto manager = std::make_shared(); + manager->dataAbilityRecordsLoaded_.insert( std::pair>(dataAbilityName, dataAbilityRecord)); std::vector infos; - abilityMs_->subManagersHelper_->currentDataAbilityManager_->GetAbilityRunningInfos(infos, true); + manager->GetAbilityRunningInfos(infos, true); size_t infoCount{ 1 }; EXPECT_TRUE(infos.size() == infoCount); if (infos.size() == infoCount) { @@ -650,7 +655,6 @@ HWTEST_F(RunningInfosTest, DataGetAbilityRunningInfos_002, TestSize.Level1) HWTEST_F(RunningInfosTest, DataGetAbilityRunningInfos_003, TestSize.Level1) { auto abilityMs_ = std::make_shared(); - abilityMs_->OnStart(); Want want; ElementName element("device", "com.ix.hiMusic", "MusicAbility"); want.SetElement(element); @@ -666,7 +670,8 @@ HWTEST_F(RunningInfosTest, DataGetAbilityRunningInfos_003, TestSize.Level1) abilityRequest.requestCode); dataAbilityRecord->ability_ = abilityRecord; const std::string dataAbilityName(abilityRequest.abilityInfo.bundleName + '.' + abilityRequest.abilityInfo.name); - abilityMs_->subManagersHelper_->currentDataAbilityManager_->dataAbilityRecordsLoading_.insert( + auto manager = std::make_shared(); + manager->dataAbilityRecordsLoading_.insert( std::pair>(dataAbilityName, dataAbilityRecord)); ElementName element2("device", "com.ix.hiMusic", "MusicAbilityOther"); @@ -681,11 +686,11 @@ HWTEST_F(RunningInfosTest, DataGetAbilityRunningInfos_003, TestSize.Level1) abilityRequest2.requestCode); dataAbilityRecord2->ability_ = abilityRecord2; const std::string dataAbilityName2(abilityRequest2.abilityInfo.bundleName + '.' + abilityRequest2.abilityInfo.name); - abilityMs_->subManagersHelper_->currentDataAbilityManager_->dataAbilityRecordsLoaded_.insert( + manager->dataAbilityRecordsLoaded_.insert( std::pair>(dataAbilityName2, dataAbilityRecord2)); std::vector infos; - abilityMs_->subManagersHelper_->currentDataAbilityManager_->GetAbilityRunningInfos(infos, true); + manager->GetAbilityRunningInfos(infos, true); size_t infoCount{ 2 }; EXPECT_TRUE(infos.size() == infoCount); if (infos.size() == infoCount) { diff --git a/test/unittest/runtime_test/BUILD.gn b/test/unittest/runtime_test/BUILD.gn index 42a7f3e8f9..9e429c934f 100644 --- a/test/unittest/runtime_test/BUILD.gn +++ b/test/unittest/runtime_test/BUILD.gn @@ -125,24 +125,17 @@ ohos_unittest("hdc_register_test") { "hdc_register_test.cpp", ] - configs = [ - "${ability_runtime_services_path}/abilitymgr:abilityms_config", - ":coverage_flags", - ] + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] deps = [ "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] external_deps = [ - "ability_runtime:js_environment", - "ability_runtime:runtime", "bundle_framework:appexecfwk_core", "c_utils:utils", - "eventhandler:libeventhandler", "hilog:libhilog", "ipc:ipc_core", - "napi:ace_napi", ] } diff --git a/test/unittest/runtime_test/hdc_register_test.cpp b/test/unittest/runtime_test/hdc_register_test.cpp index b55da21f25..ce2e3a3986 100644 --- a/test/unittest/runtime_test/hdc_register_test.cpp +++ b/test/unittest/runtime_test/hdc_register_test.cpp @@ -17,17 +17,10 @@ #define private public #define protected public -#include "js_runtime.h" -#include "js_runtime_utils.h" -#include "js_worker.h" #include "hdc_register.h" #undef private #undef protected -#include "event_runner.h" -#include "mock_js_runtime.h" -#include "hilog_wrapper.h" - using namespace testing; using namespace testing::ext; diff --git a/test/unittest/runtime_test/js_runtime_test.cpp b/test/unittest/runtime_test/js_runtime_test.cpp index 7d5abc7dbc..0e266604e5 100755 --- a/test/unittest/runtime_test/js_runtime_test.cpp +++ b/test/unittest/runtime_test/js_runtime_test.cpp @@ -28,7 +28,6 @@ #include "mock_js_runtime.h" #include "mock_jsnapi.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace testing; using namespace testing::ext; @@ -1015,36 +1014,6 @@ HWTEST_F(JsRuntimeTest, PostSyncTask_0100, TestSize.Level0) std::this_thread::sleep_for(std::chrono::milliseconds(200)); } -/** - * @tc.name: PostSyncTask_0200 - * @tc.desc: Js runtime post sync task in preload scene. - * @tc.type: FUNC - * @tc.require: issueI7C87T - */ -HWTEST_F(JsRuntimeTest, PostSyncTask_0200, TestSize.Level1) -{ - options_.preload = true; - std::unique_ptr jsRuntime = JsRuntime::Create(options_); - EXPECT_TRUE(jsRuntime != nullptr); - - Runtime::SavePreloaded(std::move(jsRuntime)); - - options_.preload = false; - auto newJsRuntime = JsRuntime::Create(options_); - EXPECT_TRUE(newJsRuntime != nullptr); - - std::string taskName = "syncTask002"; - bool taskExecuted = false; - auto task = [taskName, &taskExecuted]() { - TAG_LOGI(AAFwkTag::TEST, "%{public}s called.", taskName.c_str()); - taskExecuted = true; - }; - newJsRuntime->PostSyncTask(task, taskName); - EXPECT_EQ(taskExecuted, true); - jsRuntime.reset(); - std::this_thread::sleep_for(std::chrono::milliseconds(200)); -} - /** * @tc.name: ReInitJsEnvImpl_0100 * @tc.desc: Js runtime reinit js env impl. @@ -1465,7 +1434,7 @@ HWTEST_F(JsRuntimeTest, DumpCpuProfile_0100, TestSize.Level1) { auto jsRuntime = std::make_unique(); bool isPrivate = true; - jsRuntime->DumpCpuProfile(isPrivate); + jsRuntime->DumpCpuProfile(); EXPECT_TRUE(jsRuntime != nullptr); } @@ -1532,5 +1501,22 @@ HWTEST_F(JsRuntimeTest, RegisterQuickFixQueryFunc_0200, TestSize.Level1) jsRuntime->RegisterQuickFixQueryFunc(moduleAndPath); EXPECT_TRUE(jsRuntime != nullptr); } + +/** + * @tc.name: UpdatePkgContextInfoJson_0100 + * @tc.desc: JsRuntime test for UpdatePkgContextInfoJson. + * @tc.type: FUNC + */ +HWTEST_F(JsRuntimeTest, UpdatePkgContextInfoJson_0100, TestSize.Level1) +{ + auto jsRuntime = std::make_unique(); + EXPECT_NE(jsRuntime, nullptr); + std::string moduleName = "moduleName"; + jsRuntime->pkgContextInfoJsonStringMap_.insert(std::make_pair(moduleName, "test2")); + std::string hapPath = TEST_HAP_PATH; + std::string packageName = "packageName"; + jsRuntime->UpdatePkgContextInfoJson(moduleName, hapPath, packageName); + EXPECT_EQ(jsRuntime->pkgContextInfoJsonStringMap_[moduleName], "test2"); +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/test/unittest/runtime_test/js_worker_test.cpp b/test/unittest/runtime_test/js_worker_test.cpp index 516acfa687..3517f5fd84 100644 --- a/test/unittest/runtime_test/js_worker_test.cpp +++ b/test/unittest/runtime_test/js_worker_test.cpp @@ -17,7 +17,6 @@ #include #include -#include "hilog_wrapper.h" #include "js_environment_impl.h" #define private public #define protected public diff --git a/test/unittest/runtime_test/mock_jsnapi.cpp b/test/unittest/runtime_test/mock_jsnapi.cpp index f76413abfe..de550baa39 100644 --- a/test/unittest/runtime_test/mock_jsnapi.cpp +++ b/test/unittest/runtime_test/mock_jsnapi.cpp @@ -15,7 +15,6 @@ #include -#include "hilog_wrapper.h" #include "jsnapi.h" #include "mock_jsnapi.h" diff --git a/test/unittest/runtime_test/mock_jsnapi.h b/test/unittest/runtime_test/mock_jsnapi.h index a0737f5b2b..047f98d764 100644 --- a/test/unittest/runtime_test/mock_jsnapi.h +++ b/test/unittest/runtime_test/mock_jsnapi.h @@ -19,7 +19,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "jsnapi.h" using RequestAotCallback = diff --git a/test/unittest/runtime_test/ohos_js_environment_test.cpp b/test/unittest/runtime_test/ohos_js_environment_test.cpp index a02433dc16..398839b54f 100644 --- a/test/unittest/runtime_test/ohos_js_environment_test.cpp +++ b/test/unittest/runtime_test/ohos_js_environment_test.cpp @@ -20,7 +20,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "js_runtime.h" using namespace testing; diff --git a/test/unittest/sender_info_test/BUILD.gn b/test/unittest/sender_info_test/BUILD.gn index bb3d4217b1..42338c58b6 100644 --- a/test/unittest/sender_info_test/BUILD.gn +++ b/test/unittest/sender_info_test/BUILD.gn @@ -37,7 +37,6 @@ ohos_unittest("sender_info_test") { } deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", - "${ability_runtime_innerkits_path}/wantagent:wantagent_innerkits", "${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/service_extension_context_test/BUILD.gn b/test/unittest/service_extension_context_test/BUILD.gn index ffed8bfbaa..613a45a60a 100644 --- a/test/unittest/service_extension_context_test/BUILD.gn +++ b/test/unittest/service_extension_context_test/BUILD.gn @@ -40,7 +40,6 @@ ohos_unittest("service_extension_context_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/ability/native:ability_business_error", "${ability_runtime_native_path}/ability/native:abilitykit_native", diff --git a/test/unittest/service_extension_context_test/ability_manager_stub_mock.h b/test/unittest/service_extension_context_test/ability_manager_stub_mock.h index a22ff3eb02..3d8955c194 100644 --- a/test/unittest/service_extension_context_test/ability_manager_stub_mock.h +++ b/test/unittest/service_extension_context_test/ability_manager_stub_mock.h @@ -243,7 +243,8 @@ public: return 0; } - int RegisterWindowManagerServiceHandler(const sptr& handler) override + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true) override { return 0; } @@ -275,8 +276,8 @@ public: int32_t userId, int requestCode)); MOCK_METHOD4(StartAbilityByInsightIntent, int32_t(const Want& want, const sptr& callerToken, uint64_t intentId, int32_t userId)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo& wantSenderInfo, const sptr& callerToken)); MOCK_METHOD2(SendWantSender, int(sptr target, const SenderInfo& senderInfo)); diff --git a/test/unittest/service_extension_context_test/service_extension_context_test.cpp b/test/unittest/service_extension_context_test/service_extension_context_test.cpp index 0747759aa5..45be6a9ca9 100644 --- a/test/unittest/service_extension_context_test/service_extension_context_test.cpp +++ b/test/unittest/service_extension_context_test/service_extension_context_test.cpp @@ -58,7 +58,7 @@ HWTEST_F(ServiceExtensionContextTest, service_extension_context_startAbility_001 ServiceExtensionContext serviceExtensionContextTest; Want want; ErrCode result = serviceExtensionContextTest.StartAbility(want); - EXPECT_EQ(ERR_BLOCK_START_FIRST_BOOT_SCREEN_UNLOCK, result); + EXPECT_EQ(ERR_IMPLICIT_START_ABILITY_FAIL, result); } /* @@ -75,7 +75,7 @@ HWTEST_F(ServiceExtensionContextTest, service_extension_context_startAbility_002 Want want; StartOptions startOptions; ErrCode result = serviceExtensionContextTest.StartAbility(want, startOptions); - EXPECT_EQ(ERR_BLOCK_START_FIRST_BOOT_SCREEN_UNLOCK, result); + EXPECT_EQ(ERR_IMPLICIT_START_ABILITY_FAIL, result); } /* @@ -91,8 +91,8 @@ HWTEST_F(ServiceExtensionContextTest, service_extension_context_StartAbilityAsCa ServiceExtensionContext serviceExtensionContextTest; Want want; ErrCode result = serviceExtensionContextTest.StartAbilityAsCaller(want); - GTEST_LOG_(INFO) <StartAbility(want, option, nullptr); if (result == OHOS::ERR_OK) { - auto topAbility = abilityMs_->GetMissionListManagerByUserId(USER_ID_U100)->GetCurrentTopAbilityLocked(); + auto topAbility = reinterpret_cast(abilityMs_-> + GetMissionListManagerByUserId(USER_ID_U100).get())->GetCurrentTopAbilityLocked(); if (topAbility) { auto defualtDisplayId = 0; auto displayId = topAbility->GetWant().GetIntParam(Want::PARAM_RESV_DISPLAY_ID, defualtDisplayId); diff --git a/test/unittest/start_options_test/BUILD.gn b/test/unittest/start_options_test/BUILD.gn index 842bfdcec1..eb8b0f8469 100755 --- a/test/unittest/start_options_test/BUILD.gn +++ b/test/unittest/start_options_test/BUILD.gn @@ -30,7 +30,6 @@ ohos_unittest("start_options_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${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}/common:perm_verification", diff --git a/test/unittest/sys_mgr_client_test/mock_ability_manager_service.h b/test/unittest/sys_mgr_client_test/mock_ability_manager_service.h index 6019d0afd3..493fe7e4d4 100644 --- a/test/unittest/sys_mgr_client_test/mock_ability_manager_service.h +++ b/test/unittest/sys_mgr_client_test/mock_ability_manager_service.h @@ -91,6 +91,7 @@ public: MOCK_METHOD2(KillProcess, int(const std::string& bundleName, const bool clearPageStack)); MOCK_METHOD2(UninstallApp, int(const std::string& bundleName, int32_t uid)); + MOCK_METHOD3(UninstallApp, int32_t(const std::string& bundleName, int32_t uid, int32_t appIndex)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo& wantSenderInfo, const sptr& callerToken)); MOCK_METHOD2(SendWantSender, int(sptr target, const SenderInfo& senderInfo)); @@ -107,8 +108,8 @@ public: const sptr& callerToken, int32_t userId, int requestCode)); MOCK_METHOD4(StartAbilityByInsightIntent, int32_t(const Want& want, const sptr& callerToken, uint64_t intentId, int32_t userId)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want& want, const sptr& callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD6(StartAbilityAsCaller, int(const Want &want, const StartOptions &startOptions, const sptr &callerToken, sptr asCallerSourceToken, int32_t userId, int requestCode)); @@ -245,7 +246,8 @@ public: return 0; } - int RegisterWindowManagerServiceHandler(const sptr& handler) override + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true) override { return 0; } diff --git a/test/unittest/task_data_persistence_mgr_test/BUILD.gn b/test/unittest/task_data_persistence_mgr_test/BUILD.gn index 5ab7bb6b82..2c505dbd0c 100755 --- a/test/unittest/task_data_persistence_mgr_test/BUILD.gn +++ b/test/unittest/task_data_persistence_mgr_test/BUILD.gn @@ -41,6 +41,7 @@ ohos_unittest("task_data_persistence_mgr_test") { "${ability_runtime_innerkits_path}/ability_manager:mission_info", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/abilitymgr:mission_list", "${ability_runtime_services_path}/common:perm_verification", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_appmgr_mock", diff --git a/test/unittest/trigger_Info_test/BUILD.gn b/test/unittest/trigger_Info_test/BUILD.gn index 4dfb289f4e..7c883d7e15 100644 --- a/test/unittest/trigger_Info_test/BUILD.gn +++ b/test/unittest/trigger_Info_test/BUILD.gn @@ -29,7 +29,6 @@ ohos_unittest("trigger_Info_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${ability_runtime_innerkits_path}/ability_manager:ability_start_options", "${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 e85f589d8f..6d3d0939a3 100644 --- a/test/unittest/ui_ability_lifecycle_manager_test/BUILD.gn +++ b/test/unittest/ui_ability_lifecycle_manager_test/BUILD.gn @@ -45,10 +45,10 @@ ohos_unittest("ui_ability_lifecycle_manager_test") { 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:process_options", "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", "${ability_runtime_native_path}/ability/native:abilitykit_native", "${ability_runtime_native_path}/ability/native:auto_startup_callback", "${ability_runtime_native_path}/appkit:appkit_manager_helper", 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 8c139a582e..8ade21a1d1 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 @@ -39,6 +39,7 @@ namespace OHOS { namespace AAFwk { namespace { const std::string DLP_INDEX = "ohos.dlp.params.index"; +constexpr int32_t TEST_UID = 20010001; }; class UIAbilityLifecycleManagerTest : public testing::Test { public: @@ -1174,7 +1175,8 @@ HWTEST_F(UIAbilityLifecycleManagerTest, NotifySCBToHandleException_001, TestSize { auto uiAbilityLifecycleManager = std::make_shared(); ASSERT_NE(uiAbilityLifecycleManager, nullptr); - uiAbilityLifecycleManager->NotifySCBToHandleException(nullptr, + std::shared_ptr record = nullptr; + uiAbilityLifecycleManager->NotifySCBToHandleException(record, static_cast(ErrorLifecycleState::ABILITY_STATE_LOAD_TIMEOUT), "handleLoadTimeout"); uiAbilityLifecycleManager.reset(); } @@ -2854,10 +2856,9 @@ HWTEST_F(UIAbilityLifecycleManagerTest, GetActiveAbilityList_001, TestSize.Level 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->GetActiveAbilityList(TEST_UID, abilityList, pid); uiAbilityLifecycleManager.reset(); } @@ -2875,13 +2876,13 @@ HWTEST_F(UIAbilityLifecycleManagerTest, GetActiveAbilityList_002, TestSize.Level abilityRequest.abilityInfo.name = "testAbility"; abilityRequest.abilityInfo.moduleName = "testModule"; abilityRequest.abilityInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.applicationInfo.uid = TEST_UID; 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->GetActiveAbilityList(TEST_UID, abilityList, pid); uiAbilityLifecycleManager.reset(); } @@ -3870,7 +3871,6 @@ HWTEST_F(UIAbilityLifecycleManagerTest, DispatchBackground_002, TestSize.Level1) { auto uiAbilityLifecycleManager = std::make_unique(); EXPECT_NE(uiAbilityLifecycleManager, nullptr); - OHOS::DelayedSingleton::GetInstance()->OnStart(); std::shared_ptr abilityRecord = nullptr; EXPECT_EQ(uiAbilityLifecycleManager->DispatchBackground(abilityRecord), ERR_INVALID_VALUE); } diff --git a/test/unittest/ui_extension/ui_extension_get_host_info_test/ui_extension_get_host_info_test.cpp b/test/unittest/ui_extension/ui_extension_get_host_info_test/ui_extension_get_host_info_test.cpp index 92ece14c81..68951f703d 100644 --- a/test/unittest/ui_extension/ui_extension_get_host_info_test/ui_extension_get_host_info_test.cpp +++ b/test/unittest/ui_extension/ui_extension_get_host_info_test/ui_extension_get_host_info_test.cpp @@ -16,7 +16,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "ability_manager_client.h" #include "mock_ability_token.h" #include "mock_native_token.h" diff --git a/test/unittest/ui_extension_ability_test/ui_extension_connect_test/ui_extension_connect_test.cpp b/test/unittest/ui_extension_ability_test/ui_extension_connect_test/ui_extension_connect_test.cpp index 99b2b51422..ff836cc3b4 100644 --- a/test/unittest/ui_extension_ability_test/ui_extension_connect_test/ui_extension_connect_test.cpp +++ b/test/unittest/ui_extension_ability_test/ui_extension_connect_test/ui_extension_connect_test.cpp @@ -18,7 +18,6 @@ #include "ability_connect_callback_stub.h" #include "ability_manager_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "session_info.h" #include "want.h" diff --git a/test/unittest/ui_extension_ability_test/ui_extension_preload_test/ui_extension_preload_test.cpp b/test/unittest/ui_extension_ability_test/ui_extension_preload_test/ui_extension_preload_test.cpp index ddfda6c00b..c19e877428 100644 --- a/test/unittest/ui_extension_ability_test/ui_extension_preload_test/ui_extension_preload_test.cpp +++ b/test/unittest/ui_extension_ability_test/ui_extension_preload_test/ui_extension_preload_test.cpp @@ -17,7 +17,6 @@ #include "ability_manager_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "session_info.h" #include "want.h" diff --git a/test/unittest/ui_extension_context_test/ui_extension_context_test.cpp b/test/unittest/ui_extension_context_test/ui_extension_context_test.cpp index df578f8c5c..68670b3d1f 100644 --- a/test/unittest/ui_extension_context_test/ui_extension_context_test.cpp +++ b/test/unittest/ui_extension_context_test/ui_extension_context_test.cpp @@ -23,7 +23,6 @@ #undef protected #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "want.h" #include "mock_window.h" @@ -360,5 +359,61 @@ HWTEST_F(UIExtensionContextTest, OpenAtomicService_0100, TestSize.Level1) TAG_LOGI(AAFwkTag::TEST, "OpenAtomicService_0100 end"); } + +/** + * @tc.number: OpenLink_0100 + * @tc.name: OpenLink + * @tc.desc: OpenLink. + */ +HWTEST_F(UIExtensionContextTest, OpenLink_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "OpenLink_0100 start"); + AAFwk::Want want; + int requestCode = 0; + auto context = std::make_shared(); + EXPECT_NE(context, nullptr); + context->OpenLink(want, requestCode); + EXPECT_TRUE(context != nullptr); + TAG_LOGI(AAFwkTag::TEST, "OpenLink_0100 end"); +} + +/** + * @tc.number: RemoveResultCallbackTask_0100 + * @tc.name: RemoveResultCallbackTask + * @tc.desc: RemoveResultCallbackTask. + */ +HWTEST_F(UIExtensionContextTest, RemoveResultCallbackTask_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "RemoveResultCallbackTask_0100 start"); + auto context = std::make_shared(); + EXPECT_NE(context, nullptr); + sptr window(new (std::nothrow) MockWindow()); + context->SetWindow(window); + int requestCode = 0; + RuntimeTask task = [](const int32_t count, const Want &want, bool isInner) { + GTEST_LOG_(INFO) << "RemoveResultCallbackTask_0100 task called"; + }; + context->InsertResultCallbackTask(requestCode, std::move(task)); + context->RemoveResultCallbackTask(requestCode); + auto count = context->resultCallbacks_.size(); + EXPECT_EQ(count, 0); + TAG_LOGI(AAFwkTag::TEST, "RemoveResultCallbackTask_0100 end"); +} + +/** + * @tc.number: AddFreeInstallObserver_0100 + * @tc.name: AddFreeInstallObserver + * @tc.desc: AddFreeInstallObserver. + */ +HWTEST_F(UIExtensionContextTest, AddFreeInstallObserver_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AddFreeInstallObserver_0100 start"); + sptr observer; + auto context = std::make_shared(); + EXPECT_NE(context, nullptr); + context->AddFreeInstallObserver(observer); + EXPECT_TRUE(context != nullptr); + TAG_LOGI(AAFwkTag::TEST, "AddFreeInstallObserver_0100 end"); +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/test/unittest/uri_perm_mgr_test/BUILD.gn b/test/unittest/uri_perm_mgr_test/BUILD.gn index 3f559f1258..34d8b6c347 100644 --- a/test/unittest/uri_perm_mgr_test/BUILD.gn +++ b/test/unittest/uri_perm_mgr_test/BUILD.gn @@ -25,7 +25,13 @@ config("coverage_flags") { ohos_unittest("uri_perm_mgr_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper" ] sources = [ @@ -54,6 +60,7 @@ ohos_unittest("uri_perm_mgr_test") { "access_token:libtokenid_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", + "hilog:libhilog", "storage_service:storage_manager_sa_proxy", ] if (background_task_mgr_continuous_task_enable) { diff --git a/test/unittest/uri_permission_impl_test/BUILD.gn b/test/unittest/uri_permission_impl_test/BUILD.gn index 76433b40e9..7cbea733b4 100755 --- a/test/unittest/uri_permission_impl_test/BUILD.gn +++ b/test/unittest/uri_permission_impl_test/BUILD.gn @@ -18,7 +18,13 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("uri_permission_impl_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", "${ability_runtime_test_path}/mock/common/include", @@ -59,6 +65,7 @@ ohos_unittest("uri_permission_impl_test") { "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", + "hilog:libhilog", "init:libbeget_proxy", "init:libbegetutil", "storage_service:storage_manager_sa_proxy", 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 9fbf20c88b..14cdb59e90 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 @@ -282,7 +282,8 @@ public: } virtual int32_t GetBundleStatsForIncrease(uint32_t userId, const std::vector &bundleNames, - const std::vector &incrementalBackTimes, std::vector &pkgFileSizes) override + const std::vector &incrementalBackTimes, std::vector &pkgFileSizes, + std::vector &incPkgFileSizes) override { return E_OK; } diff --git a/test/unittest/uri_permission_impl_test/mock/src/mock_bundle_mgr_helper.cpp b/test/unittest/uri_permission_impl_test/mock/src/mock_bundle_mgr_helper.cpp index 4947983781..5859e7b056 100644 --- a/test/unittest/uri_permission_impl_test/mock/src/mock_bundle_mgr_helper.cpp +++ b/test/unittest/uri_permission_impl_test/mock/src/mock_bundle_mgr_helper.cpp @@ -15,7 +15,6 @@ #include "mock_bundle_mgr_helper.h" -#include "hilog_wrapper.h" #include "hilog_tag_wrapper.h" namespace OHOS { diff --git a/test/unittest/uri_permission_manager_test/BUILD.gn b/test/unittest/uri_permission_manager_test/BUILD.gn index 10ca05bf81..b9666a9c38 100644 --- a/test/unittest/uri_permission_manager_test/BUILD.gn +++ b/test/unittest/uri_permission_manager_test/BUILD.gn @@ -18,7 +18,13 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("uri_permission_manager_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/mock_sa_call" ] sources = [ "uri_permission_manager_test.cpp" ] diff --git a/test/unittest/uri_permission_test/BUILD.gn b/test/unittest/uri_permission_test/BUILD.gn index 290d49299f..1926f1b7ad 100755 --- a/test/unittest/uri_permission_test/BUILD.gn +++ b/test/unittest/uri_permission_test/BUILD.gn @@ -18,6 +18,13 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("uri_permission_test") { module_out_path = module_output_path + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper" ] sources = [ "uri_permission_test.cpp" ] diff --git a/test/unittest/want_receiver_proxy_test/BUILD.gn b/test/unittest/want_receiver_proxy_test/BUILD.gn index dfc727d91d..b89a6d5b07 100644 --- a/test/unittest/want_receiver_proxy_test/BUILD.gn +++ b/test/unittest/want_receiver_proxy_test/BUILD.gn @@ -18,7 +18,13 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("want_receiver_proxy_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", diff --git a/test/unittest/want_receiver_stub_test/BUILD.gn b/test/unittest/want_receiver_stub_test/BUILD.gn index 4cb687cb2b..3cd0a69ab2 100644 --- a/test/unittest/want_receiver_stub_test/BUILD.gn +++ b/test/unittest/want_receiver_stub_test/BUILD.gn @@ -40,7 +40,6 @@ ohos_unittest("want_receiver_stub_test") { } deps = [ "${ability_runtime_innerkits_path}/ability_manager:ability_manager", - "${ability_runtime_innerkits_path}/wantagent:wantagent_innerkits", "${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/want_sender_proxy_test/BUILD.gn b/test/unittest/want_sender_proxy_test/BUILD.gn index a9c48baba8..18c88df499 100644 --- a/test/unittest/want_sender_proxy_test/BUILD.gn +++ b/test/unittest/want_sender_proxy_test/BUILD.gn @@ -18,7 +18,13 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("want_sender_proxy_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", @@ -38,7 +44,6 @@ ohos_unittest("want_sender_proxy_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${ability_runtime_innerkits_path}/wantagent:wantagent_innerkits", "${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/want_sender_stub_test/BUILD.gn b/test/unittest/want_sender_stub_test/BUILD.gn index 96fdb67b2d..c75793b578 100644 --- a/test/unittest/want_sender_stub_test/BUILD.gn +++ b/test/unittest/want_sender_stub_test/BUILD.gn @@ -18,7 +18,13 @@ module_output_path = "ability_runtime/abilitymgr" ohos_unittest("want_sender_stub_test") { module_out_path = module_output_path - + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" include_dirs = [ "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock", "${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include", @@ -39,7 +45,6 @@ ohos_unittest("want_sender_stub_test") { cflags += [ "-DBINDER_IPC_32BIT" ] } deps = [ - "${ability_runtime_innerkits_path}/wantagent:wantagent_innerkits", "${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 c1ff67f383..488bdcaa85 100644 --- a/tools/aa/BUILD.gn +++ b/tools/aa/BUILD.gn @@ -100,6 +100,7 @@ ohos_executable("aa") { "ability_base:base", "ability_base:configuration", "ability_base:session_info", + "hicollie:libhicollie", "hilog:libhilog", "ipc:ipc_core", ] diff --git a/tools/aa/include/ability_command.h b/tools/aa/include/ability_command.h index 929f1c38c2..98e2f46cd5 100644 --- a/tools/aa/include/ability_command.h +++ b/tools/aa/include/ability_command.h @@ -70,8 +70,8 @@ const std::string HELP_MSG_START = "usage: aa start \n" "options list:\n" " -h, --help list available commands\n" - " [-d ] [-a -b ] [-m ] [-p ] [-D] [-S] [-N] [-R]" - " [--ps ] " + " [-d ] [-a -b ] [-m ] [-p ] [-D] [-E] [-S] [-N]" + " [-R] [--ps ] " " [--pi ] " " [--pb ] " " [--psn ] " @@ -234,6 +234,7 @@ private: ErrCode RunAsHelpCommand(); ErrCode RunAsScreenCommand(); + void HandleInvalidScreenOptions(int& result); ErrCode RunAsStartAbility(); ErrCode RunAsStopService(); ErrCode RunAsDumpsysCommand(); diff --git a/tools/aa/include/accessibility_ability_command.h b/tools/aa/include/accessibility_ability_command.h index 06eb255370..ee4f9e12e2 100644 --- a/tools/aa/include/accessibility_ability_command.h +++ b/tools/aa/include/accessibility_ability_command.h @@ -55,6 +55,7 @@ private: ErrCode RunAsGetInstalledAbilities(); ErrCode MakeEnableCommandArgumentFromCmd(AccessibilityCommandArgument& argument); + void CheckEnableCommandOption(const int option, AccessibilityCommandArgument& argument); ErrCode MakeDisableCommandArgumentFromCmd(AccessibilityCommandArgument& argument); const std::vector GetEnabledAbilities(); const std::vector GetInstalledAbilities(); diff --git a/tools/aa/src/ability_command.cpp b/tools/aa/src/ability_command.cpp index 53bdff6eb4..0dfbdd53de 100644 --- a/tools/aa/src/ability_command.cpp +++ b/tools/aa/src/ability_command.cpp @@ -21,7 +21,6 @@ #include "ability_manager_client.h" #include "app_mgr_client.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iservice_registry.h" #include "mission_snapshot.h" #include "bool_wrapper.h" @@ -52,7 +51,7 @@ constexpr int OPTION_WINDOW_WIDTH = 264; const std::string DEVELOPERMODE_STATE = "const.security.developermode.state"; -const std::string SHORT_OPTIONS = "ch:d:a:b:e:t:p:s:m:A:U:CDSNR"; +const std::string SHORT_OPTIONS = "ch:d:a:b:e:t:p:s:m:A:U:CDESNR"; constexpr struct option LONG_OPTIONS[] = { {"help", no_argument, nullptr, 'h'}, {"device", required_argument, nullptr, 'd'}, @@ -63,6 +62,7 @@ constexpr struct option LONG_OPTIONS[] = { {"module", required_argument, nullptr, 'm'}, {"cold-start", no_argument, nullptr, 'C'}, {"debug", no_argument, nullptr, 'D'}, + {"error-info-enhance", no_argument, nullptr, 'E'}, {"native-debug", no_argument, nullptr, 'N'}, {"mutil-thread", no_argument, nullptr, 'R'}, {"action", required_argument, nullptr, 'A'}, @@ -185,142 +185,39 @@ ErrCode AbilityManagerShellCommand::CreateCommandMap() ErrCode AbilityManagerShellCommand::CreateMessageMap() { - messageMap_ = { - // code + message - { - RESOLVE_ABILITY_ERR, - "error: resolve ability err.", - }, - { - GET_ABILITY_SERVICE_FAILED, - "error: get ability service failed.", - }, - { - ABILITY_SERVICE_NOT_CONNECTED, - "error: ability service not connected.", - }, - { - RESOLVE_APP_ERR, - "error: resolve app err.", - }, - { - ABILITY_EXISTED, - "error: ability existed.", - }, - { - CREATE_MISSION_STACK_FAILED, - "error: create mission stack failed.", - }, - { - CREATE_ABILITY_RECORD_FAILED, - "error: create ability record failed.", - }, - { - START_ABILITY_WAITING, - "start ability successfully. waiting...", - }, - { - TERMINATE_LAUNCHER_DENIED, - "error: terminate launcher denied.", - }, - { - CONNECTION_NOT_EXIST, - "error: connection not exist.", - }, - { - INVALID_CONNECTION_STATE, - "error: invalid connection state.", - }, - { - LOAD_ABILITY_TIMEOUT, - "error: load ability timeout.", - }, - { - CONNECTION_TIMEOUT, - "error: connection timeout.", - }, - { - GET_BUNDLE_MANAGER_SERVICE_FAILED, - "error: get bundle manager service failed.", - }, - { - REMOVE_MISSION_FAILED, - "error: remove mission failed.", - }, - { - INNER_ERR, - "error: inner err.", - }, - { - GET_RECENT_MISSIONS_FAILED, - "error: get recent missions failed.", - }, - { - REMOVE_STACK_LAUNCHER_DENIED, - "error: remove stack launcher denied.", - }, - { - TARGET_ABILITY_NOT_SERVICE, - "error: target ability not service.", - }, - { - TERMINATE_SERVICE_IS_CONNECTED, - "error: terminate service is connected.", - }, - { - START_SERVICE_ABILITY_ACTIVATING, - "error: start service ability activating.", - }, - { - KILL_PROCESS_FAILED, - "error: kill process failed.", - }, - { - UNINSTALL_APP_FAILED, - "error: uninstall app failed.", - }, - { - TERMINATE_ABILITY_RESULT_FAILED, - "error: terminate ability result failed.", - }, - { - CHECK_PERMISSION_FAILED, - "error: check permission failed.", - }, - { - NO_FOUND_ABILITY_BY_CALLER, - "error: no found ability by caller.", - }, - { - ABILITY_VISIBLE_FALSE_DENY_REQUEST, - "error: ability visible false deny request.", - }, - { - GET_BUNDLE_INFO_FAILED, - "error: get bundle info failed.", - }, - { - ERR_NOT_DEVELOPER_MODE, - "error: not developer mode.", - }, - { - KILL_PROCESS_KEEP_ALIVE, - "error: keep alive process can not be killed.", - }, - { - ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE, - "error: unlock screen failed in developer mode." - }, - { - ERR_NOT_SUPPORTED_PRODUCT_TYPE, - "error: not supported in the current product type." - }, - { - ERR_NOT_IN_APP_PROVISION_MODE, - "error: not supported in non-app-provision mode." - } - }; - + messageMap_[RESOLVE_ABILITY_ERR] = "error: resolve ability err."; + messageMap_[GET_ABILITY_SERVICE_FAILED] = "error: get ability service failed."; + messageMap_[ABILITY_SERVICE_NOT_CONNECTED] = "error: ability service not connected."; + messageMap_[RESOLVE_APP_ERR] = "error: resolve app err."; + messageMap_[ABILITY_EXISTED] = "error: ability existed."; + messageMap_[CREATE_MISSION_STACK_FAILED] = "error: create mission stack failed."; + messageMap_[CREATE_ABILITY_RECORD_FAILED] = "error: create ability record failed."; + messageMap_[START_ABILITY_WAITING] = "start ability successfully. waiting..."; + messageMap_[TERMINATE_LAUNCHER_DENIED] = "error: terminate launcher denied."; + messageMap_[CONNECTION_NOT_EXIST] = "error: connection not exist."; + messageMap_[INVALID_CONNECTION_STATE] = "error: invalid connection state."; + messageMap_[LOAD_ABILITY_TIMEOUT] = "error: load ability timeout."; + messageMap_[CONNECTION_TIMEOUT] = "error: connection timeout."; + messageMap_[GET_BUNDLE_MANAGER_SERVICE_FAILED] = "error: get bundle manager service failed."; + messageMap_[REMOVE_MISSION_FAILED] = "error: remove mission failed."; + messageMap_[INNER_ERR] = "error: inner err."; + messageMap_[GET_RECENT_MISSIONS_FAILED] = "error: get recent missions failed."; + messageMap_[REMOVE_STACK_LAUNCHER_DENIED] = "error: remove stack launcher denied."; + messageMap_[TARGET_ABILITY_NOT_SERVICE] = "error: target ability not service."; + messageMap_[TERMINATE_SERVICE_IS_CONNECTED] = "error: terminate service is connected."; + messageMap_[START_SERVICE_ABILITY_ACTIVATING] = "error: start service ability activating."; + messageMap_[KILL_PROCESS_FAILED] = "error: kill process failed."; + messageMap_[UNINSTALL_APP_FAILED] = "error: uninstall app failed."; + messageMap_[TERMINATE_ABILITY_RESULT_FAILED] = "error: terminate ability result failed."; + messageMap_[CHECK_PERMISSION_FAILED] = "error: check permission failed."; + messageMap_[NO_FOUND_ABILITY_BY_CALLER] = "error: no found ability by caller."; + messageMap_[ABILITY_VISIBLE_FALSE_DENY_REQUEST] = "error: ability visible false deny request."; + messageMap_[GET_BUNDLE_INFO_FAILED] = "error: get bundle info failed."; + messageMap_[ERR_NOT_DEVELOPER_MODE] = "error: not developer mode."; + messageMap_[KILL_PROCESS_KEEP_ALIVE] = "error: keep alive process can not be killed."; + messageMap_[ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE] = "error: unlock screen failed in developer mode."; + messageMap_[ERR_NOT_SUPPORTED_PRODUCT_TYPE] = "error: not supported in the current product type."; + messageMap_[ERR_NOT_IN_APP_PROVISION_MODE] = "error: not supported in non-app-provision mode."; return OHOS::ERR_OK; } @@ -336,6 +233,46 @@ ErrCode AbilityManagerShellCommand::RunAsHelpCommand() return OHOS::ERR_OK; } +void AbilityManagerShellCommand::HandleInvalidScreenOptions(int& result) +{ + switch (optopt) { + case 'p': { + // 'aa screen -p' with no argument + TAG_LOGI(AAFwkTag::AA_TOOL, "'aa %{public}s -p' with no argument.", cmd_.c_str()); + + resultReceiver_.append("error: option "); + resultReceiver_.append("requires a value.\n"); + + result = OHOS::ERR_INVALID_VALUE; + break; + } + case 0: { + // 'aa screen' with an unknown option: aa screen --x + // 'aa screen' with an unknown option: aa screen --xxx + std::string unknownOption = ""; + std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption); + + TAG_LOGI(AAFwkTag::AA_TOOL, "'aa screen' with an unknown option."); + + resultReceiver_.append(unknownOptionMsg); + result = OHOS::ERR_INVALID_VALUE; + break; + } + default: { + // 'aa screen' with an unknown option: aa screen -x + // 'aa screen' with an unknown option: aa screen -xxx + std::string unknownOption = ""; + std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption); + + TAG_LOGI(AAFwkTag::AA_TOOL, "'aa screen' with an unknown option."); + + resultReceiver_.append(unknownOptionMsg); + result = OHOS::ERR_INVALID_VALUE; + break; + } + } +} + ErrCode AbilityManagerShellCommand::RunAsScreenCommand() { TAG_LOGI(AAFwkTag::AA_TOOL, "enter"); @@ -370,42 +307,7 @@ ErrCode AbilityManagerShellCommand::RunAsScreenCommand() } if (option == '?') { - switch (optopt) { - case 'p': { - // 'aa screen -p' with no argument - TAG_LOGI(AAFwkTag::AA_TOOL, "'aa %{public}s -p' with no argument.", cmd_.c_str()); - - resultReceiver_.append("error: option "); - resultReceiver_.append("requires a value.\n"); - - result = OHOS::ERR_INVALID_VALUE; - break; - } - case 0: { - // 'aa screen' with an unknown option: aa screen --x - // 'aa screen' with an unknown option: aa screen --xxx - std::string unknownOption = ""; - std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption); - - TAG_LOGI(AAFwkTag::AA_TOOL, "'aa screen' with an unknown option."); - - resultReceiver_.append(unknownOptionMsg); - result = OHOS::ERR_INVALID_VALUE; - break; - } - default: { - // 'aa screen' with an unknown option: aa screen -x - // 'aa screen' with an unknown option: aa screen -xxx - std::string unknownOption = ""; - std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption); - - TAG_LOGI(AAFwkTag::AA_TOOL, "'aa screen' with an unknown option."); - - resultReceiver_.append(unknownOptionMsg); - result = OHOS::ERR_INVALID_VALUE; - break; - } - } + HandleInvalidScreenOptions(result); break; } @@ -819,7 +721,7 @@ pid_t AbilityManagerShellCommand::ConvertPid(std::string& inputPid) ErrCode AbilityManagerShellCommand::RunAsAttachDebugCommand() { - TAG_LOGD(AAFwkTag::AA_TOOL, "Called."); + TAG_LOGD(AAFwkTag::AA_TOOL, "called"); std::string bundleName = ""; ParseBundleName(bundleName); if (bundleName.empty()) { @@ -840,7 +742,7 @@ ErrCode AbilityManagerShellCommand::RunAsAttachDebugCommand() ErrCode AbilityManagerShellCommand::RunAsDetachDebugCommand() { - TAG_LOGD(AAFwkTag::AA_TOOL, "Called."); + TAG_LOGD(AAFwkTag::AA_TOOL, "called"); std::string bundleName = ""; ParseBundleName(bundleName); if (bundleName.empty()) { @@ -944,7 +846,7 @@ bool AbilityManagerShellCommand::ParseAppDebugParameter( ErrCode AbilityManagerShellCommand::RunAsAppDebugDebugCommand() { - TAG_LOGD(AAFwkTag::AA_TOOL, "Called."); + TAG_LOGD(AAFwkTag::AA_TOOL, "called"); std::string bundleName; bool isPersist = false; bool isCancel = false; @@ -1488,6 +1390,7 @@ ErrCode AbilityManagerShellCommand::MakeWantFromCmd(Want& want, std::string& win std::string typeVal; bool isColdStart = false; bool isDebugApp = false; + bool isErrorInfoEnhance = false; bool isContinuation = false; bool isSandboxApp = false; bool isNativeDebug = false; @@ -1984,6 +1887,13 @@ ErrCode AbilityManagerShellCommand::MakeWantFromCmd(Want& want, std::string& win isDebugApp = true; break; } + case 'E': { + // 'aa start -E' + // error info enhance + isErrorInfoEnhance = true; + TAG_LOGD(AAFwkTag::AA_TOOL, "isErrorInfoEnhance"); + break; + } case 'S': { // 'aa start -b -a -p -S' // enter sandbox to perform app @@ -2073,6 +1983,9 @@ ErrCode AbilityManagerShellCommand::MakeWantFromCmd(Want& want, std::string& win if (!typeVal.empty()) { want.SetType(typeVal); } + if (isErrorInfoEnhance) { + want.SetParam("errorInfoEnhance", isErrorInfoEnhance); + } if (isMultiThread) { want.SetParam("multiThread", isMultiThread); } diff --git a/tools/aa/src/ability_tool_command.cpp b/tools/aa/src/ability_tool_command.cpp index 3b8191cc63..3e8be20324 100644 --- a/tools/aa/src/ability_tool_command.cpp +++ b/tools/aa/src/ability_tool_command.cpp @@ -24,7 +24,6 @@ #include "bool_wrapper.h" #include "element_name.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using namespace OHOS::AppExecFwk; diff --git a/tools/aa/src/accessibility_ability_command.cpp b/tools/aa/src/accessibility_ability_command.cpp index d9ce4afe78..075efcb25d 100644 --- a/tools/aa/src/accessibility_ability_command.cpp +++ b/tools/aa/src/accessibility_ability_command.cpp @@ -26,7 +26,6 @@ #include "accessibility_system_ability_client.h" #include "bool_wrapper.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iservice_registry.h" #include "mission_snapshot.h" #include "sa_mgr_client.h" @@ -326,6 +325,33 @@ ErrCode AccessibilityAbilityShellCommand::RunAsHelpCommand() return OHOS::ERR_OK; } +void AccessibilityAbilityShellCommand::CheckEnableCommandOption(const int option, + AccessibilityCommandArgument& argument) +{ + switch (option) { + case 'a': { + argument.abilityName = optarg; + argument.abilityArgumentNum++; + break; + } + case 'b': { + argument.bundleName = optarg; + argument.bundleArgumentNum++; + break; + } + case 'c': { + argument.capabilityNames = optarg; + argument.capabilityNamesArgumentNum++; + break; + } + default: { + argument.unknownArgumentNum++; + argument.unknownArguments.push_back(argv_[optind - 1]); + break; + } + } +} + ErrCode AccessibilityAbilityShellCommand::MakeEnableCommandArgumentFromCmd(AccessibilityCommandArgument& argument) { int option = -1; @@ -371,29 +397,7 @@ ErrCode AccessibilityAbilityShellCommand::MakeEnableCommandArgumentFromCmd(Acces } } } - - switch (option) { - case 'a': { - argument.abilityName = optarg; - argument.abilityArgumentNum++; - break; - } - case 'b': { - argument.bundleName = optarg; - argument.bundleArgumentNum++; - break; - } - case 'c': { - argument.capabilityNames = optarg; - argument.capabilityNamesArgumentNum++; - break; - } - default: { - argument.unknownArgumentNum++; - argument.unknownArguments.push_back(argv_[optind - 1]); - break; - } - } + CheckEnableCommandOption(option, argument); } return CheckEnableCommandArgument(argument, resultReceiver_); } diff --git a/tools/aa/src/accessibility_ability_utils.cpp b/tools/aa/src/accessibility_ability_utils.cpp index d4f8a1369a..e32b7e2d7e 100644 --- a/tools/aa/src/accessibility_ability_utils.cpp +++ b/tools/aa/src/accessibility_ability_utils.cpp @@ -18,7 +18,6 @@ #include "accesstoken_kit.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "nativetoken_kit.h" #include "token_setproc.h" diff --git a/tools/aa/src/main.cpp b/tools/aa/src/main.cpp index e417af1d24..3df1473590 100644 --- a/tools/aa/src/main.cpp +++ b/tools/aa/src/main.cpp @@ -18,13 +18,45 @@ #include "ability_command.h" #include "ability_tool_command.h" -#include "hilog_wrapper.h" +#include "xcollie/xcollie.h" +#include "xcollie/xcollie_define.h" #ifdef A11Y_ENABLE #include "accessibility_ability_command.h" #endif // A11Y_ENABLE + +using namespace OHOS; +constexpr uint32_t COMMAND_TIME_OUT = 60; + +class CommandTimer { +public: + CommandTimer(const std::string &timerName, uint32_t timeout, const std::string &operation) + { + if (operation != "test") { + setTimer_ = true; + timerId_ = HiviewDFX::XCollie::GetInstance().SetTimer("ability::aa_command", timeout, + nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_LOG | HiviewDFX::XCOLLIE_FLAG_RECOVERY); + } + } + ~CommandTimer() + { + if (setTimer_) { + HiviewDFX::XCollie::GetInstance().CancelTimer(timerId_); + } + } +private: + bool setTimer_ = false; + int32_t timerId_ = 0; +}; + int main(int argc, char* argv[]) { + std::string operation; + if (argc > 1) { + operation = argv[1]; + } + if (strstr(argv[0], "aa") != nullptr) { + CommandTimer commandTimer("ability::aa_command", COMMAND_TIME_OUT, operation); OHOS::AAFwk::AbilityManagerShellCommand cmd(argc, argv); std::cout << cmd.ExecCommand(); } else if (strstr(argv[0], "ability_tool") != nullptr) { diff --git a/tools/aa/src/shell_command.cpp b/tools/aa/src/shell_command.cpp index 62cc2d4e04..016ee992d5 100644 --- a/tools/aa/src/shell_command.cpp +++ b/tools/aa/src/shell_command.cpp @@ -17,7 +17,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/tools/aa/src/shell_command_config_loader.cpp b/tools/aa/src/shell_command_config_loader.cpp index 68f70ffad0..999d0234fe 100644 --- a/tools/aa/src/shell_command_config_loader.cpp +++ b/tools/aa/src/shell_command_config_loader.cpp @@ -19,7 +19,6 @@ #include #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" using json = nlohmann::json; namespace OHOS { diff --git a/tools/aa/src/shell_command_executor.cpp b/tools/aa/src/shell_command_executor.cpp index 480dcb5fa5..44d8090ea8 100644 --- a/tools/aa/src/shell_command_executor.cpp +++ b/tools/aa/src/shell_command_executor.cpp @@ -21,7 +21,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "shell_command_config_loader.h" using namespace std::chrono_literals; diff --git a/tools/aa/src/shell_command_result.cpp b/tools/aa/src/shell_command_result.cpp index 47f30688cc..a671d2218e 100644 --- a/tools/aa/src/shell_command_result.cpp +++ b/tools/aa/src/shell_command_result.cpp @@ -16,7 +16,6 @@ #include "shell_command_result.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/tools/aa/src/system_time.cpp b/tools/aa/src/system_time.cpp index 972696d017..14d27fd5ec 100644 --- a/tools/aa/src/system_time.cpp +++ b/tools/aa/src/system_time.cpp @@ -16,7 +16,6 @@ #include "system_time.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "inner_event.h" namespace OHOS { diff --git a/tools/aa/src/test_observer.cpp b/tools/aa/src/test_observer.cpp index 21c76ee856..262c608b56 100644 --- a/tools/aa/src/test_observer.cpp +++ b/tools/aa/src/test_observer.cpp @@ -20,7 +20,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "shell_command_config_loader.h" #include "shell_command_executor.h" #include "system_time.h" diff --git a/tools/aa/src/test_observer_proxy.cpp b/tools/aa/src/test_observer_proxy.cpp index 783f3e8956..6a77473b14 100644 --- a/tools/aa/src/test_observer_proxy.cpp +++ b/tools/aa/src/test_observer_proxy.cpp @@ -15,7 +15,6 @@ #include "test_observer_proxy.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/tools/aa/src/test_observer_stub.cpp b/tools/aa/src/test_observer_stub.cpp index bab144909c..4135cfe09c 100644 --- a/tools/aa/src/test_observer_stub.cpp +++ b/tools/aa/src/test_observer_stub.cpp @@ -15,7 +15,6 @@ #include "test_observer_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/tools/test/mock/mock_ability_manager_stub.h b/tools/test/mock/mock_ability_manager_stub.h index 9bd184342a..e671de9128 100644 --- a/tools/test/mock/mock_ability_manager_stub.h +++ b/tools/test/mock/mock_ability_manager_stub.h @@ -21,7 +21,6 @@ #include "string_ex.h" #include "ability_manager_errors.h" #include "ability_manager_stub.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { @@ -31,8 +30,8 @@ public: MOCK_METHOD4(StartAbility, int(const Want& want, const sptr& callerToken, int32_t userId, int requestCode)); - MOCK_METHOD6(StartAbilityAsCaller, int(const Want &want, const sptr &callerToken, - sptr asCallerSourceToken, int32_t userId, int requestCode, bool isSendDialogResult)); + MOCK_METHOD5(StartAbilityAsCaller, int(const Want &want, const sptr &callerToken, + sptr asCallerSourceToken, int32_t userId, int requestCode)); MOCK_METHOD3(TerminateAbility, int(const sptr& token, int resultCode, const Want* resultWant)); MOCK_METHOD3(TerminateUIExtensionAbility, int(const sptr &extensionSessionInfo, int resultCode, const Want* resultWant)); @@ -72,6 +71,7 @@ public: MOCK_METHOD2(KillProcess, int(const std::string& bundleName, const bool clearPageStack)); MOCK_METHOD2(UninstallApp, int(const std::string& bundleName, int32_t uid)); + MOCK_METHOD3(UninstallApp, int32_t(const std::string& bundleName, int32_t uid, int32_t appIndex)); MOCK_METHOD2( GetWantSender, sptr(const WantSenderInfo& wantSenderInfo, const sptr& callerToken)); @@ -205,7 +205,8 @@ public: return 0; } - int RegisterWindowManagerServiceHandler(const sptr& handler) override + int RegisterWindowManagerServiceHandler(const sptr& handler, + bool animationEnabled = true) override { return 0; } diff --git a/tools/test/moduletest/ability_delegator/ability_command_module_test.cpp b/tools/test/moduletest/ability_delegator/ability_command_module_test.cpp index 185a7a81fc..7797fad544 100644 --- a/tools/test/moduletest/ability_delegator/ability_command_module_test.cpp +++ b/tools/test/moduletest/ability_delegator/ability_command_module_test.cpp @@ -21,7 +21,6 @@ #undef private #include "ability_manager_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_manager_stub.h" using namespace testing::ext; diff --git a/tools/test/moduletest/ability_delegator/shell_command_result_module_test.cpp b/tools/test/moduletest/ability_delegator/shell_command_result_module_test.cpp index 59d18a0715..b21b17e34f 100644 --- a/tools/test/moduletest/ability_delegator/shell_command_result_module_test.cpp +++ b/tools/test/moduletest/ability_delegator/shell_command_result_module_test.cpp @@ -19,7 +19,6 @@ #include "ability_manager_client.h" #undef private #include "shell_command_result.h" -#include "hilog_wrapper.h" #include "mock_ability_manager_stub.h" using namespace testing::ext; diff --git a/tools/test/moduletest/ability_delegator/test_observer_module_test.cpp b/tools/test/moduletest/ability_delegator/test_observer_module_test.cpp index 6f727ccae6..cca5f15c9b 100644 --- a/tools/test/moduletest/ability_delegator/test_observer_module_test.cpp +++ b/tools/test/moduletest/ability_delegator/test_observer_module_test.cpp @@ -19,7 +19,6 @@ #include #include -#include "hilog_wrapper.h" #include "system_time.h" #define private public diff --git a/tools/test/systemtest/aa/aa_command_dump_system_test.cpp b/tools/test/systemtest/aa/aa_command_dump_system_test.cpp index f6d13100d3..900e6e6bd5 100644 --- a/tools/test/systemtest/aa/aa_command_dump_system_test.cpp +++ b/tools/test/systemtest/aa/aa_command_dump_system_test.cpp @@ -67,7 +67,7 @@ HWTEST_F(AaCommandDumpSystemTest, Aa_Command_Dump_SystemTest_0100, Function | Me ToolSystemTest::UninstallBundle(STRING_PAGE_ABILITY_BUNDLE_NAME); // install the bundle - ToolSystemTest::InstallBundle(STRING_PAGE_ABILITY_BUNDLE_PATH, true); + ToolSystemTest::InstallBundle(STRING_PAGE_ABILITY_BUNDLE_PATH, false); // dump the abilities std::string command = "aa dump -a"; @@ -90,7 +90,7 @@ HWTEST_F(AaCommandDumpSystemTest, Aa_Command_Dump_SystemTest_0200, Function | Me ToolSystemTest::UninstallBundle(STRING_DATA_ABILITY_BUNDLE_NAME); // install the bundle - ToolSystemTest::InstallBundle(STRING_DATA_ABILITY_BUNDLE_PATH, true); + ToolSystemTest::InstallBundle(STRING_DATA_ABILITY_BUNDLE_PATH, false); // dump the abilities std::string command = "aa dump -d"; @@ -113,7 +113,7 @@ HWTEST_F(AaCommandDumpSystemTest, Aa_Command_Dump_SystemTest_0300, Function | Me ToolSystemTest::UninstallBundle(STRING_SERVICE_ABILITY_BUNDLE_NAME); // install the bundle - ToolSystemTest::InstallBundle(STRING_SERVICE_ABILITY_BUNDLE_PATH, true); + ToolSystemTest::InstallBundle(STRING_SERVICE_ABILITY_BUNDLE_PATH, false); // dump the abilities std::string command = "aa dump -d"; diff --git a/tools/test/unittest/ability_delegator/ability_command_test.cpp b/tools/test/unittest/ability_delegator/ability_command_test.cpp index 37aee7dc87..807c29411e 100644 --- a/tools/test/unittest/ability_delegator/ability_command_test.cpp +++ b/tools/test/unittest/ability_delegator/ability_command_test.cpp @@ -21,7 +21,6 @@ #undef private #include "ability_manager_interface.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "mock_ability_manager_stub.h" using namespace testing::ext; diff --git a/tools/test/unittest/ability_delegator/accessibility_ability_command_first_test.cpp b/tools/test/unittest/ability_delegator/accessibility_ability_command_first_test.cpp index 1da2e1578b..f743e13c38 100644 --- a/tools/test/unittest/ability_delegator/accessibility_ability_command_first_test.cpp +++ b/tools/test/unittest/ability_delegator/accessibility_ability_command_first_test.cpp @@ -1113,7 +1113,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_SCREEN_MAGNIFICATION_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetScreenMagnificationState_0200 end"; } @@ -1162,7 +1162,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_SHORT_KEY_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0100 end"; } @@ -1186,7 +1186,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_SHORT_KEY_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetShortKeyState_0200 end"; } @@ -1256,7 +1256,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_MOUSE_KEY_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0100 end"; } @@ -1280,7 +1280,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_MOUSE_KEY_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseKeyState_0200 end"; } @@ -1350,7 +1350,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_CAPTION_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetCaptionState_0100 end"; } @@ -1375,7 +1375,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_CAPTION_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetCaptionState_0200 end"; } @@ -1445,7 +1445,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUTO_CLICK_TIME_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0100 end"; } @@ -1469,7 +1469,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUTO_CLICK_TIME_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetMouseAutoClick_0200 end"; } @@ -1560,7 +1560,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_HIGH_CONTRAST_TEXT_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0100 end"; } @@ -1584,7 +1584,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_HIGH_CONTRAST_TEXT_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetHighContrastTextState_0200 end"; } @@ -1654,7 +1654,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_INVERT_COLOR_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0100 end"; } @@ -1678,7 +1678,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_INVERT_COLOR_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetInvertColorState_0200 end"; } @@ -1748,7 +1748,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0100 end"; } @@ -1772,7 +1772,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0200 end"; } @@ -1796,7 +1796,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0300 end"; } @@ -1820,7 +1820,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_DALTONIZATIONZATION_COLOR_FILTER_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetDaltonizationColorFilter_0400 end"; } @@ -1889,7 +1889,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_CONTENT_TIME_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0100 end"; } @@ -1914,7 +1914,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_CONTENT_TIME_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetContentTimeout_0200 end"; } @@ -1984,7 +1984,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_ANIMATION_OFF_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0100 end"; } @@ -2008,7 +2008,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_ANIMATION_OFF_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAnimationOffState_0200 end"; } @@ -2177,7 +2177,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUDIO_MONO_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0100 end"; } @@ -2201,7 +2201,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_NG + "\n"); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUDIO_MONO_STATE_OK + "\n"); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioMonoState_0200 end"; } diff --git a/tools/test/unittest/ability_delegator/accessibility_ability_command_second_test.cpp b/tools/test/unittest/ability_delegator/accessibility_ability_command_second_test.cpp index 03eaed87fd..2d4a678991 100644 --- a/tools/test/unittest/ability_delegator/accessibility_ability_command_second_test.cpp +++ b/tools/test/unittest/ability_delegator/accessibility_ability_command_second_test.cpp @@ -88,7 +88,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_NG); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUDIO_BALANCE_OK); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0100 end"; } @@ -112,7 +112,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_NG); + EXPECT_EQ(cmd.resultReceiver_, ACCESSIBILITY_SET_AUDIO_BALANCE_OK); GTEST_LOG_(INFO) << "AccessibilityAbilityShellCommand_RunAsSetAudioBalance_0200 end"; } diff --git a/tools/test/unittest/ability_delegator/mock_test_observer_stub.cpp b/tools/test/unittest/ability_delegator/mock_test_observer_stub.cpp index d68422fd44..14a60cad15 100644 --- a/tools/test/unittest/ability_delegator/mock_test_observer_stub.cpp +++ b/tools/test/unittest/ability_delegator/mock_test_observer_stub.cpp @@ -15,7 +15,6 @@ #include "mock_test_observer_stub.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS { namespace AAFwk { diff --git a/tools/test/unittest/ability_delegator/shell_command_result_test.cpp b/tools/test/unittest/ability_delegator/shell_command_result_test.cpp index 2b298cc4b2..0e69ee7e3b 100644 --- a/tools/test/unittest/ability_delegator/shell_command_result_test.cpp +++ b/tools/test/unittest/ability_delegator/shell_command_result_test.cpp @@ -19,7 +19,6 @@ #include "ability_manager_client.h" #undef private #include "shell_command_result.h" -#include "hilog_wrapper.h" using namespace testing::ext; using namespace OHOS; diff --git a/tools/test/unittest/ability_delegator/test_observer_proxy_test.cpp b/tools/test/unittest/ability_delegator/test_observer_proxy_test.cpp index dfc6fd4349..e5b28fe4b0 100644 --- a/tools/test/unittest/ability_delegator/test_observer_proxy_test.cpp +++ b/tools/test/unittest/ability_delegator/test_observer_proxy_test.cpp @@ -30,7 +30,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_proxy.h" #include "test_observer_proxy.h" diff --git a/tools/test/unittest/ability_delegator/test_observer_stub_test.cpp b/tools/test/unittest/ability_delegator/test_observer_stub_test.cpp index 7ba41620a0..9738944a1d 100644 --- a/tools/test/unittest/ability_delegator/test_observer_stub_test.cpp +++ b/tools/test/unittest/ability_delegator/test_observer_stub_test.cpp @@ -15,7 +15,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "iremote_proxy.h" #include "mock_test_observer_stub.h" #include "test_observer_stub.h" diff --git a/tools/test/unittest/ability_delegator/test_observer_test.cpp b/tools/test/unittest/ability_delegator/test_observer_test.cpp index 4ea4f16a87..170d4b9808 100644 --- a/tools/test/unittest/ability_delegator/test_observer_test.cpp +++ b/tools/test/unittest/ability_delegator/test_observer_test.cpp @@ -20,7 +20,6 @@ #include #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" #include "system_time.h" #define private public diff --git a/utils/global/freeze/src/freeze_util.cpp b/utils/global/freeze/src/freeze_util.cpp index 28f861bd90..045e356578 100644 --- a/utils/global/freeze/src/freeze_util.cpp +++ b/utils/global/freeze/src/freeze_util.cpp @@ -16,7 +16,6 @@ #include "freeze_util.h" #include "hilog_tag_wrapper.h" -#include "hilog_wrapper.h" namespace OHOS::AbilityRuntime { FreezeUtil& FreezeUtil::GetInstance() diff --git a/utils/server/startup/src/startup_util.cpp b/utils/server/startup/src/startup_util.cpp index eeec9b65e5..3a292a49b2 100644 --- a/utils/server/startup/src/startup_util.cpp +++ b/utils/server/startup/src/startup_util.cpp @@ -25,13 +25,17 @@ namespace OHOS::AbilityRuntime { bool StartupUtil::GetAppIndex(const AAFwk::Want &want, int32_t &appIndex) { appIndex = want.GetIntParam(ServerConstant::DLP_INDEX, 0); + if (appIndex > GlobalConstant::MAX_APP_CLONE_INDEX) { + return true; + } if (appIndex == 0) { appIndex = want.GetIntParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, 0); if (appIndex < 0 || appIndex > GlobalConstant::MAX_APP_CLONE_INDEX) { return false; } + return true; } - return true; + return false; } int32_t StartupUtil::BuildAbilityInfoFlag()