diff --git a/bundle.json b/bundle.json index 9f833fc068..02f2392f67 100644 --- a/bundle.json +++ b/bundle.json @@ -64,16 +64,21 @@ "hitrace", "hiview", "i18n", + "icu", "image_framework", "init", "input", "ipc", + "json", + "jsoncpp", "kv_store", + "libuv", "memmgr", "memmgr_override", "memory_utils", "napi", "netmanager_base", + "node", "os_account", "relational_store", "resource_management", @@ -84,20 +89,10 @@ "toolchain", "webview", "window_manager", - "icu", - "jsoncpp", - "libuv", - "zlib", - "node" + "zlib" ], "third_party": [ - "icu", - "json", - "jsoncpp", - "libjpeg-turbo", - "libuv", - "node", - "zlib" + "libjpeg-turbo" ] }, "build": { diff --git a/frameworks/js/napi/BUILD.gn b/frameworks/js/napi/BUILD.gn index cbe398b703..2cdc32765b 100644 --- a/frameworks/js/napi/BUILD.gn +++ b/frameworks/js/napi/BUILD.gn @@ -43,6 +43,8 @@ group("napi_packages") { "${ability_runtime_napi_path}/app/js_app_manager:appmanager", "${ability_runtime_napi_path}/app/recovery:apprecovery_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", "${ability_runtime_napi_path}/app_startup/startup_config_entry:startupconfigentry_napi", "${ability_runtime_napi_path}/app_startup/startup_listener:startuplistener_napi", "${ability_runtime_napi_path}/app_startup/startup_manager:startupmanager_napi", diff --git a/frameworks/js/napi/ability_manager/js_ability_manager.cpp b/frameworks/js/napi/ability_manager/js_ability_manager.cpp index 91ef385375..1d67686f66 100644 --- a/frameworks/js/napi/ability_manager/js_ability_manager.cpp +++ b/frameworks/js/napi/ability_manager/js_ability_manager.cpp @@ -124,6 +124,11 @@ public: GET_NAPI_INFO_AND_CALL(env, info, JsAbilityManager, OnIsEmbeddedOpenAllowed); } + static napi_value SetResidentProcessEnabled(napi_env env, napi_callback_info info) + { + GET_CB_INFO_AND_CALL(env, info, JsAbilityManager, OnSetResidentProcessEnabled); + } + static napi_value NotifyDebugAssertResult(napi_env env, napi_callback_info info) { GET_CB_INFO_AND_CALL(env, info, JsAbilityManager, OnNotifyDebugAssertResult); @@ -152,15 +157,15 @@ private: } if (!AppExecFwk::IsTypeForNapiValue(env, argv[INDEX_ONE], napi_object)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid param."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param observer failed, must be a AbilityForegroundStateObserver"); return CreateJsUndefined(env); } std::string type = ParseParamType(env, argc, argv); if (type == ON_OFF_TYPE_ABILITY_FOREGROUND_STATE) { - OnOnAbilityForeground(env, argc, argv); + return OnOnAbilityForeground(env, argc, argv); } - + ThrowInvalidParamError(env, "Parse param type failed, must be a string, value must be abilityForegroundState"); return CreateJsUndefined(env); } @@ -198,14 +203,15 @@ private: } if (argc == ARGC_TWO && !AppExecFwk::IsTypeForNapiValue(env, argv[INDEX_ONE], napi_object)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid param."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param observer failed, must be a AbilityForegroundStateObserver"); return CreateJsUndefined(env); } std::string type = ParseParamType(env, argc, argv); if (type == ON_OFF_TYPE_ABILITY_FOREGROUND_STATE) { - OnOffAbilityForeground(env, argc, argv); + return OnOffAbilityForeground(env, argc, argv); } + ThrowInvalidParamError(env, "Parse param type failed, must be a string, value must be abilityForegroundState"); return CreateJsUndefined(env); } @@ -237,19 +243,19 @@ private: std::string assertSessionStr; if (!ConvertFromJsValue(env, argv[INDEX_ZERO], assertSessionStr) || !CheckIsNumString(assertSessionStr)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Convert session id error."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param sessionId failed, must be a string"); return CreateJsUndefined(env); } uint64_t assertSessionId = std::stoull(assertSessionStr); if (assertSessionId == 0) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Convert session id failed."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param sessionId failed, value must not be equal to zero"); return CreateJsUndefined(env); } int32_t userStatus; if (!ConvertFromJsValue(env, argv[INDEX_ONE], userStatus)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Convert status failed."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param status failed, must be a UserStatus"); return CreateJsUndefined(env); } @@ -340,7 +346,7 @@ private: int upperLimit = -1; if (!ConvertFromJsValue(env, info.argv[0], upperLimit)) { #ifdef ENABLE_ERRCODE - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param upperLimit failed, must be a number"); #endif return CreateJsUndefined(env); } @@ -391,7 +397,7 @@ private: AppExecFwk::Configuration changeConfig; if (!UnwrapConfiguration(env, info.argv[0], changeConfig)) { #ifdef ENABLE_ERRCODE - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param config failed, must be a Configuration"); #else complete = [](napi_env env, NapiAsyncTask& task, int32_t status) { task.Reject(env, CreateJsError(env, ERR_INVALID_VALUE, "config is invalid.")); @@ -456,12 +462,12 @@ private: { TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s is called", __FUNCTION__); if (info.argc < ARGC_ONE) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowTooFewParametersError(env); return CreateJsUndefined(env); } int32_t missionId = -1; if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], missionId)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param missionId failed, must be a number"); return CreateJsUndefined(env); } napi_value lastParam = info.argc > ARGC_ONE ? info.argv[INDEX_ONE] : nullptr; @@ -509,7 +515,7 @@ private: int reqCode = 0; if (!ConvertFromJsValue(env, info.argv[1], reqCode)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Get requestCode param error"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param requestCode failed, must be a number"); break; } @@ -517,7 +523,7 @@ private: int resultCode = ERR_OK; if (!AppExecFwk::UnWrapAbilityResult(env, info.argv[0], resultCode, want)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Unrwrap abilityResult param error"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param parameter failed, must be a AbilityResult"); break; } @@ -563,6 +569,58 @@ private: return result; } + napi_value OnSetResidentProcessEnabled(napi_env env, size_t argc, napi_value *argv) + { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + if (argc < ARGC_TWO) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Not enough params when off."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + + std::string bundleName; + if (!ConvertFromJsValue(env, argv[INDEX_ZERO], bundleName) || bundleName.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Convert session id error."); + auto errMsg = "Non empty package name needs to be provided"; + ThrowError(env, static_cast(AbilityErrorCode::ERROR_CODE_INVALID_PARAM), errMsg); + return CreateJsUndefined(env); + } + + bool enableState = false; + if (!ConvertFromJsValue(env, argv[INDEX_ONE], enableState)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Convert status failed."); + auto errMsg = "The second parameter needs to provide a Boolean type setting value"; + ThrowError(env, static_cast(AbilityErrorCode::ERROR_CODE_INVALID_PARAM), errMsg); + return CreateJsUndefined(env); + } + + auto innerErrorCode = std::make_shared(ERR_OK); + NapiAsyncTask::ExecuteCallback execute = [bundleName, enableState, innerErrorCode, env]() { + auto amsClient = AbilityManagerClient::GetInstance(); + if (amsClient == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability manager service instance is nullptr."); + *innerErrorCode = static_cast(AAFwk::INNER_ERR); + return; + } + *innerErrorCode = amsClient->SetResidentProcessEnabled(bundleName, enableState); + }; + + NapiAsyncTask::CompleteCallback complete = [innerErrorCode](napi_env env, NapiAsyncTask &task, int32_t status) { + if (*innerErrorCode != ERR_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Set resident process result failed, error is %{public}d.", + *innerErrorCode); + task.Reject(env, CreateJsErrorByNativeErr(env, *innerErrorCode)); + return; + } + task.ResolveWithNoError(env, CreateJsUndefined(env)); + }; + + napi_value result = nullptr; + NapiAsyncTask::Schedule("JsAbilityManager::OnSetResidentProcessEnabled", env, + CreateAsyncTaskWithLastParam(env, nullptr, std::move(execute), std::move(complete), &result)); + return result; + } + napi_value OnIsEmbeddedOpenAllowed(napi_env env, NapiCallbackInfo& info) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); @@ -576,26 +634,26 @@ private: napi_status status = OHOS::AbilityRuntime::IsStageContext(env, info.argv[0], stageMode); if (status != napi_ok || !stageMode) { TAG_LOGE(AAFwkTag::ABILITYMGR, "it is not a stage mode"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param context failed, must be stageMode"); return CreateJsUndefined(env); } auto context = OHOS::AbilityRuntime::GetStageModeContext(env, info.argv[0]); if (context == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "get context failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param context failed, must not be nullptr"); return CreateJsUndefined(env); } auto uiAbilityContext = AbilityRuntime::Context::ConvertTo(context); if (uiAbilityContext == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "convert to UIAbility context failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param context failed, must be UIAbilityContext"); return CreateJsUndefined(env); } std::string appId; if (!ConvertFromJsValue(env, info.argv[1], appId)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "OnOpenAtomicService, parse appId failed."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param appId failed, must be a string"); return CreateJsUndefined(env); } @@ -644,6 +702,8 @@ napi_value JsAbilityManagerInit(napi_env env, napi_value exportObj) BindNativeFunction( env, exportObj, "notifyDebugAssertResult", moduleName, JsAbilityManager::NotifyDebugAssertResult); BindNativeFunction(env, exportObj, "isEmbeddedOpenAllowed", moduleName, JsAbilityManager::IsEmbeddedOpenAllowed); + BindNativeFunction( + env, exportObj, "setResidentProcessEnabled", moduleName, JsAbilityManager::SetResidentProcessEnabled); TAG_LOGD(AAFwkTag::ABILITYMGR, "end"); return CreateJsUndefined(env); } 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 30e6a1a254..c5189a6c2b 100644 --- a/frameworks/js/napi/app/error_manager/js_error_manager.cpp +++ b/frameworks/js/napi/app/error_manager/js_error_manager.cpp @@ -243,7 +243,7 @@ private: std::string type; if (!ConvertFromJsValue(env, argv[INDEX_ZERO], type) || type != ON_OFF_TYPE) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Parse type failed, must be a string error."); TAG_LOGE(AAFwkTag::JSNAPI, "Parse type failed"); return CreateJsUndefined(env); } @@ -297,7 +297,7 @@ private: if (!CheckTypeForNapiValue(env, argv[INDEX_ONE], napi_object)) { TAG_LOGE(AAFwkTag::JSNAPI, "Invalid param"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Parse ovserver failed, must be a ErrorObserver."); return CreateJsUndefined(env); } @@ -363,7 +363,7 @@ private: std::string type; if (!ConvertFromJsValue(env, argv[INDEX_ZERO], type) || type != ON_OFF_TYPE) { TAG_LOGE(AAFwkTag::JSNAPI, "Parse type failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Parse type failed, must be a string error."); return CreateJsUndefined(env); } @@ -434,7 +434,7 @@ private: int32_t observerId = -1; if (!ConvertFromJsValue(env, argv[INDEX_ONE], observerId)) { TAG_LOGE(AAFwkTag::JSNAPI, "Parse observerId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Parse observerId failed, must be a number."); return CreateJsUndefined(env); } if (observer_ == nullptr) { @@ -511,23 +511,23 @@ private: } if (!CheckTypeForNapiValue(env, argv[INDEX_ONE], napi_number)) { TAG_LOGE(AAFwkTag::JSNAPI, "OnSetLoopWatch: Invalid param"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Failed to parse timeout, must be a number."); return CreateJsUndefined(env); } if (!CheckTypeForNapiValue(env, argv[INDEX_TWO], napi_object)) { TAG_LOGE(AAFwkTag::JSNAPI, "OnSetLoopWatch: Invalid param"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Failed to parse observer, must be a LoopObserver."); return CreateJsUndefined(env); } int64_t number; if (!ConvertFromJsNumber(env, argv[INDEX_ONE], number)) { TAG_LOGE(AAFwkTag::JSNAPI, "OnSetLoopWatch: Parse timeout failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Failed to parse timeout, must be a number."); return CreateJsUndefined(env); } if (number <= 0) { TAG_LOGE(AAFwkTag::JSNAPI, "The timeout cannot be less than 0"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: The timeout cannot be less than 0."); return CreateJsUndefined(env); } 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 59c6e2e81c..add1fc82bf 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 @@ -22,6 +22,7 @@ #include "ability_manager_interface.h" #include "ability_runtime_error_util.h" #include "app_mgr_interface.h" +#include "application_info.h" #include "event_runner.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" @@ -99,6 +100,11 @@ public: GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnGetRunningProcessInformation); } + static napi_value GetRunningProcessInformationByBundleType(napi_env env, napi_callback_info info) + { + GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnGetRunningProcessInformationByBundleType); + } + static napi_value IsRunningInStabilityTest(napi_env env, napi_callback_info info) { GET_CB_INFO_AND_CALL(env, info, JsAppManager, OnIsRunningInStabilityTest); @@ -233,7 +239,8 @@ private: } if (!CheckOnOffType(env, argc, argv)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param type failed, must be a string," + "value must be applicationState, appForegroundState or abilityFirstFrameState"); return CreateJsUndefined(env); } @@ -279,7 +286,7 @@ private: } if (!AppExecFwk::IsTypeForNapiValue(env, argv[INDEX_ONE], napi_object)) { TAG_LOGE(AAFwkTag::APPMGR, "Invalid param"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param observer failed, must be a ApplicationStateObserver"); return CreateJsUndefined(env); } std::vector bundleNameList; @@ -322,7 +329,7 @@ private: } if (!AppExecFwk::IsTypeForNapiValue(env, argv[INDEX_ONE], napi_object)) { TAG_LOGE(AAFwkTag::APPMGR, "Invalid param."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param observer failed, must be a AppForegroundStateObserver"); return CreateJsUndefined(env); } if (observerForeground_ == nullptr) { @@ -385,7 +392,7 @@ private: if (!AppExecFwk::IsTypeForNapiValue(env, argv[INDEX_ONE], napi_object) || !IsJSFunctionExist(env, argv[INDEX_ONE], "onAbilityFirstFrameDrawn")) { TAG_LOGE(AAFwkTag::APPMGR, "Invalid param."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param observer failed, must be a AbilityFirstFrameStateObserver"); return CreateJsUndefined(env); } std::string bundleName; @@ -393,7 +400,7 @@ private: if (!IsParasNullOrUndefined(env, argv[INDEX_TWO]) && (!ConvertFromJsValue(env, argv[INDEX_TWO], bundleName) || bundleName.empty())) { TAG_LOGE(AAFwkTag::APPMGR, "Get bundleName error or bundleName empty!"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param bundleName failed, must be a string"); return CreateJsUndefined(env); } } @@ -439,7 +446,7 @@ private: (!AppExecFwk::IsTypeForNapiValue(env, argv[INDEX_ONE], napi_object) || !IsJSFunctionExist(env, argv[INDEX_ONE], "onAbilityFirstFrameDrawn"))) { TAG_LOGE(AAFwkTag::APPMGR, "Invalid param."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param observer failed, must be a AbilityFirstFrameStateObserver"); return CreateJsUndefined(env); } } @@ -463,20 +470,21 @@ private: return CreateJsUndefined(env); } if (!CheckOnOffType(env, argc, argv)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param type failed, must be a string," + "value must be applicationState, appForegroundState or abilityFirstFrameState"); return CreateJsUndefined(env); } int64_t observerId = -1; napi_get_value_int64(env, argv[INDEX_ONE], &observerId); if (observer_ == nullptr) { - TAG_LOGE(AAFwkTag::APPMGR, "observer_ is nullpter, please register first"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + TAG_LOGE(AAFwkTag::APPMGR, "observer_ is nullptr, please register first"); + ThrowInvalidParamError(env, "observer is nullptr, please register first"); return CreateJsUndefined(env); } if (!observer_->FindObserverByObserverId(observerId)) { TAG_LOGE(AAFwkTag::APPMGR, "not find observer, observer:%{public}d", static_cast(observerId)); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "not find observerId"); return CreateJsUndefined(env); } TAG_LOGD(AAFwkTag::APPMGR, "find observer exist observer:%{public}d", static_cast(observerId)); @@ -518,7 +526,7 @@ private: int32_t observerId = -1; if (!ConvertFromJsValue(env, argv[INDEX_ONE], observerId)) { TAG_LOGE(AAFwkTag::APPMGR, "Parse observerId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param observerId failed, must be a number"); return CreateJsUndefined(env); } @@ -529,7 +537,7 @@ private: } if (!observerSync_->FindObserverByObserverId(observerId)) { TAG_LOGE(AAFwkTag::APPMGR, "not find observer, observer:%{public}d", static_cast(observerId)); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "not find observerId"); return CreateJsUndefined(env); } int32_t ret = appManager_->UnregisterApplicationStateObserver(observerSync_); @@ -553,7 +561,7 @@ private: } if (argc == ARGC_TWO && !AppExecFwk::IsTypeForNapiValue(env, argv[INDEX_ONE], napi_object)) { TAG_LOGE(AAFwkTag::APPMGR, "Invalid param."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param observer failed, must be a AppForegroundStateObserver"); return CreateJsUndefined(env); } if (observerForeground_ == nullptr || appManager_ == nullptr) { @@ -632,6 +640,49 @@ private: return result; } + napi_value OnGetRunningProcessInformationByBundleType(napi_env env, size_t argc, napi_value* argv) + { + TAG_LOGD(AAFwkTag::APPMGR, "called"); + if (argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::APPMGR, "Not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + int32_t bundleType = -1; + if (!ConvertFromJsValue(env, argv[INDEX_ZERO], bundleType)) { + TAG_LOGE(AAFwkTag::APPMGR, "get bundleType error!"); + ThrowInvalidParamError(env, "failed to get bundleType"); + return CreateJsUndefined(env); + } + if (bundleType < 0) { + TAG_LOGE(AAFwkTag::APPMGR, "Invalid bundle type:%{public}d", bundleType); + ThrowInvalidParamError(env, "invalid bundle type"); + 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)); + return result; + } + napi_value OnIsRunningInStabilityTest(napi_env env, size_t argc, napi_value* argv) { TAG_LOGD(AAFwkTag::APPMGR, "called"); @@ -666,7 +717,7 @@ private: std::string bundleName; if (!ConvertFromJsValue(env, argv[0], bundleName)) { TAG_LOGE(AAFwkTag::APPMGR, "get bundleName error!"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param bundleName failed, must be a string"); return CreateJsUndefined(env); } @@ -705,7 +756,7 @@ private: std::string bundleName; if (!ConvertFromJsValue(env, argv[0], bundleName)) { TAG_LOGE(AAFwkTag::APPMGR, "get bundleName failed!"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param bundleName failed, must be a string"); return CreateJsUndefined(env); } @@ -743,14 +794,14 @@ private: std::string bundleName; if (!ConvertFromJsValue(env, argv[0], bundleName)) { TAG_LOGE(AAFwkTag::APPMGR, "get bundleName wrong!"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param bundleName failed, must be a string"); return CreateJsUndefined(env); } uint32_t versionCode = 0; if (!ConvertFromJsValue(env, argv[1], versionCode)) { TAG_LOGE(AAFwkTag::APPMGR, "get versionCode failed!"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param versionCode failed, must be a number"); return CreateJsUndefined(env); } @@ -785,13 +836,13 @@ private: std::string bundleName; if (!ConvertFromJsValue(env, argv[0], bundleName)) { TAG_LOGE(AAFwkTag::APPMGR, "Parse bundleName failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param bundleName failed, must be a string"); return CreateJsUndefined(env); } int32_t accountId = -1; if (!ConvertFromJsValue(env, argv[1], accountId)) { TAG_LOGE(AAFwkTag::APPMGR, "Parse userId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param accountId failed, must be a number"); return CreateJsUndefined(env); } @@ -871,7 +922,7 @@ private: int32_t pid; if (!ConvertFromJsValue(env, argv[0], pid)) { TAG_LOGE(AAFwkTag::APPMGR, "get pid failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param pid failed, must be a number"); return CreateJsUndefined(env); } @@ -910,7 +961,7 @@ private: bool isPromiseType = false; if (!ConvertFromJsValue(env, argv[0], bundleName)) { TAG_LOGE(AAFwkTag::APPMGR, "First parameter must be string"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param bundleName failed, must be a string"); return CreateJsUndefined(env); } if (argc == ARGC_ONE) { @@ -922,11 +973,11 @@ private: } else if (argc == ARGC_THREE) { if (!ConvertFromJsValue(env, argv[1], userId)) { TAG_LOGW(AAFwkTag::APPMGR, "Must input userid and use callback when argc is three."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param userId failed, must be a number"); return CreateJsUndefined(env); } } else { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "The number of param exceeded"); return CreateJsUndefined(env); } @@ -963,7 +1014,7 @@ private: std::string bundleName; if (!ConvertFromJsValue(env, argv[0], bundleName)) { TAG_LOGE(AAFwkTag::APPMGR, "Get bundle name wrong."); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param bundleName failed, must be a string"); return CreateJsUndefined(env); } @@ -1139,6 +1190,8 @@ napi_value JsAppManagerInit(napi_env env, napi_value exportObj) JsAppManager::IsApplicationRunning); BindNativeFunction(env, exportObj, "preloadApplication", moduleName, JsAppManager::PreloadApplication); + BindNativeFunction(env, exportObj, "getRunningProcessInformationByBundleType", moduleName, + JsAppManager::GetRunningProcessInformationByBundleType); TAG_LOGD(AAFwkTag::APPMGR, "end"); return CreateJsUndefined(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 25985fbafc..7bc476e546 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 @@ -146,6 +146,7 @@ napi_value CreateJsRunningProcessInfo(napi_env env, const RunningProcessInfo &in napi_set_named_property(env, object, "bundleNames", CreateNativeArray(env, info.bundleNames)); napi_set_named_property(env, object, "state", CreateJsValue(env, ConvertToJsAppProcessState(info.state_, info.isFocused))); + napi_set_named_property(env, object, "bundleType", CreateJsValue(env, info.bundleType)); return object; } diff --git a/frameworks/js/napi/app_startup/async_task_callback/BUILD.gn b/frameworks/js/napi/app_startup/async_task_callback/BUILD.gn new file mode 100644 index 0000000000..9d39201ce6 --- /dev/null +++ b/frameworks/js/napi/app_startup/async_task_callback/BUILD.gn @@ -0,0 +1,61 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd.libasynctaskexcutorcallback_napi +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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") + +es2abc_gen_abc("gen_async_task_callback_abc") { + src_js = rebase_path("async_task_callback.ts") + dst_file = rebase_path(target_out_dir + "/async_task_callback.abc") + in_puts = [ "async_task_callback.ts" ] + out_puts = [ target_out_dir + "/async_task_callback.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("async_task_callback_js") { + input = "async_task_callback.ts" + output = target_out_dir + "/async_task_callback.o" +} + +gen_js_obj("async_task_callback_abc") { + input = get_label_info(":gen_async_task_callback_abc", "target_out_dir") + + "/async_task_callback.abc" + output = target_out_dir + "/async_task_callback_abc.o" + dep = ":gen_async_task_callback_abc" +} + +ohos_shared_library("asynctaskcallback_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 = [ "async_task_callback_module.cpp" ] + + deps = [ + ":async_task_callback_abc", + ":async_task_callback_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/app/appstartup" + subsystem_name = "ability" + part_name = "ability_runtime" +} diff --git a/frameworks/js/napi/app_startup/async_task_callback/async_task_callback.ts b/frameworks/js/napi/app_startup/async_task_callback/async_task_callback.ts new file mode 100644 index 0000000000..a27cc37299 --- /dev/null +++ b/frameworks/js/napi/app_startup/async_task_callback/async_task_callback.ts @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class AsyncTaskCallback { + private __impl__: AsyncTaskCallback; + constructor(object) { + "use sendable" + this.__impl__ = object; + } + + onAsyncTaskCompleted(startupName) { + console.log('AsyncTaskCallback onAsyncTaskCompleted called, startupName: ' + startupName); + this.__impl__.onAsyncTaskCompleted(startupName); + } +} + +export default AsyncTaskCallback; \ No newline at end of file diff --git a/frameworks/js/napi/app_startup/async_task_callback/async_task_callback_module.cpp b/frameworks/js/napi/app_startup/async_task_callback/async_task_callback_module.cpp new file mode 100644 index 0000000000..f4150fb616 --- /dev/null +++ b/frameworks/js/napi/app_startup/async_task_callback/async_task_callback_module.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 "native_engine/native_engine.h" + +extern const char _binary_async_task_callback_abc_start[]; +extern const char _binary_async_task_callback_abc_end[]; + +static napi_module _module = { + .nm_version = 0, + .nm_filename = "app/appstartup/libasynctaskcallback_napi.so/async_task_callback.js", + .nm_modname = "app.appstartup.AsyncTaskCallback", +}; +extern "C" __attribute__((constructor)) +void NAPI_app_appstartup_AsyncTaskCallback_AutoRegister() +{ + napi_module_register(&_module); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_app_appstartup_AsyncTaskCallback_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_async_task_callback_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_async_task_callback_abc_end - _binary_async_task_callback_abc_start; + } +} + diff --git a/frameworks/js/napi/app_startup/async_task_excutor/BUILD.gn b/frameworks/js/napi/app_startup/async_task_excutor/BUILD.gn new file mode 100644 index 0000000000..d83dae5e86 --- /dev/null +++ b/frameworks/js/napi/app_startup/async_task_excutor/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("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") +import("//build/ohos.gni") + +es2abc_gen_abc("gen_async_task_excutor_abc") { + src_js = rebase_path("async_task_excutor.ts") + dst_file = rebase_path(target_out_dir + "/async_task_excutor.abc") + in_puts = [ "async_task_excutor.ts" ] + out_puts = [ target_out_dir + "/async_task_excutor.abc" ] + extra_args = [ "--module" ] +} + +gen_js_obj("async_task_excutor_js") { + input = "async_task_excutor.ts" + output = target_out_dir + "/async_task_excutor.o" +} + +gen_js_obj("async_task_excutor_abc") { + input = get_label_info(":gen_async_task_excutor_abc", "target_out_dir") + + "/async_task_excutor.abc" + output = target_out_dir + "/async_task_excutor_abc.o" + dep = ":gen_async_task_excutor_abc" +} + +ohos_shared_library("asynctaskexcutor_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 = [ "async_task_excutor_module.cpp" ] + + deps = [ + ":async_task_excutor_abc", + ":async_task_excutor_js", + ] + + external_deps = [ "napi:ace_napi" ] + + relative_install_dir = "module/app/appstartup" + subsystem_name = "ability" + part_name = "ability_runtime" +} diff --git a/frameworks/js/napi/app_startup/async_task_excutor/async_task_excutor.ts b/frameworks/js/napi/app_startup/async_task_excutor/async_task_excutor.ts new file mode 100644 index 0000000000..d7cad8eea9 --- /dev/null +++ b/frameworks/js/napi/app_startup/async_task_excutor/async_task_excutor.ts @@ -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. + */ + +function concurrentFunc(startup, asyncCallback, context, startupName) { + "use concurrent"; + console.log('concurrentFunc start.'); + let taskPool = requireNapi('taskpool'); + startup.init(context); + taskPool.Task.sendData(asyncCallback, startupName); + console.log('concurrentFunc end.'); +} + +function receiveResult(asyncCallback, startupName) { + console.log('receiveResult called.'); + asyncCallback.onAsyncTaskCompleted(startupName); +} + +function pushTask(startup, asyncCallback, context, startupName) { + console.log('pushTask start.'); + let taskPool = requireNapi('taskpool'); + let task = new taskPool.Task(concurrentFunc, startup, asyncCallback, context, startupName); + task.onReceiveData(receiveResult); + taskPool.execute(task); + console.log('pushTask end.'); +} + +class AsyncTaskExcutor { + public asyncPushTask(startup, asyncCallback, context, startupName) { + console.log('asyncPushTask AsyncPushTask start.'); + pushTask(startup, asyncCallback, context, startupName); + console.log('asyncPushTask AsyncPushTask end.'); + } +} + +export default AsyncTaskExcutor; \ No newline at end of file diff --git a/frameworks/js/napi/app_startup/async_task_excutor/async_task_excutor_module.cpp b/frameworks/js/napi/app_startup/async_task_excutor/async_task_excutor_module.cpp new file mode 100644 index 0000000000..7f367d9283 --- /dev/null +++ b/frameworks/js/napi/app_startup/async_task_excutor/async_task_excutor_module.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 "native_engine/native_engine.h" + +extern const char _binary_async_task_excutor_abc_start[]; +extern const char _binary_async_task_excutor_abc_end[]; + +static napi_module _module = { + .nm_version = 0, + .nm_filename = "app/appstartup/libasynctaskexcutor_napi.so/async_task_excutor.js", + .nm_modname = "app.appstartup.AsyncTaskExcutor", +}; +extern "C" __attribute__((constructor)) +void NAPI_app_appstartup_AsyncTaskExcutor_AutoRegister() +{ + napi_module_register(&_module); +} + +extern "C" __attribute__((visibility("default"))) +void NAPI_app_appstartup_AsyncTaskExcutor_GetABCCode(const char **buf, int *buflen) +{ + if (buf != nullptr) { + *buf = _binary_async_task_excutor_abc_start; + } + if (buflen != nullptr) { + *buflen = _binary_async_task_excutor_abc_end - _binary_async_task_excutor_abc_start; + } +} \ No newline at end of file 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 fc1f3d3ff3..500409ce04 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 @@ -22,6 +22,7 @@ #include "js_startup_task_result.h" #include "napi/native_api.h" #include "startup_manager.h" +#include "js_error_utils.h" namespace OHOS { namespace AbilityRuntime { @@ -67,7 +68,7 @@ napi_value JsStartupManager::OnRun(napi_env env, NapiCallbackInfo &info) TAG_LOGD(AAFwkTag::STARTUP, "called."); if (info.argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::STARTUP, "the param is invalid."); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowTooFewParametersError(env); return CreateJsUndefined(env); } @@ -115,13 +116,13 @@ napi_value JsStartupManager::OnGetResult(napi_env env, NapiCallbackInfo &info) TAG_LOGD(AAFwkTag::STARTUP, "called."); if (info.argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::STARTUP, "the param is invalid."); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowTooFewParametersError(env); return CreateJsUndefined(env); } std::string startupTask; if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], startupTask)) { TAG_LOGE(AAFwkTag::STARTUP, "convert startupTask name failed."); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "Parameter error: Failed to convert startupTask, must be a string."); return CreateJsUndefined(env); } @@ -129,18 +130,18 @@ napi_value JsStartupManager::OnGetResult(napi_env env, NapiCallbackInfo &info) int32_t res = DelayedSingleton::GetInstance()->GetResult(startupTask, result); if (res != ERR_OK || result == nullptr || result->GetResultCode() != ERR_OK) { TAG_LOGE(AAFwkTag::STARTUP, "%{public}s, failed to get result.", startupTask.c_str()); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "%{public}s, failed to get result."); return CreateJsUndefined(env); } if (result->GetResultType() != StartupTaskResult::ResultType::JS) { TAG_LOGE(AAFwkTag::STARTUP, "%{public}s, the result type is not js.", startupTask.c_str()); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "%{public}s, the result type is not js."); return CreateJsUndefined(env); } std::shared_ptr jsResult = std::static_pointer_cast(result); if (jsResult == nullptr) { TAG_LOGE(AAFwkTag::STARTUP, "%{public}s, failed to convert to js result.", startupTask.c_str()); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "%{public}s, failed to convert to js result."); return CreateJsUndefined(env); } std::shared_ptr jsResultRef = jsResult->GetJsStartupResultRef(); @@ -155,13 +156,14 @@ napi_value JsStartupManager::OnIsInitialized(napi_env env, NapiCallbackInfo &inf TAG_LOGD(AAFwkTag::STARTUP, "called."); if (info.argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::STARTUP, "the param is invalid."); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowTooFewParametersError(env); return CreateJsUndefined(env); } std::string startupTask; if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], startupTask)) { TAG_LOGE(AAFwkTag::STARTUP, "convert startupTask name failed."); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "Parameter error: Failed to convert startupTask," + "must be a string or startupTask name is not matched."); return CreateJsUndefined(env); } @@ -169,7 +171,7 @@ napi_value JsStartupManager::OnIsInitialized(napi_env env, NapiCallbackInfo &inf int32_t res = DelayedSingleton::GetInstance()->IsInitialized(startupTask, isInitialized); if (res != ERR_OK) { TAG_LOGE(AAFwkTag::STARTUP, "%{public}s, failed to get result, res = %{public}d.", startupTask.c_str(), res); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "%{public}s, failed to get result, res = %{public}d."); return CreateJsUndefined(env); } return CreateJsValue(env, isInitialized); @@ -180,20 +182,21 @@ napi_value JsStartupManager::OnRemoveResult(napi_env env, NapiCallbackInfo &info TAG_LOGD(AAFwkTag::STARTUP, "called."); if (info.argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::STARTUP, "the param is invalid."); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowTooFewParametersError(env); return CreateJsUndefined(env); } std::string startupTask; if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], startupTask)) { TAG_LOGE(AAFwkTag::STARTUP, "convert startupTask name failed."); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "Parameter error: Failed to convert startupTask," + "must be a string or startupTask name is not matched."); return CreateJsUndefined(env); } int32_t res = DelayedSingleton::GetInstance()->RemoveResult(startupTask); if (res != ERR_OK) { TAG_LOGE(AAFwkTag::STARTUP, "%{public}s, failed to remove result, res = %{public}d.", startupTask.c_str(), res); - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "%{public}s, failed to get result, res = %{public}d."); return CreateJsUndefined(env); } return CreateJsUndefined(env); @@ -225,6 +228,7 @@ int32_t JsStartupManager::GetDependencies(napi_env env, napi_value value, std::v napi_is_array(env, value, &isArray); if (!isArray) { TAG_LOGE(AAFwkTag::STARTUP, "value is not array."); + ThrowInvalidParamError(env, "Parameter error: StartupTasks must be a Array."); return ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER; } @@ -239,12 +243,14 @@ int32_t JsStartupManager::GetDependencies(napi_env env, napi_value value, std::v napi_typeof(env, napiDep, &valueType); if (valueType != napi_string) { TAG_LOGE(AAFwkTag::STARTUP, "element is not string."); + ThrowInvalidParamError(env, "Parameter error: StartupTasks element must be a string."); return ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER; } std::string startupTask; if (!ConvertFromJsValue(env, napiDep, startupTask)) { TAG_LOGE(AAFwkTag::STARTUP, "convert startupTask name failed."); + ThrowInvalidParamError(env, "Parameter error: Convert startupTask name failed. Please check it."); return ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER; } dependencies.push_back(startupTask); @@ -261,6 +267,7 @@ int32_t JsStartupManager::GetConfig(napi_env env, napi_value value, std::shared_ } if (startupConfig->Init(value) != ERR_OK) { TAG_LOGE(AAFwkTag::STARTUP, "failed to init config"); + ThrowInvalidParamError(env, "Parameter error: Failed to init config, must be a StartupConfig."); return ERR_STARTUP_INVALID_VALUE; } config = startupConfig; diff --git a/frameworks/js/napi/app_startup/startup_task/BUILD.gn b/frameworks/js/napi/app_startup/startup_task/BUILD.gn index 456a4cfe40..8b732f6131 100644 --- a/frameworks/js/napi/app_startup/startup_task/BUILD.gn +++ b/frameworks/js/napi/app_startup/startup_task/BUILD.gn @@ -15,15 +15,15 @@ import("//arkcompiler/ets_frontend/es2panda/es2abc_config.gni") import("//build/ohos.gni") es2abc_gen_abc("gen_startup_task_abc") { - src_js = rebase_path("startup_task.js") + src_js = rebase_path("startup_task.ts") dst_file = rebase_path(target_out_dir + "/startup_task.abc") - in_puts = [ "startup_task.js" ] + in_puts = [ "startup_task.ts" ] out_puts = [ target_out_dir + "/startup_task.abc" ] extra_args = [ "--module" ] } gen_js_obj("startup_task_js") { - input = "startup_task.js" + input = "startup_task.ts" output = target_out_dir + "/startup_task.o" } diff --git a/frameworks/js/napi/app_startup/startup_task/startup_task.js b/frameworks/js/napi/app_startup/startup_task/startup_task.ts similarity index 94% rename from frameworks/js/napi/app_startup/startup_task/startup_task.js rename to frameworks/js/napi/app_startup/startup_task/startup_task.ts index 18714afcea..f2cdd0cef4 100644 --- a/frameworks/js/napi/app_startup/startup_task/startup_task.js +++ b/frameworks/js/napi/app_startup/startup_task/startup_task.ts @@ -14,6 +14,10 @@ */ class StartupTask { + constructor () { + "use sendable" + } + onDependenceCompleted(dependence, result) { console.log('onDependenceCompleted'); } diff --git a/frameworks/js/napi/app_startup/startup_task/startup_task_module.cpp b/frameworks/js/napi/app_startup/startup_task/startup_task_module.cpp index 2281c58da7..72600ed021 100644 --- a/frameworks/js/napi/app_startup/startup_task/startup_task_module.cpp +++ b/frameworks/js/napi/app_startup/startup_task/startup_task_module.cpp @@ -15,8 +15,6 @@ #include "native_engine/native_engine.h" -extern const char _binary_startup_task_js_start[]; -extern const char _binary_startup_task_js_end[]; extern const char _binary_startup_task_abc_start[]; extern const char _binary_startup_task_abc_end[]; @@ -31,18 +29,6 @@ void NAPI_app_appstartup_StartupTask_AutoRegister() napi_module_register(&_module); } -extern "C" __attribute__((visibility("default"))) -void NAPI_app_appstartup_StartupTask_GetJSCode(const char **buf, int *bufLen) -{ - if (buf != nullptr) { - *buf = _binary_startup_task_js_start; - } - - if (bufLen != nullptr) { - *bufLen = _binary_startup_task_js_end - _binary_startup_task_js_start; - } -} - extern "C" __attribute__((visibility("default"))) void NAPI_app_appstartup_StartupTask_GetABCCode(const char **buf, int *buflen) { diff --git a/frameworks/js/napi/callee/callee.js b/frameworks/js/napi/callee/callee.js index 16b5625832..f527037bbe 100644 --- a/frameworks/js/napi/callee/callee.js +++ b/frameworks/js/napi/callee/callee.js @@ -49,6 +49,15 @@ class BusinessError extends Error { } } +class ThrowInvalidParamError extends Error { + constructor(msg) { + let code = ERROR_CODE_INVALID_PARAM; + let oriMsg = ERROR_MSG_INVALID_PARAM; + super(code); + this.msg = oriMsg + msg; + } +} + class Callee extends rpc.RemoteObject { constructor(des) { if (typeof des === 'string') { @@ -118,7 +127,8 @@ class Callee extends rpc.RemoteObject { if (typeof method !== 'string' || method === '' || typeof callback !== 'function') { console.log( 'Callee on error, method is [' + typeof method + '], typeof callback [' + typeof callback + ']'); - throw new BusinessError(ERROR_CODE_INVALID_PARAM); + throw new ThrowInvalidParamError('Parameter error: Failed to get method or callback.' + + 'method must be a non-empty string, callback must be a function.'); } if (this.callList == null) { @@ -138,7 +148,7 @@ class Callee extends rpc.RemoteObject { off(method) { if (typeof method !== 'string' || method === '') { console.log('Callee off error, method is [' + typeof method + ']'); - throw new BusinessError(ERROR_CODE_INVALID_PARAM); + throw new ThrowInvalidParamError('Parameter error: Failed to get method, must be a string.'); } if (this.callList == null) { diff --git a/frameworks/js/napi/caller/caller.js b/frameworks/js/napi/caller/caller.js index cec3b33c5c..1f1f165b98 100644 --- a/frameworks/js/napi/caller/caller.js +++ b/frameworks/js/napi/caller/caller.js @@ -46,6 +46,15 @@ class BusinessError extends Error { } } +class ThrowInvalidParamError extends Error { + constructor(msg) { + let code = ERROR_CODE_INVALID_PARAM; + let oriMsg = ERROR_MSG_INVALID_PARAM; + super(code); + this.msg = oriMsg + msg; + } +} + class Caller { constructor(obj) { console.log('Caller::constructor obj is ' + typeof obj); @@ -181,7 +190,7 @@ class Caller { console.log('Caller onRelease jscallback called.'); if (typeof callback !== 'function') { console.log('Caller onRelease ' + typeof callback); - throw new BusinessError(ERROR_CODE_INVALID_PARAM); + throw new ThrowInvalidParamError('Parameter error: Failed to get callback, must be a function.'); } if (this.releaseState === true) { @@ -196,7 +205,7 @@ class Caller { console.log('Caller onRemoteStateChange jscallback called.'); if (typeof callback !== 'function') { console.log('Caller onRemoteStateChange ' + typeof callback); - throw new BusinessError(ERROR_CODE_INVALID_PARAM); + throw new ThrowInvalidParamError('Parameter error: Failed to get callback, must be a function.'); } if (this.releaseState === true) { @@ -212,12 +221,12 @@ class Caller { if (typeof type !== 'string' || type !== 'release') { console.log( 'Caller onRelease error, input [type] is invalid.'); - throw new BusinessError(ERROR_CODE_INVALID_PARAM); + throw new ThrowInvalidParamError('Parameter error: Failed to get type, must be string type release.'); } if (typeof callback !== 'function') { console.log('Caller onRelease error ' + typeof callback); - throw new BusinessError(ERROR_CODE_INVALID_PARAM); + throw new ThrowInvalidParamError('Parameter error: Failed to get callback, must be a function.'); } if (this.releaseState === true) { @@ -232,12 +241,12 @@ class Caller { if (typeof type !== 'string' || type !== 'release') { console.log( 'Caller onRelease error, input [type] is invalid.'); - throw new BusinessError(ERROR_CODE_INVALID_PARAM); + throw new ThrowInvalidParamError('Parameter error: Failed to get type, must be string type release.'); } if (callback && typeof callback !== 'function') { console.log('Caller onRelease error ' + typeof callback); - throw new BusinessError(ERROR_CODE_INVALID_PARAM); + throw new ThrowInvalidParamError('Parameter error: Failed to get callback, must be a function.'); } // Empty } @@ -245,12 +254,13 @@ class Caller { callCheck(method, data) { if (typeof method !== 'string' || typeof data !== 'object') { console.log('Caller callCheck ' + typeof method + ' ' + typeof data); - return new BusinessError(ERROR_CODE_INVALID_PARAM); + return new ThrowInvalidParamError('Parameter error: Failed to get method or data, ' + + 'method must be a string, data must be a rpc.Parcelable'); } if (method === '' || data == null) { console.log('Caller callCheck ' + method + ', ' + data); - return new BusinessError(ERROR_CODE_INVALID_PARAM); + return new ThrowInvalidParamError('Parameter error: method or data is empty, Please check it.'); } if (this.releaseState === true) { diff --git a/frameworks/js/napi/inner/napi_ability_common/BUILD.gn b/frameworks/js/napi/inner/napi_ability_common/BUILD.gn index f2f29a1cc8..3017b49183 100644 --- a/frameworks/js/napi/inner/napi_ability_common/BUILD.gn +++ b/frameworks/js/napi/inner/napi_ability_common/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. +# Copyright (c) 2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -55,6 +55,8 @@ ohos_shared_library("napi_ability_common") { "napi:ace_napi", ] + public_external_deps = [ "bundle_framework:appexecfwk_core" ] + if (ability_runtime_graphics) { defines = [ "SUPPORT_GRAPHICS" ] } 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 eeb17ee10e..19b179a514 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 @@ -1748,83 +1748,73 @@ HapModuleInfoCB *CreateHapModuleInfoCBInfo(napi_env env) return hapModuleInfoCB; } -napi_value WrapHapModuleInfo(napi_env env, const HapModuleInfoCB &hapModuleInfoCB) +napi_value WrapHapModuleInfo(napi_env env, const HapModuleInfoCB &cb) { TAG_LOGI(AAFwkTag::JSNAPI, "%{public}s called.", __func__); napi_value result = nullptr; napi_value proValue = nullptr; NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL( - env, napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.name.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_create_string_utf8(env, cb.hapModuleInfo.name.c_str(), NAPI_AUTO_LENGTH, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "name", proValue)); - NAPI_CALL(env, - napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.description.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_create_string_utf8(env, cb.hapModuleInfo.description.c_str(), NAPI_AUTO_LENGTH, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "description", proValue)); - NAPI_CALL( - env, napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.iconPath.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_create_string_utf8(env, cb.hapModuleInfo.iconPath.c_str(), NAPI_AUTO_LENGTH, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "icon", proValue)); - NAPI_CALL( - env, napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.label.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_create_string_utf8(env, cb.hapModuleInfo.label.c_str(), NAPI_AUTO_LENGTH, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "label", proValue)); - NAPI_CALL(env, - napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.backgroundImg.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_create_string_utf8(env, cb.hapModuleInfo.backgroundImg.c_str(), NAPI_AUTO_LENGTH, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "backgroundImg", proValue)); - NAPI_CALL(env, - napi_create_string_utf8(env, hapModuleInfoCB.hapModuleInfo.moduleName.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_create_string_utf8(env, cb.hapModuleInfo.moduleName.c_str(), NAPI_AUTO_LENGTH, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "moduleName", proValue)); - NAPI_CALL(env, napi_create_int32(env, hapModuleInfoCB.hapModuleInfo.supportedModes, &proValue)); + NAPI_CALL(env, napi_create_int32(env, cb.hapModuleInfo.supportedModes, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "supportedModes", proValue)); - NAPI_CALL(env, napi_create_int32(env, hapModuleInfoCB.hapModuleInfo.descriptionId, &proValue)); + NAPI_CALL(env, napi_create_int32(env, cb.hapModuleInfo.descriptionId, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "descriptionId", proValue)); - NAPI_CALL(env, napi_create_int32(env, hapModuleInfoCB.hapModuleInfo.labelId, &proValue)); + NAPI_CALL(env, napi_create_int32(env, cb.hapModuleInfo.labelId, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "labelId", proValue)); - NAPI_CALL(env, napi_create_int32(env, hapModuleInfoCB.hapModuleInfo.iconId, &proValue)); + NAPI_CALL(env, napi_create_int32(env, cb.hapModuleInfo.iconId, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "iconId", proValue)); - NAPI_CALL(env, - napi_create_string_utf8( - env, hapModuleInfoCB.hapModuleInfo.mainAbility.c_str(), NAPI_AUTO_LENGTH, &proValue)); + NAPI_CALL(env, napi_create_string_utf8(env, cb.hapModuleInfo.mainAbility.c_str(), NAPI_AUTO_LENGTH, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "mainAbilityName", proValue)); - NAPI_CALL(env, napi_get_boolean(env, hapModuleInfoCB.hapModuleInfo.installationFree, &proValue)); + NAPI_CALL(env, napi_get_boolean(env, cb.hapModuleInfo.installationFree, &proValue)); NAPI_CALL(env, napi_set_named_property(env, result, "installationFree", proValue)); napi_value jsArrayreqCapabilities = nullptr; NAPI_CALL(env, napi_create_array(env, &jsArrayreqCapabilities)); - for (size_t i = 0; i < hapModuleInfoCB.hapModuleInfo.reqCapabilities.size(); i++) { + for (size_t i = 0; i < cb.hapModuleInfo.reqCapabilities.size(); i++) { proValue = nullptr; NAPI_CALL(env, - napi_create_string_utf8( - env, hapModuleInfoCB.hapModuleInfo.reqCapabilities.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); + napi_create_string_utf8(env, cb.hapModuleInfo.reqCapabilities.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); NAPI_CALL(env, napi_set_element(env, jsArrayreqCapabilities, i, proValue)); } NAPI_CALL(env, napi_set_named_property(env, result, "reqCapabilities", jsArrayreqCapabilities)); napi_value jsArraydeviceTypes = nullptr; NAPI_CALL(env, napi_create_array(env, &jsArraydeviceTypes)); - for (size_t i = 0; i < hapModuleInfoCB.hapModuleInfo.deviceTypes.size(); i++) { + for (size_t i = 0; i < cb.hapModuleInfo.deviceTypes.size(); i++) { proValue = nullptr; NAPI_CALL(env, - napi_create_string_utf8( - env, hapModuleInfoCB.hapModuleInfo.deviceTypes.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); + napi_create_string_utf8(env, cb.hapModuleInfo.deviceTypes.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); NAPI_CALL(env, napi_set_element(env, jsArraydeviceTypes, i, proValue)); } NAPI_CALL(env, napi_set_named_property(env, result, "deviceTypes", jsArraydeviceTypes)); napi_value abilityInfos = nullptr; NAPI_CALL(env, napi_create_array(env, &abilityInfos)); - for (size_t i = 0; i < hapModuleInfoCB.hapModuleInfo.abilityInfos.size(); i++) { + for (size_t i = 0; i < cb.hapModuleInfo.abilityInfos.size(); i++) { napi_value abilityInfo = nullptr; - abilityInfo = WrapAbilityInfo(env, hapModuleInfoCB.hapModuleInfo.abilityInfos.at(i)); + abilityInfo = WrapAbilityInfo(env, cb.hapModuleInfo.abilityInfos.at(i)); NAPI_CALL(env, napi_set_element(env, abilityInfos, i, abilityInfo)); } NAPI_CALL(env, napi_set_named_property(env, result, "abilityInfo", abilityInfos)); @@ -2413,11 +2403,7 @@ napi_value GetContextAsync( TAG_LOGD(AAFwkTag::JSNAPI, "napi_create_reference"); napi_create_reference(env, args[argCallback], 1, &asyncCallbackInfo->cbInfo.callback); } - napi_create_async_work( - env, - nullptr, - resourceName, - GetContextAsyncExecuteCB, + napi_create_async_work(env, nullptr, resourceName, GetContextAsyncExecuteCB, [](napi_env env, napi_status, void *data) { TAG_LOGI(AAFwkTag::JSNAPI, "GetContextAsync, main event thread complete."); AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); @@ -2443,9 +2429,7 @@ napi_value GetContextAsync( delete asyncCallbackInfo; asyncCallbackInfo = nullptr; TAG_LOGI(AAFwkTag::JSNAPI, "GetContextAsync, main event thread complete end."); - }, - static_cast(asyncCallbackInfo), - &asyncCallbackInfo->asyncWork); + }, static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork); napi_queue_async_work_with_qos(env, asyncCallbackInfo->asyncWork, napi_qos_user_initiated); napi_value result = nullptr; napi_get_null(env, &result); @@ -2604,11 +2588,7 @@ napi_value GetWantAsync(napi_env env, napi_value *args, const size_t argCallback TAG_LOGD(AAFwkTag::JSNAPI, "napi_create_reference."); napi_create_reference(env, args[argCallback], 1, &asyncCallbackInfo->cbInfo.callback); } - napi_create_async_work( - env, - nullptr, - resourceName, - GetWantExecuteCB, + napi_create_async_work(env, nullptr, resourceName, GetWantExecuteCB, [](napi_env env, napi_status, void *data) { TAG_LOGI(AAFwkTag::JSNAPI, "GetWantAsync, main event thread complete."); AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); @@ -3689,14 +3669,12 @@ napi_value AcquireDataAbilityHelperWrap(napi_env env, napi_callback_info info, D return nullptr; } } - napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, args[uriIndex], &valuetype)); if (valuetype != napi_string) { TAG_LOGE(AAFwkTag::JSNAPI, "%{public}s, Wrong argument type.", __func__); return nullptr; } - napi_value result = nullptr; NAPI_CALL(env, napi_new_instance(env, GetGlobalDataAbilityHelper(env), uriIndex + 1, &args[PARAM0], &result)); @@ -4098,15 +4076,13 @@ napi_value JsNapiCommon::JsConnectAbility(napi_env env, napi_callback_info info, abilityConnection->AddConnectionCallback(connectionCallback); // Judge connection-state auto connectionState = abilityConnection->GetConnectionState(); + TAG_LOGI(AAFwkTag::JSNAPI, "connectionState = %{public}d", connectionState); if (connectionState == CONNECTION_STATE_CONNECTED) { - TAG_LOGI(AAFwkTag::JSNAPI, "Ability is connected, callback to client."); abilityConnection->HandleOnAbilityConnectDone(*connectionCallback, ERR_OK); return CreateJsValue(env, id); } else if (connectionState == CONNECTION_STATE_CONNECTING) { - TAG_LOGI(AAFwkTag::JSNAPI, "Ability is connecting, just wait callback."); return CreateJsValue(env, id); } else { - TAG_LOGE(AAFwkTag::JSNAPI, "AbilityConnection has disconnected, erase it."); RemoveConnectionLocked(want); return CreateJsUndefined(env); } diff --git a/frameworks/js/napi/inner/napi_common/BUILD.gn b/frameworks/js/napi/inner/napi_common/BUILD.gn index a1a621ffe2..de57564b9d 100644 --- a/frameworks/js/napi/inner/napi_common/BUILD.gn +++ b/frameworks/js/napi/inner/napi_common/BUILD.gn @@ -60,6 +60,8 @@ ohos_shared_library("napi_common") { "napi:ace_napi", ] + public_external_deps = [ "bundle_framework:appexecfwk_core" ] + if (ability_runtime_graphics) { defines = [ "SUPPORT_GRAPHICS" ] } 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 22a1a53332..6487a5028f 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 @@ -105,7 +105,7 @@ private: InsightIntentExecuteParam param; if (!UnwrapExecuteParam(env, info.argv[INDEX_ZERO], param)) { TAG_LOGE(AAFwkTag::INTENT, "CheckOnOffType, Parse on off type failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Parse param failed, param must be a ExecuteParam."); return CreateJsUndefined(env); } diff --git a/frameworks/js/napi/js_dialog_session/BUILD.gn b/frameworks/js/napi/js_dialog_session/BUILD.gn index 13d1e852b2..19e7a4e7ed 100644 --- a/frameworks/js/napi/js_dialog_session/BUILD.gn +++ b/frameworks/js/napi/js_dialog_session/BUILD.gn @@ -30,7 +30,6 @@ ohos_shared_library("dialogsession_napi") { "${ability_runtime_innerkits_path}/runtime:runtime", "${ability_runtime_napi_path}/inner/napi_common:napi_common", "${ability_runtime_native_path}/appkit:app_context", - "//third_party/json:nlohmann_json_static", ] external_deps = [ @@ -44,6 +43,7 @@ ohos_shared_library("dialogsession_napi") { "hilog:libhilog", "init:libbegetutil", "ipc:ipc_core", + "json:nlohmann_json_static", "jsoncpp:jsoncpp", "napi:ace_napi", "samgr:samgr_proxy", diff --git a/frameworks/js/napi/js_mission_manager/BUILD.gn b/frameworks/js/napi/js_mission_manager/BUILD.gn index 930849d948..f501ff6223 100755 --- a/frameworks/js/napi/js_mission_manager/BUILD.gn +++ b/frameworks/js/napi/js_mission_manager/BUILD.gn @@ -46,7 +46,6 @@ ohos_shared_library("missionmanager") { ] if (ability_runtime_graphics) { - include_dirs += [] external_deps += [ "graphic_2d:color_manager", "icu:shared_icuuc", diff --git a/frameworks/js/napi/js_mission_manager/mission_manager.cpp b/frameworks/js/napi/js_mission_manager/mission_manager.cpp index 4759f5644e..dcad35035d 100755 --- a/frameworks/js/napi/js_mission_manager/mission_manager.cpp +++ b/frameworks/js/napi/js_mission_manager/mission_manager.cpp @@ -146,7 +146,7 @@ private: } if (!CheckOnOffType(env, argc, argv)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param type failed, must be a string, value must be mission"); return CreateJsUndefined(env); } @@ -183,7 +183,7 @@ private: } if (!AppExecFwk::IsTypeForNapiValue(env, argv[1], napi_object)) { TAG_LOGE(AAFwkTag::MISSION, "Invalid param"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param listener failed, must be a MissionListener"); return CreateJsUndefined(env); } @@ -230,14 +230,14 @@ private: } if (!CheckOnOffType(env, argc, argv)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param type failed, must be a string, value must be mission"); return CreateJsUndefined(env); } int32_t missionListenerId = -1; if (!ConvertFromJsValue(env, argv[ARGC_ONE], missionListenerId)) { TAG_LOGE(AAFwkTag::MISSION, "Parse missionListenerId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param listenerId failed, must be a number"); return CreateJsUndefined(env); } @@ -282,7 +282,7 @@ private: int32_t missionListenerId = -1; if (!ConvertFromJsValue(env, argv[INDEX_ONE], missionListenerId)) { TAG_LOGE(AAFwkTag::MISSION, "Parse missionListenerId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param listenerId failed, must be a number"); return CreateJsUndefined(env); } @@ -326,13 +326,13 @@ private: std::string deviceId; if (!ConvertFromJsValue(env, argv[0], deviceId)) { TAG_LOGE(AAFwkTag::MISSION, "Parse deviceId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param deviceId failed, must be a string"); return CreateJsUndefined(env); } int numMax = -1; if (!ConvertFromJsValue(env, argv[1], numMax)) { TAG_LOGE(AAFwkTag::MISSION, "Parse numMax failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param numMax failed, must be a number"); return CreateJsUndefined(env); } @@ -366,13 +366,13 @@ private: std::string deviceId; if (!ConvertFromJsValue(env, argv[0], deviceId)) { TAG_LOGE(AAFwkTag::MISSION, "Parse deviceId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param deviceId failed, must be a string"); return CreateJsUndefined(env); } int32_t missionId = -1; if (!ConvertFromJsValue(env, argv[1], missionId)) { TAG_LOGE(AAFwkTag::MISSION, "Parse missionId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param missionId failed, must be a number"); return CreateJsUndefined(env); } @@ -467,13 +467,13 @@ private: if (!ConvertFromJsValue(env, argv[0], deviceId)) { TAG_LOGE(AAFwkTag::MISSION, "missionSnapshot: Parse deviceId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param deviceId failed, must be a string"); return false; } if (!ConvertFromJsValue(env, argv[1], missionId)) { TAG_LOGE(AAFwkTag::MISSION, "missionSnapshot: Parse missionId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param missionId failed, must be a number"); return false; } @@ -491,7 +491,7 @@ private: int32_t missionId = -1; if (!ConvertFromJsValue(env, argv[0], missionId)) { TAG_LOGE(AAFwkTag::MISSION, "OnLockMission Parse missionId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param missionId failed, must be a number"); return CreateJsUndefined(env); } @@ -524,7 +524,7 @@ private: int32_t missionId = -1; if (!ConvertFromJsValue(env, argv[0], missionId)) { TAG_LOGE(AAFwkTag::MISSION, "OnUnlockMission Parse missionId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param missionId failed, must be a number"); return CreateJsUndefined(env); } @@ -557,7 +557,7 @@ private: int32_t missionId = -1; if (!ConvertFromJsValue(env, argv[0], missionId)) { TAG_LOGE(AAFwkTag::MISSION, "OnClearMission Parse missionId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param missionId failed, must be a number"); return CreateJsUndefined(env); } @@ -611,7 +611,7 @@ private: int32_t missionId = -1; if (!ConvertFromJsValue(env, argv[0], missionId)) { TAG_LOGE(AAFwkTag::MISSION, "OnMoveMissionToFront Parse missionId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param missionId failed, must be a number"); return CreateJsUndefined(env); } decltype(argc) unwrapArgc = 1; @@ -654,7 +654,7 @@ private: napi_get_array_length(env, argv[0], &nativeArrayLen); if (nativeArrayLen == 0) { TAG_LOGE(AAFwkTag::MISSION, "OnMoveMissionsToForeground MissionId is null"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param missionIds failed, the size of missionIds must above zero"); return CreateJsUndefined(env); } napi_value element = nullptr; @@ -663,7 +663,7 @@ private: napi_get_element(env, argv[0], i, &element); if (!ConvertFromJsValue(env, element, missionId)) { TAG_LOGE(AAFwkTag::MISSION, "OnMoveMissionsToForeground Parse missionId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param missionIds failed, missionId must be a number"); return CreateJsUndefined(env); } missionIds.push_back(missionId); @@ -674,7 +674,7 @@ private: if (argc > ARGC_ONE && AppExecFwk::IsTypeForNapiValue(env, argv[1], napi_number)) { if (!ConvertFromJsValue(env, argv[1], topMissionId)) { TAG_LOGE(AAFwkTag::MISSION, "OnMoveMissionsToForeground Parse topMissionId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param topMission failed, must be a number"); return CreateJsUndefined(env); } unwrapArgc++; @@ -713,7 +713,7 @@ private: napi_get_array_length(env, argv[0], &nativeArrayLen); if (nativeArrayLen == 0) { TAG_LOGE(AAFwkTag::MISSION, "OnMoveMissionsToBackground MissionId is null"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param missionIds failed, the size of missionIds must above zero"); return CreateJsUndefined(env); } napi_value element = nullptr; @@ -722,7 +722,7 @@ private: napi_get_element(env, argv[0], i, &element); if (!ConvertFromJsValue(env, element, missionId)) { TAG_LOGE(AAFwkTag::MISSION, "OnMoveMissionsToBackground Parse topMissionId failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param missionIds failed, missionId must be a number"); return CreateJsUndefined(env); } missionIds.push_back(missionId); diff --git a/frameworks/js/napi/mission_manager/BUILD.gn b/frameworks/js/napi/mission_manager/BUILD.gn index c5b8238ec0..ef94b19dd4 100644 --- a/frameworks/js/napi/mission_manager/BUILD.gn +++ b/frameworks/js/napi/mission_manager/BUILD.gn @@ -45,7 +45,6 @@ ohos_shared_library("missionmanager_napi") { ] if (ability_runtime_graphics) { - include_dirs += [] external_deps += [ "graphic_2d:color_manager", "icu:shared_icuuc", 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 d875b0af70..062496f908 100644 --- a/frameworks/js/napi/quick_fix/js_quick_fix_manager.cpp +++ b/frameworks/js/napi/quick_fix/js_quick_fix_manager.cpp @@ -22,6 +22,7 @@ #include "napi_common_util.h" #include "quick_fix_error_utils.h" #include "quick_fix_manager_client.h" +#include "js_error_utils.h" namespace OHOS { namespace AbilityRuntime { @@ -79,14 +80,14 @@ private: TAG_LOGD(AAFwkTag::QUICKFIX, "function called."); if (info.argc != ARGC_ONE && info.argc != ARGC_TWO) { TAG_LOGE(AAFwkTag::QUICKFIX, "The number of parameter is invalid."); - Throw(env, AAFwk::ERR_QUICKFIX_PARAM_INVALID); + ThrowInvalidParamError(env, "Parameter error: The number of parameter is invalid."); return CreateJsUndefined(env); } std::string bundleName; if (!OHOS::AppExecFwk::UnwrapStringFromJS2(env, info.argv[0], bundleName)) { TAG_LOGE(AAFwkTag::QUICKFIX, "The bundleName is invalid."); - Throw(env, AAFwk::ERR_QUICKFIX_PARAM_INVALID); + ThrowInvalidParamError(env, "Parameter error: The bundleName is invalid, must be a string."); return CreateJsUndefined(env); } @@ -114,14 +115,14 @@ private: TAG_LOGD(AAFwkTag::QUICKFIX, "function called."); if (info.argc != ARGC_ONE && info.argc != ARGC_TWO) { TAG_LOGE(AAFwkTag::QUICKFIX, "The number of parameter is invalid."); - Throw(env, AAFwk::ERR_QUICKFIX_PARAM_INVALID); + ThrowInvalidParamError(env, "Parameter error: The number of parameter is invalid."); return CreateJsUndefined(env); } std::vector hapQuickFixFiles; if (!OHOS::AppExecFwk::UnwrapArrayStringFromJS(env, info.argv[0], hapQuickFixFiles)) { TAG_LOGE(AAFwkTag::QUICKFIX, "Hap quick fix files is invalid."); - Throw(env, AAFwk::ERR_QUICKFIX_PARAM_INVALID); + ThrowInvalidParamError(env, "Parameter error: Hap quick fix files is invalid, must be a Array."); return CreateJsUndefined(env); } @@ -148,14 +149,14 @@ private: TAG_LOGD(AAFwkTag::QUICKFIX, "called."); if (info.argc == ARGC_ZERO) { TAG_LOGE(AAFwkTag::QUICKFIX, "The number of parameter is invalid."); - Throw(env, AAFwk::ERR_QUICKFIX_PARAM_INVALID); + ThrowInvalidParamError(env, "Parameter error: The number of parameter is invalid."); return CreateJsUndefined(env); } std::string bundleName; if (!ConvertFromJsValue(env, info.argv[ARGC_ZERO], bundleName)) { TAG_LOGE(AAFwkTag::QUICKFIX, "The bundleName is invalid."); - Throw(env, AAFwk::ERR_QUICKFIX_PARAM_INVALID); + ThrowInvalidParamError(env, "Parameter error: The bundleName is invalid, must be a string."); return CreateJsUndefined(env); } diff --git a/frameworks/js/napi/wantagent/napi_want_agent.cpp b/frameworks/js/napi/wantagent/napi_want_agent.cpp index 855f8f552c..93bf7d9328 100644 --- a/frameworks/js/napi/wantagent/napi_want_agent.cpp +++ b/frameworks/js/napi/wantagent/napi_want_agent.cpp @@ -27,8 +27,9 @@ #include "js_runtime_utils.h" #include "napi_common.h" #include "start_options.h" -#include "tokenid_kit.h" #include "want_agent_helper.h" +#include "tokenid_kit.h" +#include "js_error_utils.h" using namespace OHOS::AbilityRuntime; namespace OHOS { @@ -318,13 +319,12 @@ napi_value JsWantAgent::OnEqual(napi_env env, napi_callback_info info) napi_value argv[ARGS_MAX_COUNT] = {nullptr}; napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); TAG_LOGD(AAFwkTag::WANTAGENT, "enter, argc = %{public}d", static_cast(argc)); - int32_t errCode = BUSINESS_ERROR_CODE_OK; WantAgent* pWantAgentFirst = nullptr; WantAgent* pWantAgentSecond = nullptr; if (argc < ARGC_TWO || argc > ARGC_THREE) { TAG_LOGE(AAFwkTag::WANTAGENT, "Not enough params"); #ifdef ENABLE_ERRCODE - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowTooFewParametersError(env); #endif return CreateJsUndefined(env); } @@ -333,12 +333,10 @@ napi_value JsWantAgent::OnEqual(napi_env env, napi_callback_info info) if (!CheckTypeForNapiValue(env, argv[0], napi_object)) { TAG_LOGE(AAFwkTag::WANTAGENT, "Wrong argument type. Object expected."); #ifdef ENABLE_ERRCODE - errCode = ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER; - AbilityRuntimeErrorUtil::Throw(env, errCode); + ThrowInvalidParamError(env, "Wrong argument type. Agent must be a WantAgent."); return CreateJsUndefined(env); #else - errCode = ERR_NOT_OK; - return RetErrMsg(env, lastParam, errCode); + return RetErrMsg(env, lastParam, ERR_NOT_OK); #endif } @@ -346,22 +344,20 @@ napi_value JsWantAgent::OnEqual(napi_env env, napi_callback_info info) if (pWantAgentFirst == nullptr) { TAG_LOGE(AAFwkTag::WANTAGENT, "Parse pWantAgentFirst failed"); #ifdef ENABLE_ERRCODE - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "Parse pWantAgentFirst failed. Agent must be a WantAgent."); return CreateJsUndefined(env); #else - errCode = ERR_NOT_OK; - return RetErrMsg(env, lastParam, errCode); + return RetErrMsg(env, lastParam, ERR_NOT_OK); #endif } if (!CheckTypeForNapiValue(env, argv[1], napi_object)) { TAG_LOGE(AAFwkTag::WANTAGENT, "Wrong argument type. Object expected."); #ifdef ENABLE_ERRCODE - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "Wrong argument type. OtherAgent must be a WantAgent."); return CreateJsUndefined(env); #else - errCode = ERR_NOT_OK; - return RetErrMsg(env, lastParam, errCode); + return RetErrMsg(env, lastParam, ERR_NOT_OK); #endif } @@ -369,11 +365,10 @@ napi_value JsWantAgent::OnEqual(napi_env env, napi_callback_info info) if (pWantAgentSecond == nullptr) { TAG_LOGE(AAFwkTag::WANTAGENT, "Parse pWantAgentSceond failed"); #ifdef ENABLE_ERRCODE - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "Parse pWantAgentSceond failed. OtherAgent must be a WantAgent."); return CreateJsUndefined(env); #else - errCode = ERR_NOT_OK; - return RetErrMsg(env, lastParam, errCode); + return RetErrMsg(env, lastParam, ERR_NOT_OK); #endif } @@ -421,12 +416,14 @@ napi_value JsWantAgent::OnGetWant(napi_env env, napi_callback_info info) WantAgent* pWantAgent = nullptr; if (argc > ARGC_TWO || argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::WANTAGENT, "Not enough arguments"); + ThrowTooFewParametersError(env); return CreateJsUndefined(env); } napi_value lastParam = (argc >= ARGC_TWO) ? argv[INDEX_ONE] : nullptr; if (!CheckTypeForNapiValue(env, argv[0], napi_object)) { TAG_LOGE(AAFwkTag::WANTAGENT, "Wrong parameter type. Object expected."); + ThrowInvalidParamError(env, "Wrong argument type. Agent must be a WantAgent."); errCode = ERR_NOT_OK; return RetErrMsg(env, lastParam, errCode); } @@ -434,6 +431,7 @@ napi_value JsWantAgent::OnGetWant(napi_env env, napi_callback_info info) UnwrapWantAgent(env, argv[0], reinterpret_cast(&pWantAgent)); if (pWantAgent == nullptr) { TAG_LOGE(AAFwkTag::WANTAGENT, "Parse pWantAgent error"); + ThrowInvalidParamError(env, "Parse pWantAgent error. Agent must be a WantAgent."); errCode = ERR_NOT_OK; return RetErrMsg(env, lastParam, errCode); } @@ -466,12 +464,14 @@ napi_value JsWantAgent::OnGetOperationType(napi_env env, napi_callback_info info WantAgent* pWantAgent = nullptr; if (argc > ARGC_TWO || argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::WANTAGENT, "Not enough params"); + ThrowTooFewParametersError(env); return CreateJsUndefined(env); } napi_value lastParam = (argc >= ARGC_TWO) ? argv[INDEX_ONE] : nullptr; if (!CheckTypeForNapiValue(env, argv[0], napi_object)) { TAG_LOGE(AAFwkTag::WANTAGENT, "Wrong argument type. Object expected."); + ThrowInvalidParamError(env, "Wrong argument type. Agent must be a WantAgent."); errCode = ERR_NOT_OK; return RetErrMsg(env, lastParam, errCode); } @@ -479,6 +479,7 @@ napi_value JsWantAgent::OnGetOperationType(napi_env env, napi_callback_info info UnwrapWantAgent(env, argv[0], reinterpret_cast(&pWantAgent)); if (pWantAgent == nullptr) { TAG_LOGE(AAFwkTag::WANTAGENT, "Parse pWantAgent failed"); + ThrowInvalidParamError(env, "Parse pWantAgent failed. Agent must be a WantAgent."); errCode = ERR_NOT_OK; return RetErrMsg(env, lastParam, errCode); } @@ -502,12 +503,11 @@ napi_value JsWantAgent::OnGetBundleName(napi_env env, napi_callback_info info) size_t argc = ARGS_MAX_COUNT; napi_value argv[ARGS_MAX_COUNT] = {nullptr}; napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); - int32_t errCode = BUSINESS_ERROR_CODE_OK; WantAgent* pWantAgent = nullptr; if (argc > ARGC_TWO || argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::WANTAGENT, "Not enough params"); #ifdef ENABLE_ERRCODE - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowTooFewParametersError(env); #endif return CreateJsUndefined(env); } @@ -516,11 +516,10 @@ napi_value JsWantAgent::OnGetBundleName(napi_env env, napi_callback_info info) if (!CheckTypeForNapiValue(env, argv[0], napi_object)) { TAG_LOGE(AAFwkTag::WANTAGENT, "Wrong argument type. Object expected."); #ifdef ENABLE_ERRCODE - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "Wrong argument type. Agent must be a WantAgent."); return CreateJsUndefined(env); #else - errCode = ERR_NOT_OK; - return RetErrMsg(env, lastParam, errCode); + return RetErrMsg(env, lastParam, ERR_NOT_OK); #endif } @@ -528,12 +527,10 @@ napi_value JsWantAgent::OnGetBundleName(napi_env env, napi_callback_info info) if (pWantAgent == nullptr) { TAG_LOGE(AAFwkTag::WANTAGENT, "Parse pWantAgent failed"); #ifdef ENABLE_ERRCODE - errCode = ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER; - AbilityRuntimeErrorUtil::Throw(env, errCode); + ThrowInvalidParamError(env, "Parse pWantAgent failed. Agent must be a WantAgent."); return CreateJsUndefined(env); #else - errCode = ERR_NOT_OK; - return RetErrMsg(env, lastParam, errCode); + return RetErrMsg(env, lastParam, ERR_NOT_OK); #endif } @@ -566,13 +563,11 @@ napi_value JsWantAgent::OnGetUid(napi_env env, napi_callback_info info) size_t argc = ARGS_MAX_COUNT; napi_value argv[ARGS_MAX_COUNT] = {nullptr}; napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); - int32_t errCode = BUSINESS_ERROR_CODE_OK; WantAgent* pWantAgent = nullptr; if (argc > ARGC_TWO || argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::WANTAGENT, "Not enough params"); #ifdef ENABLE_ERRCODE - errCode = ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER; - AbilityRuntimeErrorUtil::Throw(env, errCode); + ThrowTooFewParametersError(env); #endif return CreateJsUndefined(env); } @@ -581,12 +576,10 @@ napi_value JsWantAgent::OnGetUid(napi_env env, napi_callback_info info) if (!CheckTypeForNapiValue(env, argv[0], napi_object)) { TAG_LOGE(AAFwkTag::WANTAGENT, "Wrong argument type. Object expected."); #ifdef ENABLE_ERRCODE - errCode = ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER; - AbilityRuntimeErrorUtil::Throw(env, errCode); + ThrowInvalidParamError(env, "Wrong argument type. Agent must be a WantAgent."); return CreateJsUndefined(env); #else - errCode = ERR_NOT_OK; - return RetErrMsg(env, lastParam, errCode); + return RetErrMsg(env, lastParam, ERR_NOT_OK); #endif } @@ -594,11 +587,10 @@ napi_value JsWantAgent::OnGetUid(napi_env env, napi_callback_info info) if (pWantAgent == nullptr) { TAG_LOGE(AAFwkTag::WANTAGENT, "Parse pWantAgent error"); #ifdef ENABLE_ERRCODE - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "Parse pWantAgent error. Agent must be a WantAgent."); return CreateJsUndefined(env); #else - errCode = ERR_NOT_OK; - return RetErrMsg(env, lastParam, errCode); + return RetErrMsg(env, lastParam, ERR_NOT_OK); #endif } @@ -627,7 +619,6 @@ napi_value JsWantAgent::OnGetUid(napi_env env, napi_callback_info info) napi_value JsWantAgent::OnCancel(napi_env env, napi_callback_info info) { TAG_LOGD(AAFwkTag::WANTAGENT, "%{public}s is called", __FUNCTION__); - int32_t errCode = BUSINESS_ERROR_CODE_OK; WantAgent* pWantAgent = nullptr; size_t argc = ARGS_MAX_COUNT; napi_value argv[ARGS_MAX_COUNT] = {nullptr}; @@ -635,7 +626,7 @@ napi_value JsWantAgent::OnCancel(napi_env env, napi_callback_info info) if (argc > ARGC_TWO || argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::WANTAGENT, "Not enough params"); #ifdef ENABLE_ERRCODE - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowTooFewParametersError(env); #endif return CreateJsUndefined(env); } @@ -644,12 +635,10 @@ napi_value JsWantAgent::OnCancel(napi_env env, napi_callback_info info) if (!CheckTypeForNapiValue(env, argv[0], napi_object)) { TAG_LOGE(AAFwkTag::WANTAGENT, "Wrong argument type. Object expected."); #ifdef ENABLE_ERRCODE - errCode = ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER; - AbilityRuntimeErrorUtil::Throw(env, errCode); + ThrowInvalidParamError(env, "Wrong argument type. Agent must be a WantAgent."); return CreateJsUndefined(env); #else - errCode = ERR_NOT_OK; - return RetErrMsg(env, lastParam, errCode); + return RetErrMsg(env, lastParam, ERR_NOT_OK); #endif } @@ -657,11 +646,10 @@ napi_value JsWantAgent::OnCancel(napi_env env, napi_callback_info info) if (pWantAgent == nullptr) { TAG_LOGE(AAFwkTag::WANTAGENT, "Parse pWantAgent failed"); #ifdef ENABLE_ERRCODE - AbilityRuntimeErrorUtil::Throw(env, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_PARAMETER); + ThrowInvalidParamError(env, "Parse pWantAgent error. Agent must be a WantAgent."); return CreateJsUndefined(env); #else - errCode = ERR_NOT_OK; - return RetErrMsg(env, lastParam, errCode); + return RetErrMsg(env, lastParam, ERR_NOT_OK); #endif } @@ -696,6 +684,7 @@ napi_value JsWantAgent::OnTrigger(napi_env env, napi_callback_info info) napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); if (argc != ARGC_THREE) { TAG_LOGE(AAFwkTag::WANTAGENT, "Not enough params"); + ThrowTooFewParametersError(env); return CreateJsUndefined(env); } @@ -720,11 +709,13 @@ int32_t JsWantAgent::UnWrapTriggerInfoParam(napi_env env, napi_callback_info inf napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); if (argc != ARGC_THREE) { TAG_LOGE(AAFwkTag::WANTAGENT, "Not enough params"); + ThrowTooFewParametersError(env); return ERR_NOT_OK; } if (!CheckTypeForNapiValue(env, argv[ARGC_ZERO], napi_object)) { TAG_LOGE(AAFwkTag::WANTAGENT, "Wrong argument type. Object expected."); + ThrowInvalidParamError(env, "Wrong argument type. Agent must be a WantAgent."); return ERR_NOT_OK; } WantAgent* pWantAgent = nullptr; @@ -732,6 +723,7 @@ int32_t JsWantAgent::UnWrapTriggerInfoParam(napi_env env, napi_callback_info inf if (pWantAgent == nullptr) { TAG_LOGE(AAFwkTag::WANTAGENT, "Parse pWantAgent failed"); + ThrowInvalidParamError(env, "Parse pWantAgent failed. Agent must be a WantAgent."); return ERR_NOT_OK; } wantAgent = std::make_shared(*pWantAgent); @@ -739,6 +731,7 @@ int32_t JsWantAgent::UnWrapTriggerInfoParam(napi_env env, napi_callback_info inf int32_t ret = GetTriggerInfo(env, argv[ARGC_ONE], triggerInfo); if (ret != BUSINESS_ERROR_CODE_OK) { TAG_LOGE(AAFwkTag::WANTAGENT, "Get trigger info error"); + ThrowInvalidParamError(env, "Get trigger info error. TriggerInfo must be a TriggerInfo."); return ret; } @@ -1046,6 +1039,7 @@ napi_value JsWantAgent::OnGetWantAgent(napi_env env, napi_callback_info info) TAG_LOGD(AAFwkTag::WANTAGENT, "enter, argc = %{public}d", static_cast(argc)); if (argc > ARGC_TWO || argc < ARGC_ONE) { TAG_LOGE(AAFwkTag::WANTAGENT, "Not enough params"); + ThrowTooFewParametersError(env); return CreateJsUndefined(env); } @@ -1054,6 +1048,7 @@ napi_value JsWantAgent::OnGetWantAgent(napi_env env, napi_callback_info info) int32_t ret = GetWantAgentParam(env, info, *spParas); if (ret != 0) { TAG_LOGE(AAFwkTag::WANTAGENT, "Failed to get wantAgent parameter."); + ThrowInvalidParamError(env, "Failed to get wantAgent parameter. Agent must be a WantAgent."); return RetErrMsg(env, lastParam, ret); } diff --git a/frameworks/native/ability/BUILD.gn b/frameworks/native/ability/BUILD.gn index 92f9ee19d3..22ab306501 100644 --- a/frameworks/native/ability/BUILD.gn +++ b/frameworks/native/ability/BUILD.gn @@ -82,7 +82,10 @@ ohos_shared_library("ability_context_native") { "ipc:ipc_core", "napi:ace_napi", ] - public_external_deps = [ "ability_base:extractortool" ] + public_external_deps = [ + "ability_base:extractortool", + "background_task_mgr:bgtaskmgr_innerkits", + ] if (ability_runtime_graphics) { external_deps += [ "ace_engine:ace_uicontent", diff --git a/frameworks/native/ability/native/BUILD.gn b/frameworks/native/ability/native/BUILD.gn index 7746f8b38e..345983499c 100644 --- a/frameworks/native/ability/native/BUILD.gn +++ b/frameworks/native/ability/native/BUILD.gn @@ -119,7 +119,6 @@ config("abilitykit_utils_public_config") { ] if (ability_runtime_graphics) { - include_dirs += [] defines = [ "SUPPORT_GRAPHICS" ] } } @@ -147,13 +146,16 @@ ohos_shared_library("abilitykit_utils") { external_deps = [ "ability_base:configuration", "ability_base:want", + "bundle_framework:appexecfwk_base", "c_utils:utils", "eventhandler:libeventhandler", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_napi", "napi:ace_napi", "resource_management:global_resmgr", ] + public_external_deps = [ "bundle_framework:appexecfwk_core", "jsoncpp:jsoncpp", @@ -161,9 +163,9 @@ ohos_shared_library("abilitykit_utils") { ] if (ability_runtime_graphics) { - deps += [ "//third_party/icu/icu4c:shared_icuuc" ] external_deps += [ "ability_base:session_info", + "icu:shared_icuuc", "window_manager:libwm", ] public_external_deps += [ @@ -271,11 +273,14 @@ ohos_shared_library("abilitykit_native") { "resource_management:global_resmgr", "samgr:samgr_proxy", ] + public_external_deps = [ "accessibility:accessibility_common", + "bundle_framework:appexecfwk_core", "jsoncpp:jsoncpp", "libuv:uv", ] + defines = [] if (background_task_mgr_continuous_task_enable) { @@ -300,11 +305,11 @@ ohos_shared_library("abilitykit_native") { "${ability_runtime_native_path}/ability/native/ability_window.cpp", "${ability_runtime_native_path}/ability/native/page_ability_impl.cpp", ] - deps += [ "//third_party/icu/icu4c:shared_icuuc" ] external_deps += [ "ability_base:session_info", "form_fwk:form_manager", + "icu:shared_icuuc", "image_framework:image", "image_framework:image", "image_framework:image_native", @@ -382,11 +387,13 @@ ohos_shared_library("extensionkit_native") { "hitrace:hitrace_meter", "napi:ace_napi", ] + + public_deps = [ ":abilitykit_utils" ] + public_external_deps = [ "bundle_framework:appexecfwk_core", "jsoncpp:jsoncpp", ] - public_deps = [ ":abilitykit_utils" ] if (ability_runtime_graphics) { external_deps += [ "ability_base:session_info" ] @@ -528,9 +535,9 @@ ohos_shared_library("uiabilitykit_native") { ] if (ability_runtime_graphics) { - deps += [ "//third_party/icu/icu4c:shared_icuuc" ] external_deps += [ "ability_base:session_info", + "icu:shared_icuuc", "window_manager:libwm", "window_manager:libwsutils", "window_manager:windowstage_kit", @@ -635,6 +642,7 @@ ohos_shared_library("form_extension") { "form_fwk:form_manager", "form_fwk:formutil_napi", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_core", "ipc:ipc_napi", "napi:ace_napi", @@ -793,8 +801,8 @@ ohos_shared_library("data_ability_helper") { "${ability_runtime_native_path}/ability/native/data_ability_helper.cpp", ] - configs = [] - public_configs = [] + configs = [ ":ability_config" ] + public_configs = [ ":ability_public_config" ] deps = [ ":abilitykit_native" ] 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 87737ea943..8c4c18d0c3 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 @@ -76,6 +76,8 @@ constexpr const char* ERROR_MSG_NOT_SUPPORT_CROSS_APP_START = 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."; // follow ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST of appexecfwk_errors.h in bundle_framework constexpr int32_t ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST = 8521220; @@ -128,6 +130,7 @@ static std::unordered_map ERR_CODE_MAP = { { 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 }, }; static std::unordered_map INNER_TO_JS_ERROR_CODE_MAP { @@ -183,6 +186,7 @@ static std::unordered_map INNER_TO_JS_ERROR_CODE_MAP {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}, }; } 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 20ee35dec9..b1378f09ff 100644 --- a/frameworks/native/ability/native/ability_runtime/js_ui_ability.cpp +++ b/frameworks/native/ability/native/ability_runtime/js_ui_ability.cpp @@ -1086,6 +1086,7 @@ int32_t JsUIAbility::OnSaveState(int32_t reason, WantParams &wantParams) void JsUIAbility::OnConfigurationUpdated(const Configuration &configuration) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); UIAbility::OnConfigurationUpdated(configuration); TAG_LOGD(AAFwkTag::UIABILITY, "Called."); if (abilityContext_ == nullptr) { 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 de319784f2..eff917b506 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 @@ -46,6 +46,8 @@ constexpr const char *WANT_PARAMS_UPDATE_POPUP_HEIGHT = "ohos.ability.params.pop constexpr const char *WANT_PARAMS_UPDATE_POPUP_PLACEMENT = "ohos.ability.params.popupPlacement"; constexpr const char *CONFIG_POPUP_SIZE = "popupSize"; constexpr const char *CONFIG_POPUP_PLACEMENT = "placement"; +constexpr const char *WANT_PARAMS_FILL_CONTENT = "ohos.ability.params.fillContent"; +constexpr const char *ERROR_MSG_INVALID_PARAM = "Invalid input parameter, unable to parse json."; } // namespace JsFillRequestCallback::JsFillRequestCallback( @@ -113,7 +115,25 @@ napi_value JsFillRequestCallback::OnFillRequestFailed(napi_env env, NapiCallback napi_value JsFillRequestCallback::OnFillRequestCanceled(napi_env env, NapiCallbackInfo &info) { TAG_LOGD(AAFwkTag::AUTOFILL_EXT, "Called."); - SendResultCodeAndViewData(JsAutoFillExtensionUtil::AutoFillResultCode::CALLBACK_CANCEL, ""); + if (info.argc < ARGC_ONE) { + SendResultCodeAndViewData(JsAutoFillExtensionUtil::AutoFillResultCode::CALLBACK_CANCEL, ""); + return CreateJsUndefined(env); + } + if (!IsTypeForNapiValue(env, info.argv[INDEX_ZERO], napi_string)) { + TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Failed to parse fillContent JsonString!"); + ThrowError(env, static_cast(AbilityErrorCode::ERROR_CODE_INVALID_PARAM), ERROR_MSG_INVALID_PARAM); + SendResultCodeAndViewData( + JsAutoFillExtensionUtil::AutoFillResultCode::CALLBACK_FAILED_INVALID_PARAM, ""); + return CreateJsUndefined(env); + } + std::string jsonString = UnwrapStringFromJS(env, info.argv[INDEX_ZERO], ""); + if (jsonString.empty()) { + TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "JsonString is empty"); + SendResultCodeAndViewData( + JsAutoFillExtensionUtil::AutoFillResultCode::CALLBACK_FAILED_INVALID_PARAM, ""); + return CreateJsUndefined(env); + } + SendResultCodeAndViewData(JsAutoFillExtensionUtil::AutoFillResultCode::CALLBACK_CANCEL, jsonString); return CreateJsUndefined(env); } @@ -190,6 +210,10 @@ void JsFillRequestCallback::SendResultCodeAndViewData( want.SetParam(WANT_PARAMS_AUTO_FILL_CMD, WANT_PARAMS_AUTO_FILL_CMD_AUTOFILL); } + if (resultCode == JsAutoFillExtensionUtil::AutoFillResultCode::CALLBACK_CANCEL) { + want.SetParam(WANT_PARAMS_FILL_CONTENT, jsString); + } + auto ret = uiWindow_->TransferAbilityResult(resultCode, want); if (ret != Rosen::WMError::WM_OK) { TAG_LOGE(AAFwkTag::AUTOFILL_EXT, "Transfer ability result failed."); 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 96bf9e41e6..c377797192 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 @@ -46,6 +46,7 @@ namespace OHOS { namespace AbilityRuntime { namespace { bool g_jitEnabled = false; + AbilityRuntime::Runtime::DebugOption g_debugOption; } bool ChildProcessManager::signalRegistered_ = false; @@ -79,7 +80,12 @@ ChildProcessManagerErrorCode ChildProcessManager::StartChildProcessBySelfFork(co TAG_LOGE(AAFwkTag::PROCESSMGR, "Fork process failed"); return ChildProcessManagerErrorCode::ERR_FORK_FAILED; } + MakeProcessName(srcEntry); // set process name if (pid == 0) { + const char *processName = g_debugOption.processName.c_str(); + if (prctl(PR_SET_NAME, processName) < 0) { + TAG_LOGW(AAFwkTag::PROCESSMGR, "Set process name failed with %{public}d", errno); + } HandleChildProcessBySelfFork(srcEntry, bundleInfo); } return ChildProcessManagerErrorCode::ERR_OK; @@ -88,7 +94,8 @@ ChildProcessManagerErrorCode ChildProcessManager::StartChildProcessBySelfFork(co ChildProcessManagerErrorCode ChildProcessManager::StartChildProcessByAppSpawnFork( const std::string &srcEntry, pid_t &pid) { - TAG_LOGI(AAFwkTag::PROCESSMGR, "called."); + 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(); if (errorCode != ChildProcessManagerErrorCode::ERR_OK) { return errorCode; @@ -98,7 +105,8 @@ ChildProcessManagerErrorCode ChildProcessManager::StartChildProcessByAppSpawnFor TAG_LOGE(AAFwkTag::PROCESSMGR, "GetAppMgr failed."); return ChildProcessManagerErrorCode::ERR_GET_APP_MGR_FAILED; } - auto ret = appMgr->StartChildProcess(srcEntry, pid); + auto ret = appMgr->StartChildProcess(srcEntry, pid, childProcessCount_, g_debugOption.isStartWithDebug); + childProcessCount_++; TAG_LOGD(AAFwkTag::PROCESSMGR, "AppMgr StartChildProcess ret:%{public}d", ret); if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::PROCESSMGR, "AppMgr StartChildProcess failed, ret:%{public}d", ret); @@ -164,6 +172,10 @@ void ChildProcessManager::HandleChildProcessBySelfFork(const std::string &srcEnt TAG_LOGE(AAFwkTag::PROCESSMGR, "Failed to create child process runtime"); return; } + TAG_LOGD(AAFwkTag::PROCESSMGR, "StartDebugMode, isStartWithDebug is %{public}d, processName is %{public}s, " + "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); TAG_LOGD(AAFwkTag::PROCESSMGR, "HandleChildProcessBySelfFork end."); exit(0); @@ -291,5 +303,33 @@ void ChildProcessManager::SetForkProcessJITEnabled(bool jitEnabled) { g_jitEnabled = jitEnabled; } + +void ChildProcessManager::SetForkProcessDebugOption(const std::string bundleName, const bool isStartWithDebug, + const bool isDebugApp, const bool isStartWithNative) +{ + g_debugOption.bundleName = bundleName; + g_debugOption.isStartWithDebug = isStartWithDebug; + g_debugOption.isDebugApp = isDebugApp; + g_debugOption.isStartWithNative = isStartWithNative; +} + +void ChildProcessManager::MakeProcessName(const std::string &srcEntry) +{ + std::string processName = g_debugOption.bundleName; + if (srcEntry.empty()) { + TAG_LOGE(AAFwkTag::PROCESSMGR, "srcEntry empty."); + } else { + TAG_LOGW(AAFwkTag::PROCESSMGR, "srcEntry is not empty."); + std::string filename = std::filesystem::path(srcEntry).stem(); + if (!filename.empty()) { + processName.append(":"); + processName.append(filename); + } + } + processName.append(std::to_string(childProcessCount_)); + childProcessCount_++; + TAG_LOGD(AAFwkTag::PROCESSMGR, "SetForkProcessDebugOption processName is %{public}s", processName.c_str()); + g_debugOption.processName = processName; +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/frameworks/native/ability/native/configuration_utils.cpp b/frameworks/native/ability/native/configuration_utils.cpp index ad3ec6ece9..ec2ecbe14f 100644 --- a/frameworks/native/ability/native/configuration_utils.cpp +++ b/frameworks/native/ability/native/configuration_utils.cpp @@ -18,6 +18,7 @@ #include "configuration_convertor.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" +#include "hitrace_meter.h" #ifdef SUPPORT_GRAPHICS #include "window.h" #endif @@ -29,6 +30,7 @@ using namespace AppExecFwk; void ConfigurationUtils::UpdateGlobalConfig(const Configuration &configuration, std::shared_ptr resourceManager) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITY, "Enter"); if (resourceManager == nullptr) { TAG_LOGE(AAFwkTag::ABILITY, "Resource manager is invalid."); @@ -73,6 +75,7 @@ void ConfigurationUtils::UpdateGlobalConfig(const Configuration &configuration, TAG_LOGD(AAFwkTag::ABILITY, "Update config, hasPointerDevice: %{public}d", resConfig->GetInputDevice()); } + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "resourceManager->UpdateResConfig"); Global::Resource::RState ret = resourceManager->UpdateResConfig(*resConfig); if (ret != Global::Resource::RState::SUCCESS) { TAG_LOGE(AAFwkTag::ABILITY, "Update resource config failed with %{public}d.", static_cast(ret)); diff --git a/frameworks/native/ability/native/js_service_extension_context.cpp b/frameworks/native/ability/native/js_service_extension_context.cpp index 5265d67ec9..42cf3daa7e 100644 --- a/frameworks/native/ability/native/js_service_extension_context.cpp +++ b/frameworks/native/ability/native/js_service_extension_context.cpp @@ -221,7 +221,6 @@ private: AAFwk::Want want; AAFwk::StartOptions startOptions; if (!CheckStartAbilityInputParam(env, info, want, startOptions, unwrapArgc)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); return CreateJsUndefined(env); } @@ -272,22 +271,26 @@ private: { if (info.argc != ARGC_TWO) { TAG_LOGE(AAFwkTag::SERVICE_EXT, "wrong arguments num"); + ThrowTooFewParametersError(env); return false; } if (!CheckTypeForNapiValue(env, info.argv[ARGC_ZERO], napi_string)) { TAG_LOGE(AAFwkTag::SERVICE_EXT, "link must be string"); + ThrowInvalidParamError(env, "Parse param link failed, must be a string"); return false; } if (!ConvertFromJsValue(env, info.argv[ARGC_ZERO], linkValue) || !CheckUrl(linkValue)) { TAG_LOGE(AAFwkTag::SERVICE_EXT, "link parameter invalid"); + ThrowInvalidParamError(env, "link parameter invalid"); return false; } if (CheckTypeForNapiValue(env, info.argv[INDEX_ONE], napi_object)) { TAG_LOGD(AAFwkTag::SERVICE_EXT, "OpenLinkOptions is used."); if (!AppExecFwk::UnwrapOpenLinkOptions(env, info.argv[INDEX_ONE], openLinkOptions, want)) { - TAG_LOGE(AAFwkTag::SERVICE_EXT, "openLinkOptions parse failed"); + TAG_LOGE(AAFwkTag::SERVICE_EXT, "OpenLinkOptions parse failed"); + ThrowInvalidParamError(env, "Parse param options failed, must be a OpenLinkOptions"); return false; } } @@ -307,7 +310,6 @@ private: if (!ParseOpenLinkParams(env, info, linkValue, openLinkOptions, want)) { TAG_LOGE(AAFwkTag::SERVICE_EXT, "parse openLink arguments failed"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); return CreateJsUndefined(env); } @@ -361,7 +363,6 @@ private: AAFwk::Want want; AAFwk::StartOptions startOptions; if (!CheckStartAbilityInputParam(env, info, want, startOptions, unwrapArgc)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); return CreateJsUndefined(env); } @@ -396,11 +397,13 @@ private: AAFwk::Want& want, AAFwk::StartOptions& startOptions, size_t& unwrapArgc) const { if (info.argc < ARGC_ONE) { + ThrowTooFewParametersError(env); return false; } unwrapArgc = ARGC_ZERO; // Check input want if (!AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want)) { + ThrowInvalidParamError(env, "Parse param want failed, must be a Want"); return false; } ++unwrapArgc; @@ -423,7 +426,6 @@ private: AAFwk::Want want; int32_t accountId = DEFAULT_INVAL_VALUE; if (!CheckStartAbilityByCallInputParam(env, info, want, accountId)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); return CreateJsUndefined(env); } @@ -463,6 +465,7 @@ private: napi_env env, NapiCallbackInfo& info, AAFwk::Want& want, int32_t& accountId) { if (!AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want)) { + ThrowInvalidParamError(env, "Parse param want failed, must be a Want"); return false; } @@ -470,10 +473,12 @@ private: if (CheckTypeForNapiValue(env, info.argv[INDEX_ONE], napi_number)) { if (!ConvertFromJsValue(env, info.argv[1], accountId)) { TAG_LOGE(AAFwkTag::SERVICE_EXT, "check input param accountId failed"); + ThrowInvalidParamError(env, "Parse param accountId failed, must be a number"); return false; } } else { TAG_LOGE(AAFwkTag::SERVICE_EXT, "input parameter type invalid"); + ThrowInvalidParamError(env, "Parse param accountId failed, must be a number"); return false; } } @@ -574,7 +579,6 @@ private: AAFwk::Want want; int32_t accountId = 0; if (!CheckStartAbilityWithAccountInputParam(env, info, want, accountId, unwrapArgc)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); return CreateJsUndefined(env); } @@ -612,15 +616,18 @@ private: AAFwk::Want& want, int32_t& accountId, size_t& unwrapArgc) const { if (info.argc < ARGC_TWO) { + ThrowTooFewParametersError(env); return false; } unwrapArgc = ARGC_ZERO; // Check input want if (!AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want)) { + ThrowInvalidParamError(env, "Parse param want failed, must be a Want"); return false; } ++unwrapArgc; if (!AppExecFwk::UnwrapInt32FromJS2(env, info.argv[INDEX_ONE], accountId)) { + ThrowInvalidParamError(env, "Parse param accountId failed, must be a number"); return false; } ++unwrapArgc; @@ -667,12 +674,14 @@ private: // Unwrap want and connection AAFwk::Want want; sptr connection = new JSServiceExtensionConnection(env); - if (!AppExecFwk::UnwrapWant(env, info.argv[0], want) || - !CheckConnectionParam(env, info.argv[1], connection, want)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + if (!AppExecFwk::UnwrapWant(env, info.argv[0], want)) { + ThrowInvalidParamError(env, "Parse param want failed, must be a Want"); + return CreateJsUndefined(env); + } + if (!CheckConnectionParam(env, info.argv[1], connection, want)) { + ThrowInvalidParamError(env, "Parse param options failed, must be a ConnectOptions"); return CreateJsUndefined(env); } - int64_t connectId = connection->GetConnectionId(); auto innerErrorCode = std::make_shared(ERR_OK); auto execute = GetConnectAbilityExecFunc(want, connection, connectId, innerErrorCode); @@ -710,10 +719,12 @@ private: AAFwk::Want want; int32_t accountId = 0; sptr connection = new JSServiceExtensionConnection(env); - if (!AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want) || - !AppExecFwk::UnwrapInt32FromJS2(env, info.argv[INDEX_ONE], accountId) || - !CheckConnectionParam(env, info.argv[INDEX_TWO], connection, want)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + size_t unwrapArgc = 0; + if (!CheckStartAbilityWithAccountInputParam(env, info, want, accountId, unwrapArgc)) { + return CreateJsUndefined(env); + } + if (!CheckConnectionParam(env, info.argv[INDEX_TWO], connection, want)) { + ThrowInvalidParamError(env, "Parse param options failed, must be a ConnectOptions"); return CreateJsUndefined(env); } int64_t connectId = connection->GetConnectionId(); @@ -778,7 +789,7 @@ private: } int64_t connectId = -1; if (!AppExecFwk::UnwrapInt64FromJS2(env, info.argv[INDEX_ZERO], connectId)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param connection failed, must be a number"); return CreateJsUndefined(env); } @@ -845,7 +856,7 @@ private: } AAFwk::Want want; if (!AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param want failed, must be a Want"); return CreateJsUndefined(env); } @@ -882,9 +893,8 @@ private: } AAFwk::Want want; int32_t accountId = -1; - if (!AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want) || - !AppExecFwk::UnwrapInt32FromJS2(env, info.argv[INDEX_ONE], accountId)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + size_t unwrapArgc = 0; + if (!CheckStartAbilityWithAccountInputParam(env, info, want, accountId, unwrapArgc)) { return CreateJsUndefined(env); } @@ -921,7 +931,7 @@ private: } AAFwk::Want want; if (!AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param want failed, must be a Want"); return CreateJsUndefined(env); } @@ -958,10 +968,8 @@ private: } AAFwk::Want want; int32_t accountId = -1; - if (!AppExecFwk::UnwrapWant(env, info.argv[INDEX_ZERO], want) || - !AppExecFwk::UnwrapInt32FromJS2(env, info.argv[INDEX_ONE], accountId)) { - TAG_LOGD(AAFwkTag::SERVICE_EXT, "Failed, input parameter type invalid"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + size_t unwrapArgc = 0; + if (!CheckStartAbilityWithAccountInputParam(env, info, want, accountId, unwrapArgc)) { return CreateJsUndefined(env); } @@ -1000,7 +1008,7 @@ private: AAFwk::Want want; if (!AppExecFwk::UnwrapWant(env, info.argv[0], want)) { TAG_LOGE(AAFwkTag::SERVICE_EXT, "Failed to parse want!"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parse param want failed, must be a Want"); return CreateJsUndefined(env); } 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 120f24263a..ab83b5a417 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 @@ -141,7 +141,6 @@ std::shared_ptr JsUIExtensionBase::Init(const std::shared_ptrmoduleName); moduleName.append("::").append(abilityInfo_->name); HandleScope handleScope(jsRuntime_); - napi_env env = jsRuntime_.GetNapiEnv(); jsObj_ = jsRuntime_.LoadModule( moduleName, srcPath, abilityInfo_->hapPath, abilityInfo_->compileMode == CompileMode::ES_MODULE); @@ -150,25 +149,26 @@ std::shared_ptr JsUIExtensionBase::Init(const std::shared_ptrGetNapiValue(); - if (!CheckTypeForNapiValue(env, obj, napi_object)) { - TAG_LOGE(AAFwkTag::UI_EXT, "obj is not object"); - return nullptr; - } - - BindContext(env, obj); + BindContext(); return JsExtensionCommon::Create(jsRuntime_, static_cast(*jsObj_), shellContextRef_); } -void JsUIExtensionBase::BindContext(napi_env env, napi_value obj) +void JsUIExtensionBase::BindContext() { - if (context_ == nullptr) { - TAG_LOGE(AAFwkTag::UI_EXT, "context_ is nullptr"); + HandleScope handleScope(jsRuntime_); + if (jsObj_ == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "jsObj_ is nullptr"); return; } - if (obj == nullptr) { - TAG_LOGE(AAFwkTag::UI_EXT, "obj is nullptr"); + napi_env env = jsRuntime_.GetNapiEnv(); + napi_value obj = jsObj_->GetNapiValue(); + if (!CheckTypeForNapiValue(env, obj, napi_object)) { + TAG_LOGE(AAFwkTag::UI_EXT, "obj is not object"); + return; + } + if (context_ == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "context_ is nullptr"); return; } TAG_LOGD(AAFwkTag::UI_EXT, "BindContext CreateJsUIExtensionContext."); 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 13bd6a1d1f..fe5ccc8acf 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 @@ -238,7 +238,7 @@ napi_value JsUIExtensionContentSession::OnStartAbility(napi_env env, NapiCallbac size_t unwrapArgc = 1; if (!OHOS::AppExecFwk::UnwrapWant(env, info.argv[0], want)) { TAG_LOGE(AAFwkTag::UI_EXT, "Failed to parse want!"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Failed to parse want! Want must be a Want."); return CreateJsUndefined(env); } if (!want.HasParameter(Want::PARAM_BACK_TO_OTHER_MISSION_STACK)) { @@ -331,7 +331,7 @@ napi_value JsUIExtensionContentSession::OnStartAbilityAsCaller(napi_env env, Nap AAFwk::Want want; bool unWrapWantFlag = OHOS::AppExecFwk::UnwrapWant(env, info.argv[0], want); if (!unWrapWantFlag) { - ThrowTooFewParametersError(env); + ThrowInvalidParamError(env, "Parameter error: Parse want failed! Want must be a Want."); } decltype(info.argc) unwrapArgc = 1; TAG_LOGI(AAFwkTag::UI_EXT, "StartAbilityAsCaller, ability:%{public}s.", want.GetElement().GetAbilityName().c_str()); @@ -340,7 +340,7 @@ napi_value JsUIExtensionContentSession::OnStartAbilityAsCaller(napi_env env, Nap TAG_LOGD(AAFwkTag::UI_EXT, "OnStartAbilityAsCaller start options is used."); bool unWrapStartOptionsFlag = AppExecFwk::UnwrapStartOptions(env, info.argv[INDEX_ONE], startOptions); if (!unWrapStartOptionsFlag) { - ThrowTooFewParametersError(env); + ThrowInvalidParamError(env, "Parameter error: Parse startOptions failed! Options must be a StartOption."); } unwrapArgc++; } @@ -380,7 +380,10 @@ NapiAsyncTask::ExecuteCallback JsUIExtensionContentSession::StartAbilityExecuteC AAFwk::StartOptions startOptions; if (info.argc > ARGC_ONE && CheckTypeForNapiValue(env, info.argv[1], napi_object)) { TAG_LOGD(AAFwkTag::UI_EXT, "OnStartAbility start options is used."); - AppExecFwk::UnwrapStartOptions(env, info.argv[1], startOptions); + bool unWrapStartOptionsFlag = AppExecFwk::UnwrapStartOptions(env, info.argv[1], startOptions); + if (!unWrapStartOptionsFlag) { + ThrowInvalidParamError(env, "Parameter error: Parse startOptions failed! Options must be a StartOption."); + } unwrapArgc++; } @@ -425,7 +428,7 @@ napi_value JsUIExtensionContentSession::OnStartAbilityForResult(napi_env env, Na AAFwk::Want want; if (!AppExecFwk::UnwrapWant(env, info.argv[0], want)) { TAG_LOGE(AAFwkTag::UI_EXT, "Error to parse want!"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Failed to parse want! Want must be a Want."); return CreateJsUndefined(env); } if (!want.HasParameter(Want::PARAM_BACK_TO_OTHER_MISSION_STACK)) { @@ -435,7 +438,10 @@ napi_value JsUIExtensionContentSession::OnStartAbilityForResult(napi_env env, Na AAFwk::StartOptions startOptions; if (info.argc > ARGC_ONE && CheckTypeForNapiValue(env, info.argv[1], napi_object)) { TAG_LOGD(AAFwkTag::UI_EXT, "OnStartAbilityForResult start options is used."); - AppExecFwk::UnwrapStartOptions(env, info.argv[1], startOptions); + bool unWrapStartOptionsFlag = AppExecFwk::UnwrapStartOptions(env, info.argv[1], startOptions); + if (!unWrapStartOptionsFlag) { + ThrowInvalidParamError(env, "Parameter error: Parse startOptions failed! Options must be a StartOption."); + } unwrapArgc++; } @@ -546,15 +552,15 @@ napi_value JsUIExtensionContentSession::OnTerminateSelfWithResult(napi_env env, { TAG_LOGI(AAFwkTag::UI_EXT, "called"); if (info.argc < ARGC_ONE) { - TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + TAG_LOGE(AAFwkTag::UI_EXT, "Not enough params."); + ThrowTooFewParametersError(env); return CreateJsUndefined(env); } int resultCode = 0; AAFwk::Want want; if (!AppExecFwk::UnWrapAbilityResult(env, info.argv[INDEX_ZERO], resultCode, want)) { TAG_LOGE(AAFwkTag::UI_EXT, "OnTerminateSelfWithResult Failed to parse ability result!"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Failed to parse parameter! Parameter must be a AbilityResult."); return CreateJsUndefined(env); } @@ -591,14 +597,14 @@ napi_value JsUIExtensionContentSession::OnSendData(napi_env env, NapiCallbackInf TAG_LOGD(AAFwkTag::UI_EXT, "called"); CHECK_IS_SYSTEM_APP; if (info.argc < ARGC_ONE) { - TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + TAG_LOGE(AAFwkTag::UI_EXT, "Not enough params."); + ThrowTooFewParametersError(env); return CreateJsUndefined(env); } AAFwk::WantParams params; if (!AppExecFwk::UnwrapWantParams(env, info.argv[INDEX_ZERO], params)) { TAG_LOGE(AAFwkTag::UI_EXT, "OnSendData Failed to parse param!"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "OnSendData Failed to parse param! Data must be a Record."); return CreateJsUndefined(env); } @@ -622,9 +628,15 @@ napi_value JsUIExtensionContentSession::OnSetReceiveDataCallback(napi_env env, N { TAG_LOGD(AAFwkTag::UI_EXT, "called"); CHECK_IS_SYSTEM_APP; - if (info.argc < ARGC_ONE || !CheckTypeForNapiValue(env, info.argv[INDEX_ZERO], napi_function)) { + if (info.argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::UI_EXT, "Not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + + if (!CheckTypeForNapiValue(env, info.argv[INDEX_ZERO], napi_function)) { TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Callback must be a function."); return CreateJsUndefined(env); } @@ -664,9 +676,15 @@ napi_value JsUIExtensionContentSession::OnSetReceiveDataForResultCallback(napi_e { TAG_LOGD(AAFwkTag::UI_EXT, "called"); CHECK_IS_SYSTEM_APP; - if (info.argc < ARGC_ONE || !CheckTypeForNapiValue(env, info.argv[INDEX_ZERO], napi_function)) { + if (info.argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::UI_EXT, "Not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + + if (!CheckTypeForNapiValue(env, info.argv[INDEX_ZERO], napi_function)) { TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Callback must be a function."); return CreateJsUndefined(env); } @@ -710,14 +728,25 @@ napi_value JsUIExtensionContentSession::OnLoadContent(napi_env env, NapiCallback { TAG_LOGD(AAFwkTag::UI_EXT, "called"); std::string contextPath; - if (info.argc < ARGC_ONE || !ConvertFromJsValue(env, info.argv[INDEX_ZERO], contextPath)) { + if (info.argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::UI_EXT, "Not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + + if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], contextPath)) { TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Path must be a string."); return CreateJsUndefined(env); } TAG_LOGD(AAFwkTag::UI_EXT, "contextPath: %{public}s", contextPath.c_str()); napi_value storage = nullptr; - if (info.argc > ARGC_ONE && CheckTypeForNapiValue(env, info.argv[INDEX_ONE], napi_object)) { + if (info.argc > ARGC_ONE) { + if (!CheckTypeForNapiValue(env, info.argv[INDEX_ONE], napi_object)) { + TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); + ThrowInvalidParamError(env, "Parameter error: Storage must be a LocalStorage."); + return CreateJsUndefined(env); + } storage = info.argv[INDEX_ONE]; } if (uiWindow_ == nullptr || sessionInfo_ == nullptr) { @@ -747,9 +776,15 @@ napi_value JsUIExtensionContentSession::OnSetWindowBackgroundColor(napi_env env, TAG_LOGD(AAFwkTag::UI_EXT, "called"); CHECK_IS_SYSTEM_APP; std::string color; - if (info.argc < ARGC_ONE || !ConvertFromJsValue(env, info.argv[INDEX_ZERO], color)) { + if (info.argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::UI_EXT, "Not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + + if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], color)) { TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Parse color failed! Color must be a string."); return CreateJsUndefined(env); } @@ -772,9 +807,15 @@ napi_value JsUIExtensionContentSession::OnSetWindowPrivacyMode(napi_env env, Nap { TAG_LOGD(AAFwkTag::UI_EXT, "called"); bool isPrivacyMode = false; - if (info.argc < ARGC_ONE || !ConvertFromJsValue(env, info.argv[INDEX_ZERO], isPrivacyMode)) { + if (info.argc < ARGC_ONE) { + TAG_LOGE(AAFwkTag::UI_EXT, "Not enough params."); + ThrowTooFewParametersError(env); + return CreateJsUndefined(env); + } + + if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], isPrivacyMode)) { TAG_LOGE(AAFwkTag::UI_EXT, "invalid param"); - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + ThrowInvalidParamError(env, "Parameter error: Failed to parse isPrivacyMode! IsPrivacyMode must be a boolean."); return CreateJsUndefined(env); } auto selfToken = IPCSkeleton::GetSelfTokenID(); @@ -808,16 +849,13 @@ napi_value JsUIExtensionContentSession::OnSetWindowPrivacyMode(napi_env env, Nap napi_value JsUIExtensionContentSession::OnStartAbilityByType(napi_env env, NapiCallbackInfo& info) { TAG_LOGI(AAFwkTag::UI_EXT, "called"); - if (info.argc < ARGC_THREE) { - ThrowTooFewParametersError(env); - return CreateJsUndefined(env); - } - + std::string type; AAFwk::WantParams wantParam; - if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], type) || - !AppExecFwk::UnwrapWantParams(env, info.argv[INDEX_ONE], wantParam)) { - ThrowError(env, AbilityErrorCode::ERROR_CODE_INVALID_PARAM); + + bool checkResult = CheckStartAbilityByTypeParam(env, info, type, wantParam); + if (!checkResult) { + TAG_LOGI(AAFwkTag::UI_EXT, "check startAbilityByCall param failed."); return CreateJsUndefined(env); } @@ -860,6 +898,32 @@ napi_value JsUIExtensionContentSession::OnStartAbilityByType(napi_env env, NapiC return result; } +bool JsUIExtensionContentSession::CheckStartAbilityByTypeParam(napi_env env, + NapiCallbackInfo& info, std::string type, AAFwk::WantParams wantParam) +{ + TAG_LOGI(AAFwkTag::UI_EXT, "start"); + + if (info.argc < ARGC_THREE) { + TAG_LOGW(AAFwkTag::UI_EXT, "Not enough params."); + ThrowTooFewParametersError(env); + return false; + } + + if (!ConvertFromJsValue(env, info.argv[INDEX_ZERO], type)) { + TAG_LOGW(AAFwkTag::UI_EXT, "Failed to parse type!"); + ThrowInvalidParamError(env, "Parameter error: Failed to parse type! Type must be a string."); + return false; + } + + if (!AppExecFwk::UnwrapWantParams(env, info.argv[INDEX_ONE], wantParam)) { + TAG_LOGW(AAFwkTag::UI_EXT, "Failed to parse wantParam"); + ThrowInvalidParamError(env, "Parameter error: Failed to parse wantParam, must be a Record."); + return false; + } + + return true; +} + napi_value JsUIExtensionContentSession::CreateJsUIExtensionContentSession(napi_env env, sptr sessionInfo, sptr uiWindow, std::weak_ptr context, diff --git a/frameworks/native/appkit/BUILD.gn b/frameworks/native/appkit/BUILD.gn index 6e9e9cd1db..fe7f696ec0 100644 --- a/frameworks/native/appkit/BUILD.gn +++ b/frameworks/native/appkit/BUILD.gn @@ -64,8 +64,6 @@ config("appkit_public_config") { ] if (ability_runtime_graphics) { - include_dirs += [] - defines = [ "SUPPORT_GRAPHICS", "SUPPORT_APP_PREFERRED_LANGUAGE", @@ -195,7 +193,6 @@ ohos_shared_library("appkit_native") { public_external_deps = [ "ability_base:configuration" ] if (ability_runtime_graphics) { - deps += [] external_deps += [ "ace_engine:ace_forward_compatibility", "graphic_2d:librender_service_client", @@ -272,6 +269,7 @@ ohos_shared_library("app_context") { "c_utils:utils", "common_event_service:cesfwk_innerkits", "hilog:libhilog", + "hitrace:hitrace_meter", "init:libbegetutil", "ipc:ipc_core", "napi:ace_napi", @@ -281,7 +279,6 @@ ohos_shared_library("app_context") { public_external_deps = [ "ability_base:configuration" ] if (ability_runtime_graphics) { - deps += [] external_deps += [ "i18n:intl_util", "icu:shared_icuuc", @@ -333,6 +330,7 @@ ohos_shared_library("app_context_utils") { "bundle_framework:appexecfwk_core", "c_utils:utils", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_core", "napi:ace_napi", "resource_management:global_resmgr", @@ -340,7 +338,6 @@ ohos_shared_library("app_context_utils") { ] public_external_deps = [ "ability_base:configuration" ] if (ability_runtime_graphics) { - deps += [] external_deps += [ "i18n:intl_util", "icu:shared_icuuc", @@ -405,7 +402,6 @@ ohos_shared_library("appkit_delegator") { ] public_external_deps = [ "ability_base:configuration" ] if (ability_runtime_graphics) { - deps += [] external_deps += [ "icu:shared_icuuc" ] } @@ -452,7 +448,6 @@ ohos_shared_library("appkit_manager_helper") { ] if (ability_runtime_graphics) { - deps += [] external_deps += [ "icu:shared_icuuc" ] } 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 58f8d635ab..732169263b 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 @@ -185,6 +185,7 @@ ErrCode BundleMgrHelper::GetSandboxHapModuleInfo(const AbilityInfo &abilityInfo, sptr BundleMgrHelper::Connect() { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::BUNDLEMGRHELPER, "Called."); std::lock_guard lock(mutex_); if (bundleMgr_ == 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 29ddf4cc01..099fa9b80d 100644 --- a/frameworks/native/appkit/ability_runtime/app/js_ability_stage.cpp +++ b/frameworks/native/appkit/ability_runtime/app/js_ability_stage.cpp @@ -48,6 +48,8 @@ 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"; napi_value AttachAbilityStageContext(napi_env env, void *value, void *) { @@ -569,8 +571,16 @@ void JsAbilityStage::SetOptionalParameters( jsStartupTask.SetIsExcludeFromAutoStart(false); } - // always true - jsStartupTask.SetCallCreateOnMainThread(true); + 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) { + jsStartupTask.SetCallCreateOnMainThread(false); + } else { + TAG_LOGW(AAFwkTag::APPKIT, "RunOnThread configuration is invalid."); + } + } if (module.contains(WAIT_ON_MAIN_THREAD) && module[WAIT_ON_MAIN_THREAD].is_boolean()) { jsStartupTask.SetWaitOnMainThread(module.at(WAIT_ON_MAIN_THREAD).get()); diff --git a/frameworks/native/appkit/ability_runtime/context/application_context.cpp b/frameworks/native/appkit/ability_runtime/context/application_context.cpp index 699f96ed70..29980816e1 100644 --- a/frameworks/native/appkit/ability_runtime/context/application_context.cpp +++ b/frameworks/native/appkit/ability_runtime/context/application_context.cpp @@ -21,6 +21,7 @@ #include "configuration_convertor.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" +#include "hitrace_meter.h" #include "running_process_info.h" namespace OHOS { diff --git a/frameworks/native/appkit/ability_runtime/context/context_impl.cpp b/frameworks/native/appkit/ability_runtime/context/context_impl.cpp index 4d0b97849d..269fc95aa6 100644 --- a/frameworks/native/appkit/ability_runtime/context/context_impl.cpp +++ b/frameworks/native/appkit/ability_runtime/context/context_impl.cpp @@ -30,6 +30,7 @@ #include "file_ex.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" +#include "hitrace_meter.h" #include "ipc_singleton.h" #include "js_runtime_utils.h" #ifdef SUPPORT_GRAPHICS @@ -366,6 +367,7 @@ std::shared_ptr ContextImpl::CreateModuleContext(const std::string &mod std::shared_ptr ContextImpl::CreateModuleContext(const std::string &bundleName, const std::string &moduleName) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPKIT, "begin."); if (bundleName.empty() || moduleName.empty()) { return nullptr; @@ -608,6 +610,7 @@ std::string ContextImpl::GetBaseDir() const int ContextImpl::GetCurrentAccountId() const { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int userId = 0; auto instance = DelayedSingleton::GetInstance(); if (instance == nullptr) { @@ -620,6 +623,7 @@ int ContextImpl::GetCurrentAccountId() const int ContextImpl::GetCurrentActiveAccountId() const { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::vector accountIds; auto instance = DelayedSingleton::GetInstance(); if (instance == nullptr) { @@ -647,6 +651,7 @@ int ContextImpl::GetCurrentActiveAccountId() const std::shared_ptr ContextImpl::CreateBundleContext(const std::string &bundleName) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPKIT, "begin."); if (parentContext_ != nullptr) { return parentContext_->CreateBundleContext(bundleName); @@ -670,6 +675,7 @@ std::shared_ptr ContextImpl::CreateBundleContext(const std::string &bun } TAG_LOGD(AAFwkTag::APPKIT, "length: %{public}zu, bundleName: %{public}s", (size_t)bundleName.length(), bundleName.c_str()); + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "bundleMgr_->GetBundleInfo"); bundleMgr_->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, accountId); if (bundleInfo.name.empty() || bundleInfo.applicationInfo.name.empty()) { @@ -690,6 +696,7 @@ std::shared_ptr ContextImpl::CreateBundleContext(const std::string &bun void ContextImpl::InitResourceManager(const AppExecFwk::BundleInfo &bundleInfo, const std::shared_ptr &appContext, bool currentBundle, const std::string& moduleName) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPKIT, "begin, bundleName:%{public}s, moduleName:%{public}s", bundleInfo.name.c_str(), moduleName.c_str()); @@ -722,6 +729,7 @@ void ContextImpl::InitResourceManager(const AppExecFwk::BundleInfo &bundleInfo, std::shared_ptr ContextImpl::InitOthersResourceManagerInner( const AppExecFwk::BundleInfo &bundleInfo, bool currentBundle, const std::string& moduleName) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::unique_ptr resConfig(Global::Resource::CreateResConfig()); std::string hapPath; std::vector overlayPaths; @@ -741,6 +749,7 @@ std::shared_ptr ContextImpl::InitOthersResour std::shared_ptr ContextImpl::InitResourceManagerInner( const AppExecFwk::BundleInfo &bundleInfo, bool currentBundle, const std::string& moduleName) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::shared_ptr resourceManager = InitOthersResourceManagerInner( bundleInfo, currentBundle, moduleName); if (resourceManager == nullptr) { @@ -753,71 +762,75 @@ std::shared_ptr ContextImpl::InitResourceMana std::regex outer_pattern(ABS_CODE_PATH); std::regex hsp_pattern(std::string(ABS_CODE_PATH) + FILE_SEPARATOR + bundleInfo.name + PATTERN_VERSION); std::string hsp_sandbox = std::string(LOCAL_CODE_PATH) + FILE_SEPARATOR + bundleInfo.name + FILE_SEPARATOR; - for (auto hapModuleInfo : bundleInfo.hapModuleInfos) { - TAG_LOGD(AAFwkTag::APPKIT, "hapModuleInfo abilityInfo size: %{public}zu", - hapModuleInfo.abilityInfos.size()); - if (!moduleName.empty() && hapModuleInfo.moduleName != moduleName) { - continue; - } - std::string loadPath = hapModuleInfo.hapPath.empty() ? hapModuleInfo.resourcePath : hapModuleInfo.hapPath; - if (loadPath.empty()) { - TAG_LOGD(AAFwkTag::APPKIT, "loadPath is empty"); - continue; - } - if (currentBundle) { - loadPath = std::regex_replace(loadPath, inner_pattern, LOCAL_CODE_PATH); - } else if (bundleInfo.applicationInfo.bundleType == AppExecFwk::BundleType::SHARED) { - loadPath = std::regex_replace(loadPath, hsp_pattern, hsp_sandbox); - } else if (bundleInfo.applicationInfo.bundleType == AppExecFwk::BundleType::APP_SERVICE_FWK) { - TAG_LOGD(AAFwkTag::APPKIT, "System hsp path, not need translate."); - } else { - loadPath = std::regex_replace(loadPath, outer_pattern, LOCAL_BUNDLES); - } - - 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()); + { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "for (auto hapModuleInfo : bundleInfo.hapModuleInfos)"); + for (auto hapModuleInfo : bundleInfo.hapModuleInfos) { + TAG_LOGD(AAFwkTag::APPKIT, "hapModuleInfo abilityInfo size: %{public}zu", + hapModuleInfo.abilityInfos.size()); + if (!moduleName.empty() && hapModuleInfo.moduleName != moduleName) { + continue; } - } 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); - } + std::string loadPath = + hapModuleInfo.hapPath.empty() ? hapModuleInfo.resourcePath : hapModuleInfo.hapPath; + if (loadPath.empty()) { + TAG_LOGD(AAFwkTag::APPKIT, "loadPath is empty"); + continue; } - 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); + loadPath = std::regex_replace(loadPath, inner_pattern, LOCAL_CODE_PATH); + } else if (bundleInfo.applicationInfo.bundleType == AppExecFwk::BundleType::SHARED) { + loadPath = std::regex_replace(loadPath, hsp_pattern, hsp_sandbox); + } else if (bundleInfo.applicationInfo.bundleType == AppExecFwk::BundleType::APP_SERVICE_FWK) { + TAG_LOGD(AAFwkTag::APPKIT, "System hsp path, not need translate."); + } else { + loadPath = std::regex_replace(loadPath, outer_pattern, LOCAL_BUNDLES); + } + + 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); + } } } } @@ -827,6 +840,7 @@ std::shared_ptr ContextImpl::InitResourceMana void ContextImpl::UpdateResConfig(std::shared_ptr &resourceManager) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::unique_ptr resConfig(Global::Resource::CreateResConfig()); if (resConfig == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "create ResConfig failed"); @@ -866,6 +880,7 @@ void ContextImpl::UpdateResConfig(std::shared_ptr lock(bundleManagerMutex_); if (bundleMgr_ != nullptr && !resetFlag_) { return ERR_OK; @@ -1059,6 +1074,7 @@ Global::Resource::DeviceType ContextImpl::GetDeviceType() const ErrCode ContextImpl::GetOverlayMgrProxy() { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int errCode = GetBundleManager(); if (errCode != ERR_OK) { TAG_LOGE(AAFwkTag::APPKIT, "failed, errCode: %{public}d.", errCode); @@ -1083,16 +1099,19 @@ ErrCode ContextImpl::GetOverlayMgrProxy() int ContextImpl::GetOverlayModuleInfos(const std::string &bundleName, const std::string &moduleName, std::vector &overlayModuleInfos) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int errCode = GetOverlayMgrProxy(); if (errCode != ERR_OK) { TAG_LOGE(AAFwkTag::APPKIT, "failed, errCode: %{public}d.", errCode); return errCode; } - - auto ret = overlayMgrProxy_->GetTargetOverlayModuleInfo(moduleName, overlayModuleInfos); - if (ret != ERR_OK) { - TAG_LOGD(AAFwkTag::APPKIT, "GetOverlayModuleInfo form bms failed."); - return ret; + { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "overlayMgrProxy_->GetTargetOverlayModuleInfo"); + auto ret = overlayMgrProxy_->GetTargetOverlayModuleInfo(moduleName, overlayModuleInfos); + if (ret != ERR_OK) { + TAG_LOGD(AAFwkTag::APPKIT, "GetOverlayModuleInfo form bms failed."); + return ret; + } } std::sort(overlayModuleInfos.begin(), overlayModuleInfos.end(), [](const AppExecFwk::OverlayModuleInfo& lhs, const AppExecFwk::OverlayModuleInfo& rhs) -> bool { @@ -1105,6 +1124,7 @@ int ContextImpl::GetOverlayModuleInfos(const std::string &bundleName, const std: std::vector ContextImpl::GetAddOverlayPaths( const std::vector &overlayModuleInfos) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::vector addPaths; for (auto it : overlayModuleInfos) { auto iter = std::find_if( @@ -1125,6 +1145,7 @@ std::vector ContextImpl::GetAddOverlayPaths( std::vector ContextImpl::GetRemoveOverlayPaths( const std::vector &overlayModuleInfos) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::vector removePaths; for (auto it : overlayModuleInfos) { auto iter = std::find_if( @@ -1146,6 +1167,7 @@ void ContextImpl::OnOverlayChanged(const EventFwk::CommonEventData &data, const std::shared_ptr &resourceManager, const std::string &bundleName, const std::string &moduleName, const std::string &loadPath) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPKIT, "begin."); auto want = data.GetWant(); std::string action = want.GetAction(); diff --git a/frameworks/native/appkit/ability_runtime/context/environment_callback.cpp b/frameworks/native/appkit/ability_runtime/context/environment_callback.cpp index 031b49f0b7..7b325cc761 100755 --- a/frameworks/native/appkit/ability_runtime/context/environment_callback.cpp +++ b/frameworks/native/appkit/ability_runtime/context/environment_callback.cpp @@ -17,6 +17,7 @@ #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/form_extension_context.cpp b/frameworks/native/appkit/ability_runtime/form_extension_context.cpp index cef645aa90..c664ade993 100644 --- a/frameworks/native/appkit/ability_runtime/form_extension_context.cpp +++ b/frameworks/native/appkit/ability_runtime/form_extension_context.cpp @@ -22,6 +22,7 @@ #include "form_mgr_errors.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" +#include "hitrace_meter.h" namespace OHOS { namespace AbilityRuntime { @@ -48,6 +49,7 @@ int FormExtensionContext::UpdateForm(const int64_t formId, const AppExecFwk::For } // update form request to fms + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "AppExecFwk::FormMgr::GetInstance().UpdateForm"); return AppExecFwk::FormMgr::GetInstance().UpdateForm(formId, formProviderData); } diff --git a/frameworks/native/appkit/app/ability_manager.cpp b/frameworks/native/appkit/app/ability_manager.cpp index 36f06e9510..7160811e41 100644 --- a/frameworks/native/appkit/app/ability_manager.cpp +++ b/frameworks/native/appkit/app/ability_manager.cpp @@ -16,6 +16,7 @@ #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" #include "system_ability_definition.h" @@ -52,6 +53,7 @@ int32_t AbilityManager::ClearUpApplicationData(const std::string &bundleName) std::vector AbilityManager::GetAllRunningProcesses() { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPKIT, "%s, %d", __func__, __LINE__); auto object = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID); sptr appMgr_ = iface_cast(object); diff --git a/frameworks/native/appkit/app/application_impl.cpp b/frameworks/native/appkit/app/application_impl.cpp index 72cd979029..018d74bbf8 100644 --- a/frameworks/native/appkit/app/application_impl.cpp +++ b/frameworks/native/appkit/app/application_impl.cpp @@ -17,6 +17,7 @@ #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" +#include "hitrace_meter.h" #include "ohos_application.h" #include "uri_permission_manager_client.h" @@ -159,6 +160,7 @@ void ApplicationImpl::PerformMemoryLevel(int level) */ void ApplicationImpl::PerformConfigurationUpdated(const Configuration &config) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPKIT, "called"); if (application_ != nullptr) { application_->OnConfigurationUpdated(config); diff --git a/frameworks/native/appkit/app/child_main_thread.cpp b/frameworks/native/appkit/app/child_main_thread.cpp index 56bb3eaea5..004d0cca2b 100644 --- a/frameworks/native/appkit/app/child_main_thread.cpp +++ b/frameworks/native/appkit/app/child_main_thread.cpp @@ -152,6 +152,15 @@ void ChildMainThread::HandleLoadJs() TAG_LOGE(AAFwkTag::APPKIT, "Failed to create child process runtime"); return; } + AbilityRuntime::Runtime::DebugOption debugOption; + debugOption.isStartWithDebug = processInfo_->isStartWithDebug; + debugOption.processName = processInfo_->processName; + debugOption.isDebugApp = processInfo_->isDebugApp; + debugOption.isStartWithNative = processInfo_->isStartWithNative; + 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_); TAG_LOGD(AAFwkTag::APPKIT, "ChildMainThread::HandleLoadJs end."); ExitProcessSafely(); diff --git a/frameworks/native/appkit/app/main_thread.cpp b/frameworks/native/appkit/app/main_thread.cpp index df25ea3589..f3aee7dc9d 100644 --- a/frameworks/native/appkit/app/main_thread.cpp +++ b/frameworks/native/appkit/app/main_thread.cpp @@ -825,6 +825,7 @@ void MainThread::ScheduleProfileChanged(const Profile &profile) */ void MainThread::ScheduleConfigurationUpdated(const Configuration &config) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPKIT, "called"); wptr weak = this; auto task = [weak, config]() { @@ -1378,8 +1379,16 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con options.uid = bundleInfo.applicationInfo.uid; options.apiTargetVersion = appInfo.apiTargetVersion; options.pkgContextInfoJsonStringMap = pkgContextInfoJsonStringMap; + if (applicationInfo_->appProvisionType == Constants::APP_PROVISION_TYPE_DEBUG) { + TAG_LOGD(AAFwkTag::JSRUNTIME, "Start Multi-Thread Mode: %{public}d.", appLaunchData.GetMultiThread()); + options.isMultiThread = appLaunchData.GetMultiThread(); + } options.jitEnabled = appLaunchData.IsJITEnabled(); AbilityRuntime::ChildProcessManager::GetInstance().SetForkProcessJITEnabled(appLaunchData.IsJITEnabled()); + TAG_LOGD(AAFwkTag::APPKIT, "isStartWithDebug:%{public}d, debug:%{public}d, isNativeStart:%{public}d", + appLaunchData.GetDebugApp(), appInfo.debug, appLaunchData.isNativeStart()); + AbilityRuntime::ChildProcessManager::GetInstance().SetForkProcessDebugOption(appInfo.bundleName, + appLaunchData.GetDebugApp(), appInfo.debug, appLaunchData.isNativeStart()); if (!bundleInfo.hapModuleInfos.empty()) { for (auto hapModuleInfo : bundleInfo.hapModuleInfos) { options.hapModulePath[hapModuleInfo.moduleName] = hapModuleInfo.hapPath; diff --git a/frameworks/native/appkit/app/ohos_application.cpp b/frameworks/native/appkit/app/ohos_application.cpp index db7e1dfedc..77d7dce47e 100644 --- a/frameworks/native/appkit/app/ohos_application.cpp +++ b/frameworks/native/appkit/app/ohos_application.cpp @@ -428,6 +428,7 @@ void OHOSApplication::UnregisterElementsCallbacks(const std::shared_ptr changeKeyV; - configuration_->CompareDifferent(changeKeyV, config); - configuration_->Merge(changeKeyV, config); + { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "configuration_->CompareDifferent"); + configuration_->CompareDifferent(changeKeyV, config); + configuration_->Merge(changeKeyV, config); + } TAG_LOGD(AAFwkTag::UIABILITY, "configuration_: %{public}s", configuration_->GetName().c_str()); // Update resConfig of resource manager, which belongs to application context. diff --git a/frameworks/native/appkit/app_startup/js_startup_task.cpp b/frameworks/native/appkit/app_startup/js_startup_task.cpp index 7c44c27b8f..fbad92d8d5 100644 --- a/frameworks/native/appkit/app_startup/js_startup_task.cpp +++ b/frameworks/native/appkit/app_startup/js_startup_task.cpp @@ -19,8 +19,13 @@ #include "hilog_wrapper.h" #include "js_runtime_utils.h" +namespace { +constexpr size_t ARGC_ONE = 1; +constexpr int32_t INDEX_ZERO = 0; +} namespace OHOS { namespace AbilityRuntime { +std::map> AsyncTaskCallBack::jsStartupTaskObjects_; JsStartupTask::JsStartupTask(const std::string &name, JsRuntime &jsRuntime, std::unique_ptr &startupJsRef, std::shared_ptr &contextJsRef) : StartupTask(name), jsRuntime_(jsRuntime), startupJsRef_(std::move(startupJsRef)), contextJsRef_(contextJsRef) {} @@ -52,8 +57,77 @@ int32_t JsStartupTask::RunTaskInit(std::unique_ptr ca startupTask->SaveResult(result); startupTask->CallExtraCallback(result); }); - TAG_LOGD(AAFwkTag::STARTUP, "%{public}s, RunOnMainThread", name_.c_str()); - return JsStartupTaskExecutor::RunOnMainThread(jsRuntime_, startupJsRef_, contextJsRef_, std::move(callback)); + + if (callCreateOnMainThread_) { + return JsStartupTaskExecutor::RunOnMainThread(jsRuntime_, startupJsRef_, contextJsRef_, std::move(callback)); + } + + if (LoadJsAsyncTaskExcutor() != ERR_OK) { + TAG_LOGE(AAFwkTag::STARTUP, "Load async task excutor is failed."); + return ERR_STARTUP_INTERNAL_ERROR; + } + LoadJsAsyncTaskCallback(); + + startupTaskResultCallback_ = std::move(callback); + + auto startupName = GetName(); + auto result = JsStartupTaskExecutor::RunOnTaskPool( + jsRuntime_, startupJsRef_, contextJsRef_, AsyncTaskExcutorJsRef_, AsyncTaskExcutorCallbackJsRef_, startupName); + if (result == ERR_OK) { + AsyncTaskCallBack::jsStartupTaskObjects_.emplace(startupName, shared_from_this()); + } + return result; +} + +int32_t JsStartupTask::LoadJsAsyncTaskExcutor() +{ + TAG_LOGD(AAFwkTag::STARTUP, "Called."); + HandleScope handleScope(jsRuntime_); + auto env = jsRuntime_.GetNapiEnv(); + + napi_value object = nullptr; + napi_create_object(env, &object); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::STARTUP, "Object is nullptr."); + return ERR_STARTUP_INTERNAL_ERROR; + } + + AsyncTaskExcutorJsRef_ = + JsRuntime::LoadSystemModuleByEngine(env, "app.appstartup.AsyncTaskExcutor", &object, 1); + return ERR_OK; +} + +void JsStartupTask::LoadJsAsyncTaskCallback() +{ + TAG_LOGD(AAFwkTag::STARTUP, "Called."); + HandleScope handleScope(jsRuntime_); + auto env = jsRuntime_.GetNapiEnv(); + + napi_value config; + std::string value = "This is callback value"; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, value.c_str(), value.length(), &config)); + + napi_property_descriptor props[] = { + DECLARE_NAPI_STATIC_FUNCTION("onAsyncTaskCompleted", AsyncTaskCallBack::AsyncTaskCompleted), + DECLARE_NAPI_INSTANCE_PROPERTY("config", config), + }; + napi_value asyncTaskCallbackClass = nullptr; + napi_define_sendable_class(env, "AsyncTaskCallback", NAPI_AUTO_LENGTH, AsyncTaskCallBack::Constructor, + nullptr, sizeof(props) / sizeof(props[0]), props, nullptr, &asyncTaskCallbackClass); + AsyncTaskExcutorCallbackJsRef_ = + JsRuntime::LoadSystemModuleByEngine(env, "app.appstartup.AsyncTaskCallback", &asyncTaskCallbackClass, 1); +} + +void JsStartupTask::OnAsyncTaskCompleted() +{ + TAG_LOGD(AAFwkTag::STARTUP, "Called."); + if (startupTaskResultCallback_ == nullptr) { + TAG_LOGE(AAFwkTag::STARTUP, "Startup task result callback object is nullptr."); + return; + } + std::shared_ptr result = std::make_shared(nullptr); + startupTaskResultCallback_->Call(result); } int32_t JsStartupTask::RunTaskOnDependencyCompleted(const std::string &dependencyName, @@ -111,5 +185,40 @@ napi_value JsStartupTask::GetDependencyResult(napi_env env, const std::string &d return jsResultRef->GetNapiValue(); } } + +napi_value AsyncTaskCallBack::AsyncTaskCompleted(napi_env env, napi_callback_info info) +{ + TAG_LOGD(AAFwkTag::STARTUP, "Called."); + size_t argc = ARGC_ONE; + napi_value argv[ARGC_ONE] = { nullptr }; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + + std::string startupName; + if (!ConvertFromJsValue(env, argv[INDEX_ZERO], startupName)) { + TAG_LOGE(AAFwkTag::STARTUP, "Convert from js startupName error."); + return CreateJsUndefined(env); + } + + std::shared_ptr startupTask; + for (auto iter : AsyncTaskCallBack::jsStartupTaskObjects_) { + if (iter.first == startupName) { + startupTask = iter.second.lock(); + } + } + + if (startupTask != nullptr) { + startupTask->OnAsyncTaskCompleted(); + AsyncTaskCallBack::jsStartupTaskObjects_.erase(startupName); + } + + return CreateJsUndefined(env); +} + +napi_value AsyncTaskCallBack::Constructor(napi_env env, napi_callback_info cbinfo) +{ + TAG_LOGD(AAFwkTag::STARTUP, "Called."); + return CreateJsUndefined(env); +} } // namespace AbilityRuntime } // namespace OHOS 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 ffd6d90890..8ea932fc5a 100644 --- a/frameworks/native/appkit/app_startup/js_startup_task_executor.cpp +++ b/frameworks/native/appkit/app_startup/js_startup_task_executor.cpp @@ -21,7 +21,9 @@ #include "js_startup_task_result.h" #define TMP_NAPI_ANONYMOUS_FUNC "_" - +namespace { +constexpr size_t ARGC_FOUR = 4; +} namespace OHOS { namespace AbilityRuntime { int32_t JsStartupTaskExecutor::RunOnMainThread(JsRuntime &jsRuntime, @@ -39,10 +41,43 @@ int32_t JsStartupTaskExecutor::RunOnMainThread(JsRuntime &jsRuntime, return HandleReturnVal(env, returnVal, callback); } -int32_t JsStartupTaskExecutor::RunOnTaskPool(JsRuntime &jsRuntime, - const std::unique_ptr &startup, const std::shared_ptr &context, - std::unique_ptr callback) +int32_t JsStartupTaskExecutor::RunOnTaskPool( + JsRuntime &jsRuntime, + const std::unique_ptr &startup, + const std::shared_ptr &context, + const std::unique_ptr &asyncTaskExcutor, + const std::unique_ptr &asyncTaskCallback, + const std::string &startupName) { + TAG_LOGD(AAFwkTag::STARTUP, "Called."); + HandleScope handleScope(jsRuntime); + auto env = jsRuntime.GetNapiEnv(); + + if (startup == nullptr || context == nullptr || asyncTaskExcutor == nullptr || asyncTaskCallback == nullptr) { + TAG_LOGE(AAFwkTag::STARTUP, "AsyncTaskExcutor or startup or context or async task callback is null."); + return ERR_STARTUP_INTERNAL_ERROR; + } + napi_value asyncTaskExcutorValue = asyncTaskExcutor->GetNapiValue(); + if (!CheckTypeForNapiValue(env, asyncTaskExcutorValue, napi_object)) { + TAG_LOGE(AAFwkTag::STARTUP, "AsyncTaskExcutor is not napi object."); + return ERR_STARTUP_INTERNAL_ERROR; + } + napi_value asyncPushTask = nullptr; + napi_get_named_property(env, asyncTaskExcutorValue, "asyncPushTask", &asyncPushTask); + if (asyncPushTask == nullptr) { + TAG_LOGE(AAFwkTag::STARTUP, "Failed to get property asyncPushTask from AsyncTaskExcutor."); + return ERR_STARTUP_FAILED_TO_EXECUTE_STARTUP; + } + bool isCallable = false; + napi_is_callable(env, asyncPushTask, &isCallable); + if (!isCallable) { + TAG_LOGE(AAFwkTag::STARTUP, "AsyncPushTask is not callable."); + return ERR_STARTUP_FAILED_TO_EXECUTE_STARTUP; + } + napi_value returnVal = nullptr; + napi_value argv[] = { startup->GetNapiValue(), asyncTaskCallback->GetNapiValue(), + context->GetNapiValue(), CreateJsValue(env, startupName) }; + napi_call_function(env, asyncTaskExcutorValue, asyncPushTask, ARGC_FOUR, argv, &returnVal); return ERR_OK; } diff --git a/frameworks/native/appkit/app_startup/startup_utils.cpp b/frameworks/native/appkit/app_startup/startup_utils.cpp index ea278f04f4..73b7bd1781 100644 --- a/frameworks/native/appkit/app_startup/startup_utils.cpp +++ b/frameworks/native/appkit/app_startup/startup_utils.cpp @@ -32,7 +32,6 @@ const std::map ERR_MSG_MAP = { std::string StartupUtils::GetErrorMessage(int32_t errCode) { - std::string errMsg; auto iter = ERR_MSG_MAP.find(errCode); if (iter == ERR_MSG_MAP.end()) { return ERR_MSG_MAP.at(ERR_STARTUP_INTERNAL_ERROR); diff --git a/frameworks/native/appkit/dfr/watchdog.cpp b/frameworks/native/appkit/dfr/watchdog.cpp index 241c479b84..5b5db864da 100644 --- a/frameworks/native/appkit/dfr/watchdog.cpp +++ b/frameworks/native/appkit/dfr/watchdog.cpp @@ -54,6 +54,7 @@ Watchdog::~Watchdog() void Watchdog::Init(const std::shared_ptr mainHandler) { + std::unique_lock lock(cvMutex_); Watchdog::appMainHandler_ = mainHandler; if (appMainHandler_ != nullptr) { TAG_LOGD(AAFwkTag::APPDFR, "Watchdog init send event"); @@ -85,6 +86,7 @@ void Watchdog::Stop() void Watchdog::SetAppMainThreadState(const bool appMainThreadState) { + std::unique_lock lock(cvMutex_); appMainThreadIsAlive_.store(appMainThreadState); } @@ -95,12 +97,14 @@ void Watchdog::SetBundleInfo(const std::string& bundleName, const std::string& b void Watchdog::SetBackgroundStatus(const bool isInBackground) { + std::unique_lock lock(cvMutex_); isInBackground_.store(isInBackground); OHOS::HiviewDFX::Watchdog::GetInstance().SetForeground(!isInBackground); } void Watchdog::AllowReportEvent() { + std::unique_lock lock(cvMutex_); needReport_.store(true); isSixSecondEvent_.store(false); backgroundReportCount_.store(0); @@ -118,6 +122,7 @@ bool Watchdog::IsReportEvent() bool Watchdog::IsStopWatchdog() { + std::unique_lock lock(cvMutex_); return stopWatchdog_; } 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 b275de7374..2bcef8817b 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 @@ -44,14 +44,15 @@ napi_value JsInsightIntentContext::OnStartAbility(napi_env env, NapiCallbackInfo { TAG_LOGD(AAFwkTag::INTENT, "enter"); HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - if (info.argc == 0) { - TAG_LOGE(AAFwkTag::INTENT, "not enough args"); - ThrowTooFewParametersError(env); - return CreateJsUndefined(env); - } + // unwrap want AAFwk::Want want; - OHOS::AppExecFwk::UnwrapWant(env, info.argv[0], want); + + bool checkParamResult = CheckStartAbilityParam(env, info, want); + if (!checkParamResult) { + TAG_LOGE(AAFwkTag::INTENT, "check startAbility param failed"); + return CreateJsUndefined(env); + } auto context = context_.lock(); if (context == nullptr) { @@ -116,5 +117,23 @@ napi_value CreateJsInsightIntentContext(napi_env env, const std::shared_ptr func; }; -class SimulatorImpl : public Simulator { +class SimulatorImpl : public Simulator, public std::enable_shared_from_this { public: SimulatorImpl() = default; ~SimulatorImpl(); @@ -124,6 +124,7 @@ private: panda::ecmascript::EcmaVM *vm_ = nullptr; DebuggerTask debuggerTask_; napi_env nativeEngine_ = nullptr; + TerminateCallback terminateCallback_; int64_t currentId_ = 0; std::unordered_map> abilities_; @@ -357,6 +358,7 @@ int64_t SimulatorImpl::StartAbility( } ++currentId_; + terminateCallback_ = callback; InitResourceMgr(); InitJsAbilityContext(nativeEngine_, instanceValue); DispatchStartLifecycle(instanceValue); @@ -684,6 +686,20 @@ bool SimulatorImpl::OnInit() return false; } napi_env env = reinterpret_cast(nativeEngine); + auto uncaughtTask = [weak = weak_from_this()](napi_value value) { + TAG_LOGE(AAFwkTag::ABILITY_SIM, "uncaught exception"); + auto self = weak.lock(); + if (self == nullptr) { + TAG_LOGE(AAFwkTag::ABILITY_SIM, "SimulatorImpl is nullptr."); + return; + } + if (self->terminateCallback_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITY_SIM, "terminateCallback is nullptr."); + return; + } + self->terminateCallback_(self->currentId_); + }; + nativeEngine->RegisterNapiUncaughtExceptionHandler(uncaughtTask); napi_value globalObj; napi_get_global(env, &globalObj); diff --git a/interfaces/inner_api/ability_manager/BUILD.gn b/interfaces/inner_api/ability_manager/BUILD.gn index f86f39ec30..e89282cdd4 100644 --- a/interfaces/inner_api/ability_manager/BUILD.gn +++ b/interfaces/inner_api/ability_manager/BUILD.gn @@ -27,6 +27,8 @@ 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/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", @@ -150,6 +152,7 @@ ohos_shared_library("ability_manager") { "relational_store:native_rdb", "samgr:samgr_proxy", ] + public_external_deps = [ "ability_base:configuration", "ability_base:want", 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 10e2bd3297..505bd3ba93 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_client.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_client.h @@ -1451,6 +1451,15 @@ public: */ int32_t NotifyDebugAssertResult(uint64_t assertFaultSessionId, AAFwk::UserStatus userStatus); + /** + * Set the enable status for starting and stopping resident processes. + * The caller application can only set the resident status of the configured process. + * @param bundleName The bundle name of the resident process. + * @param enable Set resident process enable status. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t SetResidentProcessEnabled(const std::string &bundleName, bool enable); + /** * Starts a new ability with specific start options. * 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 b91a830185..9e9a725637 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_errors.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_errors.h @@ -499,6 +499,11 @@ enum { * Result(2097248) for get ExtensionName by uid fail. */ GET_EXTENSION_NAME_BY_UID_FAIL, + + /** + * Native error(2097249) no resident process permissions set. + */ + ERR_NO_RESIDENT_PERMISSION, }; enum { diff --git a/interfaces/inner_api/ability_manager/include/ability_manager_interface.h b/interfaces/inner_api/ability_manager/include/ability_manager_interface.h index a66417a988..15212da991 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_interface.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_interface.h @@ -1522,6 +1522,18 @@ public: return 0; } + /* + * Set the enable status for starting and stopping resident processes. + * The caller application can only set the resident status of the configured process. + * @param bundleName The bundle name of the resident process. + * @param enable Set resident process enable status. + * @return Returns ERR_OK on success, others on failure. + */ + virtual int32_t SetResidentProcessEnabled(const std::string &bundleName, bool enable) + { + return 0; + } + /** * @brief Querying whether to allow embedded startup of atomic service. * 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 2eaf49a7ea..9dbbf3df41 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 @@ -241,6 +241,9 @@ enum class AbilityManagerInterfaceCode { // Starts a new ability by shortcut. START_SHORTCUT = 79, + // Set resident process enable status. + SET_RESIDENT_PROCESS_ENABLE = 80, + // ipc id 1001-2000 for DMS // ipc id for starting ability (1001) START_ABILITY = 1001, 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 f726761eac..19ffa2c25a 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 @@ -285,6 +285,13 @@ public: */ virtual void SetAppAssertionPauseState(int32_t pid, bool flag) {} + /** + * @brief Set resident process enable status. + * @param bundleName The application bundle name. + * @param enable The current updated enable status. + */ + virtual void SetKeepAliveEnableState(const std::string &bundleName, bool enable) {}; + /** * To clear the process by ability token. * @@ -342,6 +349,7 @@ public: KILL_PROCESSES_BY_PIDS, ATTACH_PID_TO_PARENT, IS_MEMORY_SIZE_SUFFICIENT, + SET_KEEP_ALIVE_ENABLE_STATE, }; }; } // 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 9fe2cc2487..cbd091bdf0 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 @@ -262,6 +262,13 @@ public: */ void SetAppAssertionPauseState(int32_t pid, bool flag) override; + /** + * @brief Set resident process enable status. + * @param bundleName The application bundle name. + * @param enable The current updated enable status. + */ + void SetKeepAliveEnableState(const std::string &bundleName, bool enable) override; + /** * To clear the process by ability token. * 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 091e427c41..cde52456cd 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 @@ -83,6 +83,7 @@ private: int32_t HandleSetAppAssertionPauseState(MessageParcel &data, MessageParcel &reply); int32_t HandleClearProcessByToken(MessageParcel &data, MessageParcel &reply); int32_t HandleIsMemorySizeSufficent(MessageParcel &data, MessageParcel &reply); + int32_t HandleSetKeepAliveEnableState(MessageParcel &data, MessageParcel &reply); using AmsMgrFunc = int32_t (AmsMgrStub::*)(MessageParcel &data, MessageParcel &reply); std::map memberFuncMap_; 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 525c5b0ded..801af1606d 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 @@ -172,6 +172,16 @@ public: return perfCmd_; } + inline void SetMultiThread(const bool multiThread) + { + isMultiThread_ = multiThread; + } + + inline bool GetMultiThread() const + { + return isMultiThread_; + } + inline void SetJITEnabled(const bool jitEnabled) { jitEnabled_ = jitEnabled; @@ -238,6 +248,7 @@ private: std::string perfCmd_; bool jitEnabled_ = false; bool isNativeStart_ = false; + bool isMultiThread_ = 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 73bf07afb7..f18c6ef7ca 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 @@ -612,6 +612,13 @@ public: */ bool IsAttachDebug(const std::string &bundleName); + /** + * @brief Set resident process enable status. + * @param bundleName The application bundle name. + * @param enable The current updated enable status. + */ + void SetKeepAliveEnableState(const std::string &bundleName, bool enable); + /** * Set application assertion pause state. * 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 6b2db8672a..723d2a714b 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 @@ -143,6 +143,17 @@ public: */ virtual int GetAllRunningProcesses(std::vector &info) = 0; + /** + * GetRunningProcessesByBundleType, call GetRunningProcessesByBundleType() through proxy project. + * Obtains information about application processes by bundle type that are running on the device. + * + * @param bundleType, bundle type of the processes + * @param info, app name in Application record. + * @return ERR_OK ,return back success,others fail. + */ + virtual int GetRunningProcessesByBundleType(const BundleType bundleType, + std::vector &info) = 0; + /** * GetAllRenderProcesses, call GetAllRenderProcesses() through proxy project. * Obtains information about render processes that are running on the device. @@ -539,7 +550,8 @@ public: * @param childPid Created child process pid. * @return Returns ERR_OK on success, others on failure. */ - virtual int32_t StartChildProcess(const std::string &srcEntry, pid_t &childPid) = 0; + virtual int32_t StartChildProcess(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount, + bool isStartWithDebug) = 0; /** * Get child process record for self. 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 190d019bd2..abc01de315 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 @@ -98,6 +98,7 @@ enum class AppMgrInterfaceCode { NOTIFY_MEMORY_SIZE_STATE_CHANGED = 72, PRELOAD_APPLICATION = 73, SET_SUPPORTED_PROCESS_CACHE_SELF = 74, + APP_GET_RUNNING_PROCESSES_BY_BUNDLE_TYPE = 75, }; } // 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 fe80854025..3b5c4feebc 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 @@ -122,6 +122,17 @@ public: */ virtual int32_t GetAllRunningProcesses(std::vector &info) override; + /** + * GetRunningProcessesByBundleType, call GetRunningProcessesByBundleType() through proxy project. + * Obtains information about application processes by bundle type that are running on the device. + * + * @param bundleType, bundle type of the processes + * @param info, app name in Application record. + * @return ERR_OK ,return back success,others fail. + */ + virtual int GetRunningProcessesByBundleType(const BundleType bundleType, + std::vector &info) override; + /** * GetAllRenderProcesses, call GetAllRenderProcesses() through proxy project. * Obtains information about render processes that are running on the device. @@ -476,7 +487,8 @@ public: * @param childPid Created child process pid. * @return Returns ERR_OK on success, others on failure. */ - int32_t StartChildProcess(const std::string &srcEntry, pid_t &childPid) override; + int32_t StartChildProcess(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount, + bool isStartWithDebug) override; /** * Get child process record for self. 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 b1d0aa3f07..51de220229 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 @@ -65,6 +65,7 @@ private: int32_t HandleGetAmsMgr(MessageParcel &data, MessageParcel &reply); int32_t HandleClearUpApplicationData(MessageParcel &data, MessageParcel &reply); int32_t HandleGetAllRunningProcesses(MessageParcel &data, MessageParcel &reply); + int32_t HandleGetRunningProcessesByBundleType(MessageParcel &data, MessageParcel &reply); int32_t HandleGetProcessRunningInfosByUserId(MessageParcel &data, MessageParcel &reply); int32_t HandleGetProcessRunningInformation(MessageParcel &data, MessageParcel &reply); int32_t HandleGetAllRenderProcesses(MessageParcel &data, MessageParcel &reply); 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 cc0e4430d2..89b4706190 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 @@ -30,6 +30,9 @@ struct ChildProcessInfo : public Parcelable { std::string processName; std::string srcEntry; bool jitEnabled = false; + bool isDebugApp = true; + bool isStartWithDebug = false; + bool isStartWithNative = false; bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; diff --git a/interfaces/inner_api/app_manager/include/appmgr/running_process_info.h b/interfaces/inner_api/app_manager/include/appmgr/running_process_info.h index 4644711d19..9c19ef40f9 100644 --- a/interfaces/inner_api/app_manager/include/appmgr/running_process_info.h +++ b/interfaces/inner_api/app_manager/include/appmgr/running_process_info.h @@ -62,6 +62,7 @@ struct RunningProcessInfo : public Parcelable { bool isTestProcess = false; bool isAbilityForegrounding = false; bool isTestMode = false; + std::int32_t bundleType = 0; bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; 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 2d36fc364f..6fc6a49476 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 @@ -840,6 +840,31 @@ int32_t AmsMgrProxy::DetachAppDebug(const std::string &bundleName) return reply.ReadInt32(); } +void AmsMgrProxy::SetKeepAliveEnableState(const std::string &bundleName, bool enable) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called."); + MessageParcel data; + if (!WriteInterfaceToken(data)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write interface token failed."); + return; + } + if (bundleName.empty() || !data.WriteString(bundleName)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write bundle name fail."); + return; + } + if (!data.WriteBool(enable)) { + TAG_LOGE(AAFwkTag::APPMGR, "Write flag fail."); + return; + } + MessageParcel reply; + MessageOption option; + auto ret = SendTransactCmd(static_cast(IAmsMgr::Message::SET_KEEP_ALIVE_ENABLE_STATE), + data, reply, option); + if (ret != NO_ERROR) { + TAG_LOGE(AAFwkTag::APPMGR, "Send request failed, err: %{public}d", ret); + } +} + int32_t AmsMgrProxy::SetAppWaitingDebug(const std::string &bundleName, bool isPersist) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); 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 92733b9b34..864ea07e3d 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 @@ -122,6 +122,8 @@ void AmsMgrStub::CreateMemberFuncMap() &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; } int AmsMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -598,6 +600,15 @@ int32_t AmsMgrStub::HandleIsWaitingDebugApp(MessageParcel &data, MessageParcel & return NO_ERROR; } +int32_t AmsMgrStub::HandleSetKeepAliveEnableState(MessageParcel &data, MessageParcel &reply) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called."); + auto bundleName = data.ReadString(); + auto enable = data.ReadBool(); + SetKeepAliveEnableState(bundleName, enable); + return NO_ERROR; +} + int32_t AmsMgrStub::HandleClearNonPersistWaitingDebugFlag(MessageParcel &data, MessageParcel &reply) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); 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 42f6ecbd99..7f6c872d4b 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 @@ -96,6 +96,12 @@ bool AppLaunchData::Marshalling(Parcel &parcel) const TAG_LOGE(AAFwkTag::APPMGR, "Marshalling, Failed to write app running unique id."); return false; } + + if (!parcel.WriteBool(isMultiThread_)) { + TAG_LOGE(AAFwkTag::APPMGR, "Failed to write is multi thread flag."); + return false; + } + return true; } @@ -140,6 +146,7 @@ bool AppLaunchData::ReadFromParcel(Parcel &parcel) jitEnabled_ = parcel.ReadBool(); isNativeStart_ = parcel.ReadBool(); appRunningUniqueId_ = parcel.ReadString(); + isMultiThread_ = 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 e604592938..8a65c60534 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 @@ -26,6 +26,7 @@ #include "app_service_manager.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" +#include "hitrace_meter.h" #include "app_mem_info.h" namespace OHOS { @@ -508,6 +509,7 @@ void AppMgrClient::PrepareTerminate(const sptr &token) void AppMgrClient::GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); sptr service = iface_cast(mgrHolder_->GetRemoteObject()); if (service != nullptr) { sptr amsService = service->GetAmsMgr(); @@ -595,6 +597,14 @@ void AppMgrClient::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecF amsService->StartSpecifiedAbility(want, abilityInfo); } +void AppMgrClient::SetKeepAliveEnableState(const std::string &bundleName, bool enable) +{ + if (!IsAmsServiceReady()) { + return; + } + amsService_->SetKeepAliveEnableState(bundleName, enable); +} + void AppMgrClient::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) { TAG_LOGD(AAFwkTag::APPMGR, "call."); 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 8a0ec0c609..aec1f49eb8 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 @@ -218,6 +218,7 @@ int32_t AppMgrProxy::ClearUpApplicationDataBySelf(int32_t userId) int32_t AppMgrProxy::GetAllRunningProcesses(std::vector &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); MessageParcel data; MessageParcel reply; MessageOption option(MessageOption::TF_SYNC); @@ -236,6 +237,31 @@ int32_t AppMgrProxy::GetAllRunningProcesses(std::vector &inf return result; } +int32_t AppMgrProxy::GetRunningProcessesByBundleType(const BundleType bundleType, + std::vector &info) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_SYNC); + 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; + } + if (!SendTransactCmd(AppMgrInterfaceCode::APP_GET_RUNNING_PROCESSES_BY_BUNDLE_TYPE, data, reply)) { + return ERR_NULL_OBJECT; + } + auto error = GetParcelableInfos(reply, info); + if (error != NO_ERROR) { + TAG_LOGE(AAFwkTag::APPMGR, "GetParcelableInfos fail, error: %{public}d", error); + return error; + } + int result = reply.ReadInt32(); + return result; +} + int32_t AppMgrProxy::GetAllRenderProcesses(std::vector &info) { MessageParcel data; @@ -545,6 +571,7 @@ int AppMgrProxy::UnregisterApplicationStateObserver( int32_t AppMgrProxy::RegisterAbilityForegroundStateObserver(const sptr &observer) { TAG_LOGD(AAFwkTag::APPMGR, "Called."); + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (observer == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Observer is null."); return ERR_INVALID_VALUE; @@ -1600,7 +1627,8 @@ int32_t AppMgrProxy::IsApplicationRunning(const std::string &bundleName, bool &i return reply.ReadInt32(); } -int32_t AppMgrProxy::StartChildProcess(const std::string &srcEntry, pid_t &childPid) +int32_t AppMgrProxy::StartChildProcess(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount, + bool isStartWithDebug) { TAG_LOGD(AAFwkTag::APPMGR, "called"); if (srcEntry.empty()) { @@ -1616,6 +1644,14 @@ int32_t AppMgrProxy::StartChildProcess(const std::string &srcEntry, pid_t &child 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; + } MessageParcel reply; MessageOption option; 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 a56ab0129c..b1c3946e05 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 @@ -188,6 +188,8 @@ AppMgrStub::AppMgrStub() &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; } AppMgrStub::~AppMgrStub() @@ -324,6 +326,24 @@ int32_t AppMgrStub::HandleGetAllRunningProcesses(MessageParcel &data, MessagePar return NO_ERROR; } +int32_t AppMgrStub::HandleGetRunningProcessesByBundleType(MessageParcel &data, MessageParcel &reply) +{ + HITRACE_METER(HITRACE_TAG_APP); + int32_t bundleType = data.ReadInt32(); + std::vector info; + auto result = GetRunningProcessesByBundleType(static_cast(bundleType), info); + reply.WriteInt32(info.size()); + for (auto &it : info) { + if (!reply.WriteParcelable(&it)) { + return ERR_INVALID_VALUE; + } + } + if (!reply.WriteInt32(result)) { + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + int32_t AppMgrStub::HandleGetProcessRunningInfosByUserId(MessageParcel &data, MessageParcel &reply) { HITRACE_METER(HITRACE_TAG_APP); @@ -501,6 +521,7 @@ int32_t AppMgrStub::HandleUnregisterApplicationStateObserver(MessageParcel &data int32_t AppMgrStub::HandleRegisterAbilityForegroundStateObserver(MessageParcel &data, MessageParcel &reply) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto callback = iface_cast(data.ReadRemoteObject()); if (callback == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Callback is null."); @@ -1098,7 +1119,9 @@ int32_t AppMgrStub::HandleStartChildProcess(MessageParcel &data, MessageParcel & TAG_LOGD(AAFwkTag::APPMGR, "called."); std::string srcEntry = data.ReadString(); int32_t childPid = 0; - int32_t result = StartChildProcess(srcEntry, childPid); + int32_t childProcessCount = data.ReadInt32(); + int32_t isStartWithDebug = data.ReadBool(); + int32_t result = StartChildProcess(srcEntry, childPid, childProcessCount, isStartWithDebug); if (!reply.WriteInt32(result)) { TAG_LOGE(AAFwkTag::APPMGR, "Write result error."); return ERR_INVALID_VALUE; 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 d16522f326..6672d3cf82 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 @@ -268,6 +268,7 @@ int32_t AppSchedulerHost::HandleScheduleProfileChanged(MessageParcel &data, Mess int32_t AppSchedulerHost::HandleScheduleConfigurationUpdated(MessageParcel &data, MessageParcel &reply) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); HITRACE_METER(HITRACE_TAG_APP); std::unique_ptr configuration(data.ReadParcelable()); if (!configuration) { 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 22840507c3..c86db0c84e 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 @@ -345,6 +345,7 @@ void AppSchedulerProxy::ScheduleProfileChanged(const Profile &profile) void AppSchedulerProxy::ScheduleConfigurationUpdated(const Configuration &config) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); MessageParcel data; MessageParcel reply; MessageOption option(MessageOption::TF_ASYNC); @@ -705,12 +706,14 @@ int32_t AppSchedulerProxy::ScheduleDumpIpcStat(std::string& result) int32_t AppSchedulerProxy::SendTransactCmd(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); sptr remote = Remote(); if (remote == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Remote is nullptr."); return ERR_NULL_OBJECT; } + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "remote->SendRequest"); auto ret = remote->SendRequest(code, data, reply, option); if (ret != NO_ERROR) { TAG_LOGE(AAFwkTag::APPMGR, "Send request failed with error code: %{public}d", ret); 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 eda7ae0ada..490bbe820b 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 @@ -41,6 +41,9 @@ bool ChildProcessInfo::ReadFromParcel(Parcel &parcel) processName = Str16ToStr8(parcel.ReadString16()); srcEntry = Str16ToStr8(parcel.ReadString16()); jitEnabled = parcel.ReadBool(); + isDebugApp = parcel.ReadBool(); + isStartWithDebug = parcel.ReadBool(); + isStartWithNative = parcel.ReadBool(); return true; } @@ -65,6 +68,9 @@ bool ChildProcessInfo::Marshalling(Parcel &parcel) const 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(Bool, parcel, jitEnabled); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isDebugApp); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isStartWithDebug); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isStartWithNative); return true; } } // namespace AppExecFwk 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 74f7401cd7..1c32b360d9 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 @@ -48,6 +48,9 @@ bool RunningProcessInfo::ReadFromParcel(Parcel &parcel) isTestProcess = parcel.ReadBool(); isAbilityForegrounding = parcel.ReadBool(); isTestMode = parcel.ReadBool(); + int32_t bundleTypeData; + READ_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, bundleTypeData); + bundleType = static_cast(bundleTypeData); if (!parcel.ReadStringVector(&bundleNames)) { TAG_LOGE(AAFwkTag::APPMGR, "read bundleNames failed."); return false; @@ -84,6 +87,7 @@ bool RunningProcessInfo::Marshalling(Parcel &parcel) const WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isTestProcess); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isAbilityForegrounding); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isTestMode); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Int32, parcel, static_cast(bundleType)); if (!parcel.WriteStringVector(bundleNames)) { TAG_LOGE(AAFwkTag::APPMGR, "write bundleNames failed."); return false; 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 f2135aa353..b6c9f7ea97 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 @@ -58,7 +58,7 @@ public: private: void SendAutoFillSucess(const AAFwk::Want &want); - void SendAutoFillFailed(int32_t errCode); + void SendAutoFillFailed(int32_t errCode, const AAFwk::Want &want = AAFwk::Want()); void CloseModalUIExtension(); void HandleReloadInModal(const AAFwk::WantParams &wantParams); 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 0cd5114526..acec2951d7 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * 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 @@ -25,7 +25,7 @@ public: virtual ~IFillRequestCallback() {} virtual void OnFillRequestSuccess(const AbilityBase::ViewData &viewData) = 0; - virtual void OnFillRequestFailed(int32_t errCode) = 0; + virtual void OnFillRequestFailed(int32_t errCode, const std::string& fillContent = "") = 0; }; } // AbilityRuntime } // OHOS diff --git a/interfaces/inner_api/auto_fill_manager/src/auto_fill_extension_callback.cpp b/interfaces/inner_api/auto_fill_manager/src/auto_fill_extension_callback.cpp index f219d159f0..abe2d0609e 100644 --- a/interfaces/inner_api/auto_fill_manager/src/auto_fill_extension_callback.cpp +++ b/interfaces/inner_api/auto_fill_manager/src/auto_fill_extension_callback.cpp @@ -31,6 +31,7 @@ constexpr static char WANT_PARAMS_AUTO_FILL_CMD_KEY[] = "ohos.ability.params.aut constexpr static char WANT_PARAMS_UPDATE_POPUP_WIDTH[] = "ohos.ability.params.popupWidth"; constexpr static char WANT_PARAMS_UPDATE_POPUP_HEIGHT[] = "ohos.ability.params.popupHeight"; constexpr static char WANT_PARAMS_UPDATE_POPUP_PLACEMENT[] = "ohos.ability.params.popupPlacement"; +constexpr static char WANT_PARAMS_FILL_CONTENT[] = "ohos.ability.params.fillContent"; } // namespace void AutoFillExtensionCallback::OnResult(int32_t errCode, const AAFwk::Want &want) { @@ -50,7 +51,7 @@ void AutoFillExtensionCallback::OnResult(int32_t errCode, const AAFwk::Want &wan } else { auto resultCode = (errCode == AutoFill::AUTO_FILL_CANCEL) ? AutoFill::AUTO_FILL_CANCEL : AutoFill::AUTO_FILL_FAILED; - SendAutoFillFailed(resultCode); + SendAutoFillFailed(resultCode, want); } } @@ -254,10 +255,11 @@ void AutoFillExtensionCallback::SendAutoFillSucess(const AAFwk::Want &want) } } -void AutoFillExtensionCallback::SendAutoFillFailed(int32_t errCode) +void AutoFillExtensionCallback::SendAutoFillFailed(int32_t errCode, const AAFwk::Want &want) { if (fillCallback_ != nullptr) { - fillCallback_->OnFillRequestFailed(errCode); + std::string fillContent = want.GetStringParam(WANT_PARAMS_FILL_CONTENT); + fillCallback_->OnFillRequestFailed(errCode, fillContent); fillCallback_ = 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 f4eb2f167f..3bf2137fe4 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 @@ -48,6 +48,8 @@ public: bool LoadJsFile(const std::string &srcEntry, const AppExecFwk::HapModuleInfo &hapModuleInfo, std::unique_ptr &runtime); void SetForkProcessJITEnabled(bool jitEnabled); + void SetForkProcessDebugOption(const std::string bundleName, const bool isStartWithDebug, const bool isDebugApp, + const bool isStartWithNative); private: ChildProcessManager(); @@ -57,9 +59,11 @@ private: void HandleChildProcessBySelfFork(const std::string &srcEntry, const AppExecFwk::BundleInfo &bundleInfo); 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); }; 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 f3ee43064c..7fbcd0e40f 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 @@ -60,6 +60,17 @@ private: */ napi_value CreateJsInsightIntentContext(napi_env env, const std::shared_ptr& context); +/** + * Function of check startAbiliryParam parammeters. + * + * @param env, the napi environment. + * @param info, Indicates the parameters from js. + * @param want, the want of the ability to start. + * + * @return result of check startAbiliryParam parammeters. + */ +bool CheckStartAbilityParam(napi_env env, NapiCallbackInfo& info, AAFwk::Want want); + } // namespace AbilityRuntime } // namespace OHOS #endif // OHOS_ABILITY_RUNTIME_JS_INSIGHT_INTENT_CONTEXT_H diff --git a/interfaces/inner_api/napi_base_context/BUILD.gn b/interfaces/inner_api/napi_base_context/BUILD.gn index a3bc3d2821..def1216d0c 100644 --- a/interfaces/inner_api/napi_base_context/BUILD.gn +++ b/interfaces/inner_api/napi_base_context/BUILD.gn @@ -27,6 +27,12 @@ ohos_shared_library("napi_base_context") { external_deps = [ "napi:ace_napi" ] + public_external_deps = [ + "form_fwk:form_manager", + "window_manager:libdm", + "window_manager:libwm", + ] + innerapi_tags = [ "platformsdk" ] subsystem_name = "ability" part_name = "ability_runtime" diff --git a/interfaces/inner_api/quick_fix/src/quick_fix_manager_client.cpp b/interfaces/inner_api/quick_fix/src/quick_fix_manager_client.cpp index 5a1e0f6865..deeeda3c1b 100644 --- a/interfaces/inner_api/quick_fix/src/quick_fix_manager_client.cpp +++ b/interfaces/inner_api/quick_fix/src/quick_fix_manager_client.cpp @@ -78,6 +78,7 @@ int32_t QuickFixManagerClient::GetApplyedQuickFixInfo(const std::string &bundleN sptr QuickFixManagerClient::GetQuickFixMgrProxy() { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::QUICKFIX, "function called."); auto quickFixMgr = GetQuickFixMgr(); if (quickFixMgr != nullptr) { @@ -143,11 +144,13 @@ void QuickFixManagerClient::QfmsDeathRecipient::OnRemoteDied([[maybe_unused]] co bool QuickFixManagerClient::LoadQuickFixMgrService() { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); { std::unique_lock lock(loadSaMutex_); loadSaFinished_ = false; } + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "GetSystemAbilityManager"); auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (systemAbilityMgr == nullptr) { TAG_LOGE(AAFwkTag::QUICKFIX, "Failed to get SystemAbilityManager."); diff --git a/interfaces/inner_api/runtime/include/runtime.h b/interfaces/inner_api/runtime/include/runtime.h index 64b9a3459c..9282b92cfd 100644 --- a/interfaces/inner_api/runtime/include/runtime.h +++ b/interfaces/inner_api/runtime/include/runtime.h @@ -60,6 +60,7 @@ public: bool isStageModel = true; bool isTestFramework = false; bool jitEnabled = false; + bool isMultiThread = false; int32_t uid = -1; // ArkTsCard start bool isUnique = false; @@ -71,10 +72,11 @@ public: }; struct DebugOption { + std::string bundleName = ""; std::string perfCmd; - bool isStartWithDebug = false; std::string processName = ""; bool isDebugApp = true; + bool isStartWithDebug = false; bool isStartWithNative = false; }; diff --git a/interfaces/inner_api/wantagent/BUILD.gn b/interfaces/inner_api/wantagent/BUILD.gn index ab4a2a6405..04aa0574bf 100644 --- a/interfaces/inner_api/wantagent/BUILD.gn +++ b/interfaces/inner_api/wantagent/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Copyright (c) 2021-2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -36,7 +36,6 @@ config("wantagent_innerkits_public_config") { "${ability_runtime_innerkits_path}/wantagent/include", "${ability_runtime_services_path}/abilitymgr/include", "${ability_runtime_innerkits_path}/app_manager/include/appmgr", - "${bundlefwk_inner_api_path}/appexecfwk_core/include/bundlemgr", "${ability_runtime_path}/interfaces/kits/native/appkit/app", "${ability_runtime_path}/interfaces/kits/native/appkit", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime", @@ -77,12 +76,15 @@ ohos_shared_library("wantagent_innerkits") { "bundle_framework:appexecfwk_core", "c_utils:utils", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_core", "napi:ace_napi", "samgr:samgr_proxy", ] + public_external_deps = [ "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "eventhandler:libeventhandler", "icu:shared_icuuc", "image_framework:image_native", diff --git a/interfaces/inner_api/wantagent/src/pending_want.cpp b/interfaces/inner_api/wantagent/src/pending_want.cpp index 07fbb2d02d..2ddae5cf3c 100644 --- a/interfaces/inner_api/wantagent/src/pending_want.cpp +++ b/interfaces/inner_api/wantagent/src/pending_want.cpp @@ -18,6 +18,7 @@ #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" #include "want_sender_info.h" @@ -431,6 +432,7 @@ ErrCode PendingWant::GetBundleName(const sptr &target, std:: std::shared_ptr PendingWant::GetWant(const sptr &target) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::shared_ptr want = std::make_shared(); int ret = WantAgentClient::GetInstance().GetPendingRequestWant(target, want); return ret ? nullptr : want; diff --git a/interfaces/inner_api/wantagent/src/want_agent_client.cpp b/interfaces/inner_api/wantagent/src/want_agent_client.cpp index 2a8603eb60..35eae4bb08 100644 --- a/interfaces/inner_api/wantagent/src/want_agent_client.cpp +++ b/interfaces/inner_api/wantagent/src/want_agent_client.cpp @@ -21,6 +21,7 @@ #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" #include "system_ability_definition.h" @@ -261,6 +262,7 @@ void WantAgentClient::UnregisterCancelListener( ErrCode WantAgentClient::GetPendingRequestWant(const sptr &target, std::shared_ptr &want) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); CHECK_POINTER_AND_RETURN(target, ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_WANTAGENT); CHECK_POINTER_AND_RETURN(want, INVALID_PARAMETERS_ERR); auto abms = GetAbilityManager(); @@ -340,6 +342,7 @@ ErrCode WantAgentClient::GetWantSenderInfo(const sptr &target, std: sptr WantAgentClient::GetAbilityManager() { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard lock(mutex_); if (proxy_ == nullptr) { auto systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); diff --git a/interfaces/inner_api/wantagent/src/want_agent_helper.cpp b/interfaces/inner_api/wantagent/src/want_agent_helper.cpp index 63a63c0762..fa8da769b1 100644 --- a/interfaces/inner_api/wantagent/src/want_agent_helper.cpp +++ b/interfaces/inner_api/wantagent/src/want_agent_helper.cpp @@ -18,6 +18,7 @@ #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" #include "want_agent_client.h" @@ -295,6 +296,7 @@ ErrCode WantAgentHelper::GetUid(const std::shared_ptr &agent, int32_t std::shared_ptr WantAgentHelper::GetWant(const std::shared_ptr &agent) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (agent == nullptr) { TAG_LOGE(AAFwkTag::WANTAGENT, "WantAgentHelper::GetWant WantAgent invalid input param."); return nullptr; 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 36f62e6fbe..6182bbde15 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 @@ -144,6 +144,9 @@ enum class AbilityErrorCode { // invalid caller. ERROR_CODE_INVALID_CALLER = 16200001, + // Setting permissions for resident processes + ERROR_CODE_NO_RESIDENT_PERMISSION = 16200006, + // no such mission id. ERROR_CODE_NO_MISSION_ID = 16300001, diff --git a/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_base.h b/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_base.h index b7a59997d9..053a52a5f3 100644 --- a/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_base.h +++ b/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_base.h @@ -151,8 +151,8 @@ public: */ void SetContext(const std::shared_ptr &context) override; -private: - void BindContext(napi_env env, napi_value obj); + void BindContext() override; +protected: napi_value CallObjectMethod(const char *name, napi_value const *argv = nullptr, size_t argc = 0); void ForegroundWindow(const AAFwk::Want &want, const sptr &sessionInfo); void BackgroundWindow(const sptr &sessionInfo); @@ -168,15 +168,16 @@ private: void PostInsightIntentExecuted(const sptr &sessionInfo, const AppExecFwk::InsightIntentExecuteResult &result, bool needForeground); +protected: JsRuntime &jsRuntime_; - std::unique_ptr jsObj_; std::shared_ptr shellContextRef_; + std::unique_ptr jsObj_; + std::shared_ptr context_; std::map> uiWindowMap_; std::set foregroundWindows_; std::map> contentSessions_; std::shared_ptr abilityResultListeners_ = nullptr; std::shared_ptr abilityInfo_; - std::shared_ptr context_; sptr token_ = nullptr; }; } // namespace AbilityRuntime diff --git a/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_content_session.h b/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_content_session.h index 921f17cadb..0b893cff20 100644 --- a/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_content_session.h +++ b/interfaces/kits/native/ability/native/ui_extension_ability/js_ui_extension_content_session.h @@ -117,6 +117,8 @@ protected: napi_env env, NapiCallbackInfo& info, std::shared_ptr &innerErrorCode); void StartAbilityForResultRuntimeTask(napi_env env, AAFwk::Want &want, std::shared_ptr asyncTask, size_t& unwrapArgc, AAFwk::StartOptions startOptions); + bool CheckStartAbilityByTypeParam(napi_env env, NapiCallbackInfo& info, std::string type, + AAFwk::WantParams wantParam); private: sptr sessionInfo_; 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 bc8617201e..a541015e50 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 @@ -55,8 +55,9 @@ protected: virtual napi_value OnReportDrawnCompleted(napi_env env, NapiCallbackInfo& info); virtual napi_value OnOpenAtomicService(napi_env env, NapiCallbackInfo& info); -private: +protected: std::weak_ptr context_; +private: sptr freeInstallObserver_ = nullptr; friend class JsEmbeddableUIAbilityContext; diff --git a/interfaces/kits/native/ability/native/ui_extension_ability/ui_extension_base_impl.h b/interfaces/kits/native/ability/native/ui_extension_ability/ui_extension_base_impl.h index 3a24798167..15d606939b 100644 --- a/interfaces/kits/native/ability/native/ui_extension_ability/ui_extension_base_impl.h +++ b/interfaces/kits/native/ability/native/ui_extension_ability/ui_extension_base_impl.h @@ -57,6 +57,8 @@ public: virtual void SetAbilityInfo(const std::shared_ptr &abilityInfo) = 0; virtual void SetContext(const std::shared_ptr &context) = 0; + + virtual void BindContext() = 0; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/interfaces/kits/native/appkit/ability_runtime/context/context.h b/interfaces/kits/native/appkit/ability_runtime/context/context.h index 2970ed81ca..f42bb51564 100644 --- a/interfaces/kits/native/appkit/ability_runtime/context/context.h +++ b/interfaces/kits/native/appkit/ability_runtime/context/context.h @@ -23,7 +23,7 @@ #include "bindable.h" #include "configuration.h" #include "hap_module_info.h" -#include "foundation/communication/ipc/interfaces/innerkits/ipc_core/include/iremote_object.h" +#include "iremote_object.h" #include "resource_manager.h" using IRemoteObject = OHOS::IRemoteObject; diff --git a/interfaces/kits/native/appkit/app_startup/js_startup_task.h b/interfaces/kits/native/appkit/app_startup/js_startup_task.h index 9ad76f39e7..592b056432 100644 --- a/interfaces/kits/native/appkit/app_startup/js_startup_task.h +++ b/interfaces/kits/native/appkit/app_startup/js_startup_task.h @@ -17,6 +17,7 @@ #define OHOS_ABILITY_RUNTIME_JS_STARTUP_TASK_H #include "js_runtime.h" +#include "js_runtime_utils.h" #include "js_startup_task_executor.h" #include "js_startup_task_result.h" #include "startup_task.h" @@ -24,6 +25,16 @@ namespace OHOS { namespace AbilityRuntime { +class AsyncTaskCallBack { +public: + AsyncTaskCallBack() = default; + ~AsyncTaskCallBack() = default; + + static napi_value AsyncTaskCompleted(napi_env env, napi_callback_info info); + static napi_value Constructor(napi_env env, napi_callback_info cbinfo); + static std::map> jsStartupTaskObjects_; +}; + class JsStartupTask : public StartupTask { public: JsStartupTask(const std::string &name, JsRuntime &jsRuntime, @@ -38,10 +49,19 @@ public: int32_t RunTaskOnDependencyCompleted(const std::string &dependencyName, const std::shared_ptr &result) override; + int32_t LoadJsAsyncTaskExcutor(); + + void LoadJsAsyncTaskCallback(); + + void OnAsyncTaskCompleted() override; + private: JsRuntime &jsRuntime_; std::unique_ptr startupJsRef_; std::shared_ptr contextJsRef_; + std::unique_ptr AsyncTaskExcutorJsRef_; + std::unique_ptr AsyncTaskExcutorCallbackJsRef_; + std::unique_ptr startupTaskResultCallback_; static napi_value GetDependencyResult(napi_env env, const std::string &dependencyName, const std::shared_ptr &result); diff --git a/interfaces/kits/native/appkit/app_startup/js_startup_task_executor.h b/interfaces/kits/native/appkit/app_startup/js_startup_task_executor.h index 08d6939e20..dab0aab370 100644 --- a/interfaces/kits/native/appkit/app_startup/js_startup_task_executor.h +++ b/interfaces/kits/native/appkit/app_startup/js_startup_task_executor.h @@ -29,8 +29,11 @@ public: std::unique_ptr callback); static int32_t RunOnTaskPool(JsRuntime &jsRuntime, - const std::unique_ptr &startup, const std::shared_ptr &context, - std::unique_ptr callback); + const std::unique_ptr &startup, + const std::shared_ptr &context, + const std::unique_ptr &asynctaskexcutor, + const std::unique_ptr &asyncTaskCallback, + const std::string &startupName); private: static int32_t CallStartupInit(napi_env env, const std::unique_ptr &startup, diff --git a/interfaces/kits/native/appkit/app_startup/startup_task.h b/interfaces/kits/native/appkit/app_startup/startup_task.h index aaae7d5ec9..dbc881571a 100644 --- a/interfaces/kits/native/appkit/app_startup/startup_task.h +++ b/interfaces/kits/native/appkit/app_startup/startup_task.h @@ -75,6 +75,8 @@ public: void CallExtraCallback(const std::shared_ptr &result); + virtual void OnAsyncTaskCompleted() = 0; + protected: std::string name_; std::vector dependencies_; diff --git a/service_router_framework/services/srms/test/unittest/service_router_mgr_interface_test/srms_interface_test.cpp b/service_router_framework/services/srms/test/unittest/service_router_mgr_interface_test/srms_interface_test.cpp index 798161103a..ee661879ce 100755 --- a/service_router_framework/services/srms/test/unittest/service_router_mgr_interface_test/srms_interface_test.cpp +++ b/service_router_framework/services/srms/test/unittest/service_router_mgr_interface_test/srms_interface_test.cpp @@ -23,6 +23,7 @@ #include "appexecfwk_errors.h" #include "service_info.h" #include "service_router_data_mgr.h" +#include "service_router_mgr_proxy.h" #include "want.h" using namespace testing::ext; @@ -36,6 +37,8 @@ const std::string WRONG_BUNDLE_NAME = "wrong"; const std::string MIME_TYPE = "html"; const std::string BUNDLE_NAME = "bundleName"; const std::string PURPOSE_NAME = "pay"; +const int32_t ERR_COD1 = 8519924; +const int32_t ERR_COD2 = 8388613; } // namespace class ServiceRouterMgrInterfaceTest : public testing::Test { @@ -387,4 +390,71 @@ HWTEST_F(ServiceRouterMgrInterfaceTest, ServiceRouterMgrInterfaceTest_0019, Func auto ret = info.ReadFromParcel(parcel); EXPECT_TRUE(ret); } + +/** + * @tc.number: serviceRouterMgrProxy + * @tc.name: test QueryBusinessAbilityInfos + * @tc.require: I9KS48 + * @tc.desc: QueryBusinessAbilityInfos + */ +HWTEST_F(ServiceRouterMgrInterfaceTest, serviceRouterMgrProxy_0001, Function | SmallTest | Level0) +{ + auto serviceRouterMgrProxy = std::make_shared(nullptr); + EXPECT_NE(serviceRouterMgrProxy, nullptr); + BusinessAbilityFilter filter; + filter.businessType = BusinessType::UNSPECIFIED; + std::vector abilityInfos; + auto ret = serviceRouterMgrProxy->QueryBusinessAbilityInfos(filter, abilityInfos); + EXPECT_EQ(ret, ERR_COD1); +} + +/** + * @tc.number: serviceRouterMgrProxy + * @tc.name: test QueryPurposeInfos + * @tc.require: I9KS48 + * @tc.desc: QueryPurposeInfos + */ +HWTEST_F(ServiceRouterMgrInterfaceTest, serviceRouterMgrProxy_0002, Function | SmallTest | Level0) +{ + auto serviceRouterMgrProxy = std::make_shared(nullptr); + EXPECT_NE(serviceRouterMgrProxy, nullptr); + Want want; + std::vector purposeInfos; + auto ret = serviceRouterMgrProxy->QueryPurposeInfos(want, "", purposeInfos); + EXPECT_EQ(ret, ERR_COD1); +} + +/** + * @tc.number: serviceRouterMgrProxy + * @tc.name: test StartUIExtensionAbility + * @tc.require: I9KS48 + * @tc.desc: StartUIExtensionAbility + */ +HWTEST_F(ServiceRouterMgrInterfaceTest, serviceRouterMgrProxy_0003, Function | SmallTest | Level0) +{ + auto serviceRouterMgrProxy = std::make_shared(nullptr); + EXPECT_NE(serviceRouterMgrProxy, nullptr); + sptr sessionInfo = nullptr; + int32_t userId = 1; + auto ret = serviceRouterMgrProxy->StartUIExtensionAbility(sessionInfo, userId); + EXPECT_EQ(ret, ERR_COD1); +} + +/** + * @tc.number: serviceRouterMgrProxy + * @tc.name: test ConnectUIExtensionAbility + * @tc.require: I9KS48 + * @tc.desc: ConnectUIExtensionAbility + */ +HWTEST_F(ServiceRouterMgrInterfaceTest, serviceRouterMgrProxy_0004, Function | SmallTest | Level0) +{ + auto serviceRouterMgrProxy = std::make_shared(nullptr); + EXPECT_NE(serviceRouterMgrProxy, nullptr); + Want want; + sptr connect = nullptr; + sptr sessionInfo = nullptr; + int32_t userId = 1; + auto ret = serviceRouterMgrProxy->ConnectUIExtensionAbility(want, connect, sessionInfo, userId); + EXPECT_EQ(ret, ERR_COD2); +} } // OHOS \ No newline at end of file diff --git a/services/abilitymgr/BUILD.gn b/services/abilitymgr/BUILD.gn index c6a540e04c..6be6dab5dc 100644 --- a/services/abilitymgr/BUILD.gn +++ b/services/abilitymgr/BUILD.gn @@ -30,6 +30,7 @@ config("abilityms_exception_config") { config("abilityms_config") { include_dirs = [ "include/", + "include/rdb/", "${ability_runtime_innerkits_path}/ability_manager/include", "${ability_runtime_services_path}/appdfr/include", "${ability_runtime_innerkits_path}/app_manager/include", @@ -191,8 +192,6 @@ ohos_shared_library("abilityms") { } if (ability_runtime_graphics) { - deps += [] - external_deps += [ "ability_base:session_info", "i18n:intl_util", @@ -233,9 +232,16 @@ ohos_prebuilt_etc("proxy_authorization_uri.json") { part_name = "ability_runtime" } +ohos_prebuilt_etc("deeplink_reserve_config.json") { + source = "resource/deeplink_reserve_config.json" + subsystem_name = "ability" + part_name = "ability_runtime" +} + group("ams_service_config") { deps = [ ":ams_service_config.json", + ":deeplink_reserve_config.json", ":proxy_authorization_uri.json", ":uiextension_picker_config.json", ] diff --git a/services/abilitymgr/abilitymgr.gni b/services/abilitymgr/abilitymgr.gni index cd46802089..0594e38f2d 100644 --- a/services/abilitymgr/abilitymgr.gni +++ b/services/abilitymgr/abilitymgr.gni @@ -95,6 +95,9 @@ abilityms_files = [ "src/mission_listener_controller.cpp", "src/mission_listener_proxy.cpp", "src/mission_listener_stub.cpp", + "src/rdb/ability_resident_process_rdb.cpp", + "src/rdb/parser_util.cpp", + "src/rdb/rdb_data_manager.cpp", "src/remote_mission_listener_proxy.cpp", "src/remote_mission_listener_stub.cpp", "src/mission_list_manager.cpp", @@ -102,6 +105,7 @@ abilityms_files = [ "src/scene_board/status_bar_delegate_manager.cpp", "src/scene_board/ui_ability_lifecycle_manager.cpp", "src/open_link/open_link_options.cpp", + "src/deeplink_reserve/deeplink_reserve.cpp", #connection observer "src/connection_observer_controller.cpp", diff --git a/services/abilitymgr/include/ability_connect_manager.h b/services/abilitymgr/include/ability_connect_manager.h index b406ee3af0..ec1aef3b2a 100644 --- a/services/abilitymgr/include/ability_connect_manager.h +++ b/services/abilitymgr/include/ability_connect_manager.h @@ -124,7 +124,7 @@ public: * @return Returns ERR_OK on success, others on failure. */ int UnloadUIExtension(const std::shared_ptr &abilityRecord, std::string &bundleName); - + /** * DisconnectAbilityLocked, disconnect session with callback. * @@ -466,14 +466,14 @@ private: * * @param connect, callback object. */ - void AddConnectDeathRecipient(const sptr &connect); + void AddConnectDeathRecipient(sptr connectObject); /** * RemoteConnectDeathRecipient. * * @param connect, callback object. */ - void RemoveConnectDeathRecipient(const sptr &connect); + void RemoveConnectDeathRecipient(sptr connectObject); /** * RemoteConnectDeathRecipient. @@ -525,7 +525,6 @@ private: void SaveUIExtRequestSessionInfo(std::shared_ptr abilityRecord, sptr sessionInfo); void DoBackgroundAbilityWindow(const std::shared_ptr &abilityRecord, const sptr &sessionInfo); - void DoTerminateUIExtensionAbility(std::shared_ptr abilityRecord, sptr sessionInfo); /** * When a service is under starting, enque the request and handle it after the service starting completes @@ -560,17 +559,14 @@ private: void TerminateRecord(std::shared_ptr abilityRecord); int DisconnectRecordNormal(ConnectListType &list, std::shared_ptr connectRecord) const; void DisconnectRecordForce(ConnectListType &list, std::shared_ptr connectRecord); - std::shared_ptr GetServiceRecordByElementNameInner(const std::string &element); - std::shared_ptr GetExtensionFromServiceMapInner(const sptr &token); - std::shared_ptr GetExtensionFromServiceMapInner(int32_t abilityRecordId); - std::shared_ptr GetExtensionFromTerminatingMapInner(const sptr &token); + std::shared_ptr GetExtensionByIdFromServiceMap(int32_t abilityRecordId); int TerminateAbilityInner(const sptr &token); bool IsLauncher(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); inline bool CheckUIExtensionAbilityLoaded(const AbilityRequest &abilityRequest); - inline bool CheckUIExtensionAbilitySessionExistLocked(const std::shared_ptr &abilityRecord); + inline bool CheckUIExtensionAbilitySessionExist(const std::shared_ptr &abilityRecord); inline void RemoveUIExtensionAbilityRecord(const std::shared_ptr &abilityRecord); inline void AddUIExtensionAbilityRecordToTerminatedList(const std::shared_ptr &abilityRecord); inline bool IsCallerValid(const std::shared_ptr &abilityRecord); @@ -583,27 +579,45 @@ private: EventInfo BuildEventInfo(const std::shared_ptr &abilityRecord); void UpdateUIExtensionInfo(const std::shared_ptr &abilityRecord); + bool AddToServiceMap(const std::string &key, std::shared_ptr abilityRecord); + ServiceMapType GetServiceMap(); + + void AddConnectObjectToMap(sptr connectObject, const ConnectListType &connectRecordList, + bool updateOnly); + private: const std::string TASK_ON_CALLBACK_DIED = "OnCallbackDiedTask"; const std::string TASK_ON_ABILITY_DIED = "OnAbilityDiedTask"; - ffrt::mutex Lock_; + std::mutex serialMutex_; + + std::mutex connectMapMutex_; ConnectMapType connectMap_; + + std::mutex serviceMapMutex_; ServiceMapType serviceMap_; ServiceMapType terminatingExtensionMap_; std::mutex recipientMapMutex_; RecipientMapType recipientMap_; - ffrt::mutex uiExtRecipientMapMutex_; + + std::mutex uiExtRecipientMapMutex_; RecipientMapType uiExtRecipientMap_; + std::shared_ptr taskHandler_; std::shared_ptr eventHandler_; int userId_; std::vector restartResidentTaskList_; + + std::mutex startServiceReqListLock_; std::unordered_map>> startServiceReqList_; - ffrt::mutex startServiceReqListLock_; + + std::mutex uiExtensionMapMutex_; UIExtensionMapType uiExtensionMap_; + + std::mutex windowExtensionMapMutex_; WindowExtensionMapType windowExtensionMap_; + std::unique_ptr uiExtensionAbilityRecordMgr_ = nullptr; uint32_t sceneBoardTokenId_ = 0; diff --git a/services/abilitymgr/include/ability_manager_proxy.h b/services/abilitymgr/include/ability_manager_proxy.h index 68e158777b..fdd8ecd489 100644 --- a/services/abilitymgr/include/ability_manager_proxy.h +++ b/services/abilitymgr/include/ability_manager_proxy.h @@ -1197,6 +1197,15 @@ public: */ virtual bool IsEmbeddedOpenAllowed(sptr callerToken, const std::string &appId) override; + /** + * Set the enable status for starting and stopping resident processes. + * The caller application can only set the resident status of the configured process. + * @param bundleName The bundle name of the resident process. + * @param enable Set resident process enable status. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t SetResidentProcessEnabled(const std::string &bundleName, bool enable) override; + /** * @brief Request to display assert fault dialog. * @param callback Listen for user operation callbacks. diff --git a/services/abilitymgr/include/ability_manager_service.h b/services/abilitymgr/include/ability_manager_service.h index 77c20f3ece..77a2345c8f 100644 --- a/services/abilitymgr/include/ability_manager_service.h +++ b/services/abilitymgr/include/ability_manager_service.h @@ -44,6 +44,7 @@ #include "bundle_constants.h" #include "bundle_mgr_helper.h" #include "data_ability_manager.h" +#include "deeplink_reserve/deeplink_reserve.h" #include "event_report.h" #include "free_install_manager.h" #include "hilog_wrapper.h" @@ -1615,6 +1616,15 @@ public: int32_t GetUIExtensionRootHostInfo(const sptr token, UIExtensionHostInfo &hostInfo, 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. + * @param bundleName The bundle name of the resident process. + * @param enable Set resident process enable status. + * @return Returns ERR_OK on success, others on failure. + */ + int32_t SetResidentProcessEnabled(const std::string &bundleName, bool enable) override; + /** * @brief Restart app self. * @param want The ability type must be UIAbility. @@ -2097,6 +2107,7 @@ private: void InitInterceptor(); void InitPushTask(); + void InitDeepLinkReserve(); bool CheckSenderWantInfo(int32_t callerUid, const WantSenderInfo &wantSenderInfo); @@ -2201,6 +2212,8 @@ private: void CloseAssertDialog(const std::string &assertSessionId); + void SetReserveInfo(const std::string &linkString); + #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE std::shared_ptr bgtaskObserver_; #endif @@ -2219,6 +2232,7 @@ private: #endif std::shared_ptr interceptorExecuter_; std::shared_ptr afterCheckExecuter_; + std::shared_ptr deepLinkReserveConfig_; std::unordered_map appRecoveryHistory_; // uid:time bool isPrepareTerminateEnable_ = false; diff --git a/services/abilitymgr/include/ability_manager_stub.h b/services/abilitymgr/include/ability_manager_stub.h index 7be05d6ee1..58c0e0b69c 100644 --- a/services/abilitymgr/include/ability_manager_stub.h +++ b/services/abilitymgr/include/ability_manager_stub.h @@ -244,6 +244,7 @@ private: int32_t ForceExitAppInner(MessageParcel &data, MessageParcel &reply); int32_t RecordAppExitReasonInner(MessageParcel &data, MessageParcel &reply); int32_t RecordProcessExitReasonInner(MessageParcel &data, MessageParcel &reply); + int32_t SetResidentProcessEnableInner(MessageParcel &data, MessageParcel &reply); int SetRootSceneSessionInner(MessageParcel &data, MessageParcel &reply); int CallUIAbilityBySCBInner(MessageParcel &data, MessageParcel &reply); diff --git a/services/abilitymgr/include/ability_record.h b/services/abilitymgr/include/ability_record.h index 0cdaa482db..c017f6202f 100644 --- a/services/abilitymgr/include/ability_record.h +++ b/services/abilitymgr/include/ability_record.h @@ -852,7 +852,6 @@ public: void SetRestarting(const bool isRestart, int32_t canReStartCount); int32_t GetRestartCount() const; void SetRestartCount(int32_t restartCount); - void SetKeepAlive(); bool GetKeepAlive() const; void SetLoading(bool status); bool IsLoading() const; @@ -1092,7 +1091,6 @@ private: bool isWindowStarted_ = false; // is window hotstart or coldstart? bool isWindowAttached_ = false; // Is window of this ability attached? bool isLauncherAbility_ = false; // is launcher? - bool isKeepAlive_ = false; // is keep alive or resident ability? sptr scheduler_ = {}; // kit scheduler bool isLoading_ = false; // is loading? diff --git a/services/abilitymgr/include/app_scheduler.h b/services/abilitymgr/include/app_scheduler.h index 64fc9fccbe..9ef6ff0c3e 100644 --- a/services/abilitymgr/include/app_scheduler.h +++ b/services/abilitymgr/include/app_scheduler.h @@ -73,6 +73,7 @@ struct AppInfo { std::vector appData; std::string processName; AppState state; + pid_t pid = 0; }; /** * @class AppStateCallback diff --git a/services/abilitymgr/include/deeplink_reserve/deeplink_reserve.h b/services/abilitymgr/include/deeplink_reserve/deeplink_reserve.h new file mode 100644 index 0000000000..cb19ba259e --- /dev/null +++ b/services/abilitymgr/include/deeplink_reserve/deeplink_reserve.h @@ -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. + */ + +#ifndef OHOS_ABILITY_RUNTIME_DEEPLINK_RESERVE_H +#define OHOS_ABILITY_RUNTIME_DEEPLINK_RESERVE_H + +#include +#include +#include + +#include "singleton.h" + +namespace OHOS { +namespace AAFwk { + +struct ReserveUri { + std::string scheme; + std::string host; + std::string port; + std::string path; + std::string pathStartWith; + std::string pathRegex; + std::string type; + std::string utd; +}; + +class DeepLinkReserveConfig : public DelayedSingleton { +public: + DeepLinkReserveConfig() = default; + virtual ~DeepLinkReserveConfig() = default; + bool LoadConfiguration(); + bool isLinkReserved(const std::string &linkString, std::string &bundleName); +private: + std::string GetConfigPath(); + bool ReadFileInfoJson(const std::string &filePath, nlohmann::json &jsonBuf); + bool LoadReservedUriList(const nlohmann::json &object); + bool isUriMatched(const ReserveUri &reservedUri, const std::string &link); + void LoadReservedUrilItem(const nlohmann::json &jsonUriObject, std::vector &uriList); + + std::map> deepLinkReserveUris_; +}; +} // OHOS +} // AAFwk + +#endif // OHOS_ABILITY_RUNTIME_DEEPLINK_RESERVE_H + diff --git a/services/abilitymgr/include/implicit_start_processor.h b/services/abilitymgr/include/implicit_start_processor.h index 110c380aea..b61ecf71b7 100644 --- a/services/abilitymgr/include/implicit_start_processor.h +++ b/services/abilitymgr/include/implicit_start_processor.h @@ -65,6 +65,10 @@ public: 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); @@ -98,12 +102,17 @@ private: void SetTargetLinkInfo(const std::vector &skillUri, Want &want); + void OnlyKeepReserveApp(std::vector &abilityInfos, + std::vector &extensionInfos); + private: const static std::vector blackList; const static std::unordered_set extensionWhiteList; std::shared_ptr iBundleManagerHelper_; ffrt::mutex identityListLock_; std::list identityList_; + bool uriReservedFlag_ = false; + std::string reservedBundleName_; }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/include/rdb/ability_resident_process_rdb.h b/services/abilitymgr/include/rdb/ability_resident_process_rdb.h new file mode 100644 index 0000000000..9fdff34c4b --- /dev/null +++ b/services/abilitymgr/include/rdb/ability_resident_process_rdb.h @@ -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. + */ + +#ifndef OHOS_ABILITY_RUNTIME_RDB_ABILITY_RESIDENT_PROCESS_RDB_H +#define OHOS_ABILITY_RUNTIME_RDB_ABILITY_RESIDENT_PROCESS_RDB_H + +#include "rdb_data_manager.h" + +namespace OHOS { +namespace AbilityRuntime { +enum RdbResult : int32_t { + Rdb_OK = 0, + /* Representative database initialization failed */ + Rdb_Init_Err, + /* Failed to parse initialization file */ + Rdb_Parse_File_Err, + /* Parameter check failed */ + Rdb_Parameter_Err, + /* Failed to query permission settings for resident processes */ + Rdb_Permissions_Err, + /* Database query failed, key may not exist */ + Rdb_Search_Record_Err +}; + +class ScopeGuard final { +public: + using Function = std::function; + explicit ScopeGuard(Function fn) : fn_(fn), dismissed(false) {} + + ~ScopeGuard() + { + if (!dismissed) { + fn_(); + } + } + + void Dismiss() + { + dismissed = true; + } + +private: + Function fn_; + bool dismissed; +}; + +class AmsResidentProcessRdbCallBack : public NativeRdb::RdbOpenCallback { +public: + AmsResidentProcessRdbCallBack(const AmsRdbConfig &rdbConfig); + int32_t OnCreate(NativeRdb::RdbStore &rdbStore) override; + int32_t OnUpgrade(NativeRdb::RdbStore &rdbStore, int currentVersion, int targetVersion) override; + int32_t OnDowngrade(NativeRdb::RdbStore &rdbStore, int currentVersion, int targetVersion) override; + int32_t OnOpen(NativeRdb::RdbStore &rdbStore) override; + int32_t onCorruption(std::string databaseFile) override; + +private: + AmsRdbConfig rdbConfig_; +}; + +class AmsResidentProcessRdb final { +public: + AmsResidentProcessRdb() {} + ~AmsResidentProcessRdb() {} + static AmsResidentProcessRdb &GetInstance(); + int32_t Init(); + int32_t VerifyConfigurationPermissions(const std::string &bundleName, const std::string &callerName); + int32_t GetResidentProcessEnable(const std::string &bundleName, bool &enable); + int32_t UpdateResidentProcessEnable(const std::string &bundleName, bool enable); + int32_t RemoveData(std::string &bundleName); + +private: + bool ready = false; + std::unique_ptr rdbMgr_ = nullptr; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_RDB_ABILITY_RESIDENT_PROCESS_RDB_H \ No newline at end of file diff --git a/services/abilitymgr/include/rdb/parser_util.h b/services/abilitymgr/include/rdb/parser_util.h new file mode 100644 index 0000000000..e949b830c7 --- /dev/null +++ b/services/abilitymgr/include/rdb/parser_util.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_ABILITY_RUNTIME_RDB_PARSER_UTIL_H +#define OHOS_ABILITY_RUNTIME_RDB_PARSER_UTIL_H + +#include +#include +#include + +namespace OHOS { +namespace AbilityRuntime { +/* This class is used to parse the resident process information section in files(install_list_capability.json) */ +class ParserUtil final { +public: + static ParserUtil &GetInstance(); + void GetResidentProcessRawData(std::vector> &list); + +private: + void ParsePreInstallAbilityConfig( + const std::string &filePath, std::vector> &list); + void GetPreInstallRootDirList(std::vector &rootDirList); + bool ReadFileIntoJson(const std::string &filePath, nlohmann::json &jsonBuf); + bool FilterInfoFromJson( + nlohmann::json &jsonBuf, std::vector> &list); +}; +} // namespace AbilityRuntime +} // namespace OHOS + +#endif // OHOS_ABILITY_RUNTIME_RDB_PARSER_UTIL_H \ No newline at end of file diff --git a/services/abilitymgr/include/rdb/rdb_data_manager.h b/services/abilitymgr/include/rdb/rdb_data_manager.h new file mode 100644 index 0000000000..b47582d4fc --- /dev/null +++ b/services/abilitymgr/include/rdb/rdb_data_manager.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_ABILITY_RUNTIME_RDB_RDB_DATA_MANAGER_H +#define OHOS_ABILITY_RUNTIME_RDB_RDB_DATA_MANAGER_H + +#include +#include +#include + +#include "rdb_helper.h" +#include "rdb_open_callback.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr static const char *ABILITY_RDB_NAME = "/ability_manager_service.db"; +constexpr static const char *ABILITY_RDB_PATH = "/data/service/el1/public/database/ability_manager_service"; +constexpr static int32_t ABILITY_RDB_VERSION = 1; +} // namespace + +struct AmsRdbConfig { + std::string dbPath{ ABILITY_RDB_PATH }; + std::string dbName{ ABILITY_RDB_NAME }; + std::string tableName; + std::string journalMode; + std::string syncMode; + int32_t version{ ABILITY_RDB_VERSION }; +}; + +class RdbDataManager final { +public: + RdbDataManager(const AmsRdbConfig &rdbConfig) : amsRdbConfig_(rdbConfig) {} + ~RdbDataManager() {} + + int32_t Init(NativeRdb::RdbOpenCallback &rdbCallback); + + int32_t InsertData(const NativeRdb::ValuesBucket &valuesBucket); + int32_t BatchInsert(int64_t &outInsertNum, const std::vector &valuesBuckets); + int32_t UpdateData( + const NativeRdb::ValuesBucket &valuesBucket, const NativeRdb::AbsRdbPredicates &absRdbPredicates); + int32_t DeleteData(const NativeRdb::AbsRdbPredicates &absRdbPredicates); + std::shared_ptr QueryData(const NativeRdb::AbsRdbPredicates &absRdbPredicates); + void ClearCache(); + +private: + std::mutex rdbMutex_; + std::shared_ptr rdbStore_; + AmsRdbConfig amsRdbConfig_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_RDB_RDB_DATA_MANAGER_H \ No newline at end of file diff --git a/services/abilitymgr/include/resident_process_manager.h b/services/abilitymgr/include/resident_process_manager.h index 787dbb3845..dbae052f40 100644 --- a/services/abilitymgr/include/resident_process_manager.h +++ b/services/abilitymgr/include/resident_process_manager.h @@ -29,11 +29,29 @@ namespace AAFwk { class ResidentProcessManager : public std::enable_shared_from_this { DECLARE_DELAYED_SINGLETON(ResidentProcessManager) public: + + /** + * Handle tasks such as initializing databases. + * + */ + void Init(); + + /** + * Set the enable flag for resident processes. + * + * @param bundleName, The bundle name of the resident process. + * @param callerName, The name of the caller, usually the system application. + * @param updateEnable, Set value, if true, start the resident process, If false, stop the resident process + * @return Returns ERR_OK on success, others on failure. + */ + int32_t SetResidentProcessEnabled(const std::string &bundleName, const std::string &callerName, bool updateEnable); void StartResidentProcess(const std::vector &bundleInfos); void StartResidentProcessWithMainElement(std::vector &bundleInfos); + void OnAppStateChanged(const AppInfo &info); private: bool CheckMainElement(const AppExecFwk::HapModuleInfo &hapModuleInfo, const std::string &processName, std::string &mainElement, std::set &needEraseIndexSet, size_t bundleInfoIndex); + void UpdateResidentProcessesStatus(const std::string &bundleName, bool localEnable, bool updateEnable); }; } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/resource/deeplink_reserve_config.json b/services/abilitymgr/resource/deeplink_reserve_config.json new file mode 100644 index 0000000000..e69de29bb2 diff --git a/services/abilitymgr/src/ability_connect_manager.cpp b/services/abilitymgr/src/ability_connect_manager.cpp index 58decf0bf7..536d634897 100644 --- a/services/abilitymgr/src/ability_connect_manager.cpp +++ b/services/abilitymgr/src/ability_connect_manager.cpp @@ -22,6 +22,7 @@ #include "ability_connect_callback_stub.h" #include "ability_manager_errors.h" #include "ability_manager_service.h" +#include "ability_resident_process_rdb.h" #include "ability_util.h" #include "appfreeze_manager.h" #include "app_exit_reason_data_manager.h" @@ -149,7 +150,12 @@ bool IsInKeepAliveList(const AppExecFwk::AbilityInfo &abilityInfo) GetKeepAliveAbilities(); for (const auto &pair : g_keepAliveAbilities) { if (abilityInfo.bundleName == pair.first && abilityInfo.name == pair.second) { - return true; + // Fault tolerance processing, originally returning true here + bool keepAliveEnable = true; + AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(abilityInfo.bundleName, keepAliveEnable); + TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s get keep alive enable: %{public}d", + abilityInfo.bundleName.c_str(), static_cast(keepAliveEnable)); + return keepAliveEnable; } } return false; @@ -166,19 +172,19 @@ AbilityConnectManager::~AbilityConnectManager() int AbilityConnectManager::StartAbility(const AbilityRequest &abilityRequest) { - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); return StartAbilityLocked(abilityRequest); } int AbilityConnectManager::TerminateAbility(const sptr &token) { - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); return TerminateAbilityInner(token); } int AbilityConnectManager::TerminateAbilityInner(const sptr &token) { - auto abilityRecord = GetExtensionFromServiceMapInner(token); + auto abilityRecord = GetExtensionByTokenFromServiceMap(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); std::string element = abilityRecord->GetURI(); TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ability, ability is %{public}s.", element.c_str()); @@ -201,7 +207,7 @@ int AbilityConnectManager::TerminateAbilityInner(const sptr &toke int AbilityConnectManager::StopServiceAbility(const AbilityRequest &abilityRequest) { TAG_LOGI(AAFwkTag::ABILITYMGR, "call"); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); return StopServiceAbilityLocked(abilityRequest); } @@ -238,7 +244,10 @@ int AbilityConnectManager::StartAbilityLocked(const AbilityRequest &abilityReque if (IsUIExtensionAbility(targetService) && abilityRequest.sessionInfo && abilityRequest.sessionInfo->sessionToken) { auto &remoteObj = abilityRequest.sessionInfo->sessionToken; - uiExtensionMap_[remoteObj] = UIExtWindowMapValType(targetService, abilityRequest.sessionInfo); + { + std::lock_guard guard(uiExtensionMapMutex_); + uiExtensionMap_[remoteObj] = UIExtWindowMapValType(targetService, abilityRequest.sessionInfo); + } AddUIExtWindowDeathRecipient(remoteObj); if (!isLoadedAbility) { SaveUIExtRequestSessionInfo(targetService, abilityRequest.sessionInfo); @@ -333,8 +342,7 @@ void AbilityConnectManager::SaveUIExtRequestSessionInfo(std::shared_ptrSetUIExtRequestSessionInfo(sessionInfo); - auto callback = [abilityRecord, connectManager = shared_from_this()]() { - std::lock_guard guard{connectManager->Lock_}; + auto callback = [abilityRecord]() { TAG_LOGE( AAFwkTag::ABILITYMGR, "consume session timeout, abilityUri: %{public}s", abilityRecord->GetURI().c_str()); abilityRecord->SetUIExtRequestSessionInfo(nullptr); @@ -382,7 +390,7 @@ int AbilityConnectManager::TerminateAbilityLocked(const sptr &tok { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); - auto abilityRecord = GetExtensionFromTerminatingMapInner(token); + auto abilityRecord = GetExtensionByTokenFromTerminatingMap(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); if (abilityRecord->IsTerminating()) { @@ -416,9 +424,9 @@ int AbilityConnectManager::StopServiceAbilityLocked(const AbilityRequest &abilit TAG_LOGI(AAFwkTag::ABILITYMGR, "call"); AppExecFwk::ElementName element(abilityRequest.abilityInfo.deviceId, abilityRequest.abilityInfo.bundleName, abilityRequest.abilityInfo.name, abilityRequest.abilityInfo.moduleName); - auto abilityRecord = GetServiceRecordByElementNameInner(element.GetURI()); + auto abilityRecord = GetServiceRecordByElementName(element.GetURI()); if (FRS_BUNDLE_NAME == abilityRequest.abilityInfo.bundleName) { - abilityRecord = GetServiceRecordByElementNameInner( + abilityRecord = GetServiceRecordByElementName( element.GetURI() + std::to_string(abilityRequest.want.GetIntParam(FRS_APP_INDEX, 0))); } CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); @@ -458,9 +466,8 @@ int32_t AbilityConnectManager::GetOrCreateExtensionRecord(const AbilityRequest & extensionRecord->SetURI(extensionRecordKey); TAG_LOGD(AAFwkTag::ABILITYMGR, "Service map add, hostBundleName:%{public}s, key: %{public}s", hostBundleName.c_str(), extensionRecordKey.c_str()); - serviceMap_.emplace(extensionRecordKey, extensionRecord); + AddToServiceMap(extensionRecordKey, extensionRecord); if (IsAbilityNeedKeepAlive(extensionRecord)) { - extensionRecord->SetKeepAlive(); extensionRecord->SetRestartTime(abilityRequest.restartTime); extensionRecord->SetRestartCount(abilityRequest.restartCount); } @@ -477,23 +484,23 @@ void AbilityConnectManager::GetOrCreateServiceRecord(const AbilityRequest &abili bool noReuse = UIExtensionUtils::IsWindowExtension(abilityRequest.abilityInfo.extensionAbilityType); AppExecFwk::ElementName element(abilityRequest.abilityInfo.deviceId, abilityRequest.abilityInfo.bundleName, abilityRequest.abilityInfo.name, abilityRequest.abilityInfo.moduleName); - auto serviceMapIter = serviceMap_.find(element.GetURI()); - std::string frsKey = ""; + std::string serviceKey = element.GetURI(); if (FRS_BUNDLE_NAME == abilityRequest.abilityInfo.bundleName) { - frsKey = element.GetURI() + std::to_string(abilityRequest.want.GetIntParam(FRS_APP_INDEX, 0)); - serviceMapIter = serviceMap_.find(frsKey); + serviceKey = element.GetURI() + std::to_string(abilityRequest.want.GetIntParam(FRS_APP_INDEX, 0)); } - if (noReuse && serviceMapIter != serviceMap_.end()) { - if (FRS_BUNDLE_NAME == abilityRequest.abilityInfo.bundleName) { - serviceMap_.erase(frsKey); - } else { - serviceMap_.erase(element.GetURI()); - } + { + std::lock_guard lock(serviceMapMutex_); + auto serviceMapIter = serviceMap_.find(serviceKey); + targetService = serviceMapIter == serviceMap_.end() ? nullptr : serviceMapIter->second; + } + if (noReuse && targetService) { if (IsSpecialAbility(abilityRequest.abilityInfo)) { TAG_LOGI(AAFwkTag::ABILITYMGR, "Removing ability: %{public}s", element.GetURI().c_str()); } + std::lock_guard lock(serviceMapMutex_); + serviceMap_.erase(serviceKey); } - if (noReuse || serviceMapIter == serviceMap_.end()) { + if (noReuse || targetService == nullptr) { targetService = AbilityRecord::CreateAbilityRecord(abilityRequest); if (targetService) { targetService->SetOwnerMissionUserId(userId_); @@ -504,22 +511,15 @@ void AbilityConnectManager::GetOrCreateServiceRecord(const AbilityRequest &abili } if (targetService && abilityRequest.abilityInfo.name == AbilityConfig::LAUNCHER_ABILITY_NAME) { targetService->SetLauncherRoot(); - targetService->SetKeepAlive(); targetService->SetRestartTime(abilityRequest.restartTime); targetService->SetRestartCount(abilityRequest.restartCount); } else if (IsAbilityNeedKeepAlive(targetService)) { - targetService->SetKeepAlive(); targetService->SetRestartTime(abilityRequest.restartTime); targetService->SetRestartCount(abilityRequest.restartCount); } - if (FRS_BUNDLE_NAME == abilityRequest.abilityInfo.bundleName) { - serviceMap_.emplace(frsKey, targetService); - } else { - serviceMap_.emplace(element.GetURI(), targetService); - } + AddToServiceMap(serviceKey, targetService); isLoadedAbility = false; } else { - targetService = serviceMapIter->second; isLoadedAbility = true; } } @@ -527,6 +527,7 @@ void AbilityConnectManager::GetOrCreateServiceRecord(const AbilityRequest &abili void AbilityConnectManager::GetConnectRecordListFromMap( const sptr &connect, std::list> &connectRecordList) { + std::lock_guard lock(connectMapMutex_); auto connectMapIter = connectMap_.find(connect->AsObject()); if (connectMapIter != connectMap_.end()) { connectRecordList = connectMapIter->second; @@ -556,7 +557,7 @@ int32_t AbilityConnectManager::GetOrCreateTargetServiceRecord( int AbilityConnectManager::PreloadUIExtensionAbilityLocked(const AbilityRequest &abilityRequest, std::string &hostBundleName) { - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); return PreloadUIExtensionAbilityInner(abilityRequest, hostBundleName); } @@ -580,7 +581,7 @@ int AbilityConnectManager::PreloadUIExtensionAbilityInner(const AbilityRequest & abilityRequest.abilityInfo.name, abilityRequest.abilityInfo.moduleName); std::string extensionRecordKey = element.GetURI() + std::to_string(targetService->GetUIExtensionAbilityId()); targetService->SetURI(extensionRecordKey); - serviceMap_.emplace(extensionRecordKey, targetService); + AddToServiceMap(extensionRecordKey, targetService); LoadAbility(targetService); return ERR_OK; } @@ -610,8 +611,9 @@ int AbilityConnectManager::ConnectAbilityLocked(const AbilityRequest &abilityReq sptr connectInfo) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - TAG_LOGD(AAFwkTag::ABILITYMGR, "callee:%{public}s.", abilityRequest.want.GetElement().GetURI().c_str()); - std::lock_guard guard(Lock_); + CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE); + auto connectObject = connect->AsObject(); + std::lock_guard guard(serialMutex_); // 1. get target service ability record, and check whether it has been loaded. std::shared_ptr targetService; @@ -638,17 +640,13 @@ int AbilityConnectManager::ConnectAbilityLocked(const AbilityRequest &abilityReq targetService->AddConnectRecordToList(connectRecord); targetService->SetSessionInfo(sessionInfo); connectRecordList.push_back(connectRecord); - if (isCallbackConnected) { - RemoveConnectDeathRecipient(connect); - connectMap_.erase(connectMap_.find(connect->AsObject())); - } - AddConnectDeathRecipient(connect); - connectMap_.emplace(connect->AsObject(), connectRecordList); + AddConnectObjectToMap(connectObject, connectRecordList, isCallbackConnected); targetService->SetLaunchReason(LaunchReason::LAUNCHREASON_CONNECT_EXTENSION); if (UIExtensionUtils::IsWindowExtension(targetService->GetAbilityInfo().extensionAbilityType) && abilityRequest.sessionInfo) { - windowExtensionMap_.emplace(connect->AsObject(), + std::lock_guard guard(windowExtensionMapMutex_); + windowExtensionMap_.emplace(connectObject, WindowExtMapValType(targetService->GetApplicationInfo().accessTokenId, abilityRequest.sessionInfo)); } @@ -688,7 +686,7 @@ void AbilityConnectManager::HandleActiveAbility(std::shared_ptr & int AbilityConnectManager::DisconnectAbilityLocked(const sptr &connect) { - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); return DisconnectAbilityLocked(connect, false); } @@ -797,8 +795,14 @@ int AbilityConnectManager::AttachAbilityThreadLocked( const sptr &scheduler, const sptr &token) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - std::lock_guard guard(Lock_); - auto abilityRecord = GetExtensionFromServiceMapInner(token); + std::lock_guard guard(serialMutex_); + auto abilityRecord = GetExtensionByTokenFromServiceMap(token); + if (abilityRecord == nullptr) { + abilityRecord = GetExtensionByTokenFromTerminatingMap(token); + if (abilityRecord != nullptr && !IsUIExtensionAbility(abilityRecord)) { + abilityRecord = nullptr; + } + } CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); if (taskHandler_ != nullptr) { int recordId = abilityRecord->GetRecordId(); @@ -829,10 +833,10 @@ int AbilityConnectManager::AttachAbilityThreadLocked( void AbilityConnectManager::OnAbilityRequestDone(const sptr &token, const int32_t state) { TAG_LOGD(AAFwkTag::ABILITYMGR, "state: %{public}d", state); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); AppAbilityState abilityState = DelayedSingleton::GetInstance()->ConvertToAppAbilityState(state); if (abilityState == AppAbilityState::ABILITY_STATE_FOREGROUND) { - auto abilityRecord = GetExtensionFromServiceMapInner(token); + auto abilityRecord = GetExtensionByTokenFromServiceMap(token); CHECK_POINTER(abilityRecord); if (!IsUIExtensionAbility(abilityRecord)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Not ui extension."); @@ -850,8 +854,8 @@ void AbilityConnectManager::OnAbilityRequestDone(const sptr &toke void AbilityConnectManager::OnAppStateChanged(const AppInfo &info) { - std::lock_guard guard(Lock_); - std::for_each(serviceMap_.begin(), serviceMap_.end(), [&info](ServiceMapType::reference service) { + auto serviceMap = GetServiceMap(); + std::for_each(serviceMap.begin(), serviceMap.end(), [&info](ServiceMapType::reference service) { if (service.second && (info.processName == service.second->GetAbilityInfo().process || info.processName == service.second->GetApplicationInfo().bundleName)) { auto appName = service.second->GetApplicationInfo().name; @@ -869,19 +873,19 @@ void AbilityConnectManager::OnAppStateChanged(const AppInfo &info) int AbilityConnectManager::AbilityTransitionDone(const sptr &token, int state) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast(state)); std::string abilityState = AbilityRecord::ConvertAbilityState(static_cast(targetState)); std::shared_ptr abilityRecord; if (targetState == AbilityState::INACTIVE) { - abilityRecord = GetExtensionFromServiceMapInner(token); + abilityRecord = GetExtensionByTokenFromServiceMap(token); } else if (targetState == AbilityState::FOREGROUND || targetState == AbilityState::BACKGROUND) { - abilityRecord = GetExtensionFromServiceMapInner(token); + abilityRecord = GetExtensionByTokenFromServiceMap(token); if (abilityRecord == nullptr) { - abilityRecord = GetExtensionFromTerminatingMapInner(token); + abilityRecord = GetExtensionByTokenFromTerminatingMap(token); } } else if (targetState == AbilityState::INITIAL) { - abilityRecord = GetExtensionFromTerminatingMapInner(token); + abilityRecord = GetExtensionByTokenFromTerminatingMap(token); } else { abilityRecord = nullptr; } @@ -950,7 +954,7 @@ int AbilityConnectManager::ScheduleConnectAbilityDoneLocked( const sptr &token, const sptr &remoteObject) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE); auto abilityRecord = Token::GetAbilityRecordByToken(token); @@ -997,8 +1001,8 @@ int AbilityConnectManager::ScheduleConnectAbilityDoneLocked( int AbilityConnectManager::ScheduleDisconnectAbilityDoneLocked(const sptr &token) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - std::lock_guard guard(Lock_); - auto abilityRecord = GetExtensionFromServiceMapInner(token); + std::lock_guard guard(serialMutex_); + auto abilityRecord = GetExtensionByTokenFromServiceMap(token); CHECK_POINTER_AND_RETURN(abilityRecord, CONNECTION_NOT_EXIST); auto connect = abilityRecord->GetDisconnectingRecord(); @@ -1033,7 +1037,7 @@ int AbilityConnectManager::ScheduleDisconnectAbilityDoneLocked(const sptrScheduleDisconnectAbilityDone(); abilityRecord->RemoveConnectRecordFromList(connect); if (abilityRecord->IsConnectListEmpty() && abilityRecord->GetStartId() == 0) { - if (IsUIExtensionAbility(abilityRecord) && CheckUIExtensionAbilitySessionExistLocked(abilityRecord)) { + if (IsUIExtensionAbility(abilityRecord) && CheckUIExtensionAbilitySessionExist(abilityRecord)) { TAG_LOGI(AAFwkTag::ABILITYMGR, "There exist ui extension component, don't terminate when disconnect."); } else { TAG_LOGD(AAFwkTag::ABILITYMGR, "Service ability has no any connection, and not started, need terminate."); @@ -1051,7 +1055,7 @@ int AbilityConnectManager::ScheduleDisconnectAbilityDoneLocked(const sptr &token) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE); auto abilityRecord = Token::GetAbilityRecordByToken(token); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); @@ -1079,7 +1083,7 @@ int AbilityConnectManager::ScheduleCommandAbilityWindowDone( AbilityCommand abilityCmd) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE); CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE); auto abilityRecord = Token::GetAbilityRecordByToken(token); @@ -1115,11 +1119,16 @@ void AbilityConnectManager::HandleCommandDestroy(const sptr &sessio } if (sessionInfo->sessionToken) { RemoveUIExtWindowDeathRecipient(sessionInfo->sessionToken); - size_t ret = uiExtensionMap_.erase(sessionInfo->sessionToken); + size_t ret = 0; + { + std::lock_guard guard(uiExtensionMapMutex_); + ret = uiExtensionMap_.erase(sessionInfo->sessionToken); + } if (ret > 0) { return; } + std::lock_guard guard(windowExtensionMapMutex_); for (auto& item : windowExtensionMap_) { auto sessionInfoVal = item.second.second; if (sessionInfoVal && sessionInfoVal->callerToken == sessionInfo->sessionToken) { @@ -1175,12 +1184,7 @@ void AbilityConnectManager::CompleteStartServiceReq(const std::string &serviceUr std::shared_ptr AbilityConnectManager::GetServiceRecordByElementName(const std::string &element) { - std::lock_guard guard(Lock_); - return GetServiceRecordByElementNameInner(element); -} - -std::shared_ptr AbilityConnectManager::GetServiceRecordByElementNameInner(const std::string &element) -{ + std::lock_guard guard(serviceMapMutex_); auto mapIter = serviceMap_.find(element); if (mapIter != serviceMap_.end()) { return mapIter->second; @@ -1190,13 +1194,6 @@ std::shared_ptr AbilityConnectManager::GetServiceRecordByElementN std::shared_ptr AbilityConnectManager::GetExtensionByTokenFromServiceMap( const sptr &token) -{ - std::lock_guard guard(Lock_); - return GetExtensionFromServiceMapInner(token); -} - -std::shared_ptr AbilityConnectManager::GetExtensionFromServiceMapInner( - const sptr &token) { auto IsMatch = [token](auto service) { if (!service.second) { @@ -1205,6 +1202,7 @@ std::shared_ptr AbilityConnectManager::GetExtensionFromServiceMap sptr srcToken = service.second->GetToken(); return srcToken == token; }; + std::lock_guard lock(serviceMapMutex_); auto serviceRecord = std::find_if(serviceMap_.begin(), serviceMap_.end(), IsMatch); if (serviceRecord != serviceMap_.end()) { return serviceRecord->second; @@ -1212,9 +1210,10 @@ std::shared_ptr AbilityConnectManager::GetExtensionFromServiceMap return nullptr; } -std::shared_ptr AbilityConnectManager::GetExtensionFromServiceMapInner( +std::shared_ptr AbilityConnectManager::GetExtensionByIdFromServiceMap( int32_t abilityRecordId) { + std::lock_guard lock(serviceMapMutex_); for (const auto &[key, value] : serviceMap_) { if (value && value->GetAbilityRecordId() == abilityRecordId) { return value; @@ -1226,7 +1225,6 @@ std::shared_ptr AbilityConnectManager::GetExtensionFromServiceMap std::shared_ptr AbilityConnectManager::GetUIExtensioBySessionInfo( const sptr &sessionInfo) { - std::lock_guard guard(Lock_); CHECK_POINTER_AND_RETURN(sessionInfo, nullptr); auto sessionToken = iface_cast(sessionInfo->sessionToken); CHECK_POINTER_AND_RETURN(sessionToken, nullptr); @@ -1237,6 +1235,7 @@ std::shared_ptr AbilityConnectManager::GetUIExtensioBySessionInfo return nullptr; } + std::lock_guard guard(uiExtensionMapMutex_); auto it = uiExtensionMap_.find(sessionToken->AsObject()); if (it != uiExtensionMap_.end()) { auto abilityRecord = it->second.first.lock(); @@ -1261,25 +1260,19 @@ std::shared_ptr AbilityConnectManager::GetUIExtensioBySessionInfo std::shared_ptr AbilityConnectManager::GetExtensionByTokenFromTerminatingMap( const sptr &token) -{ - std::lock_guard guard(Lock_); - return GetExtensionFromTerminatingMapInner(token); -} - -std::shared_ptr AbilityConnectManager::GetExtensionFromTerminatingMapInner( - const sptr &token) { auto IsMatch = [token](auto& extension) { if (extension.second == nullptr) { return false; } - auto&& terminatingToken = extension.second->GetToken(); + auto terminatingToken = extension.second->GetToken(); if (terminatingToken != nullptr) { return terminatingToken->AsObject() == token; } return false; }; + std::lock_guard lock(serviceMapMutex_); auto terminatingExtensionRecord = std::find_if(terminatingExtensionMap_.begin(), terminatingExtensionMap_.end(), IsMatch); if (terminatingExtensionRecord != terminatingExtensionMap_.end()) { @@ -1291,7 +1284,7 @@ std::shared_ptr AbilityConnectManager::GetExtensionFromTerminatin std::list> AbilityConnectManager::GetConnectRecordListByCallback( sptr callback) { - std::lock_guard guard(Lock_); + std::lock_guard guard(connectMapMutex_); std::list> connectList; auto connectMapIter = connectMap_.find(callback->AsObject()); if (connectMapIter != connectMap_.end()) { @@ -1308,6 +1301,7 @@ std::shared_ptr AbilityConnectManager::GetAbilityRecordById(int64 } return abilityRecordId == service.second->GetAbilityRecordId(); }; + std::lock_guard lock(serviceMapMutex_); auto serviceRecord = std::find_if(serviceMap_.begin(), serviceMap_.end(), IsMatch); if (serviceRecord != serviceMap_.end()) { return serviceRecord->second; @@ -1372,7 +1366,7 @@ void AbilityConnectManager::PostRestartResidentTask(const AbilityRequest &abilit void AbilityConnectManager::HandleRestartResidentTask(const AbilityRequest &abilityRequest) { TAG_LOGI(AAFwkTag::ABILITYMGR, "HandleRestartResidentTask start."); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); auto findRestartResidentTask = [abilityRequest](const AbilityRequest &requestInfo) { return (requestInfo.want.GetElement().GetBundleName() == abilityRequest.want.GetElement().GetBundleName() && requestInfo.want.GetElement().GetModuleName() == abilityRequest.want.GetElement().GetModuleName() && @@ -1431,7 +1425,7 @@ void AbilityConnectManager::PostTimeOutTask(const std::shared_ptr void AbilityConnectManager::HandleStartTimeoutTask(const std::shared_ptr &abilityRecord) { TAG_LOGW(AAFwkTag::ABILITYMGR, "load ability timeout."); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); CHECK_POINTER(abilityRecord); if (UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) { if (uiExtensionAbilityRecordMgr_ != nullptr && IsCallerValid(abilityRecord)) { @@ -1451,7 +1445,7 @@ void AbilityConnectManager::HandleStartTimeoutTask(const std::shared_ptrGetToken()) == nullptr) { + if (GetExtensionByTokenFromServiceMap(abilityRecord->GetToken()) == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Timeout ability record is not exist in service map."); return; } @@ -1474,8 +1468,6 @@ void AbilityConnectManager::HandleStartTimeoutTask(const std::shared_ptr &abilityRecord) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "HandleCommandTimeoutTask start"); - std::lock_guard guard(Lock_); CHECK_POINTER(abilityRecord); if (abilityRecord->GetAbilityInfo().name == AbilityConfig::LAUNCHER_ABILITY_NAME) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle root launcher command timeout."); @@ -1490,7 +1482,7 @@ void AbilityConnectManager::HandleConnectTimeoutTask(std::shared_ptrGetConnectRecordList(); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); for (const auto &connectRecord : connectList) { RemoveExtensionDelayDisconnectTask(connectRecord); connectRecord->CompleteDisconnect(ERR_OK, true); @@ -1510,7 +1502,7 @@ void AbilityConnectManager::HandleCommandWindowTimeoutTask(const std::shared_ptr const sptr &sessionInfo, WindowCommand winCmd) { TAG_LOGD(AAFwkTag::ABILITYMGR, "start"); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); CHECK_POINTER(abilityRecord); abilityRecord->SetAbilityWindowState(sessionInfo, winCmd, true); // manage queued request @@ -1536,7 +1528,7 @@ void AbilityConnectManager::StartRootLauncher(const std::shared_ptr &abilityRecord) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Complete stop ability timeout start."); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); CHECK_POINTER(abilityRecord); if (UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) { if (uiExtensionAbilityRecordMgr_ != nullptr && IsCallerValid(abilityRecord)) { @@ -1699,34 +1691,10 @@ void AbilityConnectManager::CommandAbilityWindow(const std::shared_ptr &abilityRecord, - const sptr &sessionInfo) -{ - std::lock_guard guard(Lock_); - if (abilityRecord == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr"); - return; - } - if (sessionInfo == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr"); - return; - } - CommandAbilityWindow(abilityRecord, sessionInfo, WIN_CMD_FOREGROUND); -} - void AbilityConnectManager::BackgroundAbilityWindowLocked(const std::shared_ptr &abilityRecord, const sptr &sessionInfo) { - std::lock_guard guard(Lock_); - if (abilityRecord == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr"); - return; - } - if (sessionInfo == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr"); - return; - } - + std::lock_guard guard(serialMutex_); DoBackgroundAbilityWindow(abilityRecord, sessionInfo); } @@ -1751,32 +1719,17 @@ void AbilityConnectManager::DoBackgroundAbilityWindow(const std::shared_ptr &abilityRecord, const sptr &sessionInfo) -{ - std::lock_guard guard(Lock_); - if (abilityRecord == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr"); - return; - } - if (sessionInfo == nullptr) { - TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr"); - return; - } - DoTerminateUIExtensionAbility(abilityRecord, sessionInfo); -} - -void AbilityConnectManager::DoTerminateUIExtensionAbility(std::shared_ptr abilityRecord, - sptr sessionInfo) { HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); CHECK_POINTER(abilityRecord); CHECK_POINTER(sessionInfo); TAG_LOGI(AAFwkTag::ABILITYMGR, "Terminate ability: %{public}s, persistentId: %{public}d", abilityRecord->GetURI().c_str(), sessionInfo->persistentId); - EventInfo eventInfo; eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName; eventInfo.abilityName = abilityRecord->GetAbilityInfo().name; EventReport::SendAbilityEvent(EventName::TERMINATE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo); + std::lock_guard guard(serialMutex_); eventInfo.errCode = TerminateAbilityInner(abilityRecord->GetToken()); if (eventInfo.errCode != ERR_OK) { EventReport::SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo); @@ -1824,6 +1777,7 @@ bool AbilityConnectManager::IsAbilityConnected(const std::shared_ptr connection) { + std::lock_guard lock(connectMapMutex_); for (auto &connectCallback : connectMap_) { auto &connectList = connectCallback.second; auto connectRecord = std::find(connectList.begin(), connectList.end(), connection); @@ -1831,9 +1785,7 @@ void AbilityConnectManager::RemoveConnectionRecordFromMap(std::shared_ptrGetRecordId()); connectList.remove(connection); if (connectList.empty()) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "connlist"); - sptr connect = iface_cast(connectCallback.first); - RemoveConnectDeathRecipient(connect); + RemoveConnectDeathRecipient(connectCallback.first); connectMap_.erase(connectCallback.first); } return; @@ -1845,13 +1797,12 @@ void AbilityConnectManager::RemoveServiceAbility(const std::shared_ptrGetURI().c_str()); + std::lock_guard lock(serviceMapMutex_); terminatingExtensionMap_.erase(abilityRecord->GetURI()); } -void AbilityConnectManager::AddConnectDeathRecipient(const sptr &connect) +void AbilityConnectManager::AddConnectDeathRecipient(sptr connectObject) { - CHECK_POINTER(connect); - auto connectObject = connect->AsObject(); CHECK_POINTER(connectObject); { std::lock_guard guard(recipientMapMutex_); @@ -1878,10 +1829,8 @@ void AbilityConnectManager::AddConnectDeathRecipient(const sptr &connect) +void AbilityConnectManager::RemoveConnectDeathRecipient(sptr connectObject) { - CHECK_POINTER(connect); - auto connectObject = connect->AsObject(); CHECK_POINTER(connectObject); sptr deathRecipient; { @@ -1910,23 +1859,31 @@ void AbilityConnectManager::OnCallBackDied(const wptr &remote) void AbilityConnectManager::HandleCallBackDiedTask(const sptr &connect) { TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); - std::lock_guard guard(Lock_); CHECK_POINTER(connect); - auto item = windowExtensionMap_.find(connect); - if (item != windowExtensionMap_.end()) { - windowExtensionMap_.erase(item); - } - auto it = connectMap_.find(connect); - if (it != connectMap_.end()) { - ConnectListType connectRecordList = it->second; - for (auto &connRecord : connectRecordList) { - connRecord->ClearConnCallBack(); + { + std::lock_guard guard(windowExtensionMapMutex_); + auto item = windowExtensionMap_.find(connect); + if (item != windowExtensionMap_.end()) { + windowExtensionMap_.erase(item); } - } else { - TAG_LOGI(AAFwkTag::ABILITYMGR, "Died object can't find from conn map."); - return; } + + { + std::lock_guard guard(connectMapMutex_); + auto it = connectMap_.find(connect); + if (it != connectMap_.end()) { + ConnectListType connectRecordList = it->second; + for (auto &connRecord : connectRecordList) { + connRecord->ClearConnCallBack(); + } + } else { + TAG_LOGI(AAFwkTag::ABILITYMGR, "Died object can't find from conn map."); + return; + } + } + sptr object = iface_cast(connect); + std::lock_guard guard(serialMutex_); DisconnectAbilityLocked(object, true); } @@ -1963,8 +1920,6 @@ void AbilityConnectManager::OnAbilityDied(const std::shared_ptr & void AbilityConnectManager::OnTimeOut(uint32_t msgId, int64_t abilityRecordId) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "On timeout, msgId is %{public}d", msgId); - std::lock_guard guard(Lock_); auto abilityRecord = GetAbilityRecordById(abilityRecordId); if (abilityRecord == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityConnectManager on time out event: ability record is nullptr."); @@ -2005,7 +1960,6 @@ bool AbilityConnectManager::IsAbilityNeedKeepAlive(const std::shared_ptrSetKeepAlive(); return true; } return false; @@ -2015,7 +1969,7 @@ void AbilityConnectManager::HandleAbilityDiedTask( const std::shared_ptr &abilityRecord, int32_t currentUserId) { TAG_LOGD(AAFwkTag::ABILITYMGR, "called."); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); CHECK_POINTER(abilityRecord); TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability died: %{public}s", abilityRecord->GetURI().c_str()); abilityRecord->SetConnRemoteObject(nullptr); @@ -2035,7 +1989,7 @@ void AbilityConnectManager::HandleAbilityDiedTask( auto token = abilityRecord->GetToken(); bool isRemove = false; - if (GetExtensionFromServiceMapInner(abilityRecord->GetAbilityRecordId()) != nullptr) { + if (GetExtensionByIdFromServiceMap(abilityRecord->GetAbilityRecordId()) != nullptr) { MoveToTerminatingMap(abilityRecord); RemoveServiceAbility(abilityRecord); if (UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) { @@ -2111,27 +2065,35 @@ void AbilityConnectManager::HandleNotifyAssertFaultDialogDied(const std::shared_ void AbilityConnectManager::CloseAssertDialog(const std::string &assertSessionId) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Called"); - std::lock_guard guard(Lock_); - for (const auto &item : serviceMap_) { - if (item.second == nullptr) { - continue; - } + sptr token; + { + std::lock_guard lock(serviceMapMutex_); + for (const auto &item : serviceMap_) { + if (item.second == nullptr) { + continue; + } - 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); - serviceMap_.erase(item.first); - TerminateAbilityLocked(item.second->GetToken()); - return; + 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(); + serviceMap_.erase(item.first); + break; + } } } + if (token != nullptr) { + std::lock_guard lock(serialMutex_); + TerminateAbilityLocked(token); + } } void AbilityConnectManager::HandleUIExtensionDied(const std::shared_ptr &abilityRecord) { TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); CHECK_POINTER(abilityRecord); + std::lock_guard guard(uiExtensionMapMutex_); for (auto it = uiExtensionMap_.begin(); it != uiExtensionMap_.end();) { std::shared_ptr uiExtAbility = it->second.first.lock(); if (uiExtAbility == nullptr) { @@ -2151,7 +2113,7 @@ void AbilityConnectManager::HandleUIExtensionDied(const std::shared_ptr void AbilityConnectManager::DumpState(std::vector &info, bool isClient, const std::string &args) { TAG_LOGI(AAFwkTag::ABILITYMGR, "args:%{public}s.", args.c_str()); - ServiceMapType serviceMapBack; - { - std::lock_guard guard(Lock_); - serviceMapBack = serviceMap_; - } + auto serviceMapBack = GetServiceMap(); if (!args.empty()) { auto it = std::find_if(serviceMapBack.begin(), serviceMapBack.end(), [&args](const auto &service) { return service.first.compare(args) == 0; @@ -2237,7 +2195,7 @@ void AbilityConnectManager::DumpStateByUri(std::vector &info, bool TAG_LOGI(AAFwkTag::ABILITYMGR, "args:%{public}s, params size: %{public}zu", args.c_str(), params.size()); std::shared_ptr extensionAbilityRecord = nullptr; { - std::lock_guard guard(Lock_); + std::lock_guard lock(serviceMapMutex_); auto it = std::find_if(serviceMap_.begin(), serviceMap_.end(), [&args](const auto &service) { return service.first.compare(args) == 0; }); @@ -2256,10 +2214,9 @@ void AbilityConnectManager::DumpStateByUri(std::vector &info, bool void AbilityConnectManager::GetExtensionRunningInfos(int upperLimit, std::vector &info, const int32_t userId, bool isPerm) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Get extension running info."); - std::lock_guard guard(Lock_); - auto mgr = shared_from_this(); - auto queryInfo = [&info, upperLimit, userId, isPerm, mgr](ServiceMapType::reference service) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + auto serviceMapBack = GetServiceMap(); + auto queryInfo = [&](ServiceMapType::reference service) { if (static_cast(info.size()) >= upperLimit) { return; } @@ -2267,23 +2224,21 @@ void AbilityConnectManager::GetExtensionRunningInfos(int upperLimit, std::vector CHECK_POINTER(abilityRecord); if (isPerm) { - mgr->GetExtensionRunningInfo(abilityRecord, userId, info); + GetExtensionRunningInfo(abilityRecord, userId, info); } else { auto callingTokenId = IPCSkeleton::GetCallingTokenID(); auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId; if (callingTokenId == tokenID) { - mgr->GetExtensionRunningInfo(abilityRecord, userId, info); + GetExtensionRunningInfo(abilityRecord, userId, info); } } }; - std::for_each(serviceMap_.begin(), serviceMap_.end(), queryInfo); + std::for_each(serviceMapBack.begin(), serviceMapBack.end(), queryInfo); } void AbilityConnectManager::GetAbilityRunningInfos(std::vector &info, bool isPerm) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); - std::lock_guard guard(Lock_); - + auto serviceMapBack = GetServiceMap(); auto queryInfo = [&info, isPerm](ServiceMapType::reference service) { auto abilityRecord = service.second; CHECK_POINTER(abilityRecord); @@ -2299,36 +2254,17 @@ void AbilityConnectManager::GetAbilityRunningInfos(std::vector &abilityRecord, const int32_t userId, std::vector &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); ExtensionRunningInfo extensionInfo; AppExecFwk::RunningProcessInfo processInfo; extensionInfo.extension = abilityRecord->GetElementName(); - auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper(); - CHECK_POINTER(bundleMgrHelper); - - std::vector extensionInfos; - bool queryResult = IN_PROCESS_CALL(bundleMgrHelper->QueryExtensionAbilityInfos(abilityRecord->GetWant(), - AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, userId, extensionInfos)); - if (queryResult) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Success"); - auto abilityInfo = abilityRecord->GetAbilityInfo(); - auto isExist = [&abilityInfo](const AppExecFwk::ExtensionAbilityInfo &extensionInfo) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, %{public}s", extensionInfo.bundleName.c_str(), - extensionInfo.name.c_str()); - return extensionInfo.bundleName == abilityInfo.bundleName && extensionInfo.name == abilityInfo.name - && extensionInfo.applicationInfo.uid == abilityInfo.applicationInfo.uid; - }; - auto infoIter = std::find_if(extensionInfos.begin(), extensionInfos.end(), isExist); - if (infoIter != extensionInfos.end()) { - TAG_LOGD(AAFwkTag::ABILITYMGR, "Get target success."); - extensionInfo.type = (*infoIter).type; - } - } + extensionInfo.type = abilityRecord->GetAbilityInfo().extensionAbilityType; DelayedSingleton::GetInstance()-> GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo); extensionInfo.pid = processInfo.pid_; @@ -2355,34 +2291,40 @@ void AbilityConnectManager::GetExtensionRunningInfo(std::shared_ptrsecond; - if (targetExtension != nullptr && targetExtension->GetAbilityInfo().type == AbilityType::EXTENSION && - (IsLauncher(targetExtension) || targetExtension->IsSceneBoard())) { - terminatingExtensionMap_.emplace(it->first, it->second); - serviceMap_.erase(it++); - TAG_LOGI( - AAFwkTag::ABILITYMGR, "terminate ability:%{public}s.", targetExtension->GetAbilityInfo().name.c_str()); - TerminateAbilityLocked(targetExtension->GetToken()); - } else { - it++; + std::vector> needTerminatedTokens; + { + std::lock_guard lock(serviceMapMutex_); + for (auto it = serviceMap_.begin(); it != serviceMap_.end();) { + auto targetExtension = it->second; + if (targetExtension != nullptr && targetExtension->GetAbilityInfo().type == AbilityType::EXTENSION && + (IsLauncher(targetExtension) || targetExtension->IsSceneBoard())) { + terminatingExtensionMap_.emplace(it->first, it->second); + it = serviceMap_.erase(it); + TAG_LOGI(AAFwkTag::ABILITYMGR, "terminate ability:%{public}s.", + targetExtension->GetAbilityInfo().name.c_str()); + needTerminatedTokens.push_back(targetExtension->GetToken()); + } else { + ++it; + } } } + + for (const auto &token : needTerminatedTokens) { + std::lock_guard lock(serialMutex_); + TerminateAbilityLocked(token); + } } void AbilityConnectManager::RemoveLauncherDeathRecipient() { TAG_LOGI(AAFwkTag::ABILITYMGR, "Call."); - std::lock_guard guard(Lock_); - for (auto it = serviceMap_.begin(); it != serviceMap_.end();) { + 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; - } else { - it++; } } } @@ -2473,7 +2415,7 @@ void AbilityConnectManager::MoveToBackground(const std::shared_ptr &abilityRecord) { - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); if (abilityRecord == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr"); return; @@ -2495,7 +2437,7 @@ void AbilityConnectManager::CompleteForeground(const std::shared_ptr &abilityRecord) { - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); if (abilityRecord == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr"); return; @@ -2512,7 +2454,7 @@ void AbilityConnectManager::HandleForegroundTimeoutTask(const std::shared_ptr &abilityRecord) { - std::lock_guard guard(Lock_); + std::lock_guard lock(serialMutex_); if (abilityRecord == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr"); return; @@ -2591,6 +2533,7 @@ void AbilityConnectManager::MoveToTerminatingMap(const std::shared_ptrGetAbilityInfo(); + std::lock_guard lock(serviceMapMutex_); terminatingExtensionMap_.emplace(abilityRecord->GetURI(), abilityRecord); if (FRS_BUNDLE_NAME == abilityInfo.bundleName) { AppExecFwk::ElementName element(abilityInfo.deviceId, abilityInfo.bundleName, abilityInfo.name, @@ -2608,7 +2551,7 @@ void AbilityConnectManager::MoveToTerminatingMap(const std::shared_ptr &session) { CHECK_POINTER(session); - std::unique_lock lock(uiExtRecipientMapMutex_); + std::lock_guard lock(uiExtRecipientMapMutex_); auto it = uiExtRecipientMap_.find(session); if (it != uiExtRecipientMap_.end()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "This death recipient has been added."); @@ -2632,7 +2575,7 @@ void AbilityConnectManager::AddUIExtWindowDeathRecipient(const sptr &session) { CHECK_POINTER(session); - std::unique_lock lock(uiExtRecipientMapMutex_); + std::lock_guard lock(uiExtRecipientMapMutex_); auto it = uiExtRecipientMap_.find(session); if (it != uiExtRecipientMap_.end() && it->first != nullptr) { it->first->RemoveDeathRecipient(it->second); @@ -2656,29 +2599,35 @@ void AbilityConnectManager::OnUIExtWindowDied(const wptr &remote) void AbilityConnectManager::HandleUIExtWindowDiedTask(const sptr &remote) { TAG_LOGD(AAFwkTag::ABILITYMGR, "call."); - std::lock_guard guard(Lock_); CHECK_POINTER(remote); - auto it = uiExtensionMap_.find(remote); - if (it != uiExtensionMap_.end()) { - auto abilityRecord = it->second.first.lock(); - if (abilityRecord) { - DoTerminateUIExtensionAbility(abilityRecord, it->second.second); + std::shared_ptr abilityRecord; + sptr sessionInfo; + { + std::lock_guard guard(uiExtensionMapMutex_); + auto it = uiExtensionMap_.find(remote); + if (it != uiExtensionMap_.end()) { + abilityRecord = it->second.first.lock(); + sessionInfo = it->second.second; + uiExtensionMap_.erase(it); } else { - TAG_LOGI(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr"); + TAG_LOGI(AAFwkTag::ABILITYMGR, "Died object can't find from map."); + return; } - RemoveUIExtWindowDeathRecipient(remote); - uiExtensionMap_.erase(it); - } else { - TAG_LOGI(AAFwkTag::ABILITYMGR, "Died object can't find from map."); - return; } + + if (abilityRecord) { + TerminateAbilityWindowLocked(abilityRecord, sessionInfo); + } else { + TAG_LOGI(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr"); + } + RemoveUIExtWindowDeathRecipient(remote); } bool AbilityConnectManager::IsUIExtensionFocused(uint32_t uiExtensionTokenId, const sptr& focusToken) { TAG_LOGD(AAFwkTag::ABILITYMGR, "called, id: %{public}u", uiExtensionTokenId); CHECK_POINTER_AND_RETURN(uiExtensionAbilityRecordMgr_, false); - std::lock_guard guard(Lock_); + std::lock_guard guard(uiExtensionMapMutex_); for (auto& item: uiExtensionMap_) { auto uiExtension = item.second.first.lock(); auto sessionInfo = item.second.second; @@ -2698,7 +2647,7 @@ bool AbilityConnectManager::IsUIExtensionFocused(uint32_t uiExtensionTokenId, co sptr AbilityConnectManager::GetUIExtensionSourceToken(const sptr &token) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Called"); - std::lock_guard guard(Lock_); + std::lock_guard guard(uiExtensionMapMutex_); for (auto &item : uiExtensionMap_) { auto sessionInfo = item.second.second; auto uiExtension = item.second.first.lock(); @@ -2713,7 +2662,7 @@ sptr AbilityConnectManager::GetUIExtensionSourceToken(const sptr< bool AbilityConnectManager::IsWindowExtensionFocused(uint32_t extensionTokenId, const sptr& focusToken) { - std::lock_guard guard(Lock_); + std::lock_guard guard(windowExtensionMapMutex_); for (auto& item: windowExtensionMap_) { uint32_t windowExtTokenId = item.second.first; auto sessionInfo = item.second.second; @@ -2733,8 +2682,8 @@ void AbilityConnectManager::HandleProcessFrozen(const std::vector &pidL } TAG_LOGI(AAFwkTag::ABILITYMGR, "HandleProcessFrozen: %{public}d", uid); std::unordered_set pidSet(pidList.begin(), pidList.end()); - std::lock_guard guard(Lock_); - auto weakthis = weak_from_this(); + std::lock_guard lock(serviceMapMutex_); + auto weakThis = weak_from_this(); for (auto [key, abilityRecord] : serviceMap_) { if (abilityRecord && abilityRecord->GetUid() == uid && abilityRecord->GetAbilityInfo().extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE && @@ -2743,12 +2692,11 @@ void AbilityConnectManager::HandleProcessFrozen(const std::vector &pidL abilityRecord->IsConnectListEmpty() && !abilityRecord->GetKeepAlive() && abilityRecord->GetStartId() != 0) { // To be honest, this is expected to be true - taskHandler->SubmitTask([weakthis, record = abilityRecord]() { - auto connectManager = weakthis.lock(); + taskHandler->SubmitTask([weakThis, record = abilityRecord]() { + auto connectManager = weakThis.lock(); if (record && connectManager) { TAG_LOGI(AAFwkTag::ABILITYMGR, "TerminateRecord: %{public}s", record->GetAbilityInfo().bundleName.c_str()); - std::lock_guard guard(connectManager->Lock_); connectManager->TerminateRecord(record); } else { TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null"); @@ -2800,7 +2748,7 @@ void AbilityConnectManager::RemoveExtensionDelayDisconnectTask(const std::shared void AbilityConnectManager::HandleExtensionDisconnectTask(const std::shared_ptr &connectRecord) { TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); - std::lock_guard guard(Lock_); + std::lock_guard guard(serialMutex_); CHECK_POINTER(connectRecord); int result = connectRecord->DisconnectAbility(); if (result != ERR_OK) { @@ -2818,17 +2766,16 @@ bool AbilityConnectManager::IsUIExtensionAbility(const std::shared_ptrGetAbilityInfo().extensionAbilityType); } -bool AbilityConnectManager::CheckUIExtensionAbilitySessionExistLocked( +bool AbilityConnectManager::CheckUIExtensionAbilitySessionExist( const std::shared_ptr &abilityRecord) { CHECK_POINTER_AND_RETURN(abilityRecord, false); - - for (auto it = uiExtensionMap_.begin(); it != uiExtensionMap_.end();) { + std::lock_guard guard(uiExtensionMapMutex_); + for (auto it = uiExtensionMap_.begin(); it != uiExtensionMap_.end(); ++it) { std::shared_ptr uiExtAbility = it->second.first.lock(); if (abilityRecord == uiExtAbility) { return true; } - it++; } return false; @@ -2855,7 +2802,7 @@ bool AbilityConnectManager::IsCallerValid(const std::shared_ptr & auto sessionInfo = abilityRecord->GetSessionInfo(); CHECK_POINTER_AND_RETURN_LOG(sessionInfo, false, "Invalid caller for UIExtension"); CHECK_POINTER_AND_RETURN_LOG(sessionInfo->sessionToken, false, "Invalid caller for UIExtension"); - std::unique_lock lock(uiExtRecipientMapMutex_); + std::lock_guard lock(uiExtRecipientMapMutex_); if (uiExtRecipientMap_.find(sessionInfo->sessionToken) == uiExtRecipientMap_.end()) { TAG_LOGW(AAFwkTag::ABILITYMGR, "Invalid caller for UIExtension."); return false; @@ -2874,7 +2821,7 @@ std::shared_ptr AbilityConnectManager::GetUIExtensionRootH void AbilityConnectManager::SignRestartAppFlag(const std::string &bundleName) { - std::lock_guard guard(Lock_); + std::lock_guard lock(serviceMapMutex_); for (auto &[key, abilityRecord] : serviceMap_) { if (abilityRecord == nullptr || abilityRecord->GetApplicationInfo().bundleName != bundleName) { continue; @@ -2886,15 +2833,42 @@ void AbilityConnectManager::SignRestartAppFlag(const std::string &bundleName) void AbilityConnectManager::DeleteInvalidServiceRecord(const std::string &bundleName) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Delete invalid record by %{public}s.", bundleName.c_str()); + std::lock_guard lock(serviceMapMutex_); for (auto it = serviceMap_.begin(); it != serviceMap_.end();) { if (it->second != nullptr && it->second->GetApplicationInfo().bundleName == bundleName) { - serviceMap_.erase(it++); + it = serviceMap_.erase(it); } else { - it++; + ++it; } } } +bool AbilityConnectManager::AddToServiceMap(const std::string &key, std::shared_ptr abilityRecord) +{ + std::lock_guard lock(serviceMapMutex_); + if (abilityRecord == nullptr) { + return false; + } + auto insert = serviceMap_.emplace(key, abilityRecord); + return insert.second; +} + +AbilityConnectManager::ServiceMapType AbilityConnectManager::GetServiceMap() +{ + std::lock_guard lock(serviceMapMutex_); + return serviceMap_; +} + +void AbilityConnectManager::AddConnectObjectToMap(sptr connectObject, + const ConnectListType &connectRecordList, bool updateOnly) +{ + if (!updateOnly) { + AddConnectDeathRecipient(connectObject); + } + std::lock_guard guard(connectMapMutex_); + connectMap_[connectObject] = connectRecordList; +} + EventInfo AbilityConnectManager::BuildEventInfo(const std::shared_ptr &abilityRecord) { EventInfo eventInfo; diff --git a/services/abilitymgr/src/ability_manager_client.cpp b/services/abilitymgr/src/ability_manager_client.cpp index 5e44da15b1..f161c8a16f 100644 --- a/services/abilitymgr/src/ability_manager_client.cpp +++ b/services/abilitymgr/src/ability_manager_client.cpp @@ -275,6 +275,7 @@ ErrCode AbilityManagerClient::SendResultToAbility(int requestCode, int resultCod ErrCode AbilityManagerClient::StartExtensionAbility(const Want &want, sptr callerToken, int32_t userId, AppExecFwk::ExtensionAbilityType extensionType) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); TAG_LOGD(AAFwkTag::ABILITYMGR, "name:%{public}s %{public}s, userId=%{public}d.", @@ -579,6 +580,7 @@ ErrCode AbilityManagerClient::DumpSysState( ErrCode AbilityManagerClient::Connect() { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard lock(mutex_); if (proxy_ != nullptr) { return ERR_OK; @@ -742,6 +744,7 @@ ErrCode AbilityManagerClient::LockMissionForCleanup(int32_t missionId) ErrCode AbilityManagerClient::UnlockMissionForCleanup(int32_t missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { auto sceneSessionManager = SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy(); CHECK_POINTER_RETURN_INVALID_VALUE(sceneSessionManager); @@ -833,6 +836,7 @@ ErrCode AbilityManagerClient::UnRegisterMissionListener(const std::string &devic ErrCode AbilityManagerClient::GetMissionInfos(const std::string& deviceId, int32_t numMax, std::vector &missionInfos) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { auto sceneSessionManager = SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy(); CHECK_POINTER_RETURN_INVALID_VALUE(sceneSessionManager); @@ -851,6 +855,7 @@ ErrCode AbilityManagerClient::GetMissionInfos(const std::string& deviceId, int32 ErrCode AbilityManagerClient::GetMissionInfo(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { auto sceneSessionManager = SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy(); CHECK_POINTER_RETURN_INVALID_VALUE(sceneSessionManager); @@ -868,6 +873,7 @@ ErrCode AbilityManagerClient::GetMissionInfo(const std::string& deviceId, int32_ ErrCode AbilityManagerClient::CleanMission(int32_t missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { auto sceneSessionManager = SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy(); CHECK_POINTER_RETURN_INVALID_VALUE(sceneSessionManager); @@ -885,6 +891,7 @@ ErrCode AbilityManagerClient::CleanMission(int32_t missionId) ErrCode AbilityManagerClient::CleanAllMissions() { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { auto sceneSessionManager = SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy(); CHECK_POINTER_RETURN_INVALID_VALUE(sceneSessionManager); @@ -902,6 +909,7 @@ ErrCode AbilityManagerClient::CleanAllMissions() ErrCode AbilityManagerClient::MoveMissionToFront(int32_t missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->MoveMissionToFront(missionId); @@ -909,6 +917,7 @@ ErrCode AbilityManagerClient::MoveMissionToFront(int32_t missionId) ErrCode AbilityManagerClient::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->MoveMissionToFront(missionId, startOptions); @@ -1016,6 +1025,7 @@ ErrCode AbilityManagerClient::ReleaseCall( ErrCode AbilityManagerClient::GetAbilityRunningInfos(std::vector &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->GetAbilityRunningInfos(info); @@ -1023,6 +1033,7 @@ ErrCode AbilityManagerClient::GetAbilityRunningInfos(std::vector &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto abms = GetAbilityManager(); CHECK_POINTER_RETURN_NOT_CONNECTED(abms); return abms->GetExtensionRunningInfos(upperLimit, info); @@ -1108,6 +1119,7 @@ ErrCode AbilityManagerClient::RegisterSnapshotHandler(sptr han ErrCode AbilityManagerClient::GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot, bool isLowResolution) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) { auto sceneSessionManager = SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy(); CHECK_POINTER_RETURN_INVALID_VALUE(sceneSessionManager); @@ -1374,6 +1386,7 @@ ErrCode AbilityManagerClient::BlockAppService() sptr AbilityManagerClient::GetAbilityManager() { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard lock(mutex_); if (!proxy_) { (void)Connect(); @@ -1452,6 +1465,7 @@ void AbilityManagerClient::HandleDlpApp(Want &want) { #ifdef WITH_DLP if (!want.GetParams().HasParam(DLP_PARAMS_SANDBOX)) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "Security::DlpPermission::DlpFileKits::GetSandboxFlag"); bool sandboxFlag = Security::DlpPermission::DlpFileKits::GetSandboxFlag(want); want.SetParam(DLP_PARAMS_SANDBOX, sandboxFlag); } @@ -1805,6 +1819,14 @@ int32_t AbilityManagerClient::OpenAtomicService(Want& want, const StartOptions & return abms->OpenAtomicService(want, options, callerToken, requestCode, userId); } +int32_t AbilityManagerClient::SetResidentProcessEnabled(const std::string &bundleName, bool enable) +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + auto abms = GetAbilityManager(); + CHECK_POINTER_RETURN_INVALID_VALUE(abms); + return abms->SetResidentProcessEnabled(bundleName, enable); +} + bool AbilityManagerClient::IsEmbeddedOpenAllowed(sptr callerToken, const std::string &appId) { TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info."); diff --git a/services/abilitymgr/src/ability_manager_proxy.cpp b/services/abilitymgr/src/ability_manager_proxy.cpp index 1e16b01662..37058440a1 100644 --- a/services/abilitymgr/src/ability_manager_proxy.cpp +++ b/services/abilitymgr/src/ability_manager_proxy.cpp @@ -28,6 +28,7 @@ #include "appexecfwk_errors.h" #include "configuration.h" #include "hilog_tag_wrapper.h" +#include "hitrace_meter.h" #include "session_info.h" #include "status_bar_delegate_interface.h" @@ -90,6 +91,7 @@ int AbilityManagerProxy::StartAbility(const Want &want, int32_t userId, int requ AppExecFwk::ElementName AbilityManagerProxy::GetTopAbility(bool isNeedLocalDeviceId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); MessageParcel data; MessageParcel reply; MessageOption option; @@ -585,6 +587,7 @@ int AbilityManagerProxy::StartAbilityByUIContentSession(const Want &want, const int AbilityManagerProxy::StartExtensionAbility(const Want &want, const sptr &callerToken, int32_t userId, AppExecFwk::ExtensionAbilityType extensionType) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int error; MessageParcel data; MessageParcel reply; @@ -2368,6 +2371,7 @@ int AbilityManagerProxy::LockMissionForCleanup(int32_t missionId) int AbilityManagerProxy::UnlockMissionForCleanup(int32_t missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int error; MessageParcel data; MessageParcel reply; @@ -2576,6 +2580,7 @@ int AbilityManagerProxy::UnRegisterMissionListener(const sptr int AbilityManagerProxy::GetMissionInfos(const std::string& deviceId, int32_t numMax, std::vector &missionInfos) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int error; MessageParcel data; MessageParcel reply; @@ -2607,6 +2612,7 @@ int AbilityManagerProxy::GetMissionInfos(const std::string& deviceId, int32_t nu int AbilityManagerProxy::GetMissionInfo(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int error; MessageParcel data; MessageParcel reply; @@ -2639,6 +2645,7 @@ int AbilityManagerProxy::GetMissionInfo(const std::string& deviceId, int32_t mis int AbilityManagerProxy::CleanMission(int32_t missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int error; MessageParcel data; MessageParcel reply; @@ -2661,6 +2668,7 @@ int AbilityManagerProxy::CleanMission(int32_t missionId) int AbilityManagerProxy::CleanAllMissions() { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int error; MessageParcel data; MessageParcel reply; @@ -2679,6 +2687,7 @@ int AbilityManagerProxy::CleanAllMissions() int AbilityManagerProxy::MoveMissionToFront(int32_t missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int error; MessageParcel data; MessageParcel reply; @@ -2701,6 +2710,7 @@ int AbilityManagerProxy::MoveMissionToFront(int32_t missionId) int AbilityManagerProxy::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int error; MessageParcel data; MessageParcel reply; @@ -4941,6 +4951,7 @@ int32_t AbilityManagerProxy::UpdateSessionInfoBySCB(std::list &sess ErrCode AbilityManagerProxy::SendRequest(AbilityManagerInterfaceCode code, MessageParcel &data, MessageParcel &reply, MessageOption& option) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); sptr remote = Remote(); if (remote == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Remote() is NULL"); @@ -5110,6 +5121,32 @@ int32_t AbilityManagerProxy::OpenAtomicService(Want& want, const StartOptions &o return reply.ReadInt32(); } +int32_t AbilityManagerProxy::SetResidentProcessEnabled(const std::string &bundleName, bool enable) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + HILOG_ERROR("Write interface token failed."); + return INNER_ERR; + } + if (!data.WriteString(bundleName)) { + HILOG_ERROR("Write bundl name failed."); + return INNER_ERR; + } + if (!data.WriteBool(enable)) { + HILOG_ERROR("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); + return ret; + } + + return reply.ReadInt32(); +} + bool AbilityManagerProxy::IsEmbeddedOpenAllowed(sptr callerToken, const std::string &appId) { if (callerToken == nullptr) { diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp index 2a6d879019..53b7a5a0c8 100644 --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -36,6 +36,7 @@ #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" #include "app_utils.h" @@ -406,6 +407,7 @@ bool AbilityManagerService::Init() InitInterceptor(); InitStartAbilityChain(); + InitDeepLinkReserve(); abilityAutoStartupService_ = std::make_shared(); @@ -419,6 +421,18 @@ bool AbilityManagerService::Init() return true; } +void AbilityManagerService::InitDeepLinkReserve() +{ + deepLinkReserveConfig_ = DelayedSingleton::GetInstance(); + if (deepLinkReserveConfig_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Get DeepLinkReserveConfig instance is nullptr."); + return; + } + if (!deepLinkReserveConfig_->LoadConfiguration()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "InitDeepLinkReserve failed."); + } +} + void AbilityManagerService::InitInterceptor() { interceptorExecuter_ = std::make_shared(); @@ -778,6 +792,7 @@ int AbilityManagerService::StartAbilityAsCallerDetails(const Want &want, const s int AbilityManagerService::StartAbilityPublicPrechainCheck(StartAbilityParams ¶ms) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); // 1. CheckCallerToken if (params.callerToken != nullptr && !VerificationAllToken(params.callerToken)) { auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()-> @@ -800,6 +815,7 @@ int AbilityManagerService::StartAbilityPublicPrechainCheck(StartAbilityParams &p int AbilityManagerService::StartAbilityPrechainInterceptor(StartAbilityParams ¶ms) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(params.want, params.requestCode, GetUserId(), true, nullptr); auto interceptorResult = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE : @@ -814,6 +830,7 @@ int AbilityManagerService::StartAbilityPrechainInterceptor(StartAbilityParams &p bool AbilityManagerService::StartAbilityInChain(StartAbilityParams ¶ms, int &result) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::shared_ptr reqHandler; for (const auto &item : startAbilityChain_) { if (item.second->MatchStartRequest(params)) { @@ -842,6 +859,7 @@ int AbilityManagerService::StartAbilityWrap(const Want &want, const sptr(want)); startParams.callerToken = callerToken; startParams.userId = userId; @@ -858,6 +876,22 @@ int AbilityManagerService::StartAbilityWrap(const Want &want, const sptrisLinkReserved(linkString, reservedBundleName)) { + implicitStartProcessor_->SetUriReservedFlag(true); + implicitStartProcessor_->SetUriReservedBundle(reservedBundleName); + } else { + implicitStartProcessor_->SetUriReservedFlag(false); + implicitStartProcessor_->SetUriReservedBundle(reservedBundleName); + } +} + int AbilityManagerService::StartAbilityInner(const Want &want, const sptr &callerToken, int requestCode, int32_t userId, bool isStartAsCaller, bool isSendDialogResult, uint32_t specifyTokenId, bool isForegroundToRestartApp, bool isImplicit) @@ -931,6 +965,7 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptrImplicitStartAbility(abilityRequest, validUserId); } if (want.GetAction().compare(ACTION_CHOOSE) == 0) { @@ -1341,6 +1376,7 @@ int AbilityManagerService::StartAbilityDetails(const Want &want, const AbilitySt int AbilityManagerService::StartAbility(const Want &want, const StartOptions &startOptions, const sptr &callerToken, int32_t userId, int requestCode) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability with startOptions."); AbilityUtil::RemoveShowModeKey(const_cast(want)); return StartUIAbilityForOptionWrap(want, startOptions, callerToken, userId, requestCode); @@ -1357,6 +1393,7 @@ 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) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto ret = CheckProcessOptions(want, options, userId); if (ret != ERR_OK) { return ret; @@ -1423,6 +1460,7 @@ int AbilityManagerService::StartAbilityForOptionWrap(const Want &want, const Sta const sptr &callerToken, int32_t userId, int requestCode, bool isStartAsCaller, uint32_t callerTokenId, bool isImplicit) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); StartAbilityParams startParams(const_cast(want)); startParams.callerToken = callerToken; startParams.userId = userId; @@ -2022,7 +2060,9 @@ void AbilityManagerService::AppUpgradeCompleted(const std::string &bundleName, i return; } - if (!bundleInfo.isKeepAlive) { + bool keepAliveEnable = bundleInfo.isKeepAlive; + AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleInfo.name, keepAliveEnable); + if (!keepAliveEnable) { TAG_LOGW(AAFwkTag::ABILITYMGR, "Not a resident application."); return; } @@ -2344,6 +2384,7 @@ void AbilityManagerService::RegisterSuspendObserver() int AbilityManagerService::StartExtensionAbility(const Want &want, const sptr &callerToken, int32_t userId, AppExecFwk::ExtensionAbilityType extensionType) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); InsightIntentExecuteParam::RemoveInsightIntent(const_cast(want)); if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) { return StartExtensionAbilityInner(want, callerToken, userId, extensionType, false); @@ -2477,6 +2518,7 @@ int AbilityManagerService::StartExtensionAbilityInner(const Want &want, const sp int32_t userId, AppExecFwk::ExtensionAbilityType extensionType, bool checkSystemCaller, bool isImplicit, bool isDlp) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "Start extension ability come, bundlename: %{public}s, ability is %{public}s, userId is %{public}d", want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId); @@ -3231,6 +3273,7 @@ int AbilityManagerService::SendResultToAbility(int32_t requestCode, int32_t resu int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode, int32_t validUserId, const sptr &callerToken) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__); Want remoteWant = want; if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) { @@ -3273,6 +3316,7 @@ int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode, bool AbilityManagerService::CheckIsRemote(const std::string& deviceId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (deviceId.empty()) { TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckIsRemote: deviceId is empty."); return false; @@ -4219,6 +4263,7 @@ void AbilityManagerService::UnregisterCancelListener( int AbilityManagerService::GetPendingRequestWant(const sptr &target, std::shared_ptr &want) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "Get pending request want."); auto pendingWantManager = GetCurrentPendingWantManager(); CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE); @@ -4244,6 +4289,7 @@ int AbilityManagerService::LockMissionForCleanup(int32_t missionId) int AbilityManagerService::UnlockMissionForCleanup(int32_t missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock mission for clean up all, id :%{public}d", missionId); auto missionListManager = GetCurrentMissionListManager(); CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT); @@ -4304,6 +4350,7 @@ int AbilityManagerService::UnRegisterMissionListener(const sptr &missionInfos) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "request GetMissionInfos."); auto missionListManager = GetCurrentMissionListManager(); CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT); @@ -4337,6 +4384,7 @@ int AbilityManagerService::GetRemoteMissionInfos(const std::string& deviceId, in int AbilityManagerService::GetMissionInfo(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "request GetMissionInfo, missionId:%{public}d", missionId); auto missionListManager = GetCurrentMissionListManager(); CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT); @@ -4357,6 +4405,7 @@ int AbilityManagerService::GetMissionInfo(const std::string& deviceId, int32_t m int AbilityManagerService::GetRemoteMissionInfo(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "GetMissionInfoFromDms begin"); std::vector missionVector; int result = GetRemoteMissionInfos(deviceId, MAX_NUMBER_OF_DISTRIBUTED_MISSIONS, missionVector); @@ -4375,6 +4424,7 @@ int AbilityManagerService::GetRemoteMissionInfo(const std::string& deviceId, int int AbilityManagerService::CleanMission(int32_t missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "request CleanMission, missionId:%{public}d", missionId); auto missionListManager = GetCurrentMissionListManager(); CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT); @@ -4390,6 +4440,7 @@ int AbilityManagerService::CleanMission(int32_t missionId) int AbilityManagerService::CleanAllMissions() { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "request CleanAllMissions "); auto missionListManager = GetCurrentMissionListManager(); CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT); @@ -4412,6 +4463,7 @@ int AbilityManagerService::CleanAllMissions() int AbilityManagerService::MoveMissionToFront(int32_t missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId); CHECK_CALLER_IS_SYSTEM_APP; if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) { @@ -4437,6 +4489,7 @@ int AbilityManagerService::MoveMissionToFront(int32_t missionId) int AbilityManagerService::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId); CHECK_CALLER_IS_SYSTEM_APP; if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) { @@ -4517,6 +4570,7 @@ int32_t AbilityManagerService::GetMissionIdByToken(const sptr &to bool AbilityManagerService::IsAbilityControllerStartById(int32_t missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); InnerMissionInfo innerMissionInfo; int getMission = DelayedSingleton::GetInstance()->GetInnerMissionInfoById( missionId, innerMissionInfo); @@ -5478,6 +5532,10 @@ void AbilityManagerService::OnAppStateChanged(const AppInfo &info) auto dataAbilityManager = GetCurrentDataAbilityManager(); CHECK_POINTER(dataAbilityManager); dataAbilityManager->OnAppStateChanged(info); + + auto residentProcessMgr = DelayedSingleton::GetInstance(); + CHECK_POINTER(residentProcessMgr); + residentProcessMgr->OnAppStateChanged(info); } std::shared_ptr AbilityManagerService::GetEventHandler() @@ -5801,7 +5859,9 @@ int AbilityManagerService::KillProcess(const std::string &bundleName) return GET_BUNDLE_INFO_FAILED; } - if (bundleInfo.isKeepAlive && DelayedSingleton::GetInstance()->IsMemorySizeSufficent()) { + bool keepAliveEnable = bundleInfo.isKeepAlive; + AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleName, keepAliveEnable); + if (keepAliveEnable && DelayedSingleton::GetInstance()->IsMemorySizeSufficent()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Can not kill keep alive process."); return KILL_PROCESS_KEEP_ALIVE; } @@ -6104,6 +6164,7 @@ bool AbilityManagerService::VerificationToken(const sptr &token) bool AbilityManagerService::VerificationAllToken(const sptr &token) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); CHECK_POINTER_AND_RETURN(subManagersHelper_, false); return subManagersHelper_->VerificationAllToken(token); } @@ -6234,7 +6295,7 @@ void AbilityManagerService::StartResidentApps() TAG_LOGE(AAFwkTag::ABILITYMGR, "Get resident bundleinfos failed"); return; } - + DelayedSingleton::GetInstance()->Init(); TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps GetBundleInfos size: %{public}zu", bundleInfos.size()); DelayedSingleton::GetInstance()->StartResidentProcessWithMainElement(bundleInfos); @@ -6449,6 +6510,7 @@ bool AbilityManagerService::IsRamConstrainedDevice() int32_t AbilityManagerService::GetMissionIdByAbilityToken(const sptr &token) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto abilityRecord = Token::GetAbilityRecordByToken(token); if (!abilityRecord) { TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null."); @@ -6462,6 +6524,7 @@ int32_t AbilityManagerService::GetMissionIdByAbilityToken(const sptr &token) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto abilityRecord = Token::GetAbilityRecordByToken(token); if (!abilityRecord) { TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null."); @@ -6483,6 +6546,7 @@ int32_t AbilityManagerService::GetMissionIdByAbilityTokenInner(const sptr AbilityManagerService::GetAbilityTokenByMissionId(int32_t missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto missionListManager = GetCurrentMissionListManager(); if (!missionListManager) { return nullptr; @@ -6622,6 +6686,7 @@ int AbilityManagerService::StartAbilityByCall(const Want &want, const sptr &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "Get running ability infos."); CHECK_CALLER_IS_SYSTEM_APP; auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm(); @@ -6818,6 +6884,7 @@ int AbilityManagerService::GetAbilityRunningInfos(std::vector &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (info.empty()) { return; } @@ -6847,6 +6914,7 @@ void AbilityManagerService::UpdateFocusState(std::vector &in int AbilityManagerService::GetExtensionRunningInfos(int upperLimit, std::vector &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "Get extension infos, upperLimit : %{public}d", upperLimit); CHECK_CALLER_IS_SYSTEM_APP; auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm(); @@ -6892,6 +6960,7 @@ int AbilityManagerService::RegisterSnapshotHandler(const sptr& int32_t AbilityManagerService::GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& missionSnapshot, bool isLowResolution) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); CHECK_CALLER_IS_SYSTEM_APP; if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Permission verification failed", __func__); @@ -7105,6 +7174,7 @@ void AbilityManagerService::ScheduleRecoverAbility(const sptr& to int32_t AbilityManagerService::GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId, MissionSnapshot& missionSnapshot) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "GetRemoteMissionSnapshotInfo begin"); std::unique_ptr missionSnapshotPtr = std::make_unique(); DistributedClient dmsClient; @@ -7322,6 +7392,7 @@ bool AbilityManagerService::IsRunningInStabilityTest() bool AbilityManagerService::IsAbilityControllerStart(const Want &want, const std::string &bundleName) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_); if (abilityController_ == nullptr) { TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr"); @@ -7403,6 +7474,7 @@ int AbilityManagerService::FinishUserTest( int AbilityManagerService::GetTopAbility(sptr &token) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); if (!isSaCall) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed"); @@ -7632,6 +7704,7 @@ void AbilityManagerService::UpdateCallerInfoFromToken(Want& want, const sptr &info, std::shared_ptr &abilityRecord) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); AbilityRunningInfo runningInfo; AppExecFwk::RunningProcessInfo processInfo; @@ -7911,6 +7985,7 @@ int AbilityManagerService::FreeInstallAbilityFromRemote(const Want &want, const AppExecFwk::ElementName AbilityManagerService::GetTopAbility(bool isNeedLocalDeviceId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__); AppExecFwk::ElementName elementName = {}; #ifdef SUPPORT_GRAPHICS @@ -8825,6 +8900,7 @@ void AbilityManagerService::GetAbilityTokenByCalleeObj(const sptr int AbilityManagerService::AddStartControlParam(Want &want, const sptr &callerToken) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (AAFwk::PermissionVerification::GetInstance()->IsSACall() || AAFwk::PermissionVerification::GetInstance()->IsShellCall()) { return ERR_OK; @@ -8850,6 +8926,7 @@ int AbilityManagerService::CheckDlpForExtension( const Want &want, const sptr &callerToken, int32_t userId, EventInfo &eventInfo, const EventName &eventName) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); // check if form frs auto callingUid = IPCSkeleton::GetCallingUid(); std::string bundleName = want.GetBundle(); @@ -9799,6 +9876,7 @@ bool AbilityManagerService::GenerateDialogSessionRecord(AbilityRequest &abilityR 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) { @@ -9930,6 +10008,32 @@ void AbilityManagerService::CloseAssertDialog(const std::string &assertSessionId connectManager->CloseAssertDialog(assertSessionId); } +int32_t AbilityManagerService::SetResidentProcessEnabled(const std::string &bundleName, bool enable) +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall()) { + HILOG_ERROR("Permission verification failed."); + return ERR_NOT_SYSTEM_APP; + } + + auto residentProcessManager = DelayedSingleton::GetInstance(); + if (residentProcessManager == nullptr) { + HILOG_ERROR("Get resident proces mgr is nullptr"); + return INNER_ERR; + } + + std::string callerName; + int32_t uid = 0; + auto callerPid = IPCSkeleton::GetCallingPid(); + DelayedSingleton::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid); + if (callerName.empty()) { + HILOG_ERROR("Failed to obtain caller name."); + return INNER_ERR; + } + + return residentProcessManager->SetResidentProcessEnabled(bundleName, callerName, enable); +} + int32_t AbilityManagerService::RequestAssertFaultDialog( const sptr &callback, const AAFwk::WantParams &wantParams) { diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index ef87642c8b..a197384b14 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -27,6 +27,7 @@ #include "ability_scheduler_stub.h" #include "configuration.h" #include "hilog_tag_wrapper.h" +#include "hitrace_meter.h" #include "session_info.h" #include "status_bar_delegate_interface.h" @@ -432,6 +433,8 @@ void AbilityManagerStub::FourthStepInit() &AbilityManagerStub::ChangeUIAbilityVisibilityBySCBInner; requestFuncMap_[static_cast(AbilityManagerInterfaceCode::START_SHORTCUT)] = &AbilityManagerStub::StartShortcutInner; + requestFuncMap_[static_cast(AbilityManagerInterfaceCode::SET_RESIDENT_PROCESS_ENABLE)] = + &AbilityManagerStub::SetResidentProcessEnableInner; requestFuncMap_[static_cast(AbilityManagerInterfaceCode::GET_ABILITY_STATE_BY_PERSISTENT_ID)] = &AbilityManagerStub::GetAbilityStateByPersistentIdInner; } @@ -1388,6 +1391,7 @@ int AbilityManagerStub::UnregisterCancelListenerInner(MessageParcel &data, Messa int AbilityManagerStub::GetPendingRequestWantInner(MessageParcel &data, MessageParcel &reply) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); sptr wantSender = iface_cast(data.ReadRemoteObject()); if (wantSender == nullptr) { TAG_LOGE(AAFwkTag::ABILITYMGR, "wantSender is nullptr"); @@ -1555,6 +1559,7 @@ int AbilityManagerStub::LockMissionForCleanupInner(MessageParcel &data, MessageP int AbilityManagerStub::UnlockMissionForCleanupInner(MessageParcel &data, MessageParcel &reply) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int32_t id = data.ReadInt32(); int result = UnlockMissionForCleanup(id); if (!reply.WriteInt32(result)) { @@ -1600,6 +1605,7 @@ int AbilityManagerStub::UnRegisterMissionListenerInner(MessageParcel &data, Mess int AbilityManagerStub::GetMissionInfosInner(MessageParcel &data, MessageParcel &reply) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::string deviceId = Str16ToStr8(data.ReadString16()); int numMax = data.ReadInt32(); std::vector missionInfos; @@ -1618,6 +1624,7 @@ int AbilityManagerStub::GetMissionInfosInner(MessageParcel &data, MessageParcel int AbilityManagerStub::GetMissionInfoInner(MessageParcel &data, MessageParcel &reply) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); MissionInfo info; std::string deviceId = Str16ToStr8(data.ReadString16()); int32_t missionId = data.ReadInt32(); @@ -1636,6 +1643,7 @@ int AbilityManagerStub::GetMissionInfoInner(MessageParcel &data, MessageParcel & int AbilityManagerStub::CleanMissionInner(MessageParcel &data, MessageParcel &reply) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int32_t missionId = data.ReadInt32(); int result = CleanMission(missionId); if (!reply.WriteInt32(result)) { @@ -1647,6 +1655,7 @@ int AbilityManagerStub::CleanMissionInner(MessageParcel &data, MessageParcel &re int AbilityManagerStub::CleanAllMissionsInner(MessageParcel &data, MessageParcel &reply) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int result = CleanAllMissions(); if (!reply.WriteInt32(result)) { TAG_LOGE(AAFwkTag::ABILITYMGR, "CleanAllMissions failed."); @@ -1657,6 +1666,7 @@ int AbilityManagerStub::CleanAllMissionsInner(MessageParcel &data, MessageParcel int AbilityManagerStub::MoveMissionToFrontInner(MessageParcel &data, MessageParcel &reply) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int32_t missionId = data.ReadInt32(); int result = MoveMissionToFront(missionId); if (!reply.WriteInt32(result)) { @@ -1679,6 +1689,7 @@ int AbilityManagerStub::GetMissionIdByTokenInner(MessageParcel &data, MessagePar int AbilityManagerStub::MoveMissionToFrontByOptionsInner(MessageParcel &data, MessageParcel &reply) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); int32_t missionId = data.ReadInt32(); std::unique_ptr startOptions(data.ReadParcelable()); if (startOptions == nullptr) { @@ -3337,6 +3348,18 @@ int32_t AbilityManagerStub::OpenAtomicServiceInner(MessageParcel &data, MessageP return ERR_OK; } +int32_t AbilityManagerStub::SetResidentProcessEnableInner(MessageParcel &data, MessageParcel &reply) +{ + std::string bundleName = data.ReadString(); + bool enable = data.ReadBool(); + auto result = SetResidentProcessEnabled(bundleName, enable); + if (!reply.WriteInt32(result)) { + HILOG_ERROR("Write result failed."); + return ERR_INVALID_VALUE; + } + return NO_ERROR; +} + int32_t AbilityManagerStub::IsEmbeddedOpenAllowedInner(MessageParcel &data, MessageParcel &reply) { sptr callerToken = nullptr; diff --git a/services/abilitymgr/src/ability_record.cpp b/services/abilitymgr/src/ability_record.cpp index 5fe524d384..d92d3be8e1 100644 --- a/services/abilitymgr/src/ability_record.cpp +++ b/services/abilitymgr/src/ability_record.cpp @@ -24,6 +24,7 @@ #include "ability_app_state_observer.h" #include "ability_event_handler.h" #include "ability_manager_service.h" +#include "ability_resident_process_rdb.h" #include "ability_scheduler_stub.h" #include "ability_util.h" #include "app_utils.h" @@ -69,6 +70,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 MULTI_THREAD = "multiThread"; const std::string DMS_PROCESS_NAME = "distributedsched"; const std::string DMS_MISSION_ID = "dmsMissionId"; const std::string DMS_SRC_NETWORK_ID = "dmsSrcNetworkId"; @@ -182,6 +184,7 @@ Token::~Token() std::shared_ptr Token::GetAbilityRecordByToken(const sptr &token) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (token == nullptr) { return nullptr; } @@ -397,9 +400,10 @@ bool AbilityRecord::CanRestartRootLauncher() bool AbilityRecord::CanRestartResident() { + auto isKeepAlive = GetKeepAlive(); TAG_LOGD(AAFwkTag::ABILITYMGR, "isKeepAlive: %{public}d, isRestarting: %{public}d, restartCount: %{public}d", - isKeepAlive_, isRestarting_, restartCount_); - if (isKeepAlive_ && isRestarting_ && (restartCount_ < 0)) { + isKeepAlive, isRestarting_, restartCount_); + if (isKeepAlive && isRestarting_ && (restartCount_ < 0)) { int restartIntervalTime = 0; auto abilityMgr = DelayedSingleton::GetInstance(); if (abilityMgr) { @@ -2095,7 +2099,7 @@ void AbilityRecord::Dump(std::vector &info) info.push_back(dumpInfo); dumpInfo = " bundle name [" + GetAbilityInfo().bundleName + "]"; info.push_back(dumpInfo); - std::string isKeepAlive = isKeepAlive_ ? "true" : "false"; + std::string isKeepAlive = GetKeepAlive() ? "true" : "false"; dumpInfo = " isKeepAlive: " + isKeepAlive; info.push_back(dumpInfo); // get ability type(unknown/page/service/provider) @@ -2200,7 +2204,7 @@ void AbilityRecord::DumpAbilityState( callContainer_->Dump(info); } - std::string isKeepAlive = isKeepAlive_ ? "true" : "false"; + std::string isKeepAlive = GetKeepAlive() ? "true" : "false"; dumpInfo = " isKeepAlive: " + isKeepAlive; info.push_back(dumpInfo); if (isLauncherRoot_) { @@ -2252,7 +2256,7 @@ void AbilityRecord::DumpService(std::vector &info, std::vector> trustAbilities{ + { AbilityConfig::SCENEBOARD_BUNDLE_NAME, AbilityConfig::SCENEBOARD_ABILITY_NAME }, + { AbilityConfig::SYSTEM_UI_BUNDLE_NAME, AbilityConfig::SYSTEM_UI_ABILITY_NAME }, + { AbilityConfig::LAUNCHER_BUNDLE_NAME, AbilityConfig::LAUNCHER_ABILITY_NAME } + }; + for (const auto &pair : trustAbilities) { + if (pair.first == abilityInfo_.bundleName && pair.second == abilityInfo_.name) { + return true; + } + } + bool keepAliveEnable = false; + AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(applicationInfo_.bundleName, keepAliveEnable); + return keepAliveEnable; } void AbilityRecord::SetLoading(bool status) diff --git a/services/abilitymgr/src/ability_scheduler_proxy.cpp b/services/abilitymgr/src/ability_scheduler_proxy.cpp index 1ba3f2fb2f..97d783b6b5 100644 --- a/services/abilitymgr/src/ability_scheduler_proxy.cpp +++ b/services/abilitymgr/src/ability_scheduler_proxy.cpp @@ -22,6 +22,7 @@ #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" #include "pac_map.h" @@ -1113,6 +1114,7 @@ void AbilitySchedulerProxy::OnExecuteIntent(const Want &want) int32_t AbilitySchedulerProxy::CreateModalUIExtension(const Want &want) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "AbilitySchedulerProxy::CreateModalUIExtension start"); MessageParcel data; MessageParcel reply; diff --git a/services/abilitymgr/src/ams_configuration_parameter.cpp b/services/abilitymgr/src/ams_configuration_parameter.cpp index 91d327b08c..6eb3dba3b7 100644 --- a/services/abilitymgr/src/ams_configuration_parameter.cpp +++ b/services/abilitymgr/src/ams_configuration_parameter.cpp @@ -152,16 +152,14 @@ void AmsConfigurationParameter::LoadUIExtensionPickerConfig(const std::string &f return; } - if (pickerJson[AmsConfig::UIEATENSION].is_null() - || !pickerJson[AmsConfig::UIEATENSION].is_array() + if (pickerJson[AmsConfig::UIEATENSION].is_null() || !pickerJson[AmsConfig::UIEATENSION].is_array() || pickerJson[AmsConfig::UIEATENSION].empty()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid obj"); return; } for (auto extension : pickerJson[AmsConfig::UIEATENSION]) { - if (extension[AmsConfig::UIEATENSION_TYPE].is_null() - || !extension[AmsConfig::UIEATENSION_TYPE].is_string() + if (extension[AmsConfig::UIEATENSION_TYPE].is_null() || !extension[AmsConfig::UIEATENSION_TYPE].is_string() || extension[AmsConfig::UIEATENSION_TYPE_PICKER].is_null() || !extension[AmsConfig::UIEATENSION_TYPE_PICKER].is_string()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid key or value"); @@ -169,8 +167,7 @@ void AmsConfigurationParameter::LoadUIExtensionPickerConfig(const std::string &f } std::string type = extension[AmsConfig::UIEATENSION_TYPE].get(); std::string typePicker = extension[AmsConfig::UIEATENSION_TYPE_PICKER].get(); - TAG_LOGI(AAFwkTag::ABILITYMGR, - "type is %{public}s, typePicker is %{public}s", type.c_str(), typePicker.c_str()); + TAG_LOGI(AAFwkTag::ABILITYMGR, "type: %{public}s, typePicker: %{public}s", type.c_str(), typePicker.c_str()); picker_[type] = typePicker; } pickerJson.clear(); diff --git a/services/abilitymgr/src/app_scheduler.cpp b/services/abilitymgr/src/app_scheduler.cpp index c6b22a0076..3c0c21fa4d 100644 --- a/services/abilitymgr/src/app_scheduler.cpp +++ b/services/abilitymgr/src/app_scheduler.cpp @@ -302,11 +302,13 @@ void AppScheduler::OnAppStateChanged(const AppExecFwk::AppProcessData &appData) } info.processName = appData.processName; info.state = static_cast(appData.appState); + info.pid = appData.pid; callback->OnAppStateChanged(info); } void AppScheduler::GetRunningProcessInfoByToken(const sptr &token, AppExecFwk::RunningProcessInfo &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); CHECK_POINTER(appMgrClient_); IN_PROCESS_CALL_WITHOUT_RET(appMgrClient_->GetRunningProcessInfoByToken(token, info)); } diff --git a/services/abilitymgr/src/data_ability_manager.cpp b/services/abilitymgr/src/data_ability_manager.cpp index 15457a64de..6d61a7d52a 100644 --- a/services/abilitymgr/src/data_ability_manager.cpp +++ b/services/abilitymgr/src/data_ability_manager.cpp @@ -19,6 +19,7 @@ #include #include "ability_manager_service.h" +#include "ability_resident_process_rdb.h" #include "ability_util.h" #include "connection_state_manager.h" #include "hilog_tag_wrapper.h" @@ -647,7 +648,9 @@ void DataAbilityManager::RestartDataAbility(const std::shared_ptr } for (size_t i = 0; i < bundleInfos.size(); i++) { - if (!bundleInfos[i].isKeepAlive || bundleInfos[i].applicationInfo.process.empty()) { + bool keepAliveEnable = bundleInfos[i].isKeepAlive; + AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleInfos[i].name, keepAliveEnable); + if (!keepAliveEnable || bundleInfos[i].applicationInfo.process.empty()) { continue; } for (auto hapModuleInfo : bundleInfos[i].hapModuleInfos) { diff --git a/services/abilitymgr/src/deeplink_reserve/deeplink_reserve.cpp b/services/abilitymgr/src/deeplink_reserve/deeplink_reserve.cpp new file mode 100644 index 0000000000..bd06e07194 --- /dev/null +++ b/services/abilitymgr/src/deeplink_reserve/deeplink_reserve.cpp @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "deeplink_reserve/deeplink_reserve.h" +#include +#include +#include +#include + +#include "config_policy_utils.h" +#include "hilog_tag_wrapper.h" +#include "hilog_wrapper.h" + +namespace OHOS { +namespace AAFwk { +namespace { +const std::string CONFIG_PATH = "/etc/ability_runtime/deeplink_reserve_config.json"; +const std::string DEFAULT_RESERVE_CONFIG_PATH = "/system/etc/deeplink_reserve_config.json"; +const std::string DEEPLINK_RESERVED_URI_NAME = "deepLinkReservedUri"; +const std::string BUNDLE_NAME = "bundleName"; +const std::string URIS_NAME = "uris"; +const std::string SCHEME_NAME = "scheme"; +const std::string HOST_NAME = "host"; +const std::string PORT_NAME = "port"; +const std::string PATH_NAME = "path"; +const std::string PATH_START_WITH_NAME = "pathStartWith"; +const std::string PATH_REGEX_NAME = "pathRegex"; +const std::string TYPE_NAME = "type"; +const std::string UTD_NAME = "utd"; +const std::string PORT_SEPARATOR = ":"; +const std::string SCHEME_SEPARATOR = "://"; +const std::string PATH_SEPARATOR = "/"; +const std::string PARAM_SEPARATOR = "?"; +} + +std::string DeepLinkReserveConfig::GetConfigPath() +{ + char buf[MAX_PATH_LEN] = { 0 }; + char *configPath = GetOneCfgFile(CONFIG_PATH.c_str(), buf, MAX_PATH_LEN); + if (configPath == nullptr || configPath[0] == '\0' || strlen(configPath) > MAX_PATH_LEN) { + return DEFAULT_RESERVE_CONFIG_PATH; + } + return configPath; +} + +bool DeepLinkReserveConfig::LoadConfiguration() +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); + std::string configPath = GetConfigPath(); + TAG_LOGI(AAFwkTag::ABILITYMGR, "Deeplink reserve config path is: %{public}s", configPath.c_str()); + nlohmann::json jsonBuf; + if (ReadFileInfoJson(configPath, jsonBuf)) { + if (!LoadReservedUriList(jsonBuf)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "LoadConfiguration failed."); + return false; + } + } + + return true; +} + +bool DeepLinkReserveConfig::isLinkReserved(const std::string &linkString, std::string &bundleName) +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, "call"); + for (auto it = deepLinkReserveUris_.begin(); it != deepLinkReserveUris_.end(); ++it) { + for (auto &itemUri : it->second) { + if (isUriMatched(itemUri, linkString)) { + TAG_LOGI(AAFwkTag::ABILITYMGR, "link is: %{public}s, linkReserved is: %{public}s, matched!", + linkString.c_str(), itemUri.scheme.c_str()); + bundleName = it->first; + return true; + } + } + } + + return false; +} + +static std::string GetOptParamUri(const std::string &linkString) +{ + std::size_t pos = linkString.rfind(PARAM_SEPARATOR); + if (pos == std::string::npos) { + return linkString; + } + return linkString.substr(0, pos); +} + +static bool StartsWith(const std::string &sourceString, const std::string &targetPrefix) +{ + return sourceString.rfind(targetPrefix, 0) == 0; +} + + +bool DeepLinkReserveConfig::isUriMatched(const ReserveUri &reservedUri, const std::string &link) +{ + if (reservedUri.scheme.empty()) { + return false; + } + if (reservedUri.host.empty()) { + // config uri is : scheme + // belows are param uri matched conditions: + // 1.scheme + // 2.scheme: + // 3.scheme:/ + // 4.scheme:// + return link == reservedUri.scheme || StartsWith(link, reservedUri.scheme + PORT_SEPARATOR); + } + std::string optParamUri = GetOptParamUri(link); + std::string reservedUriString; + reservedUriString.append(reservedUri.scheme).append(SCHEME_SEPARATOR).append(reservedUri.host); + if (!reservedUri.port.empty()) { + reservedUriString.append(PORT_SEPARATOR).append(reservedUri.port); + } + if (reservedUri.path.empty() && reservedUri.pathStartWith.empty() && reservedUri.pathRegex.empty()) { + // with port, config uri is : scheme://host:port + // belows are param uri matched conditions: + // 1.scheme://host:port + // 2.scheme://host:port/path + + // without port, config uri is : scheme://host + // belows are param uri matched conditions: + // 1.scheme://host + // 2.scheme://host/path + // 3.scheme://host:port scheme://host:port/path + bool ret = (optParamUri == reservedUriString || StartsWith(optParamUri, reservedUriString + PATH_SEPARATOR)); + if (reservedUri.port.empty()) { + ret = ret || StartsWith(optParamUri, reservedUriString + PORT_SEPARATOR); + } + return ret; + } + reservedUriString.append(PATH_SEPARATOR); + // if one of path, pathStartWith, pathRegex match, then match + if (!reservedUri.path.empty()) { + // path match + std::string pathUri(reservedUriString); + pathUri.append(reservedUri.path); + if (optParamUri == pathUri) { + return true; + } + } + if (!reservedUri.pathStartWith.empty()) { + // pathStartWith match + std::string pathStartWithUri(reservedUriString); + pathStartWithUri.append(reservedUri.pathStartWith); + if (StartsWith(optParamUri, pathStartWithUri)) { + return true; + } + } + if (!reservedUri.pathRegex.empty()) { + // pathRegex match + std::string pathRegexUri(reservedUriString); + pathRegexUri.append(reservedUri.pathRegex); + try { + std::regex regex(pathRegexUri); + if (regex_match(optParamUri, regex)) { + return true; + } + } catch(...) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "regex error"); + } + } + return false; +} + +void DeepLinkReserveConfig::LoadReservedUrilItem(const nlohmann::json &jsonUriObject, std::vector &uriList) +{ + ReserveUri reserveUri; + if (jsonUriObject.contains(SCHEME_NAME) && jsonUriObject.at(SCHEME_NAME).is_string()) { + std::string schemeName = jsonUriObject.at(SCHEME_NAME).get(); + reserveUri.scheme = schemeName; + TAG_LOGD(AAFwkTag::ABILITYMGR, "scheme is: %{public}s", reserveUri.scheme.c_str()); + } + if (jsonUriObject.contains(HOST_NAME) && jsonUriObject.at(HOST_NAME).is_string()) { + std::string hostName = jsonUriObject.at(HOST_NAME).get(); + reserveUri.host = hostName; + TAG_LOGD(AAFwkTag::ABILITYMGR, "host is: %{public}s", reserveUri.host.c_str()); + } + if (jsonUriObject.contains(PORT_NAME) && jsonUriObject.at(PORT_NAME).is_string()) { + std::string portName = jsonUriObject.at(PORT_NAME).get(); + reserveUri.port = portName; + TAG_LOGD(AAFwkTag::ABILITYMGR, "port is: %{public}s", reserveUri.port.c_str()); + } + if (jsonUriObject.contains(PATH_NAME) && jsonUriObject.at(PATH_NAME).is_string()) { + std::string pathName = jsonUriObject.at(PATH_NAME).get(); + reserveUri.path = PATH_NAME; + TAG_LOGD(AAFwkTag::ABILITYMGR, "path is: %{public}s", reserveUri.path.c_str()); + } + if (jsonUriObject.contains(PATH_START_WITH_NAME) && jsonUriObject.at(PATH_START_WITH_NAME).is_string()) { + std::string pathStartWithName = jsonUriObject.at(PATH_START_WITH_NAME).get(); + reserveUri.pathStartWith = pathStartWithName; + TAG_LOGD(AAFwkTag::ABILITYMGR, "pathStartWith is: %{public}s", reserveUri.pathStartWith.c_str()); + } + if (jsonUriObject.contains(PATH_REGEX_NAME) && jsonUriObject.at(PATH_REGEX_NAME).is_string()) { + std::string pathRegexName = jsonUriObject.at(PATH_REGEX_NAME).get(); + reserveUri.pathRegex = pathRegexName; + TAG_LOGD(AAFwkTag::ABILITYMGR, "pathRegex is: %{public}s", reserveUri.pathRegex.c_str()); + } + if (jsonUriObject.contains(TYPE_NAME) && jsonUriObject.at(TYPE_NAME).is_string()) { + std::string typeName = jsonUriObject.at(TYPE_NAME).get(); + reserveUri.type = typeName; + TAG_LOGD(AAFwkTag::ABILITYMGR, "type is: %{public}s", reserveUri.type.c_str()); + } + if (jsonUriObject.contains(UTD_NAME) && jsonUriObject.at(UTD_NAME).is_string()) { + std::string utdName = jsonUriObject.at(UTD_NAME).get(); + reserveUri.utd = utdName; + TAG_LOGD(AAFwkTag::ABILITYMGR, "utd is: %{public}s", reserveUri.utd.c_str()); + } + + uriList.emplace_back(reserveUri); +} + +bool DeepLinkReserveConfig::LoadReservedUriList(const nlohmann::json &object) +{ + if (!object.contains(DEEPLINK_RESERVED_URI_NAME)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Deeplink reserved uri config not existed."); + return false; + } + + for (auto &item : object.at(DEEPLINK_RESERVED_URI_NAME).items()) { + const nlohmann::json& jsonObject = item.value(); + if (!jsonObject.contains(BUNDLE_NAME) || !jsonObject.at(BUNDLE_NAME).is_string()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Wrong deeplink reserve bundleName."); + return false; + } + if (!jsonObject.contains(URIS_NAME) || !jsonObject.at(URIS_NAME).is_array()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Wrong deeplink reserve uris."); + return false; + } + std::string bundleName = jsonObject.at(BUNDLE_NAME).get(); + std::vector uriList; + for (auto &uriItem : jsonObject.at(URIS_NAME).items()) { + const nlohmann::json& jsonUriObject = uriItem.value(); + LoadReservedUrilItem(jsonUriObject, uriList); + } + deepLinkReserveUris_.insert(std::make_pair(bundleName, uriList)); + } + return true; +} + +bool DeepLinkReserveConfig::ReadFileInfoJson(const std::string &filePath, nlohmann::json &jsonBuf) +{ + if (access(filePath.c_str(), F_OK) != 0) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, not existed", filePath.c_str()); + return false; + } + + std::fstream in; + char errBuf[256]; + errBuf[0] = '\0'; + in.open(filePath, std::ios_base::in); + if (!in.is_open()) { + strerror_r(errno, errBuf, sizeof(errBuf)); + TAG_LOGE(AAFwkTag::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; +} +} +} \ No newline at end of file diff --git a/services/abilitymgr/src/dialog_session_record.cpp b/services/abilitymgr/src/dialog_session_record.cpp index 3c783a523f..54413eecc9 100644 --- a/services/abilitymgr/src/dialog_session_record.cpp +++ b/services/abilitymgr/src/dialog_session_record.cpp @@ -22,6 +22,7 @@ #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" @@ -104,6 +105,7 @@ void DialogSessionRecord::ClearAllDialogContexts() 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; diff --git a/services/abilitymgr/src/free_install_manager.cpp b/services/abilitymgr/src/free_install_manager.cpp index 0e3036dd60..0613d673b1 100644 --- a/services/abilitymgr/src/free_install_manager.cpp +++ b/services/abilitymgr/src/free_install_manager.cpp @@ -131,6 +131,7 @@ int FreeInstallManager::StartFreeInstall(const Want &want, int32_t userId, int r int FreeInstallManager::RemoteFreeInstall(const Want &want, int32_t userId, int requestCode, const sptr &callerToken) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::FREE_INSTALL, "RemoteFreeInstall called"); bool isFromRemote = want.GetBoolParam(FROM_REMOTE_KEY, false); auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall(); @@ -182,6 +183,7 @@ FreeInstallInfo FreeInstallManager::BuildFreeInstallInfo(const Want &want, int32 int FreeInstallManager::StartRemoteFreeInstall(const Want &want, int requestCode, int32_t validUserId, const sptr &callerToken) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::FREE_INSTALL, "%{public}s", __func__); if (!want.GetBoolParam(Want::PARAM_RESV_FOR_RESULT, false)) { TAG_LOGI(AAFwkTag::FREE_INSTALL, "%{public}s: StartAbility freeInstall", __func__); diff --git a/services/abilitymgr/src/implicit_start_processor.cpp b/services/abilitymgr/src/implicit_start_processor.cpp index 3ce16d7879..9f5f487d66 100644 --- a/services/abilitymgr/src/implicit_start_processor.cpp +++ b/services/abilitymgr/src/implicit_start_processor.cpp @@ -26,6 +26,7 @@ #include "event_report.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" @@ -86,6 +87,7 @@ bool ImplicitStartProcessor::IsImplicitStartAction(const Want &want) int ImplicitStartProcessor::ImplicitStartAbility(AbilityRequest &request, int32_t userId, int32_t windowMode) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "implicit start ability by type: %{public}d", request.callType); auto sysDialogScheduler = DelayedSingleton::GetInstance(); CHECK_POINTER_AND_RETURN(sysDialogScheduler, ERR_INVALID_VALUE); @@ -227,6 +229,7 @@ int ImplicitStartProcessor::ImplicitStartAbility(AbilityRequest &request, int32_ 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)) { @@ -288,9 +291,42 @@ static void ProcessLinkType(std::vector &abilityInfos) } } +void ImplicitStartProcessor::SetUriReservedFlag(const bool flag) +{ + uriReservedFlag_ = flag; +} + +void ImplicitStartProcessor::SetUriReservedBundle(const std::string bundleName) +{ + reservedBundleName_ = bundleName; +} + +void ImplicitStartProcessor::OnlyKeepReserveApp(std::vector &abilityInfos, + std::vector &extensionInfos) +{ + if (!uriReservedFlag_) { + return; + } + if (extensionInfos.size() > 0) { + extensionInfos.clear(); + } + + for (auto it = abilityInfos.begin(); it != abilityInfos.end();) { + if (it->bundleName == reservedBundleName_) { + it++; + continue; + } else { + TAG_LOGI(AAFwkTag::ABILITYMGR, "Reserve App %{public}s dismatch with bundleName %{public}s.", + reservedBundleName_.c_str(), it->bundleName.c_str()); + it = abilityInfos.erase(it); + } + } +} + int ImplicitStartProcessor::GenerateAbilityRequestByAction(int32_t userId, AbilityRequest &request, std::vector &dialogAppInfos, bool isMoreHapList) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s.", __func__); // get abilityinfos from bms auto bundleMgrHelper = GetBundleManagerHelper(); @@ -322,8 +358,15 @@ int ImplicitStartProcessor::GenerateAbilityRequestByAction(int32_t userId, static_cast(AppExecFwk::GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_APP_LINKING); } + if (uriReservedFlag_) { + abilityInfoFlag = abilityInfoFlag | + static_cast(AppExecFwk::GetAbilityInfoFlag::GET_ABILITY_INFO_ONLY_SYSTEM_APP); + } + IN_PROCESS_CALL_WITHOUT_RET(bundleMgrHelper->ImplicitQueryInfos( request.want, abilityInfoFlag, userId, withDefault, abilityInfos, extensionInfos)); + + OnlyKeepReserveApp(abilityInfos, extensionInfos); if (isOpenLink && extensionInfos.size() > 0) { TAG_LOGI(AAFwkTag::ABILITYMGR, "Clear extensionInfos when isOpenLink."); extensionInfos.clear(); @@ -382,17 +425,20 @@ int ImplicitStartProcessor::GenerateAbilityRequestByAction(int32_t userId, } } - for (const auto &info : abilityInfos) { - AddInfoParam param = { - .info = info, - .userId = userId, - .isExtension = isExtension, - .isMoreHapList = isMoreHapList, - .withDefault = withDefault, - .typeName = typeName, - .infoNames = infoNames - }; - AddAbilityInfoToDialogInfos(param, dialogAppInfos); + { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "for (const auto &info : abilityInfos)"); + for (const auto &info : abilityInfos) { + AddInfoParam param = { + .info = info, + .userId = userId, + .isExtension = isExtension, + .isMoreHapList = isMoreHapList, + .withDefault = withDefault, + .typeName = typeName, + .infoNames = infoNames + }; + AddAbilityInfoToDialogInfos(param, dialogAppInfos); + } } for (const auto &info : extensionInfos) { @@ -484,6 +530,7 @@ bool ImplicitStartProcessor::CheckImplicitStartExtensionIsValid(const AbilityReq int32_t ImplicitStartProcessor::ImplicitStartAbilityInner(const Want &targetWant, const AbilityRequest &request, int32_t userId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto abilityMgr = DelayedSingleton::GetInstance(); CHECK_POINTER_AND_RETURN(abilityMgr, ERR_INVALID_VALUE); @@ -723,6 +770,7 @@ bool ImplicitStartProcessor::IsCallFromAncoShellOrBroker(const sptr &skillUri, Want &want) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); for (const auto& iter : skillUri) { if (iter.isMatch) { want.RemoveParam("send_to_erms_targetLinkFeature"); diff --git a/services/abilitymgr/src/insight_intent_execute_param.cpp b/services/abilitymgr/src/insight_intent_execute_param.cpp index f7d9e43b36..72968123ad 100644 --- a/services/abilitymgr/src/insight_intent_execute_param.cpp +++ b/services/abilitymgr/src/insight_intent_execute_param.cpp @@ -16,6 +16,7 @@ #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" @@ -100,6 +101,7 @@ bool InsightIntentExecuteParam::GenerateFromWant(const AAFwk::Want &want, bool InsightIntentExecuteParam::RemoveInsightIntent(AAFwk::Want &want) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (want.HasParameter(INSIGHT_INTENT_EXECUTE_PARAM_NAME)) { want.RemoveParam(INSIGHT_INTENT_EXECUTE_PARAM_NAME); } diff --git a/services/abilitymgr/src/mission_data_storage.cpp b/services/abilitymgr/src/mission_data_storage.cpp index fcdb9a69d0..4b5350e283 100644 --- a/services/abilitymgr/src/mission_data_storage.cpp +++ b/services/abilitymgr/src/mission_data_storage.cpp @@ -19,6 +19,7 @@ #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" #include "media_errors.h" @@ -138,6 +139,7 @@ void MissionDataStorage::DeleteMissionSnapshot(int32_t missionId) bool MissionDataStorage::GetMissionSnapshot(int32_t missionId, MissionSnapshot& missionSnapshot, bool isLowResolution) { #ifdef SUPPORT_GRAPHICS + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (GetCachedSnapshot(missionId, missionSnapshot)) { if (isLowResolution) { missionSnapshot.snapshot = GetReducedPixelMap(missionSnapshot.snapshot); diff --git a/services/abilitymgr/src/mission_info_mgr.cpp b/services/abilitymgr/src/mission_info_mgr.cpp index 81a7be4239..067244de77 100644 --- a/services/abilitymgr/src/mission_info_mgr.cpp +++ b/services/abilitymgr/src/mission_info_mgr.cpp @@ -90,6 +90,7 @@ bool MissionInfoMgr::AddMissionInfo(const InnerMissionInfo &missionInfo) bool MissionInfoMgr::AddMissionInfoInner(const InnerMissionInfo &missionInfo) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto id = missionInfo.missionInfo.id; if (missionIdMap_.find(id) != missionIdMap_.end() && missionIdMap_[id]) { TAG_LOGE(AAFwkTag::ABILITYMGR, "add mission info failed, missionId %{public}d already exists", id); @@ -115,6 +116,7 @@ bool MissionInfoMgr::AddMissionInfoInner(const InnerMissionInfo &missionInfo) bool MissionInfoMgr::UpdateMissionInfo(const InnerMissionInfo &missionInfo) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard lock(mutex_); auto id = missionInfo.missionInfo.id; if (missionIdMap_.find(id) == missionIdMap_.end() || !missionIdMap_[id]) { @@ -151,6 +153,7 @@ bool MissionInfoMgr::UpdateMissionInfo(const InnerMissionInfo &missionInfo) bool MissionInfoMgr::DeleteMissionInfo(int missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard lock(mutex_); if (missionIdMap_.find(missionId) == missionIdMap_.end()) { TAG_LOGW(AAFwkTag::ABILITYMGR, "missionId %{public}d not exists, no need delete", missionId); @@ -186,6 +189,7 @@ bool MissionInfoMgr::DeleteMissionInfo(int missionId) bool MissionInfoMgr::DeleteAllMissionInfos(const std::shared_ptr &listenerController) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard lock(mutex_); if (!taskDataPersistenceMgr_) { TAG_LOGE(AAFwkTag::ABILITYMGR, "taskDataPersistenceMgr_ is nullptr"); @@ -213,6 +217,7 @@ bool MissionInfoMgr::DeleteAllMissionInfos(const std::shared_ptr(mission.startMethod)) { case StartMethod::START_CALL: @@ -226,6 +231,7 @@ static bool DoesNotShowInTheMissionList(const InnerMissionInfo &mission) int MissionInfoMgr::GetMissionInfos(int32_t numMax, std::vector &missionInfos) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "numMax:%{public}d", numMax); if (numMax < 0) { return -1; @@ -250,6 +256,7 @@ int MissionInfoMgr::GetMissionInfos(int32_t numMax, std::vector &mi int MissionInfoMgr::GetMissionInfoById(int32_t missionId, MissionInfo &missionInfo) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::ABILITYMGR, "missionId:%{public}d", missionId); std::lock_guard lock(mutex_); if (missionIdMap_.find(missionId) == missionIdMap_.end()) { @@ -564,6 +571,7 @@ bool MissionInfoMgr::UpdateMissionSnapshot(int32_t missionId, const sptr lock(savingSnapshotLock_); auto search = savingSnapshot_.find(missionId); if (search != savingSnapshot_.end()) { diff --git a/services/abilitymgr/src/mission_list.cpp b/services/abilitymgr/src/mission_list.cpp index 2ff57d5fad..ecb7d609b8 100644 --- a/services/abilitymgr/src/mission_list.cpp +++ b/services/abilitymgr/src/mission_list.cpp @@ -17,6 +17,7 @@ #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" +#include "hitrace_meter.h" namespace OHOS { namespace AAFwk { diff --git a/services/abilitymgr/src/mission_list_manager.cpp b/services/abilitymgr/src/mission_list_manager.cpp index cb932a761b..7084e42f5a 100644 --- a/services/abilitymgr/src/mission_list_manager.cpp +++ b/services/abilitymgr/src/mission_list_manager.cpp @@ -1108,6 +1108,7 @@ std::shared_ptr MissionListManager::GetAbilityRecordByToken( std::shared_ptr MissionListManager::GetAbilityRecordByTokenInner( const sptr &token) const { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (!token) { return nullptr; } @@ -1124,6 +1125,7 @@ std::shared_ptr MissionListManager::GetAbilityRecordByTokenInner( std::shared_ptr MissionListManager::GetAliveAbilityRecordByToken( const sptr &token) const { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (!token) { return nullptr; } @@ -1833,6 +1835,7 @@ std::shared_ptr MissionListManager::GetAbilityFromTerminateListIn int MissionListManager::ClearMission(int missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (missionId < 0) { TAG_LOGE(AAFwkTag::ABILITYMGR, "Mission id is invalid."); return ERR_INVALID_VALUE; @@ -1869,6 +1872,7 @@ int MissionListManager::ClearMissionLocking(int missionId, const std::shared_ptr int MissionListManager::ClearMissionLocked(int missionId, const std::shared_ptr &mission) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (missionId != -1) { DelayedSingleton::GetInstance()->DeleteMissionInfo(missionId); if (listenerController_) { @@ -1902,19 +1906,23 @@ int MissionListManager::ClearMissionLocked(int missionId, const std::shared_ptr< int MissionListManager::ClearAllMissions() { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard guard(managerLock_); DelayedSingleton::GetInstance()->DeleteAllMissionInfos(listenerController_); std::list> foregroundAbilities; ClearAllMissionsLocked(defaultStandardList_->GetAllMissions(), foregroundAbilities, false); ClearAllMissionsLocked(defaultSingleList_->GetAllMissions(), foregroundAbilities, false); - - for (auto listIter = currentMissionLists_.begin(); listIter != currentMissionLists_.end();) { - auto missionList = (*listIter); - listIter++; - if (!missionList || missionList->GetType() == MissionListType::LAUNCHER) { - continue; + { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, + "for (auto listIter = currentMissionLists_.begin(); listIter != currentMissionLists_.end();)"); + for (auto listIter = currentMissionLists_.begin(); listIter != currentMissionLists_.end();) { + auto missionList = (*listIter); + listIter++; + if (!missionList || missionList->GetType() == MissionListType::LAUNCHER) { + continue; + } + ClearAllMissionsLocked(missionList->GetAllMissions(), foregroundAbilities, true); } - ClearAllMissionsLocked(missionList->GetAllMissions(), foregroundAbilities, true); } ClearAllMissionsLocked(foregroundAbilities, foregroundAbilities, false); @@ -1924,6 +1932,7 @@ int MissionListManager::ClearAllMissions() void MissionListManager::ClearAllMissionsLocked(std::list> &missionList, std::list> &foregroundAbilities, bool searchActive) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); for (auto listIter = missionList.begin(); listIter != missionList.end();) { auto mission = (*listIter); listIter++; @@ -1956,6 +1965,7 @@ void MissionListManager::ClearAllMissionsLocked(std::list MissionListManager::GetAbilityTokenByMissionId(int32_t missionId) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard guard(managerLock_); sptr result = nullptr; for (auto missionList : currentMissionLists_) { @@ -3588,6 +3599,7 @@ void MissionListManager::RegisterSnapshotHandler(const sptr& h bool MissionListManager::GetMissionSnapshot(int32_t missionId, const sptr& abilityToken, MissionSnapshot& missionSnapshot, bool isLowResolution) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "snapshot: Start get mission snapshot."); bool forceSnapshot = false; { @@ -3604,6 +3616,7 @@ bool MissionListManager::GetMissionSnapshot(int32_t missionId, const sptr &info, bool isPerm) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard guard(managerLock_); auto func = [&info, isPerm](const std::shared_ptr &mission) { @@ -3634,6 +3647,7 @@ void MissionListManager::GetAbilityRunningInfos(std::vector auto list = defaultSingleList_->GetAllMissions(); std::for_each(list.begin(), list.end(), func); } + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "for (auto missionList : currentMissionLists_)"); for (auto missionList : currentMissionLists_) { if (!(missionList->GetAllMissions().empty())) { auto list = missionList->GetAllMissions(); diff --git a/services/abilitymgr/src/pending_want_manager.cpp b/services/abilitymgr/src/pending_want_manager.cpp index 7d4bd058bd..f7ca346c13 100644 --- a/services/abilitymgr/src/pending_want_manager.cpp +++ b/services/abilitymgr/src/pending_want_manager.cpp @@ -24,6 +24,7 @@ #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" @@ -337,6 +338,7 @@ int32_t PendingWantManager::PendingRecordIdCreate() sptr PendingWantManager::GetPendingWantRecordByCode(int32_t code) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::WANTAGENT, "begin. wantRecords_ size = %{public}zu", wantRecords_.size()); std::lock_guard locker(mutex_); @@ -497,6 +499,7 @@ void PendingWantManager::UnregisterCancelListener(const sptr &sende int32_t PendingWantManager::GetPendingRequestWant(const sptr &target, std::shared_ptr &want) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::WANTAGENT, "begin"); if (target == nullptr) { TAG_LOGE(AAFwkTag::WANTAGENT, "%{public}s:target is nullptr.", __func__); diff --git a/services/abilitymgr/src/rdb/ability_resident_process_rdb.cpp b/services/abilitymgr/src/rdb/ability_resident_process_rdb.cpp new file mode 100644 index 0000000000..9f48d1fb73 --- /dev/null +++ b/services/abilitymgr/src/rdb/ability_resident_process_rdb.cpp @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_resident_process_rdb.h" +#include "hilog_tag_wrapper.h" +#include "parser_util.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +const std::string ABILITY_RDB_TABLE_NAME = "resident_process_list"; +const std::string KEY_BUNDLE_NAME = "KEY_BUNDLE_NAME"; +const std::string KEY_KEEP_ALIVE_ENABLE = "KEEP_ALIVE_ENABLE"; +const std::string KEY_KEEP_ALIVE_CONFIGURED_LIST = "KEEP_ALIVE_CONFIGURED_LIST"; + +const int32_t INDEX_BUNDLE_NAME = 0; +const int32_t INDEX_KEEP_ALIVE_ENABLE = 1; +const int32_t INDEX_KEEP_ALIVE_CONFIGURED_LIST = 2; +} // namespace + +AmsResidentProcessRdbCallBack::AmsResidentProcessRdbCallBack(const AmsRdbConfig &rdbConfig) : rdbConfig_(rdbConfig) {} + +int32_t AmsResidentProcessRdbCallBack::OnCreate(NativeRdb::RdbStore &rdbStore) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "OnCreate"); + + std::string createTableSql = "CREATE TABLE IF NOT EXISTS " + rdbConfig_.tableName + + " (KEY_BUNDLE_NAME TEXT NOT NULL PRIMARY KEY," + + "KEEP_ALIVE_ENABLE TEXT NOT NULL, KEEP_ALIVE_CONFIGURED_LIST TEXT NOT NULL);"; + auto sqlResult = rdbStore.ExecuteSql(createTableSql); + if (sqlResult != NativeRdb::E_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability mgr rdb execute sql error"); + return sqlResult; + } + + auto &parser = ParserUtil::GetInstance(); + std::vector> initList; + parser.GetResidentProcessRawData(initList); + + std::vector valuesBuckets; + for (const auto &item : initList) { + NativeRdb::ValuesBucket valuesBucket; + valuesBucket.PutString(KEY_BUNDLE_NAME, std::get(item)); + valuesBucket.PutString(KEY_KEEP_ALIVE_ENABLE, std::get(item)); + valuesBucket.PutString(KEY_KEEP_ALIVE_CONFIGURED_LIST, std::get(item)); + + valuesBuckets.emplace_back(valuesBucket); + } + + int64_t rowId = -1; + int64_t insertNum = 0; + int32_t ret = rdbStore.BatchInsert(insertNum, rdbConfig_.tableName, valuesBuckets); + if (ret != NativeRdb::E_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability mgr rdb batch insert error[%{public}d]", ret); + return ret; + } + return NativeRdb::E_OK; +} + +int32_t AmsResidentProcessRdbCallBack::OnUpgrade(NativeRdb::RdbStore &rdbStore, int currentVersion, int targetVersion) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "OnUpgrade currentVersion: %{plubic}d, targetVersion: %{plubic}d", currentVersion, + targetVersion); + return NativeRdb::E_OK; +} + +int32_t AmsResidentProcessRdbCallBack::OnDowngrade(NativeRdb::RdbStore &rdbStore, int currentVersion, int targetVersion) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "OnDowngrade currentVersion: %{plubic}d, targetVersion: %{plubic}d", currentVersion, + targetVersion); + return NativeRdb::E_OK; +} + +int32_t AmsResidentProcessRdbCallBack::OnOpen(NativeRdb::RdbStore &rdbStore) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "OnOpen"); + return NativeRdb::E_OK; +} + +int32_t AmsResidentProcessRdbCallBack::onCorruption(std::string databaseFile) +{ + TAG_LOGI(AAFwkTag::ABILITYMGR, "onCorruption"); + return NativeRdb::E_OK; +} + +int32_t AmsResidentProcessRdb::Init() +{ + if (rdbMgr_ != nullptr) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Rdb mgr existed."); + return Rdb_OK; + } + + AmsRdbConfig config; + config.tableName = ABILITY_RDB_TABLE_NAME; + rdbMgr_ = std::make_unique(config); + if (rdbMgr_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to create database mgr object."); + return Rdb_Init_Err; + } + + AmsResidentProcessRdbCallBack amsCallback(config); + if (rdbMgr_->Init(amsCallback) != Rdb_OK) { + return Rdb_Init_Err; + } + + return Rdb_OK; +} + +AmsResidentProcessRdb &AmsResidentProcessRdb::GetInstance() +{ + static AmsResidentProcessRdb instance; + return instance; +} + +int32_t AmsResidentProcessRdb::VerifyConfigurationPermissions( + const std::string &bundleName, const std::string &callerBundleName) +{ + if (bundleName.empty() || callerBundleName.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Bundle name is null."); + return Rdb_Parameter_Err; + } + + if (bundleName == callerBundleName) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "The caller and the called are the same."); + return Rdb_OK; + } + + if (rdbMgr_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Rdb mgr error."); + return Rdb_Parameter_Err; + } + + NativeRdb::AbsRdbPredicates absRdbPredicates(ABILITY_RDB_TABLE_NAME); + absRdbPredicates.EqualTo(KEY_BUNDLE_NAME, bundleName); + auto absSharedResultSet = rdbMgr_->QueryData(absRdbPredicates); + if (absSharedResultSet == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability mgr rdb query data failed."); + return Rdb_Permissions_Err; + } + + ScopeGuard stateGuard([absSharedResultSet] { absSharedResultSet->Close(); }); + auto ret = absSharedResultSet->GoToFirstRow(); + if (ret != NativeRdb::E_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Go to first row failed, ret: %{public}d", ret); + return Rdb_Search_Record_Err; + } + + std::string KeepAliveConfiguredList; + ret = absSharedResultSet->GetString(INDEX_KEEP_ALIVE_CONFIGURED_LIST, KeepAliveConfiguredList); + if (ret != NativeRdb::E_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Get configured list failed, ret: %{public}d", ret); + return Rdb_Search_Record_Err; + } + + if (KeepAliveConfiguredList.find(callerBundleName) != std::string::npos) { + return Rdb_OK; + } + + return Rdb_Permissions_Err; +} + +int32_t AmsResidentProcessRdb::GetResidentProcessEnable(const std::string &bundleName, bool &enable) +{ + if (bundleName.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Bundle name is null."); + return Rdb_Parameter_Err; + } + + if (rdbMgr_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Rdb mgr error."); + return Rdb_Parameter_Err; + } + + NativeRdb::AbsRdbPredicates absRdbPredicates(ABILITY_RDB_TABLE_NAME); + absRdbPredicates.EqualTo(KEY_BUNDLE_NAME, bundleName); + auto absSharedResultSet = rdbMgr_->QueryData(absRdbPredicates); + if (absSharedResultSet == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability mgr rdb query data failed."); + return Rdb_Permissions_Err; + } + + ScopeGuard stateGuard([absSharedResultSet] { absSharedResultSet->Close(); }); + auto ret = absSharedResultSet->GoToFirstRow(); + if (ret != NativeRdb::E_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Go to first row failed, ret: %{public}d", ret); + return Rdb_Search_Record_Err; + } + + std::string flag; + ret = absSharedResultSet->GetString(INDEX_KEEP_ALIVE_ENABLE, flag); + if (ret != NativeRdb::E_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Get enable status failed, ret: %{public}d", ret); + return Rdb_Search_Record_Err; + } + + enable = static_cast(std::stoul(flag)); + return Rdb_OK; +} + +int32_t AmsResidentProcessRdb::UpdateResidentProcessEnable(const std::string &bundleName, bool enable) +{ + if (bundleName.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Bundle name is null."); + return Rdb_Parameter_Err; + } + + if (rdbMgr_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Rdb mgr error."); + return Rdb_Parameter_Err; + } + + NativeRdb::ValuesBucket valuesBucket; + valuesBucket.PutString(KEY_KEEP_ALIVE_ENABLE, std::to_string(enable)); + NativeRdb::AbsRdbPredicates absRdbPredicates(ABILITY_RDB_TABLE_NAME); + absRdbPredicates.EqualTo(KEY_BUNDLE_NAME, bundleName); + return rdbMgr_->UpdateData(valuesBucket, absRdbPredicates); +} + +int32_t AmsResidentProcessRdb::RemoveData(std::string &bundleName) +{ + if (bundleName.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Bundle name is null."); + return Rdb_Parameter_Err; + } + + if (rdbMgr_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Rdb mgr error."); + return Rdb_Parameter_Err; + } + NativeRdb::AbsRdbPredicates absRdbPredicates(ABILITY_RDB_TABLE_NAME); + absRdbPredicates.EqualTo(KEY_BUNDLE_NAME, bundleName); + return rdbMgr_->DeleteData(absRdbPredicates); +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/rdb/parser_util.cpp b/services/abilitymgr/src/rdb/parser_util.cpp new file mode 100644 index 0000000000..feab00dddc --- /dev/null +++ b/services/abilitymgr/src/rdb/parser_util.cpp @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "parser_util.h" + +#include + +#include "config_policy_utils.h" +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr const char *DEFAULT_PRE_BUNDLE_ROOT_DIR = "/system"; +constexpr const char *PRODUCT_SUFFIX = "/etc/app"; +constexpr const char *INSTALL_LIST_CAPABILITY_CONFIG = "/install_list_capability.json"; +constexpr const char *INSTALL_LIST = "install_list"; +constexpr const char *BUNDLE_NAME = "bundleName"; +constexpr const char *KEEP_ALIVE = "keepAlive"; +constexpr const char *KEEP_ALIVE_ENABLE = "KeepAliveEnable"; +constexpr const char *KEEP_ALIVE_CONFIGURED_LIST = "KeepAliveConfiguredList"; + +} // namespace +ParserUtil &ParserUtil::GetInstance() +{ + static ParserUtil instance; + return instance; +} + +void ParserUtil::GetResidentProcessRawData(std::vector> &list) +{ + std::vector rootDirList; + GetPreInstallRootDirList(rootDirList); + + for (auto &root : rootDirList) { + auto fileDir = root.append(PRODUCT_SUFFIX).append(INSTALL_LIST_CAPABILITY_CONFIG); + TAG_LOGD(AAFwkTag::ABILITYMGR, "Search file dir : %{public}s", fileDir.c_str()); + ParsePreInstallAbilityConfig(fileDir, list); + } +} + +void ParserUtil::ParsePreInstallAbilityConfig( + const std::string &filePath, std::vector> &list) +{ + nlohmann::json jsonBuf; + if (!ReadFileIntoJson(filePath, jsonBuf)) { + return; + } + + if (jsonBuf.is_discarded()) { + return; + } + + FilterInfoFromJson(jsonBuf, list); +} + +bool ParserUtil::FilterInfoFromJson( + nlohmann::json &jsonBuf, std::vector> &list) +{ + if (jsonBuf.is_discarded()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Profile format error"); + return false; + } + + if (jsonBuf.find(INSTALL_LIST) == jsonBuf.end()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "InstallList not exist"); + return false; + } + + auto arrays = jsonBuf.at(INSTALL_LIST); + if (!arrays.is_array() || arrays.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Array not found"); + return false; + } + + std::string bundleName; + std::string KeepAliveEnable = "1"; + std::string KeepAliveConfiguredList; + for (const auto &array : arrays) { + if (!array.is_object()) { + continue; + } + + // Judgment logic exists, not found, not bool, not resident process + if (!(array.find(KEEP_ALIVE) != array.end() && array.at(KEEP_ALIVE).is_boolean() && + array.at(KEEP_ALIVE).get())) { + continue; + } + + if (!(array.find(BUNDLE_NAME) != array.end() && array.at(BUNDLE_NAME).is_string())) { + continue; + } + + bundleName = array.at(BUNDLE_NAME).get(); + + if (array.find(KEEP_ALIVE_ENABLE) != array.end() && array.at(KEEP_ALIVE_ENABLE).is_boolean()) { + auto val = array.at(KEEP_ALIVE_ENABLE).get(); + KeepAliveEnable = std::to_string(val); + } + + if (array.find(KEEP_ALIVE_CONFIGURED_LIST) != array.end() && array.at(KEEP_ALIVE_CONFIGURED_LIST).is_array()) { + // Save directly in the form of an array and parse it when in use + KeepAliveConfiguredList = array.at(KEEP_ALIVE_CONFIGURED_LIST).dump(); + } + + list.emplace_back(std::make_tuple(bundleName, KeepAliveEnable, KeepAliveConfiguredList)); + bundleName.clear(); + KeepAliveEnable = "1"; + KeepAliveConfiguredList.clear(); + } + + return true; +} + +void ParserUtil::GetPreInstallRootDirList(std::vector &rootDirList) +{ + auto cfgDirList = GetCfgDirList(); + if (cfgDirList != nullptr) { + for (const auto &cfgDir : cfgDirList->paths) { + if (cfgDir == nullptr) { + continue; + } + rootDirList.emplace_back(cfgDir); + } + + FreeCfgDirList(cfgDirList); + } + bool ret = std::find(rootDirList.begin(), rootDirList.end(), DEFAULT_PRE_BUNDLE_ROOT_DIR) != rootDirList.end(); + if (!ret) { + rootDirList.emplace_back(DEFAULT_PRE_BUNDLE_ROOT_DIR); + } +} + +bool ParserUtil::ReadFileIntoJson(const std::string &filePath, nlohmann::json &jsonBuf) +{ + if (filePath.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "File path empty."); + return false; + } + + std::ifstream fin(filePath); + if (!fin.is_open()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "File path exception."); + return false; + } + + fin.seekg(0, std::ios::end); + int64_t size = fin.tellg(); + if (size <= 0) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "The file is an empty file!"); + fin.close(); + return false; + } + + fin.seekg(0, std::ios::beg); + jsonBuf = nlohmann::json::parse(fin, nullptr, false); + fin.close(); + if (jsonBuf.is_discarded()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Bad profile file"); + return false; + } + return true; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/rdb/rdb_data_manager.cpp b/services/abilitymgr/src/rdb/rdb_data_manager.cpp new file mode 100644 index 0000000000..b303cad9a2 --- /dev/null +++ b/services/abilitymgr/src/rdb/rdb_data_manager.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 "rdb_data_manager.h" + +#include "hilog_tag_wrapper.h" +#include "rdb_errno.h" +#include "rdb_store_config.h" + +namespace OHOS { +namespace AbilityRuntime { +int32_t RdbDataManager::Init(NativeRdb::RdbOpenCallback &rdbCallback) +{ + std::lock_guard lock(rdbMutex_); + if (rdbStore_ != nullptr) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Ability mgr rdb has existed"); + return NativeRdb::E_OK; + } + + NativeRdb::RdbStoreConfig rdbStoreConfig(amsRdbConfig_.dbPath + amsRdbConfig_.dbName); + rdbStoreConfig.SetSecurityLevel(NativeRdb::SecurityLevel::S1); + + int32_t ret = NativeRdb::E_OK; + rdbStore_ = NativeRdb::RdbHelper::GetRdbStore(rdbStoreConfig, amsRdbConfig_.version, rdbCallback, ret); + if (rdbStore_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability mgr rdb init fail"); + return NativeRdb::E_ERROR; + } + + return NativeRdb::E_OK; +} + +int32_t RdbDataManager::InsertData(const NativeRdb::ValuesBucket &valuesBucket) +{ + std::lock_guard lock(rdbMutex_); + if (rdbStore_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Rdb store is null"); + return NativeRdb::E_ERROR; + } + + int64_t rowId = -1; + return rdbStore_->InsertWithConflictResolution( + rowId, amsRdbConfig_.tableName, valuesBucket, NativeRdb::ConflictResolution::ON_CONFLICT_REPLACE); +} + +int32_t RdbDataManager::BatchInsert(int64_t &outInsertNum, const std::vector &valuesBuckets) +{ + std::lock_guard lock(rdbMutex_); + if (rdbStore_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Rdb store is null"); + return NativeRdb::E_ERROR; + } + auto ret = rdbStore_->BatchInsert(outInsertNum, amsRdbConfig_.tableName, valuesBuckets); + return ret == NativeRdb::E_OK; +} + +int32_t RdbDataManager::UpdateData( + const NativeRdb::ValuesBucket &valuesBucket, const NativeRdb::AbsRdbPredicates &absRdbPredicates) +{ + std::lock_guard lock(rdbMutex_); + if (rdbStore_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Rdb store is null"); + return NativeRdb::E_ERROR; + } + if (absRdbPredicates.GetTableName() != amsRdbConfig_.tableName) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Rdb store table is invalid"); + return NativeRdb::E_ERROR; + } + int32_t rowId = -1; + return rdbStore_->Update(rowId, valuesBucket, absRdbPredicates); +} + +int32_t RdbDataManager::DeleteData(const NativeRdb::AbsRdbPredicates &absRdbPredicates) +{ + std::lock_guard lock(rdbMutex_); + if (rdbStore_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Rdb store is null"); + return NativeRdb::E_ERROR; + } + if (absRdbPredicates.GetTableName() != amsRdbConfig_.tableName) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Rdb store table is invalid"); + return NativeRdb::E_ERROR; + } + int32_t rowId = -1; + return rdbStore_->Delete(rowId, absRdbPredicates); +} + +std::shared_ptr RdbDataManager::QueryData( + const NativeRdb::AbsRdbPredicates &absRdbPredicates) +{ + std::lock_guard lock(rdbMutex_); + if (rdbStore_ == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Rdb store is null"); + return nullptr; + } + if (absRdbPredicates.GetTableName() != amsRdbConfig_.tableName) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Rdb store table is invalid"); + return nullptr; + } + auto absSharedResultSet = rdbStore_->Query(absRdbPredicates, std::vector()); + if (absSharedResultSet == nullptr || !absSharedResultSet->HasBlock()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Query data failed."); + return nullptr; + } + return absSharedResultSet; +} + +void RdbDataManager::ClearCache() +{ + NativeRdb::RdbHelper::ClearCache(); +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/src/resident_process_manager.cpp b/services/abilitymgr/src/resident_process_manager.cpp index 016c3d18c9..3f6b3211c5 100644 --- a/services/abilitymgr/src/resident_process_manager.cpp +++ b/services/abilitymgr/src/resident_process_manager.cpp @@ -16,6 +16,9 @@ #include "resident_process_manager.h" #include "ability_manager_service.h" +#include "ability_resident_process_rdb.h" +#include "ability_util.h" +#include "ffrt.h" #include "hilog_tag_wrapper.h" #include "user_controller.h" @@ -27,6 +30,12 @@ ResidentProcessManager::ResidentProcessManager() ResidentProcessManager::~ResidentProcessManager() {} +void ResidentProcessManager::Init() +{ + auto &amsRdb = AmsResidentProcessRdb::GetInstance(); + amsRdb.Init(); +} + void ResidentProcessManager::StartResidentProcess(const std::vector &bundleInfos) { DelayedSingleton::GetInstance()->StartupResidentProcess(bundleInfos); @@ -38,7 +47,10 @@ void ResidentProcessManager::StartResidentProcessWithMainElement(std::vector::GetInstance(); + if (appMgrClient != nullptr) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Set keep alive enable state."); + IN_PROCESS_CALL_WITHOUT_RET(appMgrClient->SetKeepAliveEnableState(bundleName, updateEnable)); + } + + ffrt::submit(std::bind(&ResidentProcessManager::UpdateResidentProcessesStatus, shared_from_this(), bundleName, + localEnable, updateEnable)); + return ERR_OK; +} + +void ResidentProcessManager::UpdateResidentProcessesStatus( + const std::string &bundleName, bool localEnable, bool updateEnable) +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, "Called."); + if (bundleName.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Bundle name is empty!"); + return; + } + + auto bms = AbilityUtil::GetBundleManagerHelper(); + if (bms == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to obtain bms handle!"); + return; + } + + AppExecFwk::BundleInfo bundleInfo; + // user 0 + int32_t userId = 0; + if (!IN_PROCESS_CALL(bms->GetBundleInfo( + bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get bundle info."); + return; + } + + // need start + if (updateEnable && !localEnable) { + std::vector bundleInfos{ bundleInfo }; + StartResidentProcessWithMainElement(bundleInfos); + if (!bundleInfos.empty()) { + StartResidentProcess(bundleInfos); + } + return; + } +} + +void ResidentProcessManager::OnAppStateChanged(const AppInfo &info) +{ + TAG_LOGD(AAFwkTag::ABILITYMGR, "Called"); + if (info.state != AppState::BEGIN) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "Not a state of concern. state: %{public}d", info.state); + return; + } + + if (info.pid <= 0) { + TAG_LOGD(AAFwkTag::ABILITYMGR, "The obtained application pid is incorrect. state: %{public}d", info.pid); + return; + } + + std::string bundleName; + // user 0 + int32_t uid = 0; + auto appScheduler = DelayedSingleton::GetInstance(); + if (appScheduler == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "App scheduler error."); + return; + } + appScheduler->GetBundleNameByPid(info.pid, bundleName, uid); + if (bundleName.empty()) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Get bundle name by pid failed."); + return; + } + + bool localEnable = false; + auto rdbResult = AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleName, localEnable); + if (rdbResult != Rdb_OK) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to obtain resident process properties. result: %{public}d", rdbResult); + return; + } + + auto appMgrClient = DelayedSingleton::GetInstance(); + if (appMgrClient == nullptr) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Set keep alive enable state error."); + return; + } + IN_PROCESS_CALL_WITHOUT_RET(appMgrClient->SetKeepAliveEnableState(bundleName, localEnable)); +} } // namespace AAFwk } // namespace OHOS 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 a6907f351c..57bcb20dd2 100644 --- a/services/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp +++ b/services/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp @@ -901,6 +901,9 @@ int UIAbilityLifecycleManager::NotifySCBPendingActivation(sptr &ses CHECK_POINTER_AND_RETURN(callerSessionInfo, ERR_INVALID_VALUE); CHECK_POINTER_AND_RETURN(callerSessionInfo->sessionToken, ERR_INVALID_VALUE); auto callerSession = iface_cast(callerSessionInfo->sessionToken); + bool hasContinuousTask = DelayedSingleton::GetInstance()-> + IsBackgroundTaskUid(abilityRecord->GetUid()); + sessionInfo->hasContinuousTask = hasContinuousTask; TAG_LOGI(AAFwkTag::ABILITYMGR, "Call PendingSessionActivation by callerSession."); return static_cast(callerSession->PendingSessionActivation(sessionInfo)); } @@ -1609,6 +1612,9 @@ int UIAbilityLifecycleManager::SendSessionInfoToSCB(std::shared_ptrGetSessionInfo(); if (callerSessionInfo != nullptr && callerSessionInfo->sessionToken != nullptr) { auto callerSession = iface_cast(callerSessionInfo->sessionToken); + bool hasContinuousTask = DelayedSingleton::GetInstance()-> + IsBackgroundTaskUid(callerAbility->GetUid()); + sessionInfo->hasContinuousTask = hasContinuousTask; callerSession->PendingSessionActivation(sessionInfo); } else { CHECK_POINTER_AND_RETURN(rootSceneSession_, ERR_INVALID_VALUE); @@ -2114,6 +2120,7 @@ void UIAbilityLifecycleManager::DumpMissionListByRecordId(std::vector startOptions) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); CHECK_POINTER_AND_RETURN(rootSceneSession_, ERR_INVALID_VALUE); std::shared_ptr abilityRecord = GetAbilityRecordsById(sessionId); CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE); 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 90295e15e7..6bd44f65a6 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 @@ -17,6 +17,7 @@ #include #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" +#include "hitrace_meter.h" #include "ability_manager_errors.h" #include "ability_util.h" #include "ability_manager_service.h" @@ -61,6 +62,7 @@ bool StartAbilitySandboxSavefile::MatchStartRequest(StartAbilityParams ¶ms) int StartAbilitySandboxSavefile::HandleStartRequest(StartAbilityParams ¶ms) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::ABILITYMGR, "called"); auto callerRecord = params.GetCallerRecord(); if (!callerRecord) { @@ -84,6 +86,7 @@ int StartAbilitySandboxSavefile::HandleStartRequest(StartAbilityParams ¶ms) int StartAbilitySandboxSavefile::StartAbility(StartAbilityParams ¶ms, int requestCode) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); AbilityRequest abilityRequest; abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; abilityRequest.callerUid = IPCSkeleton::GetCallingUid(); diff --git a/services/abilitymgr/src/system_dialog_scheduler.cpp b/services/abilitymgr/src/system_dialog_scheduler.cpp index 564d20cd64..8dd0ddb949 100644 --- a/services/abilitymgr/src/system_dialog_scheduler.cpp +++ b/services/abilitymgr/src/system_dialog_scheduler.cpp @@ -29,6 +29,7 @@ #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" #include "parameters.h" @@ -133,6 +134,7 @@ const float SETX_WIDTH_MULTIPLE = 0.1; Want SystemDialogScheduler::GetTipsDialogWant(const sptr &callerToken) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::DIALOG, "GetTipsDialogWant start"); DialogPosition position; @@ -272,6 +274,7 @@ void SystemDialogScheduler::GetSelectorDialogLandscapePosition( void SystemDialogScheduler::GetSelectorDialogPositionAndSize( DialogPosition &portraitPosition, DialogPosition &landscapePosition, int lineNums) const { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); portraitPosition.wideScreen = !AppUtils::GetInstance().IsSelectorDialogDefaultPossion(); portraitPosition.align = AppUtils::GetInstance().IsSelectorDialogDefaultPossion() ? DialogAlign::BOTTOM : DialogAlign::CENTER; @@ -316,6 +319,7 @@ void SystemDialogScheduler::GetSelectorDialogPositionAndSize( int SystemDialogScheduler::GetSelectorDialogWant(const std::vector &dialogAppInfos, Want &targetWant, const sptr &callerToken) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::DIALOG, "GetSelectorDialogWant start"); DialogPosition portraitPosition; DialogPosition landscapePosition; @@ -331,6 +335,7 @@ int SystemDialogScheduler::GetSelectorDialogWant(const std::vector &infos) const { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (infos.empty()) { TAG_LOGW(AAFwkTag::DIALOG, "Invalid abilityInfos."); return {}; @@ -357,6 +362,7 @@ const std::string SystemDialogScheduler::GetSelectorParams(const std::vector &dialogAppInfos, Want &targetWant, const std::string &type, int32_t userId, const sptr &callerToken) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::DIALOG, "GetPcSelectorDialogWant start"); DialogPosition position; GetDialogPositionAndSize(DialogType::DIALOG_SELECTOR, position, static_cast(dialogAppInfos.size())); @@ -406,6 +412,7 @@ const std::string SystemDialogScheduler::GetPcSelectorParams(const std::vector &dialogAppInfos, Want &targetWant, const sptr &callerToken) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::DIALOG, "GetSelectorDialogWantCommon start"); bool isCallerStageBasedModel = true; if (callerToken != nullptr) { @@ -526,6 +533,7 @@ void SystemDialogScheduler::DialogPositionAdaptive(DialogPosition &position, int void SystemDialogScheduler::GetDialogPositionAndSize(DialogType type, DialogPosition &position, int lineNums) const { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); InitDialogPosition(type, position); auto display = Rosen::DisplayManager::GetInstance().GetDefaultDisplay(); diff --git a/services/abilitymgr/src/task_data_persistence_mgr.cpp b/services/abilitymgr/src/task_data_persistence_mgr.cpp index d84bc34b09..ac3edcb2d9 100644 --- a/services/abilitymgr/src/task_data_persistence_mgr.cpp +++ b/services/abilitymgr/src/task_data_persistence_mgr.cpp @@ -18,6 +18,7 @@ #include "directory_ex.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" +#include "hitrace_meter.h" namespace OHOS { namespace AAFwk { @@ -149,6 +150,7 @@ std::shared_ptr TaskDataPersistenceMgr::GetSnapshot(int mission bool TaskDataPersistenceMgr::GetMissionSnapshot(int missionId, MissionSnapshot& snapshot, bool isLowResolution) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard lock(mutex_); if (!currentMissionDataStorage_) { TAG_LOGE(AAFwkTag::ABILITYMGR, "snapshot: currentMissionDataStorage_ is nullptr"); diff --git a/services/appmgr/BUILD.gn b/services/appmgr/BUILD.gn index ee52024167..71c2d417af 100644 --- a/services/appmgr/BUILD.gn +++ b/services/appmgr/BUILD.gn @@ -123,11 +123,15 @@ ohos_shared_library("libappms") { "kv_store:distributeddata_inner", "kv_store:distributeddata_mgr", "memory_utils:libmeminfo", + "os_account:libaccountkits", "resource_schedule_service:ressched_client", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] public_external_deps = [ "kv_store:distributeddata_mgr" ] + + defines += [ "OHOS_ACCOUNT_ENABLED" ] + if (product_name != "ohcore") { external_deps += [ "netmanager_base:net_conn_manager_if" ] } diff --git a/services/appmgr/include/ams_mgr_scheduler.h b/services/appmgr/include/ams_mgr_scheduler.h index 32787fa0eb..7c70d3a2e4 100644 --- a/services/appmgr/include/ams_mgr_scheduler.h +++ b/services/appmgr/include/ams_mgr_scheduler.h @@ -267,6 +267,13 @@ public: */ bool IsAttachDebug(const std::string &bundleName) override; + /** + * @brief Set resident process enable status. + * @param bundleName The application bundle name. + * @param enable The current updated enable status. + */ + void SetKeepAliveEnableState(const std::string &bundleName, bool enable) override; + /** * Set application assertion pause state. * diff --git a/services/appmgr/include/app_mgr_service.h b/services/appmgr/include/app_mgr_service.h index 74fac1222e..ce653ae473 100644 --- a/services/appmgr/include/app_mgr_service.h +++ b/services/appmgr/include/app_mgr_service.h @@ -147,6 +147,17 @@ public: */ virtual int32_t GetAllRunningProcesses(std::vector &info) override; + /** + * GetRunningProcessesByBundleType, call GetRunningProcessesByBundleType() through proxy project. + * Obtains information about application processes by bundle type that are running on the device. + * + * @param bundleType, bundle type of the processes + * @param info, app name in Application record. + * @return ERR_OK ,return back success,others fail. + */ + virtual int GetRunningProcessesByBundleType(const BundleType bundleType, + std::vector &info) override; + /** * GetAllRenderProcesses, call GetAllRenderProcesses() through proxy project. * Obtains information about render processes that are running on the device. @@ -453,7 +464,8 @@ public: * @param childPid Created child process pid. * @return Returns ERR_OK on success, others on failure. */ - int32_t StartChildProcess(const std::string &srcEntry, pid_t &childPid) override; + int32_t StartChildProcess(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCoun, + bool isStartWithDebug) override; /** * Get child process record for self. diff --git a/services/appmgr/include/app_mgr_service_inner.h b/services/appmgr/include/app_mgr_service_inner.h index 46fb78fe1b..8e94a1331f 100644 --- a/services/appmgr/include/app_mgr_service_inner.h +++ b/services/appmgr/include/app_mgr_service_inner.h @@ -305,6 +305,16 @@ public: */ virtual int32_t GetAllRunningProcesses(std::vector &info); + /** + * GetRunningProcessesByBundleType, Obtains information about application processes by bundle type. + * + * @param bundleType, the bundle type of the application process + * @param info, app name in Application record. + * + * @return ERR_OK ,return back success,others fail. + */ + virtual int32_t GetRunningProcessesByBundleType(BundleType bundleType, std::vector &info); + /** * GetProcessRunningInfosByUserId, Obtains information about application processes that are running on the device. * @@ -955,7 +965,8 @@ public: * @param childPid Created child process pid. * @return Returns ERR_OK on success, others on failure. */ - virtual int32_t StartChildProcess(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid); + virtual int32_t StartChildProcess(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid, + int32_t childProcessCount, bool isStartWithDebug); /** * Get child process record for self. @@ -1016,6 +1027,8 @@ public: void SetAppAssertionPauseState(int32_t pid, bool flag); + void SetKeepAliveEnableState(const std::string &bundleName, bool enable); + int32_t GetAppRunningUniqueIdByPid(pid_t pid, std::string &appRunningUniqueId); int32_t GetAllUIExtensionRootHostPid(pid_t pid, std::vector &hostPids); diff --git a/services/appmgr/include/app_running_record.h b/services/appmgr/include/app_running_record.h index d79be97571..200d7e34b8 100644 --- a/services/appmgr/include/app_running_record.h +++ b/services/appmgr/include/app_running_record.h @@ -536,9 +536,9 @@ public: bool IsEmptyKeepAliveApp() const; - void SetKeepAliveAppState(bool isKeepAlive, bool isEmptyKeepAliveApp); + void SetEmptyKeepAliveAppState(bool isEmptyKeepAliveApp); - void SetEmptyKeepAliveAppState(bool isEmptyKeepAlive); + void SetKeepAliveEnableState(bool isKeepAliveEnable); void SetStageModelState(bool isStageBasedModel); @@ -593,6 +593,7 @@ public: bool IsDebugging() const; 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); std::shared_ptr GetRenderRecordByPid(const pid_t pid); @@ -749,7 +750,7 @@ public: void SetAssertionPauseFlag(bool flag); bool IsAssertionPause() const; - + void SetJITEnabled(const bool jitEnabled); bool IsJITEnabled() const; @@ -906,6 +907,7 @@ private: bool isRestartApp_ = false; // Only app calling RestartApp can be set to true bool isAssertPause_ = false; bool isNativeStart_ = false; + bool isMultiThread_ = false; SupportProcessCacheState procCacheSupportState_ = SupportProcessCacheState::UNSPECIFIED; }; diff --git a/services/appmgr/include/app_spawn_client.h b/services/appmgr/include/app_spawn_client.h index b7d056f6e5..bdfc4c789e 100644 --- a/services/appmgr/include/app_spawn_client.h +++ b/services/appmgr/include/app_spawn_client.h @@ -65,6 +65,8 @@ struct AppSpawnStartMsg { std::set permissions; std::map appEnv; // environment variable to be set to the process std::string ownerId; + bool atomicServiceFlag = false; + std::string atomicAccount = ""; }; constexpr auto LEN_PID = sizeof(pid_t); @@ -150,6 +152,14 @@ public: */ int32_t SetStartFlags(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle); + /** + * Set atomic service flags. + * + * @param startMsg, request message. + * @param reqHandle, handle for request message + */ + int32_t SetAtomicServiceFlag(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle); + /** * Set extra info: render-cmd, HspList, Overlay, DataGroup, AppEnv. * diff --git a/services/appmgr/include/child_process_record.h b/services/appmgr/include/child_process_record.h index 0ca27a6a7a..bb3565a946 100644 --- a/services/appmgr/include/child_process_record.h +++ b/services/appmgr/include/child_process_record.h @@ -29,11 +29,12 @@ class AppRunningRecord; class ChildProcessRecord { public: - ChildProcessRecord(pid_t hostPid, const std::string &srcEntry, const std::shared_ptr hostRecord); + ChildProcessRecord(pid_t hostPid, const std::string &srcEntry, const std::shared_ptr hostRecord, + int32_t childProcessCount, bool isStartWithDebug); virtual ~ChildProcessRecord(); static std::shared_ptr CreateChildProcessRecord(pid_t hostPid, const std::string &srcEntry, - const std::shared_ptr hostRecord); + const std::shared_ptr hostRecord, int32_t childProcessCount, bool isStartWithDebug); void SetPid(pid_t pid); pid_t GetPid() const; @@ -49,18 +50,20 @@ public: void RegisterDeathRecipient(); void RemoveDeathRecipient(); void ScheduleExitProcessSafely(); - + bool isStartWithDebug(); private: void MakeProcessName(const std::shared_ptr hostRecord); pid_t pid_ = 0; pid_t hostPid_ = 0; int32_t uid_ = 0; + int32_t childProcessCount_ = 0; std::string processName_; std::string srcEntry_; std::weak_ptr hostRecord_; sptr scheduler_ = nullptr; sptr deathRecipient_ = nullptr; + bool isStartWithDebug_; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/appmgr/src/ams_mgr_scheduler.cpp b/services/appmgr/src/ams_mgr_scheduler.cpp index 11af7ccc97..efe550a89f 100644 --- a/services/appmgr/src/ams_mgr_scheduler.cpp +++ b/services/appmgr/src/ams_mgr_scheduler.cpp @@ -530,6 +530,15 @@ void AmsMgrScheduler::SetAppAssertionPauseState(int32_t pid, bool flag) amsMgrServiceInner_->SetAppAssertionPauseState(pid, flag); } +void AmsMgrScheduler::SetKeepAliveEnableState(const std::string &bundleName, bool enable) +{ + if (!IsReady()) { + TAG_LOGE(AAFwkTag::APPMGR, "AmsMgrService is not ready."); + return; + } + amsMgrServiceInner_->SetKeepAliveEnableState(bundleName, enable); +} + void AmsMgrScheduler::ClearProcessByToken(sptr token) { if (!IsReady()) { diff --git a/services/appmgr/src/app_lifecycle_deal.cpp b/services/appmgr/src/app_lifecycle_deal.cpp index 6987f9cd56..a553af006a 100644 --- a/services/appmgr/src/app_lifecycle_deal.cpp +++ b/services/appmgr/src/app_lifecycle_deal.cpp @@ -234,6 +234,7 @@ void AppLifeCycleDeal::ScheduleNewProcessRequest(const AAFwk::Want &want, const int32_t AppLifeCycleDeal::UpdateConfiguration(const Configuration &config) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "call"); auto appThread = GetApplicationClient(); if (!appThread) { diff --git a/services/appmgr/src/app_mgr_service.cpp b/services/appmgr/src/app_mgr_service.cpp index 45afde2338..da3a6eb82b 100644 --- a/services/appmgr/src/app_mgr_service.cpp +++ b/services/appmgr/src/app_mgr_service.cpp @@ -24,6 +24,7 @@ #include "app_mgr_constants.h" #include "datetime_ex.h" #include "hilog_tag_wrapper.h" +#include "hitrace_meter.h" #include "in_process_call_wrapper.h" #include "ipc_skeleton.h" #include "perf_profile.h" @@ -377,6 +378,15 @@ int32_t AppMgrService::GetAllRunningProcesses(std::vector &i return appMgrServiceInner_->GetAllRunningProcesses(info); } +int32_t AppMgrService::GetRunningProcessesByBundleType(BundleType bundleType, + std::vector &info) +{ + if (!IsReady()) { + return ERR_INVALID_OPERATION; + } + return appMgrServiceInner_->GetRunningProcessesByBundleType(bundleType, info); +} + int32_t AppMgrService::GetAllRenderProcesses(std::vector &info) { if (!IsReady()) { @@ -500,6 +510,7 @@ int32_t AppMgrService::UnregisterApplicationStateObserver(const sptr &observer) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (!IsReady()) { TAG_LOGE(AAFwkTag::APPMGR, "Not ready."); @@ -852,6 +863,7 @@ int32_t AppMgrService::GetConfiguration(Configuration& config) int32_t AppMgrService::UpdateConfiguration(const Configuration& config) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (!IsReady()) { TAG_LOGE(AAFwkTag::APPMGR, "UpdateConfiguration failed, AppMgrService not ready."); return ERR_INVALID_OPERATION; @@ -1168,14 +1180,16 @@ int32_t AppMgrService::IsApplicationRunning(const std::string &bundleName, bool return appMgrServiceInner_->IsApplicationRunning(bundleName, isRunning); } -int32_t AppMgrService::StartChildProcess(const std::string &srcEntry, pid_t &childPid) +int32_t AppMgrService::StartChildProcess(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount, + bool isStartWithDebug) { 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); + return appMgrServiceInner_->StartChildProcess(IPCSkeleton::GetCallingPid(), srcEntry, childPid, childProcessCount, + isStartWithDebug); } int32_t AppMgrService::GetChildProcessInfoForSelf(ChildProcessInfo &info) diff --git a/services/appmgr/src/app_mgr_service_inner.cpp b/services/appmgr/src/app_mgr_service_inner.cpp index 84f64e8a07..7cd6279cad 100644 --- a/services/appmgr/src/app_mgr_service_inner.cpp +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -57,6 +57,9 @@ #include "mem_mgr_client.h" #include "mem_mgr_process_state_info.h" #include "os_account_manager_wrapper.h" +#ifdef OHOS_ACCOUNT_ENABLED +#include "ohos_account_kits.h" +#endif // OHOS_ACCOUNT_ENABLED #include "parameter.h" #include "parameters.h" #include "perf_profile.h" @@ -118,6 +121,7 @@ const std::string FUNC_NAME = "main"; const std::string RENDER_PARAM = "invalidparam"; const std::string COLD_START = "coldStart"; const std::string PERF_CMD = "perfCmd"; +const std::string MULTI_THREAD = "multiThread"; const std::string DEBUG_CMD = "debugCmd"; const std::string ENTER_SANDBOX = "sandboxApp"; const std::string DLP_PARAMS_INDEX = "ohos.dlp.params.index"; @@ -172,6 +176,8 @@ const std::string EVENT_MESSAGE_START_SPECIFIED_PROCESS_TIMEOUT = "Start Specifi const std::string EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT = "Start Specified Ability TimeOut!"; const std::string EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT = "Start Process Specified Ability TimeOut!"; const std::string EVENT_MESSAGE_DEFAULT = "AppMgrServiceInner HandleTimeOut!"; +const std::string SUPPORT_CALL_NOTIFY_MEMORY_CHANGED = + "persist.sys.abilityms.support_call_notify_memory_changed"; const std::string SYSTEM_BASIC = "system_basic"; const std::string SYSTEM_CORE = "system_core"; @@ -612,7 +618,7 @@ void AppMgrServiceInner::LoadAbilityNoAppRecord(const std::shared_ptrSetSpecifiedProcessFlag(specifiedProcessFlag); } if (hapModuleInfo.isStageBasedModel && !IsMainProcess(appInfo, hapModuleInfo)) { - appRecord->SetKeepAliveAppState(false, false); + appRecord->SetEmptyKeepAliveAppState(false); TAG_LOGI(AAFwkTag::APPMGR, "The process %{public}s will not keepalive", hapModuleInfo.process.c_str()); } // As taskHandler_ is busy now, the task should be submit to other task queue. @@ -1346,11 +1352,12 @@ int32_t AppMgrServiceInner::ClearUpApplicationDataByUserId( int32_t AppMgrServiceInner::GetAllRunningProcesses(std::vector &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm(); // check permission for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) { const auto &appRecord = item.second; - if (!appRecord->GetSpawned()) { + if (!appRecord || !appRecord->GetSpawned()) { continue; } if (isPerm) { @@ -1370,6 +1377,28 @@ int32_t AppMgrServiceInner::GetAllRunningProcesses(std::vector &info) +{ + TAG_LOGD(AAFwkTag::APPMGR, "called."); + CHECK_CALLER_IS_SYSTEM_APP; + if (!AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm()) { + TAG_LOGE(AAFwkTag::APPMGR, "permission deny"); + return ERR_PERMISSION_DENIED; + } + for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) { + const auto &appRecord = item.second; + if (!appRecord || !appRecord->GetSpawned()) { + continue; + } + auto appInfo = appRecord->GetApplicationInfo(); + if (appInfo && appInfo->bundleType == bundleType) { + GetRunningProcesses(appRecord, info); + } + } + return ERR_OK; +} + int32_t AppMgrServiceInner::GetProcessRunningInfosByUserId(std::vector &info, int32_t userId) { if (VerifyAccountPermission(AAFwk::PermissionConstants::PERMISSION_GET_RUNNING_INFO, userId) == @@ -1511,6 +1540,7 @@ int32_t AppMgrServiceInner::DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &i void AppMgrServiceInner::GetRunningProcesses(const std::shared_ptr &appRecord, std::vector &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); RunningProcessInfo runningProcessInfo; GetRunningProcess(appRecord, runningProcessInfo); info.emplace_back(runningProcessInfo); @@ -1533,6 +1563,10 @@ void AppMgrServiceInner::GetRunningProcess(const std::shared_ptrGetUserTestInfo() != nullptr && system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) { info.isTestMode = true; } + auto appInfo = appRecord->GetApplicationInfo(); + if (appInfo) { + info.bundleType = static_cast(appInfo->bundleType); + } } void AppMgrServiceInner::GetRenderProcesses(const std::shared_ptr &appRecord, @@ -1694,8 +1728,6 @@ std::shared_ptr AppMgrServiceInner::CreateAppRunningRecord(spt } appRecord->SetProcessAndExtensionType(abilityInfo); - bool isKeepAlive = bundleInfo.isKeepAlive && bundleInfo.singleton; - appRecord->SetKeepAliveAppState(isKeepAlive, false); appRecord->SetTaskHandler(taskHandler_); appRecord->SetEventHandler(eventHandler_); appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want, abilityRecordId); @@ -1706,6 +1738,7 @@ std::shared_ptr AppMgrServiceInner::CreateAppRunningRecord(spt appRecord->SetDebugApp(true); } appRecord->SetPerfCmd(want->GetStringParam(PERF_CMD)); + appRecord->SetMultiThread(want->GetBoolParam(MULTI_THREAD, false)); appRecord->SetAppIndex(want->GetIntParam(DLP_PARAMS_INDEX, 0)); appRecord->SetSecurityFlag(want->GetBoolParam(DLP_PARAMS_SECURITY_FLAG, false)); appRecord->SetRequestProcCode(want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0)); @@ -2468,6 +2501,25 @@ void AppMgrServiceInner::StartProcess(const std::string &appName, const std::str startMsg.flags = startMsg.flags | APP_ACCESS_BUNDLE_DIR; } +#ifdef OHOS_ACCOUNT_ENABLED + TAG_LOGI(AAFwkTag::APPMGR, "execute with OHOS_ACCOUNT_ENABLED on"); + auto appInfo = appRecord->GetApplicationInfo(); + if (appInfo && appInfo->bundleType == BundleType::ATOMIC_SERVICE) { + TAG_LOGI(AAFwkTag::APPMGR, "application is of atomic service type"); + AccountSA::OhosAccountInfo accountInfo; + auto errCode = AccountSA::OhosAccountKits::GetInstance().GetOhosAccountInfo(accountInfo); + if (errCode == ERR_OK) { + TAG_LOGI(AAFwkTag::APPMGR, "GetOhosAccountInfo succeeds, uid %{public}s", accountInfo.uid_.c_str()); + startMsg.atomicServiceFlag = true; + startMsg.atomicAccount = accountInfo.uid_; + } else { + TAG_LOGE(AAFwkTag::APPMGR, "failed to get ohos account info:%{public}d", errCode); + } + } +#else + TAG_LOGI(AAFwkTag::APPMGR, "execute with OHOS_ACCOUNT_ENABLED off"); +#endif // OHOS_ACCOUNT_ENABLED + SetOverlayInfo(bundleName, userId, startMsg); SetAppEnvInfo(bundleInfo, startMsg); @@ -2985,6 +3037,7 @@ void AppMgrServiceInner::HandleAddAbilityStageTimeOut(const int64_t eventId) void AppMgrServiceInner::GetRunningProcessInfoByToken( const sptr &token, AppExecFwk::RunningProcessInfo &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!CheckGetRunningInfoPermission()) { return; @@ -3092,8 +3145,6 @@ void AppMgrServiceInner::StartEmptyResidentProcess( return; } - appRecord->SetKeepAliveAppState(true, isEmptyKeepAliveApp); - StartProcess(appInfo->name, processName, 0, appRecord, appInfo->uid, info, appInfo->bundleName, 0, appExistFlag); // If it is empty, the startup failed @@ -3106,6 +3157,8 @@ void AppMgrServiceInner::StartEmptyResidentProcess( TAG_LOGI(AAFwkTag::APPMGR, "StartEmptyResidentProcess restartCount : [%{public}d], ", restartCount); appRecord->SetRestartResidentProcCount(restartCount); } + appRecord->SetEmptyKeepAliveAppState(isEmptyKeepAliveApp); + appRecord->SetKeepAliveEnableState(true); appRecord->SetTaskHandler(taskHandler_); appRecord->SetEventHandler(eventHandler_); @@ -3235,6 +3288,7 @@ int32_t AppMgrServiceInner::UnregisterAppForegroundStateObserver(const sptr &observer) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); CHECK_CALLER_IS_SYSTEM_APP; return DelayedSingleton::GetInstance()->RegisterAbilityForegroundStateObserver(observer); } @@ -3508,7 +3562,7 @@ void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const Ap return; } if (hapModuleInfo.isStageBasedModel && !IsMainProcess(appInfo, hapModuleInfo)) { - appRecord->SetKeepAliveAppState(false, false); + appRecord->SetEmptyKeepAliveAppState(false); TAG_LOGD(AAFwkTag::APPMGR, "The process %{public}s will not keepalive", hapModuleInfo.process.c_str()); } auto wantPtr = std::make_shared(want); @@ -3525,6 +3579,7 @@ void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const Ap appRecord->SetDebugApp(true); } appRecord->SetPerfCmd(wantPtr->GetStringParam(PERF_CMD)); + appRecord->SetMultiThread(wantPtr->GetBoolParam(MULTI_THREAD, false)); } appRecord->SetProcessAndExtensionType(abilityInfoPtr); appRecord->SetTaskHandler(taskHandler_); @@ -3651,6 +3706,7 @@ void AppMgrServiceInner::HandleStartSpecifiedProcessTimeout(const int64_t eventI int32_t AppMgrServiceInner::UpdateConfiguration(const Configuration &config) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (!appRunningManager_) { TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null"); return ERR_INVALID_VALUE; @@ -3662,13 +3718,19 @@ int32_t AppMgrServiceInner::UpdateConfiguration(const Configuration &config) } std::vector changeKeyV; - configuration_->CompareDifferent(changeKeyV, config); + { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "configuration_->CompareDifferent"); + configuration_->CompareDifferent(changeKeyV, config); + } TAG_LOGI(AAFwkTag::APPMGR, "changeKeyV size :%{public}zu", changeKeyV.size()); if (config.GetItem(AAFwk::GlobalConfigurationKey::THEME).empty() && changeKeyV.empty()) { TAG_LOGE(AAFwkTag::APPMGR, "changeKeyV is empty"); return ERR_INVALID_VALUE; } - configuration_->Merge(changeKeyV, config); + { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "configuration_->Merge"); + configuration_->Merge(changeKeyV, config); + } // all app int32_t result = appRunningManager_->UpdateConfiguration(config); HandleConfigurationChange(config); @@ -3708,6 +3770,7 @@ int32_t AppMgrServiceInner::UpdateConfigurationByBundleName(const Configuration void AppMgrServiceInner::HandleConfigurationChange(const Configuration &config) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard lock(appStateCallbacksLock_); for (const auto &callback : appStateCallbacks_) { if (callback != nullptr) { @@ -5621,7 +5684,8 @@ int32_t AppMgrServiceInner::UnregisterAppRunningStatusListener(const sptrUnregisterListener(appRunningStatusListener); } -int32_t AppMgrServiceInner::StartChildProcess(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid) +int32_t AppMgrServiceInner::StartChildProcess(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid, + int32_t childProcessCount, bool isStartWithDebug) { TAG_LOGI(AAFwkTag::APPMGR, "StarChildProcess, hostPid:%{public}d", hostPid); auto errCode = StartChildProcessPreCheck(hostPid); @@ -5637,7 +5701,8 @@ 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); + auto childProcessRecord = ChildProcessRecord::CreateChildProcessRecord(hostPid, srcEntry, appRecord, + childProcessCount, isStartWithDebug); return StartChildProcessImpl(childProcessRecord, appRecord, childPid); } @@ -5740,6 +5805,13 @@ int32_t AppMgrServiceInner::GetChildProcessInfo(const std::shared_ptrGetProcessName(); info.srcEntry = childProcessRecord->GetSrcEntry(); info.jitEnabled = appRecord->IsJITEnabled(); + info.isStartWithDebug = childProcessRecord->isStartWithDebug(); + auto applicationInfo = appRecord->GetApplicationInfo(); + if (applicationInfo) { + TAG_LOGD(AAFwkTag::APPMGR, "applicationInfo is exist, debug:%{public}d", applicationInfo->debug); + info.isDebugApp = applicationInfo->debug; + } + info.isStartWithNative = appRecord->isNativeStart(); return ERR_OK; } @@ -6231,7 +6303,8 @@ int32_t AppMgrServiceInner::NotifyMemorySizeStateChanged(bool isMemorySizeSuffic isMemorySizeSufficent); bool isMemmgrCall = AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission( MEMMGR_PROC_NAME); - if (!isMemmgrCall) { + bool isSupportCall = OHOS::system::GetBoolParameter(SUPPORT_CALL_NOTIFY_MEMORY_CHANGED, false); + if (!isMemmgrCall && !isSupportCall) { TAG_LOGE(AAFwkTag::APPMGR, "callerToken not %{public}s. %{public}s", MEMMGR_PROC_NAME.c_str(), __func__); return ERR_PERMISSION_DENIED; } @@ -6264,6 +6337,29 @@ int32_t AppMgrServiceInner::NotifyMemorySizeStateChanged(bool isMemorySizeSuffic return ERR_OK; } +void AppMgrServiceInner::SetKeepAliveEnableState(const std::string &bundleName, bool enable) +{ + TAG_LOGD(AAFwkTag::APPMGR, "Called."); + if (bundleName.empty()) { + TAG_LOGE(AAFwkTag::APPMGR, "Bundle name is empty."); + return; + } + + if (appRunningManager_ == nullptr) { + TAG_LOGE(AAFwkTag::APPMGR, "App running manager error."); + return; + } + + for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) { + 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(); diff --git a/services/appmgr/src/app_running_manager.cpp b/services/appmgr/src/app_running_manager.cpp index 49e525f91e..d32ccb4657 100644 --- a/services/appmgr/src/app_running_manager.cpp +++ b/services/appmgr/src/app_running_manager.cpp @@ -194,6 +194,7 @@ std::shared_ptr AppRunningManager::GetAppRunningRecordByAbilit std::shared_ptr AppRunningManager::GetAppRunningRecordByTokenInner( const sptr &abilityToken) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); for (const auto &item : appRunningRecordMap_) { const auto &appRecord = item.second; if (appRecord && appRecord->GetAbilityRunningRecordByToken(abilityToken)) { @@ -571,6 +572,7 @@ void AppRunningManager::TerminateAbility(const sptr &token, bool void AppRunningManager::GetRunningProcessInfoByToken( const sptr &token, AppExecFwk::RunningProcessInfo &info) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard guard(lock_); auto appRecord = GetAppRunningRecordByTokenInner(token); @@ -588,6 +590,7 @@ void AppRunningManager::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExe void AppRunningManager::AssignRunningProcessInfoByAppRecord( std::shared_ptr appRecord, AppExecFwk::RunningProcessInfo &info) const { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (!appRecord) { TAG_LOGE(AAFwkTag::APPMGR, "appRecord is nullptr"); return; @@ -607,6 +610,10 @@ void AppRunningManager::AssignRunningProcessInfoByAppRecord( info.isTestMode = info.isTestProcess && system::GetBoolParameter(DEVELOPER_MODE_STATE, false); info.extensionType_ = appRecord->GetExtensionType(); info.processType_ = appRecord->GetProcessType(); + auto appInfo = appRecord->GetApplicationInfo(); + if (appInfo) { + info.bundleType = static_cast(appInfo->bundleType); + } } void AppRunningManager::SetAbilityForegroundingFlagToAppRecord(const pid_t pid) @@ -694,6 +701,7 @@ void AppRunningManager::HandleStartSpecifiedAbilityTimeOut(const int64_t eventId int32_t AppRunningManager::UpdateConfiguration(const Configuration &config) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::lock_guard guard(lock_); TAG_LOGD(AAFwkTag::APPMGR, "current app size %{public}zu", appRunningRecordMap_.size()); int32_t result = ERR_OK; diff --git a/services/appmgr/src/app_running_record.cpp b/services/appmgr/src/app_running_record.cpp index b991718c15..2d3a773529 100644 --- a/services/appmgr/src/app_running_record.cpp +++ b/services/appmgr/src/app_running_record.cpp @@ -435,6 +435,7 @@ void AppRunningRecord::LaunchApplication(const Configuration &config) launchData.SetAppIndex(appIndex_); launchData.SetDebugApp(isDebugApp_); launchData.SetPerfCmd(perfCmd_); + launchData.SetMultiThread(isMultiThread_); launchData.SetJITEnabled(jitEnabled_); launchData.SetNativeStart(isNativeStart_); launchData.SetAppRunningUniqueId(std::to_string(startTimeMillis_)); @@ -1346,14 +1347,18 @@ bool AppRunningRecord::IsKeepAliveApp() const return isKeepAliveApp_; } +void AppRunningRecord::SetKeepAliveEnableState(bool isKeepAliveEnable) +{ + isKeepAliveApp_ = isKeepAliveEnable; +} + bool AppRunningRecord::IsEmptyKeepAliveApp() const { return isEmptyKeepAliveApp_; } -void AppRunningRecord::SetKeepAliveAppState(bool isKeepAlive, bool isEmptyKeepAliveApp) +void AppRunningRecord::SetEmptyKeepAliveAppState(bool isEmptyKeepAliveApp) { - isKeepAliveApp_ = isKeepAlive; isEmptyKeepAliveApp_ = isEmptyKeepAliveApp; } @@ -1563,6 +1568,7 @@ const AAFwk::Want &AppRunningRecord::GetNewProcessRequestWant() const int32_t AppRunningRecord::UpdateConfiguration(const Configuration &config) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "called"); if (!appLifeCycleDeal_) { TAG_LOGI(AAFwkTag::APPMGR, "appLifeCycleDeal_ is null"); @@ -1644,6 +1650,11 @@ void AppRunningRecord::SetPerfCmd(const std::string &perfCmd) perfCmd_ = perfCmd; } +void AppRunningRecord::SetMultiThread(bool multiThread) +{ + isMultiThread_ = multiThread; +} + void AppRunningRecord::SetAppIndex(const int32_t appIndex) { appIndex_ = appIndex; diff --git a/services/appmgr/src/app_spawn_client.cpp b/services/appmgr/src/app_spawn_client.cpp index e5abd5ef0c..d420dbcc4d 100644 --- a/services/appmgr/src/app_spawn_client.cpp +++ b/services/appmgr/src/app_spawn_client.cpp @@ -184,6 +184,16 @@ int32_t AppSpawnClient::SetStartFlags(const AppSpawnStartMsg &startMsg, AppSpawn return ret; } +int32_t AppSpawnClient::SetAtomicServiceFlag(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle) +{ + int32_t ret = 0; + if (startMsg.atomicServiceFlag && + (ret = AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_ATOMIC_SERVICE))) { + HILOG_ERROR("AppSpawnReqMsgSetAppFlag failed, ret: %{public}d", ret); + } + return ret; +} + int32_t AppSpawnClient::AppspawnSetExtMsg(const AppSpawnStartMsg &startMsg, AppSpawnReqMsgHandle reqHandle) { int32_t ret = 0; @@ -225,6 +235,13 @@ int32_t AppSpawnClient::AppspawnSetExtMsg(const AppSpawnStartMsg &startMsg, AppS return ret; } } + if (!startMsg.atomicAccount.empty() && + (ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_ACCOUNT_ID, + reinterpret_cast(startMsg.atomicAccount.c_str()), + startMsg.atomicAccount.size()))) { + HILOG_ERROR("AppSpawnReqMsgAddExtInfo failed, ret: %{public}d", ret); + return ret; + } return ret; } @@ -269,6 +286,10 @@ int32_t AppSpawnClient::AppspawnCreateDefaultMsg(const AppSpawnStartMsg &startMs TAG_LOGE(AAFwkTag::APPMGR, "SetStartFlags failed, ret: %{public}d", ret); break; } + if ((ret = SetAtomicServiceFlag(startMsg, reqHandle))) { + HILOG_ERROR("SetAtomicServiceFlag failed, ret: %{public}d", ret); + break; + } if ((ret = SetMountPermission(startMsg, reqHandle))) { TAG_LOGE(AAFwkTag::APPMGR, "SetMountPermission failed, ret: %{public}d", ret); break; diff --git a/services/appmgr/src/app_state_observer_manager.cpp b/services/appmgr/src/app_state_observer_manager.cpp index f313b3275a..1ccbadb965 100644 --- a/services/appmgr/src/app_state_observer_manager.cpp +++ b/services/appmgr/src/app_state_observer_manager.cpp @@ -19,6 +19,7 @@ #include "app_foreground_state_observer_stub.h" #include "application_state_observer_stub.h" #include "hilog_tag_wrapper.h" +#include "hitrace_meter.h" #include "in_process_call_wrapper.h" #include "remote_client_manager.h" #include "ui_extension_utils.h" @@ -77,6 +78,7 @@ int32_t AppStateObserverManager::RegisterApplicationStateObserver( int32_t AppStateObserverManager::UnregisterApplicationStateObserver(const sptr &observer) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "called"); if (AAFwk::PermissionVerification::GetInstance()->VerifyAppStateObserverPermission() == ERR_PERMISSION_DENIED) { TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed"); @@ -124,6 +126,7 @@ int32_t AppStateObserverManager::RegisterAppForegroundStateObserver(const sptr &observer) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (observer == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Observer nullptr."); @@ -147,6 +150,7 @@ int32_t AppStateObserverManager::UnregisterAppForegroundStateObserver(const sptr int32_t AppStateObserverManager::RegisterAbilityForegroundStateObserver( const sptr &observer) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (observer == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "The param observer is nullptr."); @@ -170,6 +174,7 @@ int32_t AppStateObserverManager::RegisterAbilityForegroundStateObserver( int32_t AppStateObserverManager::UnregisterAbilityForegroundStateObserver( const sptr &observer) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "Called."); if (observer == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "Observer nullptr."); @@ -724,6 +729,7 @@ bool AppStateObserverManager::IsAppForegroundObserverExist(const sptr &observer, const ObserverType &type) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "Add observer death recipient begin."); if (observer == nullptr || observer->AsObject() == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "The param observer is nullptr."); @@ -765,6 +771,7 @@ void AppStateObserverManager::AddObserverDeathRecipient(const sptr &observer) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::APPMGR, "Remove observer death recipient begin."); if (observer == nullptr || observer->AsObject() == nullptr) { TAG_LOGE(AAFwkTag::APPMGR, "The param observer is nullptr."); @@ -798,6 +805,7 @@ AbilityforegroundObserverSet AppStateObserverManager::GetAbilityforegroundObserv void AppStateObserverManager::OnObserverDied(const wptr &remote, const ObserverType &type) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGI(AAFwkTag::APPMGR, "OnObserverDied"); auto object = remote.promote(); if (object == nullptr) { diff --git a/services/appmgr/src/child_process_record.cpp b/services/appmgr/src/child_process_record.cpp index f581a7d8a6..2bf2e9f341 100644 --- a/services/appmgr/src/child_process_record.cpp +++ b/services/appmgr/src/child_process_record.cpp @@ -22,8 +22,9 @@ namespace OHOS { namespace AppExecFwk { ChildProcessRecord::ChildProcessRecord(pid_t hostPid, const std::string &srcEntry, - const std::shared_ptr hostRecord) - : hostPid_(hostPid), srcEntry_(srcEntry), hostRecord_(hostRecord) + const std::shared_ptr hostRecord, int32_t childProcessCount, bool isStartWithDebug) + : hostPid_(hostPid), childProcessCount_(childProcessCount), srcEntry_(srcEntry), hostRecord_(hostRecord), + isStartWithDebug_(isStartWithDebug) { MakeProcessName(hostRecord); } @@ -34,14 +35,15 @@ ChildProcessRecord::~ChildProcessRecord() } std::shared_ptr ChildProcessRecord::CreateChildProcessRecord(pid_t hostPid, - const std::string &srcEntry, const std::shared_ptr hostRecord) + const std::string &srcEntry, const std::shared_ptr hostRecord, int32_t childProcessCount, + bool isStartWithDebug) { TAG_LOGD(AAFwkTag::APPMGR, "hostPid: %{public}d, srcEntry: %{public}s", hostPid, srcEntry.c_str()); if (hostPid <= 0 || srcEntry.empty() || !hostRecord) { TAG_LOGE(AAFwkTag::APPMGR, "Invalid parameter."); return nullptr; } - return std::make_shared(hostPid, srcEntry, hostRecord); + return std::make_shared(hostPid, srcEntry, hostRecord, childProcessCount, isStartWithDebug); } void ChildProcessRecord::SetPid(pid_t pid) @@ -148,6 +150,13 @@ void ChildProcessRecord::MakeProcessName(const std::shared_ptr processName_.append(":"); processName_.append(filename); } + processName_.append(std::to_string(childProcessCount_)); + TAG_LOGD(AAFwkTag::APPMGR, "MakeSpawnForkProcessName processName is %{public}s", processName_.c_str()); +} + +bool ChildProcessRecord::isStartWithDebug() +{ + return isStartWithDebug_; } } // namespace AppExecFwk } // namespace OHOS diff --git a/services/common/BUILD.gn b/services/common/BUILD.gn index 749688d916..6ef92e16be 100644 --- a/services/common/BUILD.gn +++ b/services/common/BUILD.gn @@ -1,5 +1,5 @@ # -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -62,6 +62,7 @@ ohos_shared_library("perm_verification") { "access_token:libtokenid_sdk", "c_utils:utils", "hilog:libhilog", + "hitrace:hitrace_meter", "init:libbegetutil", "ipc:ipc_core", ] @@ -79,6 +80,7 @@ ohos_shared_library("event_report") { external_deps = [ "hilog:libhilog", "hisysevent:libhisysevent", + "hitrace:hitrace_meter", ] innerapi_tags = [ "platformsdk_indirect" ] diff --git a/services/common/include/permission_constants.h b/services/common/include/permission_constants.h index 11fec4ec3e..25f5d28bc4 100644 --- a/services/common/include/permission_constants.h +++ b/services/common/include/permission_constants.h @@ -42,7 +42,7 @@ 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_GRANT_URI_PERMISSION = "ohos.permission.GRANT_URI_PERMISSION_PRIVILEGED"; +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"; diff --git a/services/common/src/event_report.cpp b/services/common/src/event_report.cpp index 227a551fd4..1afd75f643 100644 --- a/services/common/src/event_report.cpp +++ b/services/common/src/event_report.cpp @@ -18,6 +18,7 @@ #include "event_report.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" +#include "hitrace_meter.h" namespace OHOS { namespace AAFwk { @@ -142,6 +143,7 @@ void EventReport::SendAppEvent(const EventName &eventName, HiSysEventType type, void EventReport::SendAbilityEvent(const EventName &eventName, HiSysEventType type, const EventInfo &eventInfo) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::string name = ConvertEventName(eventName); if (name == INVALID_EVENT_NAME) { TAG_LOGE(AAFwkTag::DEFAULT, "invalid eventName"); @@ -230,6 +232,7 @@ void EventReport::SendAbilityEvent(const EventName &eventName, HiSysEventType ty void EventReport::SendExtensionEvent(const EventName &eventName, HiSysEventType type, const EventInfo &eventInfo) { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); std::string name = ConvertEventName(eventName); if (name == INVALID_EVENT_NAME) { TAG_LOGE(AAFwkTag::DEFAULT, "invalid eventName"); diff --git a/services/common/src/permission_verification.cpp b/services/common/src/permission_verification.cpp index 748a8ada45..e2a4794f78 100644 --- a/services/common/src/permission_verification.cpp +++ b/services/common/src/permission_verification.cpp @@ -19,6 +19,7 @@ #include "accesstoken_kit.h" #include "hilog_tag_wrapper.h" #include "hilog_wrapper.h" +#include "hitrace_meter.h" #include "permission_constants.h" #include "support_system_ability_permission.h" #include "tokenid_kit.h" @@ -53,6 +54,7 @@ bool PermissionVerification::VerifyPermissionByTokenId(const int &tokenId, const 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; @@ -94,6 +96,7 @@ bool PermissionVerification::IsShellCall() const bool PermissionVerification::CheckSpecificSystemAbilityAccessPermission(const std::string &processName) const { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); TAG_LOGD(AAFwkTag::DEFAULT, "PermissionVerification::CheckSpecifidSystemAbilityAccessToken is called."); if (!IsSACall()) { TAG_LOGE(AAFwkTag::DEFAULT, "caller tokenType is not native, verify failed."); @@ -172,6 +175,7 @@ int PermissionVerification::VerifyAccountPermission() const bool PermissionVerification::VerifyMissionPermission() const { + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); if (VerifyCallingPermission(PermissionConstants::PERMISSION_MANAGE_MISSION)) { TAG_LOGD(AAFwkTag::DEFAULT, "%{public}s: Permission verification succeeded.", __func__); return true; diff --git a/services/uripermmgr/include/uri_permission_manager_stub_impl.h b/services/uripermmgr/include/uri_permission_manager_stub_impl.h index 4ab0f96f5f..67cfd568b0 100644 --- a/services/uripermmgr/include/uri_permission_manager_stub_impl.h +++ b/services/uripermmgr/include/uri_permission_manager_stub_impl.h @@ -126,8 +126,6 @@ private: int32_t CheckProxyUriPermission(TokenIdPermission &tokenIdPermission, const Uri &uri, uint32_t flag); - bool VerifyPermissionByTokenId(uint32_t tokenId, const std::string &permissionName); - bool AccessMediaUriPermission(TokenIdPermission &tokenIdPermission, const Uri &uri, uint32_t flag); bool AccessDocsUriPermission(TokenIdPermission &tokenIdPermission, const Uri &uri, uint32_t flag); diff --git a/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp b/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp index c0190c72c3..6a8375af64 100644 --- a/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp +++ b/services/uripermmgr/src/uri_permission_manager_stub_impl.cpp @@ -47,9 +47,6 @@ constexpr int32_t ERR_OK = 0; constexpr uint32_t FLAG_READ_WRITE_URI = Want::FLAG_AUTH_READ_URI_PERMISSION | Want::FLAG_AUTH_WRITE_URI_PERMISSION; constexpr const char* CLOUND_DOCS_URI_MARK = "?networkid="; constexpr const char* FOUNDATION_PROCESS_NAME = "foundation"; -constexpr const char* UDMF_PROCESS_NAME = "distributeddata"; -constexpr const char* PASTE_BOARD_SERVICE = "pasterboard_service"; -constexpr const char* BROKER = "broker"; } bool UriPermissionManagerStubImpl::VerifyUriPermission(const Uri &uri, uint32_t flag, uint32_t tokenId) @@ -135,7 +132,8 @@ int32_t UriPermissionManagerStubImpl::GrantUriPermissionPrivileged(const std::ve auto callerName = GetTokenName(callerTokenId); TAG_LOGD(AAFwkTag::URIPERMMGR, "callerTokenId is %{public}u, callerName is %{public}s", callerTokenId, callerName.c_str()); - if (!VerifyPermissionByTokenId(callerTokenId, PermissionConstants::PERMISSION_GRANT_URI_PERMISSION)) { + auto permissionName = PermissionConstants::PERMISSION_GRANT_URI_PERMISSION_PRIVILEGED; + if (!PermissionVerification::GetInstance()->VerifyPermissionByTokenId(callerTokenId, permissionName)) { TAG_LOGE(AAFwkTag::URIPERMMGR, "No permission to call."); return CHECK_PERMISSION_FAILED; } @@ -414,7 +412,7 @@ int32_t UriPermissionManagerStubImpl::GrantBatchUriPermissionPrivileged(const st } if (uriStrVec.empty()) { TAG_LOGE(AAFwkTag::URIPERMMGR, "Valid uri list is empty."); - return ERR_CODE_INVALID_URI_FLAG; + return ERR_CODE_INVALID_URI_TYPE; } return GrantBatchUriPermissionImpl(uriStrVec, flag, callerTokenId, targetTokenId, autoRemove); } @@ -446,7 +444,7 @@ int32_t UriPermissionManagerStubImpl::GrantBatchUriPermissionFor2In1Privileged(c if (uriStrVec.empty() && docsVec.empty()) { TAG_LOGE(AAFwkTag::URIPERMMGR, "Valid uri list is empty."); - return ERR_CODE_INVALID_URI_FLAG; + return ERR_CODE_INVALID_URI_TYPE; } if (!uriStrVec.empty()) { @@ -623,6 +621,10 @@ std::vector UriPermissionManagerStubImpl::CheckUriAuthorization(const std: TokenIdPermission tokenIdPermission(tokenId); for (size_t i = 0; i < uriVec.size(); i++) { Uri uri(uriVec[i]); + if (!CheckUriTypeIsValid(uri)) { + TAG_LOGW(AAFwkTag::URIPERMMGR, "uri is invalid, uri is %{private}s.", uriVec[i].c_str()); + continue; + } result[i] = CheckUriPermission(uri, flag, tokenIdPermission); if (!result[i]) { TAG_LOGW(AAFwkTag::URIPERMMGR, "Check uri permission failed, uri is %{private}s.", uriVec[i].c_str()); @@ -946,25 +948,6 @@ bool UriPermissionManagerStubImpl::CheckUriPermission(Uri uri, uint32_t flag, To return CheckProxyUriPermission(tokenIdPermission, uri, flag); } -bool UriPermissionManagerStubImpl::VerifyPermissionByTokenId(uint32_t tokenId, const std::string &permissionName) -{ - // temporary method. - if (permissionName == PermissionConstants::PERMISSION_GRANT_URI_PERMISSION) { - Security::AccessToken::NativeTokenInfo nativeInfo; - auto result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeInfo); - if (result != ERR_OK) { - TAG_LOGE(AAFwkTag::URIPERMMGR, "GetNativeTokenInfo failed, tokenId is %{public}u.", tokenId); - return false; - } - auto callerName = nativeInfo.processName; - TAG_LOGI(AAFwkTag::URIPERMMGR, "Caller process name : %{public}s", callerName.c_str()); - // waiting accessToken permission request. - return callerName == BROKER || callerName == PASTE_BOARD_SERVICE || callerName == UDMF_PROCESS_NAME || - callerName == FOUNDATION_PROCESS_NAME; - } - return PermissionVerification::GetInstance()->VerifyPermissionByTokenId(tokenId, permissionName); -} - bool UriPermissionManagerStubImpl::AccessMediaUriPermission(TokenIdPermission &tokenIdPermission, const Uri &uri, uint32_t flag) { diff --git a/test/fuzztest/abilitystubdumpstate_fuzzer/abilitystubdumpstate_fuzzer.cpp b/test/fuzztest/abilitystubdumpstate_fuzzer/abilitystubdumpstate_fuzzer.cpp index 1c7e8d2bb2..b4b9d33a22 100644 --- a/test/fuzztest/abilitystubdumpstate_fuzzer/abilitystubdumpstate_fuzzer.cpp +++ b/test/fuzztest/abilitystubdumpstate_fuzzer/abilitystubdumpstate_fuzzer.cpp @@ -47,6 +47,8 @@ bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) std::make_shared(nullptr, nullptr); DelayedSingleton::GetInstance()->subManagersHelper_->currentUIAbilityManager_ = std::make_shared(); + DelayedSingleton::GetInstance()->subManagersHelper_->currentDataAbilityManager_ = + std::make_shared(); DelayedSingleton::GetInstance()->OnRemoteRequest(code, parcel, reply, option); return true; 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 e44570bfd3..16a3d7c22f 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 @@ -76,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_METHOD2(StartChildProcess, int32_t(const std::string &srcEntry, pid_t &childPid)); + MOCK_METHOD3(StartChildProcess, int32_t(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount)); MOCK_METHOD1(GetChildProcessInfoForSelf, int32_t(ChildProcessInfo &info)); MOCK_METHOD1(AttachChildProcess, void(const sptr &childScheduler)); MOCK_METHOD0(ExitChildProcessSafely, void()); @@ -143,16 +143,23 @@ public: int IsBackgroundRunningRestricted(const std::string& appName) { return 0; - }; + } + virtual int GetAllRunningProcesses(std::vector& info) override { return 0; - }; + } + + virtual int GetRunningProcessesByBundleType(const BundleType bundleType, + std::vector& info) override + { + return 0; + } virtual int GetAllRenderProcesses(std::vector& info) override { return 0; - }; + } virtual int32_t StartNativeProcessForDebugger(const AAFwk::Want &want) override { 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 25cc16f339..53ebaddcb8 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 @@ -61,7 +61,8 @@ 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_METHOD3(StartChildProcess, int32_t(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid)); + MOCK_METHOD5(StartChildProcess, int32_t(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid, + int32_t childProcessCount, bool inStartWithDebug)); MOCK_METHOD1(GetChildProcessInfoForSelf, int32_t(ChildProcessInfo &info)); MOCK_METHOD4(PreloadApplication, int32_t(const std::string&, int32_t, AppExecFwk::PreloadMode, int32_t)); void StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo) 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 a946e0f1bd..db078d8ea2 100644 --- a/test/mock/services_abilitymgr_test/libs/appexecfwk_core/BUILD.gn +++ b/test/mock/services_abilitymgr_test/libs/appexecfwk_core/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -44,6 +44,7 @@ ohos_static_library("appexecfwk_appmgr_mock") { "c_utils:utils", "eventhandler:libeventhandler", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_core", "safwk:system_ability_fwk", "samgr:samgr_proxy", diff --git a/test/mock/services_abilitymgr_test/libs/sa_mgr/BUILD.gn b/test/mock/services_abilitymgr_test/libs/sa_mgr/BUILD.gn index 5fa7728616..947c0b9096 100644 --- a/test/mock/services_abilitymgr_test/libs/sa_mgr/BUILD.gn +++ b/test/mock/services_abilitymgr_test/libs/sa_mgr/BUILD.gn @@ -29,8 +29,6 @@ ohos_source_set("sa_mgr_mock") { "${ability_runtime_services_path}/common:common_config", ] - deps = [] - external_deps = [ "c_utils:utils", "hilog:libhilog", 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 6c91131ce9..228775be2e 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 @@ -44,6 +44,8 @@ public: 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)); + MOCK_METHOD2(GetRunningProcessesByBundleType, int(const BundleType bundleType, + std::vector& info)); MOCK_METHOD2(GetProcessRunningInfosByUserId, int(std::vector& info, int32_t userId)); MOCK_METHOD1(GetAllRenderProcesses, int(std::vector& info)); MOCK_METHOD0(GetAmsMgr, sptr()); @@ -88,7 +90,8 @@ public: MOCK_METHOD3(GetRunningProcessInformation, int32_t(const std::string & bundleName, int32_t userId, std::vector &info)); MOCK_METHOD2(IsApplicationRunning, int32_t(const std::string &bundleName, bool &isRunning)); - MOCK_METHOD2(StartChildProcess, int32_t(const std::string &srcEntry, pid_t &childPid)); + MOCK_METHOD4(StartChildProcess, int32_t(const std::string &srcEntry, pid_t &childPid, int32_t childProcessCount, + bool isStartWithNative)); MOCK_METHOD1(GetChildProcessInfoForSelf, int32_t(ChildProcessInfo &info)); MOCK_METHOD1(AttachChildProcess, void(const sptr &childScheduler)); MOCK_METHOD0(ExitChildProcessSafely, void()); 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 a96597c37d..83712f4dfe 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 @@ -62,7 +62,8 @@ 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_METHOD3(StartChildProcess, int32_t(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid)); + MOCK_METHOD5(StartChildProcess, int32_t(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid, + int32_t childProcessCount, bool isStartWithNative)); 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/moduletest/ipc_ability_mgr_test/BUILD.gn b/test/moduletest/ipc_ability_mgr_test/BUILD.gn index 8c60de8dc4..db7fdad9ae 100644 --- a/test/moduletest/ipc_ability_mgr_test/BUILD.gn +++ b/test/moduletest/ipc_ability_mgr_test/BUILD.gn @@ -45,6 +45,7 @@ ohos_moduletest("IpcAbilityMgrServiceModuleTest") { "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", + "config_policy:configpolicy_util", "ffrt:libffrt", "hilog:libhilog", "ipc:ipc_core", diff --git a/test/moduletest/ui_extension_ability_test/ui_extension_connect_module_test/BUILD.gn b/test/moduletest/ui_extension_ability_test/ui_extension_connect_module_test/BUILD.gn index ec2d86f252..d37574c4f8 100644 --- a/test/moduletest/ui_extension_ability_test/ui_extension_connect_module_test/BUILD.gn +++ b/test/moduletest/ui_extension_ability_test/ui_extension_connect_module_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. +# Copyright (c) 2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -53,6 +53,7 @@ ohos_moduletest("ui_extension_connect_module_test") { "c_utils:utils", "ffrt:libffrt", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_core", "safwk:system_ability_fwk", "samgr:samgr_proxy", diff --git a/test/moduletest/ui_extension_ability_test/ui_extension_info_module_test/BUILD.gn b/test/moduletest/ui_extension_ability_test/ui_extension_info_module_test/BUILD.gn index a54a5c265e..7f1ce9b786 100644 --- a/test/moduletest/ui_extension_ability_test/ui_extension_info_module_test/BUILD.gn +++ b/test/moduletest/ui_extension_ability_test/ui_extension_info_module_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. +# Copyright (c) 2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -46,6 +46,7 @@ ohos_moduletest("ui_extension_info_module_test") { "c_utils:utils", "ffrt:libffrt", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_core", "safwk:system_ability_fwk", "samgr:samgr_proxy", diff --git a/test/sample/demo_ui_extension/js/napi/demo_ui_extension_ability/demo_ui_extension_ability.js b/test/sample/demo_ui_extension/js/napi/demo_ui_extension_ability/demo_ui_extension_ability.js index 04bccd8ed5..779157baee 100644 --- a/test/sample/demo_ui_extension/js/napi/demo_ui_extension_ability/demo_ui_extension_ability.js +++ b/test/sample/demo_ui_extension/js/napi/demo_ui_extension_ability/demo_ui_extension_ability.js @@ -16,6 +16,9 @@ let UIExtensionAbility = requireNapi('app.ability.UIExtensionAbility'); class DemoUIExtensionAbility extends UIExtensionAbility { + onTest(){ + console.log('DemoUIExtensionAbility onTest'); + } } export default DemoUIExtensionAbility; diff --git a/test/sample/demo_ui_extension/native/demo_ui_extension_ability/BUILD.gn b/test/sample/demo_ui_extension/native/demo_ui_extension_ability/BUILD.gn index 3db9b188e2..434bb7e823 100644 --- a/test/sample/demo_ui_extension/native/demo_ui_extension_ability/BUILD.gn +++ b/test/sample/demo_ui_extension/native/demo_ui_extension_ability/BUILD.gn @@ -38,6 +38,7 @@ ohos_shared_library("demo_ui_extension") { sources = [ "src/demo_ui_extension.cpp", "src/js_demo_ui_extension.cpp", + "src/js_demo_ui_extension_context.cpp", ] # If not in ability_runtime repo, use external_deps diff --git a/test/sample/demo_ui_extension/native/demo_ui_extension_ability/include/js_demo_ui_extension.h b/test/sample/demo_ui_extension/native/demo_ui_extension_ability/include/js_demo_ui_extension.h index 1fab78af8e..d448ce9943 100644 --- a/test/sample/demo_ui_extension/native/demo_ui_extension_ability/include/js_demo_ui_extension.h +++ b/test/sample/demo_ui_extension/native/demo_ui_extension_ability/include/js_demo_ui_extension.h @@ -17,11 +17,13 @@ #define OHOS_ABILITY_RUNTIME_JS_DEMO_UI_EXTENSION_H #include "demo_ui_extension.h" +#include "js_ui_extension_base.h" #include "runtime.h" namespace OHOS { namespace AbilityRuntime { class JsDemoUIExtension : public DemoUIExtension, + public JsUIExtensionBase, public std::enable_shared_from_this { public: explicit JsDemoUIExtension(const std::unique_ptr &runtime); @@ -34,6 +36,10 @@ public: * @return The JsDemoUIExtension instance. */ static JsDemoUIExtension *Create(const std::unique_ptr &runtime); + + void OnForeground(const Want &want, sptr sessionInfo) override; + + void BindContext() override; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/test/sample/demo_ui_extension/native/demo_ui_extension_ability/include/js_demo_ui_extension_context.h b/test/sample/demo_ui_extension/native/demo_ui_extension_ability/include/js_demo_ui_extension_context.h new file mode 100644 index 0000000000..1e03328e23 --- /dev/null +++ b/test/sample/demo_ui_extension/native/demo_ui_extension_ability/include/js_demo_ui_extension_context.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_JS_DEMO_UI_EXTENSION_CONTEXT_H +#define OHOS_ABILITY_RUNTIME_JS_DEMO_UI_EXTENSION_CONTEXT_H + +#include + +#include "ui_extension_context.h" +#include "js_free_install_observer.h" +#include "native_engine/native_engine.h" +#include "js_ui_extension_context.h" + +namespace OHOS { +namespace AbilityRuntime { +struct NapiCallbackInfo; + +class JsDemoUIExtensionContext : public JsUIExtensionContext { +public: + explicit JsDemoUIExtensionContext(const std::shared_ptr& context) + : JsUIExtensionContext(context) {} + virtual ~JsDemoUIExtensionContext() = default; + static void Finalizer(napi_env env, void* data, void* hint); + static napi_value TestMethod(napi_env env, napi_callback_info info); + static napi_value CreateJsDemoUIExtensionContext(napi_env env, std::shared_ptr context); + +protected: + virtual napi_value OnTestMethod(napi_env env, NapiCallbackInfo& info); +}; + +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_JS_DEMO_UI_EXTENSION_CONTEXT_H \ No newline at end of file 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 fc0f671291..b762e34f7a 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 @@ -17,25 +17,138 @@ #include "hilog_wrapper.h" #include "js_ui_extension_base.h" +#include "js_demo_ui_extension_context.h" namespace OHOS { namespace AbilityRuntime { +namespace { +constexpr size_t ARGC_ONE = 1; +} // namespace JsDemoUIExtension *JsDemoUIExtension::Create(const std::unique_ptr &runtime) { TAG_LOGD(AAFwkTag::TEST, "Create js demo uiextension."); return new JsDemoUIExtension(runtime); } -JsDemoUIExtension::JsDemoUIExtension(const std::unique_ptr &runtime) +JsDemoUIExtension::JsDemoUIExtension(const std::unique_ptr &runtime) : JsUIExtensionBase(runtime) { - TAG_LOGD(AAFwkTag::TEST, "Js demo uiextension constructor."); - auto uiExtensionBaseImpl = std::make_unique(runtime); - SetUIExtensionBaseImpl(std::move(uiExtensionBaseImpl)); + SetUIExtensionBaseImpl(std::shared_ptr(this)); } JsDemoUIExtension::~JsDemoUIExtension() { TAG_LOGD(AAFwkTag::TEST, "Js demo uiextension destructor."); } + +void JsDemoUIExtension::OnForeground(const Want &want, sptr sessionInfo) +{ + TAG_LOGE(AAFwkTag::UI_EXT, "OnForeground"); + + ForegroundWindow(want, sessionInfo); + HandleScope handleScope(jsRuntime_); + CallObjectMethod("onForeground"); + CallObjectMethod("onTest"); +} + +napi_value AttachUIExtensionBaseContext(napi_env env, void *value, void*) +{ + TAG_LOGD(AAFwkTag::UI_EXT, "called"); + if (value == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "invalid parameter."); + return nullptr; + } + + auto ptr = reinterpret_cast*>(value)->lock(); + if (ptr == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "invalid context."); + return nullptr; + } + napi_value object = JsDemoUIExtensionContext::CreateJsDemoUIExtensionContext(env, ptr); + if (object == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "create context error."); + return nullptr; + } + auto contextRef = JsRuntime::LoadSystemModuleByEngine( + env, "application.UIExtensionContext", &object, 1); + if (contextRef == nullptr) { + TAG_LOGD(AAFwkTag::UI_EXT, "Failed to get LoadSystemModuleByEngine"); + return nullptr; + } + auto contextObj = contextRef->GetNapiValue(); + if (contextObj == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "load context error."); + return nullptr; + } + if (!CheckTypeForNapiValue(env, contextObj, napi_object)) { + TAG_LOGE(AAFwkTag::UI_EXT, "not object."); + return nullptr; + } + napi_coerce_to_native_binding_object( + env, contextObj, DetachCallbackFunc, AttachUIExtensionBaseContext, value, nullptr); + auto workContext = new (std::nothrow) std::weak_ptr(ptr); + napi_wrap(env, contextObj, workContext, + [](napi_env, void *data, void*) { + TAG_LOGD(AAFwkTag::UI_EXT, "Finalizer for weak_ptr ui extension context is called"); + if (data == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "Finalizer for weak_ptr is nullptr"); + return; + } + delete static_cast*>(data); + }, + nullptr, nullptr); + return contextObj; +} + +void JsDemoUIExtension::BindContext() +{ + HandleScope handleScope(jsRuntime_); + std::shared_ptr context = JsUIExtensionBase::context_; + if (jsObj_ == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "jsObj_ is nullptr"); + return; + } + napi_env env = jsRuntime_.GetNapiEnv(); + napi_value obj = jsObj_->GetNapiValue(); + if (!CheckTypeForNapiValue(env, obj, napi_object)) { + TAG_LOGE(AAFwkTag::UI_EXT, "obj is not object"); + return; + } + if (context == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "context is nullptr"); + return; + } + TAG_LOGD(AAFwkTag::UI_EXT, "BindContext CreateJsDemoUIExtensionContext."); + napi_value contextObj = JsDemoUIExtensionContext::CreateJsDemoUIExtensionContext(env, context); + if (contextObj == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "Create js ui extension context error."); + return; + } + shellContextRef_ = JsRuntime::LoadSystemModuleByEngine( + env, "application.UIExtensionContext", &contextObj, ARGC_ONE); + if (shellContextRef_ == nullptr) { + TAG_LOGD(AAFwkTag::UI_EXT, "Failed to get LoadSystemModuleByEngine"); + return; + } + contextObj = shellContextRef_->GetNapiValue(); + if (!CheckTypeForNapiValue(env, contextObj, napi_object)) { + TAG_LOGE(AAFwkTag::UI_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, AttachUIExtensionBaseContext, workContext, nullptr); + context->Bind(jsRuntime_, shellContextRef_.get()); + napi_set_named_property(env, obj, "context", contextObj); + napi_wrap(env, contextObj, workContext, + [](napi_env, void *data, void*) { + TAG_LOGD(AAFwkTag::UI_EXT, "Finalizer for weak_ptr ui extension context is called"); + if (data == nullptr) { + TAG_LOGE(AAFwkTag::UI_EXT, "Finalizer for weak_ptr is nullptr"); + return; + } + delete static_cast*>(data); + }, + nullptr, nullptr); +} } // namespace AbilityRuntime } // namespace OHOS 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 new file mode 100644 index 0000000000..b162fcfc53 --- /dev/null +++ b/test/sample/demo_ui_extension/native/demo_ui_extension_ability/src/js_demo_ui_extension_context.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 "js_ui_extension_context.h" + +#include + +#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" +#include "js_demo_ui_extension_context.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_common_start_options.h" +#include "napi_remote_object.h" +#include "open_link_options.h" +#include "open_link/napi_common_open_link_options.h" +#include "start_options.h" +#include "hitrace_meter.h" +#include "uri.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr int32_t INDEX_ZERO = 0; +} // namespace + +void JsDemoUIExtensionContext::Finalizer(napi_env env, void* data, void* hint) +{ + TAG_LOGD(AAFwkTag::UI_EXT, "JsDemoUIExtensionContext Finalizer is called"); + std::unique_ptr(static_cast(data)); +} + +napi_value JsDemoUIExtensionContext::TestMethod(napi_env env, napi_callback_info info) +{ + GET_NAPI_INFO_AND_CALL(env, info, JsDemoUIExtensionContext, OnTestMethod); +} + +napi_value JsDemoUIExtensionContext::OnTestMethod(napi_env env, NapiCallbackInfo& info) +{ + TAG_LOGD(AAFwkTag::UI_EXT, "called."); + auto innerErrorCode = std::make_shared(ERR_OK); + NapiAsyncTask::ExecuteCallback execute = [weak = context_, innerErrorCode]() { + auto context = weak.lock(); + if (!context) { + TAG_LOGW(AAFwkTag::UI_EXT, "context is released"); + *innerErrorCode = static_cast(AbilityErrorCode::ERROR_CODE_INVALID_CONTEXT); + return; + } + }; + + NapiAsyncTask::CompleteCallback complete = [innerErrorCode](napi_env env, NapiAsyncTask& task, int32_t status) { + if (*innerErrorCode == ERR_OK) { + task.Resolve(env, CreateJsUndefined(env)); + } else { + task.Reject(env, CreateJsErrorByNativeErr(env, *innerErrorCode)); + } + }; + + napi_value lastParam = info.argv[INDEX_ZERO]; + napi_value result = nullptr; + NapiAsyncTask::ScheduleHighQos("JsDemoUIExtensionContext::OnTestMethod", + env, CreateAsyncTaskWithLastParam(env, lastParam, std::move(execute), std::move(complete), &result)); + return result; +} + +napi_value JsDemoUIExtensionContext::CreateJsDemoUIExtensionContext(napi_env env, + std::shared_ptr context) +{ + std::shared_ptr abilityInfo = nullptr; + if (context) { + abilityInfo = context->GetAbilityInfo(); + } + napi_value objValue = CreateJsExtensionContext(env, context, abilityInfo); + + std::unique_ptr jsContext = std::make_unique(context); + napi_wrap(env, objValue, jsContext.release(), Finalizer, nullptr, nullptr); + + const char *moduleName = "JsDemoUIExtensionContext"; + BindNativeFunction(env, objValue, "startAbility", moduleName, StartAbility); + BindNativeFunction(env, objValue, "openLink", moduleName, OpenLink); + BindNativeFunction(env, objValue, "terminateSelf", moduleName, TerminateSelf); + BindNativeFunction(env, objValue, "startAbilityForResult", moduleName, StartAbilityForResult); + BindNativeFunction(env, objValue, "terminateSelfWithResult", moduleName, TerminateSelfWithResult); + BindNativeFunction(env, objValue, "startAbilityForResultAsCaller", moduleName, StartAbilityForResultAsCaller); + BindNativeFunction(env, objValue, "connectServiceExtensionAbility", moduleName, ConnectAbility); + BindNativeFunction(env, objValue, "disconnectServiceExtensionAbility", moduleName, DisconnectAbility); + BindNativeFunction(env, objValue, "reportDrawnCompleted", moduleName, ReportDrawnCompleted); + BindNativeFunction(env, objValue, "openAtomicService", moduleName, OpenAtomicService); + BindNativeFunction(env, objValue, "testMethod", moduleName, TestMethod); + + return objValue; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/ability_interceptor_test/BUILD.gn b/test/unittest/ability_interceptor_test/BUILD.gn index 2d241f9fdc..2a59372ee6 100644 --- a/test/unittest/ability_interceptor_test/BUILD.gn +++ b/test/unittest/ability_interceptor_test/BUILD.gn @@ -26,10 +26,12 @@ ohos_unittest("ability_interceptor_test") { "${distributedschedule_path}/samgr/adapter/interfaces/innerkits/include/", "${ability_runtime_innerkits_path}/app_manager/include/appmgr", "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include", + "${ability_runtime_services_path}/abilitymgr/include", ] sources = [ # add mock file + "${ability_runtime_services_path}/abilitymgr/src/start_ability_utils.cpp", "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp", "ability_interceptor_test.cpp", ] @@ -66,6 +68,7 @@ ohos_unittest("ability_interceptor_test") { "dsoftbus:softbus_client", "ffrt:libffrt", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_core", "napi:ace_napi", ] diff --git a/test/unittest/ability_interceptor_test/ability_interceptor_test.cpp b/test/unittest/ability_interceptor_test/ability_interceptor_test.cpp index d6aca71147..f60fe46d4f 100644 --- a/test/unittest/ability_interceptor_test/ability_interceptor_test.cpp +++ b/test/unittest/ability_interceptor_test/ability_interceptor_test.cpp @@ -17,16 +17,18 @@ #define private public #define protected public #include "ability_manager_service.h" +#include "interceptor/ability_jump_interceptor.h" +#include "interceptor/ecological_rule_interceptor.h" +#include "interceptor/disposed_rule_interceptor.h" #undef private #undef protected #include "bundlemgr/mock_bundle_manager.h" #include "interceptor/ability_interceptor_executer.h" -#include "interceptor/ability_jump_interceptor.h" #include "interceptor/control_interceptor.h" #include "interceptor/crowd_test_interceptor.h" -#include "interceptor/disposed_rule_interceptor.h" -#include "interceptor/ecological_rule_interceptor.h" +#include "permission_constants.h" +#include"start_ability_utils.h" using namespace testing; using namespace testing::ext; @@ -317,5 +319,434 @@ HWTEST_F(AbilityInterceptorTest, DisposedRuleInterceptor_005, TestSize.Level1) int result = executer->DoProcess(param); EXPECT_EQ(result, ERR_OK); } + +/** + * @tc.name: AbilityInterceptorTest_DisposedRuleInterceptor_006 + * @tc.desc: DisposedRuleInterceptor + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, DisposedRuleInterceptor_006, TestSize.Level1) +{ + std::shared_ptr executer = std::make_shared(); + Want want; + ElementName element("", "com.test.disposedrule", "MainAbility5", "entry"); + want.SetElement(element); + int requestCode = 0; + int userId = 100; + AbilityInterceptorParam param = AbilityInterceptorParam(want, requestCode, userId, true, nullptr); + int result = executer->DoProcess(param); + EXPECT_EQ(result, ERR_OK); +} + +/** + * @tc.name: AbilityInterceptorTest_DisposedRuleInterceptor_007 + * @tc.desc: DisposedRuleInterceptor + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, DisposedRuleInterceptor_007, TestSize.Level1) +{ + std::shared_ptr executer = std::make_shared(); + Want want; + ElementName element("", "com.test.disposedrule", "MainAbility6", "entry"); + want.SetElement(element); + AppExecFwk::DisposedRule disposedRule; + bool result = executer->CheckDisposedRule(want, disposedRule); + EXPECT_EQ(result, false); +} + +/** + * @tc.name: AbilityInterceptorTest_DisposedRuleInterceptor_008 + * @tc.desc: DisposedRuleInterceptor + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, DisposedRuleInterceptor_008, TestSize.Level1) +{ + std::shared_ptr executer = std::make_shared(); + Want want; + ElementName element("", "com.test.disposedrule", "MainAbility6", "entry"); + want.SetElement(element); + AppExecFwk::DisposedRule disposedRule; + disposedRule.disposedType = AppExecFwk::DisposedType::NON_BLOCK; + bool result = executer->CheckDisposedRule(want, disposedRule); + EXPECT_EQ(result, false); +} + +/** + * @tc.name: AbilityInterceptorTest_DisposedRuleInterceptor_009 + * @tc.desc: DisposedRuleInterceptor + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, DisposedRuleInterceptor_009, TestSize.Level1) +{ + std::shared_ptr executer = std::make_shared(); + Want want; + ElementName element("", "com.test.disposedrule", "MainAbility6", "entry"); + want.SetElement(element); + AppExecFwk::DisposedRule disposedRule; + disposedRule.disposedType = AppExecFwk::DisposedType::BLOCK_APPLICATION; + bool result = executer->CheckDisposedRule(want, disposedRule); + EXPECT_EQ(result, false); +} + +/** + * @tc.name: AbilityInterceptorTest_DisposedRuleInterceptor_010 + * @tc.desc: DisposedRuleInterceptor + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, DisposedRuleInterceptor_010, TestSize.Level1) +{ + std::shared_ptr executer = std::make_shared(); + Want want; + ElementName element("", "com.test.disposedrule", "MainAbility6", "entry"); + want.SetElement(element); + AppExecFwk::DisposedRule disposedRule; + disposedRule.disposedType = AppExecFwk::DisposedType::BLOCK_APPLICATION; + disposedRule.controlType = AppExecFwk::ControlType::ALLOWED_LIST; + bool result = executer->CheckDisposedRule(want, disposedRule); + EXPECT_EQ(result, false); +} + +/** + * @tc.name: AbilityInterceptorTest_DisposedRuleInterceptor_011 + * @tc.desc: DisposedRuleInterceptor + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, DisposedRuleInterceptor_011, TestSize.Level1) +{ + std::shared_ptr executer = std::make_shared(); + Want want; + ElementName element("", "com.test.disposedrule", "MainAbility6", "entry"); + want.SetElement(element); + AppExecFwk::DisposedRule disposedRule; + disposedRule.disposedType = AppExecFwk::DisposedType::BLOCK_APPLICATION; + disposedRule.controlType = AppExecFwk::ControlType::DISALLOWED_LIST; + bool result = executer->CheckDisposedRule(want, disposedRule); + EXPECT_EQ(result, true); +} + +/** + * @tc.name: AbilityInterceptorTest_DisposedRuleInterceptor_012 + * @tc.desc: DisposedRuleInterceptor + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, DisposedRuleInterceptor_012, TestSize.Level1) +{ + std::shared_ptr executer = std::make_shared(); + Want want; + AppExecFwk::DisposedRule disposedRule; + ErrCode result = executer->StartNonBlockRule(want, disposedRule); + EXPECT_EQ(result, ERR_OK); +} + +/** + * @tc.name: AbilityInterceptorTest_DisposedRuleInterceptor_013 + * @tc.desc: DisposedRuleInterceptor + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, DisposedRuleInterceptor_013, TestSize.Level1) +{ + std::shared_ptr executer = std::make_shared(); + std::string bundleName = "com.example.disposedruletest1"; + Want want; + want.SetBundle(bundleName); + DisposedRule disposedRule; + ErrCode result = executer->StartNonBlockRule(want, disposedRule); + EXPECT_EQ(result, ERR_OK); +} + +/** + * @tc.name: AbilityInterceptorTest_DisposedRuleInterceptor_014 + * @tc.desc: DisposedRuleInterceptor + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, DisposedRuleInterceptor_014, TestSize.Level1) +{ + std::shared_ptr executer = std::make_shared(); + Want want; + ElementName element("", "com.acts.disposedrulehap", "MainAbility", "entry"); + want.SetElement(element); + int requestCode = 0; + int userId = 100; + AbilityInterceptorParam param = AbilityInterceptorParam(want, requestCode, userId, true, nullptr); + executer->DoProcess(param); + EXPECT_NE(executer->GetAppMgr(), nullptr); +} + +/** + * @tc.name: AbilityInterceptorTest_DisposedRuleInterceptor_015 + * @tc.desc: DisposedRuleInterceptor + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, DisposedRuleInterceptor_015, TestSize.Level1) +{ + std::shared_ptr executer = std::make_shared(); + std::string bundleName = "com.example.disposedruletest"; + Want want; + want.SetBundle(bundleName); + sptr callerToken; + ErrCode result = executer->CreateModalUIExtension(want, callerToken); + EXPECT_EQ(result, INNER_ERR); +} + +/** + * @tc.name: AbilityInterceptorTest_AbilityJumpInterceptor_001 + * @tc.desc: DoProcess + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, AbilityJumpInterceptor_001, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + Want want; + int requestCode = 0; + int userId = 100; + AbilityInterceptorParam param = AbilityInterceptorParam(want, requestCode, userId, false, nullptr); + int result = interceptor->DoProcess(param); + EXPECT_EQ(result, ERR_OK); +} + +/** + * @tc.name: AbilityInterceptorTest_AbilityJumpInterceptor_002 + * @tc.desc: DoProcess + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, AbilityJumpInterceptor_002, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + std::string bundleName = "interceptor_callerBundleName"; + Want want; + want.SetBundle(bundleName); + int requestCode = 0; + int userId = 100; + AbilityInterceptorParam param = AbilityInterceptorParam(want, requestCode, userId, true, nullptr); + int result = interceptor->DoProcess(param); + EXPECT_EQ(result, ERR_OK); +} + +/** + * @tc.name: AbilityInterceptorTest_AbilityJumpInterceptor_003 + * @tc.desc: DoProcess + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, AbilityJumpInterceptor_003, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + Want want; + ElementName element("", "com.test.jumpinterceptor", "MainAbility", "entry"); + want.SetElement(element); + int requestCode = 1; + int userId = 100; + AbilityInterceptorParam param = AbilityInterceptorParam(want, requestCode, userId, true, nullptr); + int result = interceptor->DoProcess(param); + EXPECT_EQ(result, ERR_OK); +} + +/** + * @tc.name: AbilityInterceptorTest_AbilityJumpInterceptor_004 + * @tc.desc: CheckControl + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, AbilityJumpInterceptor_004, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + std::shared_ptr bundleMgrHelper = std::make_shared(); + Want want; + int32_t userId = 10; + AppExecFwk::AppJumpControlRule controlRule; + bool result = interceptor->CheckControl(bundleMgrHelper, want, userId, controlRule); + EXPECT_EQ(result, false); +} + +/** + * @tc.name: AbilityInterceptorTest_AbilityJumpInterceptor_005 + * @tc.desc: CheckControl + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, AbilityJumpInterceptor_005, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + std::shared_ptr bundleMgrHelper = std::make_shared(); + std::string bundleName = "interceptor_callerBundleName"; + Want want; + int32_t userId = 10; + AppExecFwk::AppJumpControlRule controlRule; + bool result = interceptor->CheckControl(bundleMgrHelper, want, userId, controlRule); + EXPECT_EQ(result, false); +} + +/** + * @tc.name: AbilityInterceptorTest_AbilityJumpInterceptor_006 + * @tc.desc: CheckControl + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, AbilityJumpInterceptor_006, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + std::shared_ptr bundleMgrHelper = std::make_shared(); + std::string bundleName = "interceptor_callerBundleName"; + Want want; + want.SetBundle(bundleName); + int32_t userId = 10; + AppExecFwk::AppJumpControlRule controlRule; + controlRule.callerPkg = "interceptor_callerBundleName"; + bool result = interceptor->CheckControl(bundleMgrHelper, want, userId, controlRule); + EXPECT_EQ(result, false); +} + +/** + * @tc.name: AbilityInterceptorTest_AbilityJumpInterceptor_007 + * @tc.desc: CheckControl + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, AbilityJumpInterceptor_007, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + std::shared_ptr bundleMgrHelper = std::make_shared(); + std::string bundleName = "BundleName"; + Want want; + want.SetBundle(bundleName); + int32_t userId = 10; + AppExecFwk::AppJumpControlRule controlRule; + controlRule.callerPkg = "interceptor_callerBundleName"; + bool result = interceptor->CheckControl(bundleMgrHelper, want, userId, controlRule); + EXPECT_EQ(result, false); +} + +/** + * @tc.name: AbilityInterceptorTest_AbilityJumpInterceptor_008 + * @tc.desc: CheckIfJumpExempt + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, AbilityJumpInterceptor_008, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + AppExecFwk::AppJumpControlRule controlRule; + controlRule.callerPkg = "interceptor_callerBundleName"; + int32_t userId = 10; + bool result = interceptor->CheckIfJumpExempt(controlRule, userId); + EXPECT_EQ(result, false); +} + +/** + * @tc.name: AbilityInterceptorTest_AbilityJumpInterceptor_009 + * @tc.desc: CheckIfJumpExempt + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, AbilityJumpInterceptor_009, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + AppExecFwk::AppJumpControlRule controlRule; + controlRule.targetPkg = "interceptor_callerBundleName"; + int32_t userId = 10; + bool result = interceptor->CheckIfJumpExempt(controlRule, userId); + EXPECT_EQ(result, false); +} + +/** + * @tc.name: AbilityInterceptorTest_AbilityJumpInterceptor_010 + * @tc.desc: CheckIfExemptByBundleName + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, AbilityJumpInterceptor_010, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + std::string bundleName = "interceptor_callerBundleName"; + std::string permission = PermissionConstants::PERMISSION_EXEMPT_AS_CALLER; + int32_t userId = 10; + bool result = interceptor->CheckIfExemptByBundleName(bundleName, permission, userId); + EXPECT_EQ(result, false); +} + +/** + * @tc.name: AbilityInterceptorTest_AbilityJumpInterceptor_011 + * @tc.desc: CheckIfExemptByBundleName + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, AbilityJumpInterceptor_011, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + std::string bundleName = "interceptor_callerBundleName"; + Want want; + want.SetBundle(bundleName); + int32_t abilityuserId = 0; + int32_t appIndex = 0; + StartAbilityUtils::startAbilityInfo = StartAbilityInfo::CreateStartExtensionInfo(want, + abilityuserId, appIndex); + std::string permission = PermissionConstants::PERMISSION_EXEMPT_AS_CALLER; + int32_t userId = 10; + bool result = interceptor->CheckIfExemptByBundleName(bundleName, permission, userId); + EXPECT_EQ(result, false); +} + +/** + * @tc.name: AbilityInterceptorTest_EcologicalRuleInterceptor_001 + * @tc.desc: DoProcess + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, EcologicalRuleInterceptor_001, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + Want want; + int requestCode = 0; + int userId = 100; + AbilityInterceptorParam param = AbilityInterceptorParam(want, requestCode, userId, false, nullptr); + ErrCode result = interceptor->DoProcess(param); + EXPECT_EQ(result, ERR_OK); +} + +/** + * @tc.name: AbilityInterceptorTest_EcologicalRuleInterceptor_002 + * @tc.desc: DoProcess + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, EcologicalRuleInterceptor_002, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + std::string bundleName = "com.ohos.sceneboard"; + Want want; + want.SetBundle(bundleName); + int requestCode = 0; + int userId = 100; + AbilityInterceptorParam param = AbilityInterceptorParam(want, requestCode, userId, true, nullptr); + ErrCode result = interceptor->DoProcess(param); + EXPECT_EQ(result, ERR_OK); +} + +/** + * @tc.name: AbilityInterceptorTest_EcologicalRuleInterceptor_003 + * @tc.desc: DoProcess + * @tc.type: FUNC + * @tc.require: No + */ +HWTEST_F(AbilityInterceptorTest, EcologicalRuleInterceptor_003, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + Want want; + int userId = 100; + bool result = interceptor->DoProcess(want, userId); + EXPECT_EQ(result, true); +} } // namespace AAFwk } // namespace OHOS 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 53ccab04ab..7c9396a795 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 @@ -19,6 +19,7 @@ #include "ability_manager_client.h" #include "ability_manager_stub_mock_test.h" #include "ability_connect_manager.h" +#include "ability_manager_interface.h" #undef private #undef protected @@ -28,6 +29,7 @@ #include "mock_ability_manager_collaborator.h" #include "session/host/include/session.h" #include "scene_board_judgement.h" +#include "status_bar_delegate_interface.h" using namespace testing::ext; using namespace testing; @@ -2569,5 +2571,35 @@ HWTEST_F(AbilityManagerClientBranchTest, AbilityManagerClient_GetAbilityStateByP EXPECT_NE(client_, nullptr); GTEST_LOG_(INFO) << "AbilityManagerClient_GetAbilityStateByPersistentId_0100 end"; } + +/** + * @tc.name: AbilityManagerClient_RegisterStatusBarDelegate_0100 + * @tc.desc: RegisterStatusBarDelegate + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerClientBranchTest, AbilityManagerClient_RegisterStatusBarDelegate_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityManagerClient_RegisterStatusBarDelegate_0100 start"; + ErrCode ret = client_->RegisterStatusBarDelegate(nullptr); + EXPECT_EQ(ret, ERR_OK); + GTEST_LOG_(INFO) << "AbilityManagerClient_RegisterStatusBarDelegate_0100 end"; +} + +#ifdef SUPPORT_GRAPHICS +/** + * @tc.name: AbilityManagerClient_SetMissionLabel_0100 + * @tc.desc: SetMissionLabel + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerClientBranchTest, AbilityManagerClient_SetMissionLabel_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "AbilityManagerClient_SetMissionLabel_0100 start"; + sptr token = nullptr; + std::string label = "label"; + ErrCode ret = client_->SetMissionLabel(token, label); + EXPECT_EQ(ret, ERR_OK); + GTEST_LOG_(INFO) << "AbilityManagerClient_SetMissionLabel_0100 end"; +} +#endif } // namespace AAFwk } // namespace OHOS \ No newline at end of file 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 5d6ce671a1..bbac11080a 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 @@ -2709,6 +2709,23 @@ HWTEST_F(AbilityManagerProxyTest, QueryAllAutoStartupApplications_0100, TestSize EXPECT_EQ(res, ERR_OK); } +/** + * @tc.name: AbilityManagerProxy_SetResidentProcessEnable_0100 + * @tc.desc: RestartApp + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerProxyTest, AbilityManagerProxy_SetResidentProcessEnable_0100, TestSize.Level1) +{ + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(mock_.GetRefPtr(), &AbilityManagerStubMock::InvokeSendRequest)); + + std::string bundleName = "ability.manager.proxy.test"; + bool enable = true; + proxy_->SetResidentProcessEnabled(bundleName, enable); + EXPECT_EQ(static_cast(AbilityManagerInterfaceCode::SET_RESIDENT_PROCESS_ENABLE), mock_->code_); +} + /** * @tc.name: AbilityManagerProxy_GetUIExtensionRootHostInfo_0100 * @tc.desc: GetUIExtensionRootHostInfo diff --git a/test/unittest/ability_manager_service_second_test/ability_manager_service_second_test.cpp b/test/unittest/ability_manager_service_second_test/ability_manager_service_second_test.cpp index bd2b8cfcd4..746b5d3b2b 100644 --- a/test/unittest/ability_manager_service_second_test/ability_manager_service_second_test.cpp +++ b/test/unittest/ability_manager_service_second_test/ability_manager_service_second_test.cpp @@ -1425,6 +1425,21 @@ HWTEST_F(AbilityManagerServiceSecondTest, DumpMissionInfosInner_001, TestSize.Le TAG_LOGI(AAFwkTag::TEST, "AbilityManagerServiceSecondTest DumpMissionInfosInner_001 end"); } +/* + * Feature: AbilityManagerService + * Function: SetResidentProcessEnabled + * SubFunction: NA + * FunctionPoints: AbilityManagerService SetResidentProcessEnabled + */ +HWTEST_F(AbilityManagerServiceSecondTest, SetResidentProcessEnable_001, TestSize.Level1) +{ + auto abilityMs_ = std::make_shared(); + ASSERT_NE(abilityMs_, nullptr); + std::string bundleName = "ability.manager.service.test"; + bool enable = false; + EXPECT_EQ(abilityMs_->SetResidentProcessEnabled(bundleName, enable), ERR_NOT_SYSTEM_APP); +} + /* * Feature: AbilityManagerService * Function: DumpMissionInner 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 60ebb79ead..fc0ba078ac 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 @@ -1746,6 +1746,20 @@ HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_RegisterRemoteOnListenerInne EXPECT_EQ(res, ERR_NULL_OBJECT); } +/** + * @tc.name: SetResidentProcessEnableInner_001 + * @tc.desc: SetResidentProcessEnableInner + * @tc.type: FUNC + */ +HWTEST_F(AbilityManagerStubTest, SetResidentProcessEnableInner_001, TestSize.Level1) +{ + ASSERT_NE(stub_, nullptr); + MessageParcel data; + MessageParcel reply; + auto result = stub_->SetResidentProcessEnableInner(data, reply); + EXPECT_EQ(result, NO_ERROR); +} + /* * Feature: AbilityManagerService * Function: RegisterRemoteOffListenerInner diff --git a/test/unittest/ability_manager_test/BUILD.gn b/test/unittest/ability_manager_test/BUILD.gn index 9bd045e601..b5ab84ee6c 100644 --- a/test/unittest/ability_manager_test/BUILD.gn +++ b/test/unittest/ability_manager_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -51,6 +51,7 @@ ohos_unittest("ability_manager_test") { "ability_runtime:abilitykit_native", "c_utils:utils", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_core", "napi:ace_napi", ] diff --git a/test/unittest/ability_record_test/ability_record_test.cpp b/test/unittest/ability_record_test/ability_record_test.cpp index fc7ced6d9f..27bced463a 100644 --- a/test/unittest/ability_record_test/ability_record_test.cpp +++ b/test/unittest/ability_record_test/ability_record_test.cpp @@ -568,8 +568,10 @@ HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_Want, TestSize.Level1) { Want want; want.SetFlags(100); + want.SetParam("multiThread", true); abilityRecord_->SetWant(want); EXPECT_EQ(want.GetFlags(), abilityRecord_->GetWant().GetFlags()); + EXPECT_EQ(want.GetBoolParam("multiThread", false), abilityRecord_->GetWant().GetBoolParam("multiThread", false)); } /* @@ -2366,15 +2368,12 @@ HWTEST_F(AbilityRecordTest, AbilityRecord_GetCurrentAccountId_001, TestSize.Leve */ HWTEST_F(AbilityRecordTest, AbilityRecord_CanRestartResident_001, TestSize.Level1) { - abilityRecord_->SetKeepAlive(); - EXPECT_TRUE(abilityRecord_->isKeepAlive_); abilityRecord_->SetRestarting(true, -1); EXPECT_TRUE(abilityRecord_->isRestarting_); - EXPECT_EQ(abilityRecord_->restartCount_, -1); + EXPECT_NE(abilityRecord_->restartCount_, -1); abilityRecord_->restartTime_ = AbilityUtil::SystemTimeMillis(); - EXPECT_FALSE(abilityRecord_->CanRestartResident()); abilityRecord_->restartTime_ = 0; // restart success abilityRecord_->SetAbilityState(AbilityState::ACTIVE); @@ -2394,12 +2393,9 @@ HWTEST_F(AbilityRecordTest, AbilityRecord_CanRestartResident_001, TestSize.Level */ HWTEST_F(AbilityRecordTest, AbilityRecord_CanRestartResident_002, TestSize.Level1) { - abilityRecord_->SetKeepAlive(); - EXPECT_TRUE(abilityRecord_->isKeepAlive_); - abilityRecord_->SetRestarting(true, -1); EXPECT_TRUE(abilityRecord_->isRestarting_); - EXPECT_EQ(abilityRecord_->restartCount_, -1); + EXPECT_NE(abilityRecord_->restartCount_, -1); abilityRecord_->SetRestartTime(0); EXPECT_EQ(abilityRecord_->restartTime_, 0); diff --git a/test/unittest/ams_app_mgr_client_test/BUILD.gn b/test/unittest/ams_app_mgr_client_test/BUILD.gn index 4f5e57b103..9306b86bbf 100644 --- a/test/unittest/ams_app_mgr_client_test/BUILD.gn +++ b/test/unittest/ams_app_mgr_client_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Copyright (c) 2021-2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -58,6 +58,7 @@ ohos_unittest("AmsAppMgrClientTest") { "common_event_service:cesfwk_innerkits", "ffrt:libffrt", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_core", ] diff --git a/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp b/test/unittest/ams_app_running_record_test/ams_app_running_record_test.cpp index 5f840a033d..ada7c08ab8 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 @@ -3022,5 +3022,85 @@ HWTEST_F(AmsAppRunningRecordTest, OnWindowVisibilityChanged_001, TestSize.Level1 EXPECT_TRUE(record->isUpdateStateFromService_); GTEST_LOG_(INFO) << "OnWindowVisibilityChanged_001 end."; } + +/** + * @tc.name: AppRunningRecord_SetState_001 + * @tc.desc: verify that setState works. + * @tc.type: FUNC + */ +HWTEST_F(AmsAppRunningRecordTest, SetState_001, TestSize.Level1) +{ + std::shared_ptr appInfo; + std::shared_ptr appRunningRecord = + std::make_shared(appInfo, AppRecordId::Create(), GetTestProcessName()); + appRunningRecord->SetState(ApplicationState::APP_STATE_SET_COLD_START); + EXPECT_NE(appRunningRecord->GetState(), ApplicationState::APP_STATE_CACHED); +} + +/** + * @tc.name: AppRunningRecord_UpdateApplicationInfoInstalled_001 + * @tc.desc: verify that UpdateApplicationInfoInstalled works. + * @tc.type: FUNC + */ +HWTEST_F(AmsAppRunningRecordTest, UpdateApplicationInfoInstalled_001, TestSize.Level1) +{ + std::shared_ptr appInfo; + std::shared_ptr appRunningRecord = + std::make_shared(appInfo, AppRecordId::Create(), GetTestProcessName()); + appRunningRecord->UpdateApplicationInfoInstalled(*appInfo); + EXPECT_NE(appRunningRecord, nullptr); +} + +/** + * @tc.name: AppRunningRecord_AddAbilityStageBySpecifiedProcess_001 + * @tc.desc: verify that AddAbilityStageBySpecifiedProcess works. + * @tc.type: FUNC + */ +HWTEST_F(AmsAppRunningRecordTest, AddAbilityStageBySpecifiedProcess_001, TestSize.Level1) +{ + std::shared_ptr appInfo; + std::shared_ptr appRunningRecord = + std::make_shared(appInfo, AppRecordId::Create(), GetTestProcessName()); + + appRunningRecord->AddAbilityStageBySpecifiedProcess("com.test"); + EXPECT_NE(appRunningRecord, nullptr); + + auto runner = AAFwk::TaskHandlerWrap::CreateQueueHandler("AmsAppRunningRecordTest"); + std::shared_ptr serviceInner = std::make_shared(); + std::shared_ptr handler = std::make_shared(runner, serviceInner); + appRunningRecord->eventHandler_ = handler; + appRunningRecord->AddAbilityStageBySpecifiedProcess("com.test"); + EXPECT_NE(handler, nullptr); +} + +/** + * @tc.name: AppRunningRecord_SendEventForSpecifiedAbility_001 + * @tc.desc: verify that SendEventForSpecifiedAbility works. + * @tc.type: FUNC + */ +HWTEST_F(AmsAppRunningRecordTest, SendEventForSpecifiedAbility_001, TestSize.Level1) +{ + std::shared_ptr appInfo; + std::shared_ptr appRunningRecord = + std::make_shared(appInfo, AppRecordId::Create(), GetTestProcessName()); + appRunningRecord->SendEventForSpecifiedAbility(1, 100); + EXPECT_NE(appRunningRecord, nullptr); +} + +/** + * @tc.name: AppRunningRecord_SendAppStartupTypeEvent_001 + * @tc.desc: verify that SendAppStartupTypeEvent works. + * @tc.type: FUNC + */ +HWTEST_F(AmsAppRunningRecordTest, AppRunningRecord_SendAppStartupTypeEvent_001, TestSize.Level1) +{ + std::shared_ptr appRunningRecord = + std::make_shared(nullptr, AppRecordId::Create(), GetTestProcessName()); + std::shared_ptr abilityInfo = std::make_shared(); + std::shared_ptr abilityRecord = + std::make_shared(abilityInfo, nullptr, 0); + appRunningRecord->SendAppStartupTypeEvent(abilityRecord, AppStartType::COLD); + EXPECT_NE(appRunningRecord, nullptr); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/app_mgr_client_test/BUILD.gn b/test/unittest/app_mgr_client_test/BUILD.gn index 067ff57712..8c6e9b1bac 100644 --- a/test/unittest/app_mgr_client_test/BUILD.gn +++ b/test/unittest/app_mgr_client_test/BUILD.gn @@ -56,6 +56,7 @@ ohos_unittest("AppMgrClientTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", "ffrt:libffrt", 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 43f33d5351..b44ecad70f 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 @@ -867,7 +867,7 @@ HWTEST_F(AppMgrClientTest, AppMgrClient_RegisterAbilityDebugResponse_001, TestSi response = new MockAbilityDebugResponseStub(); EXPECT_NE(response, nullptr); resultCode = appMgrClient->RegisterAbilityDebugResponse(response); - EXPECT_EQ(resultCode, NO_ERROR); + EXPECT_EQ(resultCode, ERR_PERMISSION_DENIED); } /** @@ -1330,5 +1330,31 @@ HWTEST_F(AppMgrClientTest, GetAppRunningUniqueIdByPid_001, TestSize.Level0) appMgrClient->GetAppRunningUniqueIdByPid(pid, appRunningUniqueId); EXPECT_NE(appMgrClient, nullptr); } + +/** + * @tc.name: AppMgrClient_NotifyMemorySizeStateChanged_001 + * @tc.desc: NotifyMemorySizeStateChanged. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrClientTest, NotifyMemorySizeStateChanged_001, TestSize.Level0) +{ + auto appMgrClient = std::make_unique(); + bool isMemorySizeSufficent = false; + int32_t ret = appMgrClient->NotifyMemorySizeStateChanged(isMemorySizeSufficent); + EXPECT_EQ(ret, 1); +} + +/** + * @tc.name: AppMgrClient_SetSupportedProcessCacheSelf_001 + * @tc.desc: SetSupportedProcessCacheSelf. + * @tc.type: FUNC + */ +HWTEST_F(AppMgrClientTest, SetSupportedProcessCacheSelf_001, TestSize.Level0) +{ + auto appMgrClient = std::make_unique(); + bool isSupport = false; + int32_t ret = appMgrClient->SetSupportedProcessCacheSelf(isSupport); + EXPECT_EQ(ret, ERR_INVALID_VALUE); +} } // namespace AppExecFwk } // namespace OHOS 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 1b2a5f7040..dee1ea3a48 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 @@ -575,16 +575,20 @@ HWTEST_F(AppMgrServiceInnerTest, LaunchApplication_001, TestSize.Level0) appRecord->SetState(ApplicationState::APP_STATE_CREATE); appMgrServiceInner->LaunchApplication(appRecord); - appRecord->SetKeepAliveAppState(false, true); + appRecord->SetEmptyKeepAliveAppState(true); + appRecord->SetKeepAliveEnableState(false); appMgrServiceInner->LaunchApplication(appRecord); - appRecord->SetKeepAliveAppState(true, false); + appRecord->SetKeepAliveEnableState(true); + appRecord->SetEmptyKeepAliveAppState(false); appMgrServiceInner->LaunchApplication(appRecord); - appRecord->SetKeepAliveAppState(true, true); + appRecord->SetKeepAliveEnableState(true); + appRecord->SetEmptyKeepAliveAppState(true); appMgrServiceInner->LaunchApplication(appRecord); - appRecord->SetKeepAliveAppState(false, false); + appRecord->SetKeepAliveEnableState(false); + appRecord->SetEmptyKeepAliveAppState(false); appMgrServiceInner->LaunchApplication(appRecord); Want want; @@ -750,16 +754,20 @@ HWTEST_F(AppMgrServiceInnerTest, ApplicationTerminated_001, TestSize.Level0) appMgrServiceInner->ApplicationTerminated(recordId_); - appRecord->SetKeepAliveAppState(false, true); + appRecord->SetKeepAliveEnableState(false); + appRecord->SetEmptyKeepAliveAppState(true); appMgrServiceInner->ApplicationTerminated(recordId_); - appRecord->SetKeepAliveAppState(true, false); + appRecord->SetKeepAliveEnableState(true); + appRecord->SetEmptyKeepAliveAppState(false); appMgrServiceInner->ApplicationTerminated(recordId_); - appRecord->SetKeepAliveAppState(true, true); + appRecord->SetKeepAliveEnableState(true); + appRecord->SetEmptyKeepAliveAppState(true); appMgrServiceInner->ApplicationTerminated(recordId_); - appRecord->SetKeepAliveAppState(false, false); + appRecord->SetKeepAliveEnableState(false); + appRecord->SetEmptyKeepAliveAppState(false); appMgrServiceInner->ApplicationTerminated(recordId_); appRecord->SetState(ApplicationState::APP_STATE_FOREGROUND); @@ -1198,6 +1206,12 @@ HWTEST_F(AppMgrServiceInnerTest, CreateAppRunningRecord_001, TestSize.Level0) applicationInfo_, abilityInfo_, processName, bundleInfo, hapModuleInfo, want, 0); EXPECT_EQ(appRecord5, nullptr); + appMgrServiceInner->appRunningManager_ = nullptr; + want->SetParam("multiThread", false); + std::shared_ptr appRecord6 = appMgrServiceInner->CreateAppRunningRecord(token, nullptr, + applicationInfo_, abilityInfo_, processName, bundleInfo, hapModuleInfo, want, 0); + EXPECT_EQ(appRecord6, nullptr); + TAG_LOGI(AAFwkTag::TEST, "CreateAppRunningRecord_001 end"); } @@ -1523,7 +1537,8 @@ HWTEST_F(AppMgrServiceInnerTest, KillProcessByAbilityToken_001, TestSize.Level0) EXPECT_NE(appRecord, nullptr); appMgrServiceInner->KillProcessByAbilityToken(token); - appRecord->SetKeepAliveAppState(true, true); + appRecord->SetKeepAliveEnableState(true); + appRecord->SetEmptyKeepAliveAppState(true); appMgrServiceInner->KillProcessByAbilityToken(token); TAG_LOGI(AAFwkTag::TEST, "KillProcessByAbilityToken_001 end"); @@ -1780,9 +1795,11 @@ HWTEST_F(AppMgrServiceInnerTest, RemoveAppFromRecentList_001, TestSize.Level0) pid_t pid = 123; appMgrServiceInner->AddAppToRecentList(appName1, processName1, pid, 0); - appRecord->SetKeepAliveAppState(true, true); + appRecord->SetKeepAliveEnableState(true); + appRecord->SetEmptyKeepAliveAppState(true); appMgrServiceInner->RemoveAppFromRecentList(appName1, processName1); - appRecord->SetKeepAliveAppState(false, false); + appRecord->SetKeepAliveEnableState(false); + appRecord->SetEmptyKeepAliveAppState(false); appMgrServiceInner->RemoveAppFromRecentList(appName1, processName1); TAG_LOGI(AAFwkTag::TEST, "RemoveAppFromRecentList_001 end"); @@ -3882,7 +3899,8 @@ HWTEST_F(AppMgrServiceInnerTest, SendAppLaunchEvent_001, TestSize.Level0) appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, info); recordId_ += 1; appRecord->SetState(ApplicationState::APP_STATE_CREATE); - appRecord->SetKeepAliveAppState(false, false); + appRecord->SetKeepAliveEnableState(false); + appRecord->SetEmptyKeepAliveAppState(false); Want want; appRecord->SetSpecifiedAbilityFlagAndWant(false, want, ""); appMgrServiceInner->SendAppLaunchEvent(appRecord); 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 9c10b3741a..07b0e72d83 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 @@ -1444,11 +1444,11 @@ 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); + int32_t res = appMgrService->StartChildProcess("./ets/AProcess.ts", pid, 1, false); EXPECT_EQ(res, ERR_OK); } 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 6703a2c732..99dc6b0658 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 @@ -217,7 +217,7 @@ 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); + auto childRecord = ChildProcessRecord::CreateChildProcessRecord(PID, "./ets/AProcess.ts", appRecord, 1, false); pid_t childPid = 201; childRecord->pid_ = childPid; appRecord->AddChildProcessRecord(childPid, childRecord); diff --git a/test/unittest/app_running_record_test/BUILD.gn b/test/unittest/app_running_record_test/BUILD.gn index 2ec7992a4b..80ab042ba8 100644 --- a/test/unittest/app_running_record_test/BUILD.gn +++ b/test/unittest/app_running_record_test/BUILD.gn @@ -29,7 +29,11 @@ ohos_unittest("app_running_record_test") { "${ability_runtime_test_path}/mock/services_appmgr_test/include/", ] - sources = [ "app_running_record_test.cpp" ] + sources = [ + "${ability_runtime_services_path}/appmgr/src/child_process_record.cpp", + "app_running_record_test.cpp", + "child_process_record_test.cpp", + ] deps = [ "${ability_runtime_innerkits_path}/app_manager:app_manager", 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 77927ab52f..cf18cfa99f 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 @@ -201,9 +201,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); + auto childRecord = std::make_shared(101, "./ets/AProcess.ts", appRecord, 0, false); pid_t childPid = 201; - childRecord->pid_ = childPid; + childRecord->SetPid(childPid); appRecord->AddChildProcessRecord(childPid, childRecord); auto childProcessRecordMap = appRecord->childProcessRecordMap_; @@ -223,9 +223,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); + auto childRecord = std::make_shared(101, "./ets/AProcess.ts", appRecord, 0, false); pid_t childPid = 201; - childRecord->pid_ = childPid; + childRecord->SetPid(childPid); appRecord->childProcessRecordMap_.emplace(childPid, childRecord); appRecord->RemoveChildProcessRecord(childRecord); @@ -246,9 +246,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); + auto childRecord = std::make_shared(101, "./ets/AProcess.ts", appRecord, 0, false); pid_t childPid = 201; - childRecord->pid_ = childPid; + childRecord->SetPid(childPid); appRecord->childProcessRecordMap_.emplace(childPid, childRecord); auto record = appRecord->GetChildProcessRecordByPid(childPid); 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 new file mode 100644 index 0000000000..5461f04c03 --- /dev/null +++ b/test/unittest/app_running_record_test/child_process_record_test.cpp @@ -0,0 +1,330 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "app_running_record.h" +#include "hilog_tag_wrapper.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AppExecFwk { +namespace { +constexpr int32_t RECORD_ID = 1; +} +class ChildProcessRecordTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; + +void ChildProcessRecordTest::SetUpTestCase(void) +{} + +void ChildProcessRecordTest::TearDownTestCase(void) +{} + +void ChildProcessRecordTest::SetUp() +{} + +void ChildProcessRecordTest::TearDown() +{} + +/** + * @tc.name: ChildProcessRecord_0100 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0100, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_0100 called."); + std::shared_ptr appInfo = std::make_shared(); + 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); + auto hostPid = childRecord->GetHostPid(); + EXPECT_EQ(hostPid, 101); +} + +/** + * @tc.name: ChildProcessRecord_0200 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0200, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_0200 called."); + std::shared_ptr appInfo = std::make_shared(); + 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); + childRecord->SetUid(100); + auto uid = childRecord->GetUid(); + EXPECT_EQ(uid, 100); +} + +/** + * @tc.name: ChildProcessRecord_0300 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +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); + auto record = childRecord->GetHostRecord(); + EXPECT_EQ(record, nullptr); +} + +/** + * @tc.name: ChildProcessRecord_0400 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0400, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_0400 called."); + std::shared_ptr appInfo = std::make_shared(); + 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); + auto processName = childRecord->GetProcessName(); + EXPECT_TRUE(processName.length() > 0); +} + +/** + * @tc.name: ChildProcessRecord_0500 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +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); + auto processName = childRecord->GetProcessName(); + EXPECT_TRUE(processName.length() <= 0); +} + +/** + * @tc.name: ChildProcessRecord_0600 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0600, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_0600 called."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + EXPECT_NE(appRecord, nullptr); + + auto childRecord = std::make_shared(101, "", appRecord, 0, false); + auto processName = childRecord->GetProcessName(); + EXPECT_TRUE(processName.length() <= 0); +} + +/** + * @tc.name: ChildProcessRecord_0700 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_0700, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_0700 called."); + std::shared_ptr appInfo = std::make_shared(); + 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); + auto srcEntry = childRecord->GetSrcEntry(); + EXPECT_EQ(srcEntry, "./ets/AProcess.ts"); +} + +/** + * @tc.name: ChildProcessRecord_0800 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +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); + sptr scheduler; + childRecord->SetScheduler(scheduler); + EXPECT_NE(childRecord, nullptr); +} + +/** + * @tc.name: ChildProcessRecord_0900 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +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); + sptr scheduler; + childRecord->SetScheduler(scheduler); + EXPECT_EQ(childRecord->GetScheduler(), scheduler); +} + +/** + * @tc.name: ChildProcessRecord_1000 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +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); + sptr recipient; + childRecord->SetDeathRecipient(recipient); + EXPECT_NE(childRecord, nullptr); +} + +/** + * @tc.name: ChildProcessRecord_1100 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +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); + sptr scheduler; + childRecord->SetScheduler(scheduler); + sptr recipient; + childRecord->SetDeathRecipient(recipient); + childRecord->RegisterDeathRecipient(); + EXPECT_NE(childRecord, nullptr); +} + +/** + * @tc.name: ChildProcessRecord_1200 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +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); + childRecord->RemoveDeathRecipient(); + EXPECT_NE(childRecord, nullptr); +} + +/** + * @tc.name: ChildProcessRecord_1300 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +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); + sptr scheduler; + childRecord->SetScheduler(scheduler); + childRecord->RemoveDeathRecipient(); + EXPECT_NE(childRecord, nullptr); +} + +/** + * @tc.name: ChildProcessRecord_1400 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +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); + sptr scheduler; + childRecord->SetScheduler(scheduler); + childRecord->ScheduleExitProcessSafely(); + EXPECT_NE(childRecord, nullptr); +} + +/** + * @tc.name: ChildProcessRecord_1500 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +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); + childRecord->ScheduleExitProcessSafely(); + EXPECT_NE(childRecord, nullptr); +} + +/** + * @tc.name: ChildProcessRecord_1600 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_1600, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_1600 called."); + std::shared_ptr appInfo = std::make_shared(); + 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); + EXPECT_EQ(childRecord, nullptr); +} + +/** + * @tc.name: ChildProcessRecord_1700 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessRecordTest, ChildProcessRecord_1700, TestSize.Level1) +{ + TAG_LOGD(AAFwkTag::TEST, "ChildProcessRecord_1700 called."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + EXPECT_NE(appRecord, nullptr); + + auto childRecord = ChildProcessRecord::CreateChildProcessRecord(101, "", appRecord, 0, false); + EXPECT_EQ(childRecord, nullptr); +} + +/** + * @tc.name: ChildProcessRecord_1800 + * @tc.desc: Test ChildProcessRecord works. + * @tc.type: FUNC + */ +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); + EXPECT_EQ(childRecord, nullptr); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/test/unittest/app_state_observer_manager_test/app_state_observer_manager_test.cpp b/test/unittest/app_state_observer_manager_test/app_state_observer_manager_test.cpp index fb360d22ad..3f34cb5517 100644 --- a/test/unittest/app_state_observer_manager_test/app_state_observer_manager_test.cpp +++ b/test/unittest/app_state_observer_manager_test/app_state_observer_manager_test.cpp @@ -108,7 +108,8 @@ std::shared_ptr AppSpawnSocketTest::MockAppRecord() appRecord->SetUid(1); appRecord->SetState(ApplicationState::APP_STATE_CREATE); appRecord->SetContinuousTaskAppState(false); - appRecord->SetKeepAliveAppState(false, false); + appRecord->SetKeepAliveEnableState(false); + appRecord->SetEmptyKeepAliveAppState(false); appRecord->SetRequestProcCode(1); appRecord->isFocused_ = false; return appRecord; 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 e40f1f9fc5..5e8c5481ad 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 @@ -24,6 +24,16 @@ using namespace testing::ext; namespace OHOS { namespace AppExecFwk { +namespace { +const int32_t ERR_COD1 = 8519801; +const int32_t ERR_COD2 = 8519806; +const int32_t ERR_COD3 = 8519802; +const int32_t ERR_COD4 = 8519921; +const int32_t ERR_COD5 = 8519816; +const int32_t ERR_COD6 = 8519817; +const int32_t ERR_COD7 = 8521219; +} // namespace + class BundleMgrHelperTest : public testing::Test { public: static void SetUpTestCase(); @@ -506,5 +516,288 @@ HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetDefaultAppProxy_001, TestSi auto ret = bundleMgrHelper->GetDefaultAppProxy(); EXPECT_NE(ret, nullptr); } + +/** + * @tc.name: BundleMgrHelperTest_InstallSandboxApp_001 + * @tc.desc: InstallSandboxApp + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_InstallSandboxApp_001, TestSize.Level1) +{ + std::string bundleName = ""; + int32_t dlpType = 1; + int32_t userId = 1; + int32_t appIndex = 1; + auto ret = bundleMgrHelper->InstallSandboxApp(bundleName, dlpType, userId, appIndex); + EXPECT_EQ(ret, ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR); +} + +/** + * @tc.name: BundleMgrHelperTest_InstallSandboxApp_002 + * @tc.desc: InstallSandboxApp + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_InstallSandboxApp_002, TestSize.Level1) +{ + std::string bundleName = "bundleName"; + int32_t dlpType = 1; + int32_t userId = 1; + int32_t appIndex = 1; + auto ret = bundleMgrHelper->InstallSandboxApp(bundleName, dlpType, userId, appIndex); + EXPECT_EQ(ret, ERR_COD1); +} + +/** + * @tc.name: BundleMgrHelperTest_UninstallSandboxApp_001 + * @tc.desc: UninstallSandboxApp + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_UninstallSandboxApp_001, TestSize.Level1) +{ + std::string bundleName = ""; + int32_t userId = 1; + int32_t appIndex = 1; + auto ret = bundleMgrHelper->UninstallSandboxApp(bundleName, userId, appIndex); + EXPECT_EQ(ret, ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR); +} + +/** + * @tc.name: BundleMgrHelperTest_UninstallSandboxApp_002 + * @tc.desc: UninstallSandboxApp + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_UninstallSandboxApp_002, TestSize.Level1) +{ + std::string bundleName = "bundleName"; + int32_t userId = 1; + int32_t appIndex = 1; + auto ret = bundleMgrHelper->UninstallSandboxApp(bundleName, userId, appIndex); + EXPECT_EQ(ret, ERR_COD2); +} + +/** + * @tc.name: BundleMgrHelperTest_UninstallSandboxApp_003 + * @tc.desc: UninstallSandboxApp + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_UninstallSandboxApp_003, TestSize.Level1) +{ + std::string bundleName = "bundleName"; + int32_t userId = 1; + int32_t appIndex = -1; + auto ret = bundleMgrHelper->UninstallSandboxApp(bundleName, userId, appIndex); + EXPECT_EQ(ret, ERR_COD3); +} + +/** + * @tc.name: BundleMgrHelperTest_GetUninstalledBundleInfo_001 + * @tc.desc: GetUninstalledBundleInfo + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetUninstalledBundleInfo_001, TestSize.Level1) +{ + std::string bundleName = "bundleName"; + BundleInfo bundleInfo; + auto ret = bundleMgrHelper->GetUninstalledBundleInfo(bundleName, bundleInfo); + EXPECT_EQ(ret, ERR_COD4); +} + +/** + * @tc.name: BundleMgrHelperTest_GetSandboxBundleInfo_001 + * @tc.desc: GetSandboxBundleInfo + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxBundleInfo_001, TestSize.Level1) +{ + std::string bundleName = "bundleName"; + int32_t appIndex = -1; + int32_t userId = 1; + BundleInfo bundleInfo; + auto ret = bundleMgrHelper->GetSandboxBundleInfo(bundleName, appIndex, userId, bundleInfo); + EXPECT_EQ(ret, ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR); +} + +/** + * @tc.name: BundleMgrHelperTest_GetSandboxBundleInfo_002 + * @tc.desc: GetSandboxBundleInfo + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxBundleInfo_002, TestSize.Level1) +{ + std::string bundleName = ""; + int32_t appIndex = 10; + int32_t userId = 1; + BundleInfo bundleInfo; + auto ret = bundleMgrHelper->GetSandboxBundleInfo(bundleName, appIndex, userId, bundleInfo); + EXPECT_EQ(ret, ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR); +} + +/** + * @tc.name: BundleMgrHelperTest_GetSandboxAbilityInfo_001 + * @tc.desc: GetSandboxAbilityInfo + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxAbilityInfo_001, TestSize.Level1) +{ + Want want; + int32_t appIndex = 0; + int32_t flags = 1; + int32_t userId = 1; + AbilityInfo abilityInfo; + auto ret = bundleMgrHelper->GetSandboxAbilityInfo(want, appIndex, flags, userId, abilityInfo); + EXPECT_EQ(ret, ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR); +} + +/** + * @tc.name: BundleMgrHelperTest_GetSandboxAbilityInfo_002 + * @tc.desc: GetSandboxAbilityInfo + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxAbilityInfo_002, TestSize.Level1) +{ + Want want; + int32_t appIndex = 10000; + int32_t flags = 1; + int32_t userId = 1; + AbilityInfo abilityInfo; + auto ret = bundleMgrHelper->GetSandboxAbilityInfo(want, appIndex, flags, userId, abilityInfo); + EXPECT_EQ(ret, ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR); +} + +/** + * @tc.name: BundleMgrHelperTest_GetSandboxAbilityInfo_003 + * @tc.desc: GetSandboxAbilityInfo + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxAbilityInfo_003, TestSize.Level1) +{ + Want want; + int32_t appIndex = 2; + int32_t flags = 1; + int32_t userId = 1; + AbilityInfo abilityInfo; + auto ret = bundleMgrHelper->GetSandboxAbilityInfo(want, appIndex, flags, userId, abilityInfo); + EXPECT_EQ(ret, ERR_COD5); +} + +/** + * @tc.name: BundleMgrHelperTest_GetSandboxExtAbilityInfos_001 + * @tc.desc: GetSandboxExtAbilityInfos + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxExtAbilityInfos_001, TestSize.Level1) +{ + Want want; + int32_t appIndex = 2; + int32_t flags = 1; + int32_t userId = 1; + std::vector extensionInfos; + auto ret = bundleMgrHelper->GetSandboxExtAbilityInfos(want, appIndex, flags, userId, extensionInfos); + EXPECT_EQ(ret, ERR_COD5); +} + +/** + * @tc.name: BundleMgrHelperTest_GetSandboxHapModuleInfo_001 + * @tc.desc: GetSandboxHapModuleInfo + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxHapModuleInfo_001, TestSize.Level1) +{ + AbilityInfo abilityInfo; + int32_t appIndex = 0; + int32_t userId = 1; + HapModuleInfo hapModuleInfo; + auto ret = bundleMgrHelper->GetSandboxHapModuleInfo(abilityInfo, appIndex, userId, hapModuleInfo); + EXPECT_EQ(ret, ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR); +} + +/** + * @tc.name: BundleMgrHelperTest_GetSandboxHapModuleInfo_002 + * @tc.desc: GetSandboxHapModuleInfo + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxHapModuleInfo_002, TestSize.Level1) +{ + AbilityInfo abilityInfo; + int32_t appIndex = 10000; + int32_t userId = 1; + HapModuleInfo hapModuleInfo; + auto ret = bundleMgrHelper->GetSandboxHapModuleInfo(abilityInfo, appIndex, userId, hapModuleInfo); + EXPECT_EQ(ret, ERR_APPEXECFWK_SANDBOX_INSTALL_PARAM_ERROR); +} + +/** + * @tc.name: BundleMgrHelperTest_GetSandboxHapModuleInfo_003 + * @tc.desc: GetSandboxHapModuleInfo + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetSandboxHapModuleInfo_003, TestSize.Level1) +{ + AbilityInfo abilityInfo; + int32_t appIndex = 2; + int32_t userId = 1; + HapModuleInfo hapModuleInfo; + auto ret = bundleMgrHelper->GetSandboxHapModuleInfo(abilityInfo, appIndex, userId, hapModuleInfo); + EXPECT_EQ(ret, ERR_COD6); +} + +/** + * @tc.name: BundleMgrHelperTest_ConnectBundleInstaller_001 + * @tc.desc: ConnectBundleInstaller + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_ConnectBundleInstaller_001, TestSize.Level1) +{ + bundleMgrHelper->OnDeath(); + auto ret = bundleMgrHelper->ConnectBundleInstaller(); + EXPECT_NE(ret, nullptr); +} + +/** + * @tc.name: BundleMgrHelperTest_GetBundleInfoV9_001 + * @tc.desc: GetBundleInfoV9 + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, BundleMgrHelperTest_GetBundleInfoV9_001, TestSize.Level1) +{ + std::string bundleName = "bundleName"; + int32_t flags = 1; + BundleInfo bundleInfo; + int32_t userId = 1; + auto ret = bundleMgrHelper->GetBundleInfoV9(bundleName, flags, bundleInfo, userId); + EXPECT_EQ(ret, ERR_COD7); +} + +/** + * @tc.name: QueryExtensionAbilityInfosOnlyWithTypeName_001 + * @tc.desc: QueryExtensionAbilityInfosOnlyWithTypeName + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, QueryExtensionAbilityInfosOnlyWithTypeName_001, TestSize.Level1) +{ + std::string extensionTypeName = "extensionTypeName"; + uint32_t flag = 1; + int32_t userId = 1; + std::vector extensionInfos; + auto ret = bundleMgrHelper->QueryExtensionAbilityInfosOnlyWithTypeName(extensionTypeName, + flag, userId, extensionInfos); + EXPECT_EQ(ret, ERR_COD7); +} + +/** + * @tc.name: GetJsonProfile_001 + * @tc.desc: GetJsonProfile + * @tc.type: FUNC + */ +HWTEST_F(BundleMgrHelperTest, GetJsonProfile_001, TestSize.Level1) +{ + ProfileType profileType = AppExecFwk::PKG_CONTEXT_PROFILE; + std::string bundleName = "bundleName"; + std::string moduleName = "moduleName"; + std::string profile = "profile"; + int32_t userId = 1; + auto ret = bundleMgrHelper->GetJsonProfile(profileType, bundleName, moduleName, profile, userId); + EXPECT_EQ(ret, ERR_COD7); +} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/cache_process_manager_test/cache_process_manager_test.cpp b/test/unittest/cache_process_manager_test/cache_process_manager_test.cpp index 22f1c30e93..5503e31de0 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 @@ -63,7 +63,8 @@ std::shared_ptr CacheProcessManagerTest::MockAppRecord(int api appRecord->SetUid(1); appRecord->SetState(ApplicationState::APP_STATE_CREATE); appRecord->SetContinuousTaskAppState(false); - appRecord->SetKeepAliveAppState(false, false); + appRecord->SetKeepAliveEnableState(false); + appRecord->SetEmptyKeepAliveAppState(false); appRecord->SetRequestProcCode(1); appRecord->isFocused_ = false; return appRecord; @@ -121,7 +122,8 @@ HWTEST_F(CacheProcessManagerTest, CacheProcessManager_PenddingCacheProcess_0100, // keepalive not allowed auto appRecord = MockAppRecord(); EXPECT_NE(appRecord, nullptr); - appRecord->SetKeepAliveAppState(true, true); + appRecord->SetKeepAliveEnableState(true); + appRecord->SetEmptyKeepAliveAppState(true); EXPECT_EQ(cacheProcMgr->PenddingCacheProcess(appRecord), false); // nullptr not allowed std::shared_ptr appRecord2 = nullptr; 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 75f76bd8c1..1eaf3f3076 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 @@ -82,6 +82,21 @@ HWTEST_F(ChildProcessManagerTest, StartChildProcessBySelfFork_0100, TestSize.Lev EXPECT_NE(ret, ChildProcessManagerErrorCode::ERR_FORK_FAILED); } +/** + * @tc.number: StartChildProcessBySelfFork_0200 + * @tc.desc: Test StartChildProcessBySelfFork works + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessManagerTest, StartChildProcessBySelfFork_0200, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "StartChildProcessBySelfFork_0200 called."); + AAFwk::AppUtils::GetInstance().isMultiProcessModel_.isLoaded = true; + AAFwk::AppUtils::GetInstance().isMultiProcessModel_.value = true; + pid_t pid; + auto ret = ChildProcessManager::GetInstance().StartChildProcessBySelfFork("./ets/process/DemoProcess.ts", pid); + EXPECT_NE(ret, ChildProcessManagerErrorCode::ERR_FORK_FAILED); +} + /** * @tc.number: StartChildProcessByAppSpawnFork_0100 * @tc.desc: Test StartChildProcessByAppSpawnFork works. @@ -160,6 +175,31 @@ HWTEST_F(ChildProcessManagerTest, CreateRuntime_0100, TestSize.Level0) EXPECT_TRUE(runtime != nullptr); } +/** + * @tc.number: ChildProcessErrorUtils_0100 + * @tc.desc: Test ChildProcessErrorUtils. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessManagerTest, ChildProcessErrorUtils_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "ChildProcessErrorUtils_0100 called."); + auto err = ChildProcessManagerErrorUtil::GetAbilityErrorCode(ChildProcessManagerErrorCode::ERR_OK); + EXPECT_EQ(err, AbilityErrorCode::ERROR_OK); +} + +/** + * @tc.number: HandleChildProcessBySelfFork_0100 + * @tc.desc: Test HandleChildProcessBySelfFork works. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessManagerTest, HandleChildProcessBySelfFork, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "HandleChildProcessBySelfFork_0100 called."); + AppExecFwk::BundleInfo bundleInfo; + ChildProcessManager::GetInstance().HandleChildProcessBySelfFork("./ets/process/DemoProcess.ts", bundleInfo); + EXPECT_EQ(ChildProcessManager::GetInstance().isChildProcessBySelfFork_, true); +} + /** * @tc.number: LoadJsFile_0100 * @tc.desc: Test LoadJsFile works. @@ -173,5 +213,18 @@ HWTEST_F(ChildProcessManagerTest, LoadJsFile_0100, TestSize.Level0) auto ret = ChildProcessManager::GetInstance().LoadJsFile("./ets/process/AProcess.ts", hapModuleInfo, runtime); EXPECT_TRUE(ret); } + +/** + * @tc.number: SetForkProcessDebugOption_0100 + * @tc.desc: Test SetForkProcessDebugOption. + * @tc.type: FUNC + */ +HWTEST_F(ChildProcessManagerTest, SetForkProcessDebugOption_0100, TestSize.Level0) +{ +TAG_LOGD(AAFwkTag::TEST, "SetForkProcessDebugOption called."); +AbilityRuntime::Runtime::DebugOption debugOption; +ChildProcessManager::GetInstance().SetForkProcessDebugOption("test", false, false, false); +EXPECT_TRUE(true); +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file 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 04f23f38d7..b229760c48 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 @@ -80,5 +80,64 @@ HWTEST_F(JsChildProcessTest, JsChildProcessInit_0100, TestSize.Level0) process->Init(info); EXPECT_TRUE(process->processStartInfo_ != nullptr); } + +/** + * @tc.number: JsChildProcessInit_0200 + * @tc.desc: Test JsChildProcess Init works + * @tc.type: FUNC + */ +HWTEST_F(JsChildProcessTest, JsChildProcessInit_0200, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "JsChildProcessInit_0200 called."); + std::unique_ptr runtime = std::make_unique(); + auto process = JsChildProcess::Create(runtime); + EXPECT_TRUE(process != nullptr); + + auto ret = process->Init(nullptr); + EXPECT_FALSE(ret); +} + +/** + * @tc.number: JsChildProcessInit_0300 + * @tc.desc: Test JsChildProcess Init works + * @tc.type: FUNC + */ +HWTEST_F(JsChildProcessTest, JsChildProcessInit_0300, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "JsChildProcessInit_0300 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 = ""; + info->moduleName = "entry"; + + auto ret = process->Init(info); + EXPECT_FALSE(ret); +} + +/** + * @tc.number: JsChildProcessOnStart_0100 + * @tc.desc: Test JsChildProcess OnStart works + * @tc.type: FUNC + */ +HWTEST_F(JsChildProcessTest, JsChildProcessOnStart_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "JsChildProcessOnStart_0100 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 = "./ets/process/AProcess.ts"; + info->moduleName = "entry"; + + process->Init(info); + process->OnStart(); + EXPECT_TRUE(process->processStartInfo_ != nullptr); +} } // namespace AbilityRuntime } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/data_ability_manager_test/BUILD.gn b/test/unittest/data_ability_manager_test/BUILD.gn index d60cbd318f..7c82c5cbe5 100644 --- a/test/unittest/data_ability_manager_test/BUILD.gn +++ b/test/unittest/data_ability_manager_test/BUILD.gn @@ -36,6 +36,9 @@ ohos_unittest("data_ability_manager_test") { "${ability_runtime_services_path}/abilitymgr/src/ability_manager_event_subscriber.cpp", "${ability_runtime_services_path}/abilitymgr/src/app_scheduler.cpp", "${ability_runtime_services_path}/abilitymgr/src/extension_config.cpp", + "${ability_runtime_services_path}/abilitymgr/src/rdb/ability_resident_process_rdb.cpp", + "${ability_runtime_services_path}/abilitymgr/src/rdb/parser_util.cpp", + "${ability_runtime_services_path}/abilitymgr/src/rdb/rdb_data_manager.cpp", "data_ability_manager_test.cpp", # add mock file ] @@ -69,6 +72,7 @@ ohos_unittest("data_ability_manager_test") { "access_token:libtokenid_sdk", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", "ffrt:libffrt", "hilog:libhilog", "hitrace:hitrace_meter", 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 9d8dfa546b..659dfa4584 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 @@ -156,5 +156,21 @@ HWTEST_F(ExtensionManagerClientTest, ExtensionManagerClientTest_009, TestSize.Le auto result = client->DisconnectAbility(connect); EXPECT_TRUE(result != ERR_OK); } + +/* + * Feature: ExtensionManagerClient + * Function: ConnectEnterpriseAdminExtensionAbility + */ +HWTEST_F(ExtensionManagerClientTest, ExtensionManagerClientTest_010, TestSize.Level1) +{ + auto client = std::make_shared(); + + Want want; + sptr connect; + sptr callerToken; + int32_t userId = 1; + auto result = client->ConnectEnterpriseAdminExtensionAbility(want, connect, callerToken, userId); + EXPECT_TRUE(result != ERR_OK); +} } } \ No newline at end of file diff --git a/test/unittest/file_path_utils_test/file_path_utils_test.cpp b/test/unittest/file_path_utils_test/file_path_utils_test.cpp index 149c2327cb..5ec7d692cd 100644 --- a/test/unittest/file_path_utils_test/file_path_utils_test.cpp +++ b/test/unittest/file_path_utils_test/file_path_utils_test.cpp @@ -389,6 +389,20 @@ HWTEST_F(FilePathUtilsTest, FindNpmPackageInTopLevel_0100, TestSize.Level0) EXPECT_EQ(newJsModulePath, std::string()); } +/** + * @tc.name: FindNpmPackage_0100 + * @tc.desc: FindNpmPackage Test + * @tc.type: FUNC + * @tc.require: issueI581SE + */ +HWTEST_F(FilePathUtilsTest, FindNpmPackage_0100, TestSize.Level0) +{ + const std::string& curJsModulePath = ""; + const std::string& npmPackage = ""; + std::string newJsModulePath = FindNpmPackage(curJsModulePath, npmPackage); + EXPECT_EQ(newJsModulePath, std::string()); +} + /** * @tc.name: ParseOhmUri_0100 * @tc.desc: ParseOhmUri Test diff --git a/test/unittest/frameworks_kits_ability_native_test/BUILD.gn b/test/unittest/frameworks_kits_ability_native_test/BUILD.gn index 0011ac21fa..8a7c92bceb 100644 --- a/test/unittest/frameworks_kits_ability_native_test/BUILD.gn +++ b/test/unittest/frameworks_kits_ability_native_test/BUILD.gn @@ -773,6 +773,78 @@ ohos_unittest("ability_thread_test") { } } +ohos_unittest("fa_ability_thread_test") { + module_out_path = module_output_path + + include_dirs = [ + "${ability_runtime_test_path}/unittest/dataobs_mgr_stub_test", + "${ability_runtime_services_path}/dataobsmgr/include/", + "${ability_runtime_innerkits_path}/dataobs_manager/include/", + ] + + sources = [ + "${ability_runtime_innerkits_path}/app_manager/src/appmgr/process_info.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/context_container.cpp", + "${ability_runtime_native_path}/appkit/app/ohos_application.cpp", + "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include/mock_ability_manager_client.cpp", + "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include/mock_data_ability_impl.cpp", + "${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include/sys_mgr_client_mock.cpp", + "fa_ability_thread_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/dataobs_manager:dataobs_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}/appkit:app_context", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_native_path}/appkit:appkit_native", + "${ability_runtime_services_path}/dataobsmgr:dataobsms_static", + "${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_base:zuri", + "ability_runtime:ability_deps_wrapper", + "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", + "relational_store:native_appdatafwk", + "relational_store:native_dataability", + "relational_store:native_rdb", + "resource_management:global_resmgr", + ] + + if (ability_runtime_graphics) { + external_deps += [ + "ability_base:session_info", + "input:libmmi-client", + "window_manager:libwm", + ] + } +} + ohos_unittest("extension_ability_thread_test") { module_out_path = module_output_path @@ -2669,6 +2741,7 @@ group("unittest") { ":extension_ability_thread_test", ":extension_impl_test", ":extension_test", + ":fa_ability_thread_test", ":form_extension_test", ":new_ability_impl_test", ":pac_map_test", 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 319c4f42b7..fa9c1efe46 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 @@ -2318,579 +2318,5 @@ HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_DumpAbilityInfoInner_0100, Funct abilitythread->DumpAbilityInfoInner(params, info); GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpAbilityInfoInner_0100 end"; } - -/** - * @tc.number: AaFwk_AbilityThread_DumpAbilityInfoInner_0200 - * @tc.name: DumpAbilityInfoInner - * @tc.desc: Test DumpAbilityInfoInner function when currentAbility_ is nullptr - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_DumpAbilityInfoInner_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpAbilityInfoInner_0200 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::vector params; - std::vector info; - - EXPECT_EQ(abilitythread->currentAbility_, nullptr); - abilitythread->currentExtension_ = std::make_shared(); - EXPECT_NE(abilitythread->currentExtension_, nullptr); - abilitythread->DumpAbilityInfoInner(params, info); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpAbilityInfoInner_0200 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_DumpAbilityInfoInner_0300 - * @tc.name: DumpAbilityInfoInner - * @tc.desc: Test DumpAbilityInfoInner function when currentExtension_ is nullptr - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_DumpAbilityInfoInner_0300, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpAbilityInfoInner_0300 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::vector params; - std::vector info; - - abilitythread->currentAbility_ = std::make_shared(); - EXPECT_NE(abilitythread->currentAbility_, nullptr); - abilitythread->abilityImpl_ = std::make_shared(); - EXPECT_NE(abilitythread->abilityImpl_, nullptr); - EXPECT_EQ(abilitythread->currentExtension_, nullptr); - abilitythread->DumpAbilityInfoInner(params, info); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpAbilityInfoInner_0300 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_DumpOtherInfo_0100 - * @tc.name: DumpOtherInfo - * @tc.desc: Test DumpOtherInfo function when abilityHandler_ and currentAbility_ is not nullptr - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_DumpOtherInfo_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpOtherInfo_0100 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - abilitythread->abilityHandler_ = std::make_shared(nullptr); - EXPECT_NE(abilitythread->abilityHandler_, nullptr); - auto abilityInfo = std::make_shared(); - abilityInfo->name = "MockPageAbility"; - abilityInfo->type = AbilityType::PAGE; - auto setRunner = EventRunner::Create(abilityInfo->name); - abilitythread->abilityHandler_->SetEventRunner(setRunner); - auto getRunner = abilitythread->abilityHandler_->GetEventRunner(); - EXPECT_NE(getRunner, nullptr); - - std::vector info; - abilitythread->currentAbility_ = std::make_shared(); - EXPECT_NE(abilitythread->currentAbility_, nullptr); - abilitythread->DumpOtherInfo(info); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpOtherInfo_0100 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_DumpOtherInfo_0200 - * @tc.name: DumpOtherInfo - * @tc.desc: Test DumpOtherInfo function when abilityHandler_ is nullptr - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_DumpOtherInfo_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpOtherInfo_0200 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::vector info; - EXPECT_EQ(abilitythread->abilityHandler_, nullptr); - abilitythread->DumpOtherInfo(info); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpOtherInfo_0200 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_DumpOtherInfo_0300 - * @tc.name: DumpOtherInfo - * @tc.desc: Test DumpOtherInfo function when currentAbility_ is nullptr - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_DumpOtherInfo_0300, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpOtherInfo_0300 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::vector info; - abilitythread->abilityHandler_ = std::make_shared(nullptr); - EXPECT_NE(abilitythread->abilityHandler_, nullptr); - EXPECT_EQ(abilitythread->currentAbility_, nullptr); - abilitythread->DumpOtherInfo(info); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpOtherInfo_0300 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_CallRequest_0100 - * @tc.name: CallRequest - * @tc.desc: Test CallRequest function when abilityHandler_ and currentAbility_ is not nullptr - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_CallRequest_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0100 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::vector info; - abilitythread->abilityHandler_ = std::make_shared(nullptr); - EXPECT_NE(abilitythread->abilityHandler_, nullptr); - abilitythread->currentAbility_ = std::make_shared(); - EXPECT_NE(abilitythread->currentAbility_, nullptr); - abilitythread->CallRequest(); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0100 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_CallRequest_0200 - * @tc.name: CallRequest - * @tc.desc: Test CallRequest function when abilityHandler_ and currentAbility_ is not nullptr - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_CallRequest_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0200 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::vector info; - EXPECT_EQ(abilitythread->abilityHandler_, nullptr); - EXPECT_EQ(abilitythread->currentAbility_, nullptr); - abilitythread->CallRequest(); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0200 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_CreateAbilityName_0100 - * @tc.name: CreateAbilityName - * @tc.desc: Test CreateAbilityName function when parameters are application and abilityRecord - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_CreateAbilityName_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAbilityName_0100 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->name = "MockPageAbility"; - abilityInfo->type = AbilityType::PAGE; - sptr token = sptr(new (std::nothrow) MockAbilityToken()); - std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); - - std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, nullptr); - EXPECT_EQ(abilityName, ""); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAbilityName_0100 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_CreateAbilityName_0200 - * @tc.name: CreateAbilityName - * @tc.desc: Test CreateAbilityName function when parameters are application and abilityRecord - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_CreateAbilityName_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAbilityName_0200 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::shared_ptr application = std::make_shared(); - std::string abilityName = abilitythread->CreateAbilityName(nullptr, application); - EXPECT_EQ(abilityName, ""); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAbilityName_0200 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_CreateExtensionAbilityName_0101 - * @tc.name: CreateExtensionAbilityName - * @tc.desc: Test CreateExtensionAbilityName function when parameters are application and abilityRecord - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_CreateExtensionAbilityName_0101, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateExtensionAbilityName_0101 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::shared_ptr application = std::make_shared(); - std::shared_ptr abilityInfo = std::make_shared(); - std::string abilityName = "MockPageAbility"; - abilitythread->CreateExtensionAbilityName(application, abilityInfo, abilityName); - sptr token = sptr(new (std::nothrow) MockAbilityToken()); - std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); - std::string ret = abilitythread->CreateAbilityName(abilityRecord, application); - EXPECT_EQ(abilityName, "MockPageAbility"); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateExtensionAbilityName_0101 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_CreateExtensionAbilityName_0200 - * @tc.name: CreateExtensionAbilityName - * @tc.desc: Test CreateExtensionAbilityName function when parameters are application and abilityRecord - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_CreateExtensionAbilityName_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateExtensionAbilityName_0200 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - AppExecFwk::ExtensionAbilityInfo extensionInfo; - extensionInfo.type = AppExecFwk::ExtensionAbilityType::STATICSUBSCRIBER; - std::shared_ptr application = std::make_shared(); - std::shared_ptr abilityInfo = std::make_shared(); - std::string abilityName = ""; - abilitythread->CreateExtensionAbilityName(application, abilityInfo, abilityName); - sptr token = sptr(new (std::nothrow) MockAbilityToken()); - std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); - std::string ret = abilitythread->CreateAbilityName(abilityRecord, application); - EXPECT_EQ(abilityName, "ServiceExtension"); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateExtensionAbilityName_0200 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_AttachExtension_0300 - * @tc.name: AttachExtension - * @tc.desc: Test AttachExtension function when application is null - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0300, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AttachExtension_0300 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->name = "MockPageAbility"; - abilityInfo->type = AbilityType::PAGE; - sptr token = sptr(new (std::nothrow) MockAbilityToken()); - std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); - - std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); - - std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, nullptr); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); - EXPECT_EQ(extension, nullptr); - - abilitythread->AttachExtension(nullptr, abilityRecord, mainRunner); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AttachExtension_0300 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_AttachExtension_0400 - * @tc.name: AttachExtension - * @tc.desc: Test AttachExtension function when abilityRecord is null - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0400, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AttachExtension_0400 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::shared_ptr application = std::make_shared(); - - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->name = "MockPageAbility"; - std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); - - std::string abilityName = abilitythread->CreateAbilityName(nullptr, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); - EXPECT_EQ(extension, nullptr); - - abilitythread->AttachExtension(application, nullptr, mainRunner); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AttachExtension_0400 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_AttachExtension_0500 - * @tc.name: AttachExtension - * @tc.desc: Test AttachExtension function when mainRunner is null - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0500, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AttachExtension_0500 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::shared_ptr application = std::make_shared(); - - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->name = "MockPageAbility"; - abilityInfo->type = AbilityType::PAGE; - sptr token = sptr(new (std::nothrow) MockAbilityToken()); - std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); - - std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); - EXPECT_EQ(extension, nullptr); - - abilitythread->AttachExtension(application, abilityRecord, nullptr); - EXPECT_EQ(abilitythread->abilityHandler_, nullptr); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AttachExtension_0500 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_CreateAndInitContextDeal_0500 - * @tc.name: CreateAndInitContextDeal - * @tc.desc: Test CreateAndInitContextDeal function when application is null - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_CreateAndInitContextDeal_0500, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAndInitContextDeal_0500 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::shared_ptr application = std::make_shared(); - - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->name = "MockPageAbility"; - abilityInfo->type = AbilityType::PAGE; - sptr token = sptr(new (std::nothrow) MockAbilityToken()); - std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); - - std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); - EXPECT_EQ(extension, nullptr); - - auto ret = abilitythread->CreateAndInitContextDeal(application, abilityRecord, nullptr); - EXPECT_EQ(ret, nullptr); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAndInitContextDeal_0500 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_CreateAndInitContextDeal_0600 - * @tc.name: CreateAndInitContextDeal - * @tc.desc: Test CreateAndInitContextDeal function when application is null - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_CreateAndInitContextDeal_0600, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAndInitContextDeal_0600 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->name = "MockPageAbility"; - abilityInfo->type = AbilityType::PAGE; - sptr token = sptr(new (std::nothrow) MockAbilityToken()); - std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); - - std::shared_ptr abilityObject = std::make_shared(); - std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, nullptr); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); - EXPECT_EQ(extension, nullptr); - - auto ret = abilitythread->CreateAndInitContextDeal(nullptr, abilityRecord, abilityObject); - EXPECT_EQ(ret, nullptr); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAndInitContextDeal_0600 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_InitExtensionFlag_0200 - * @tc.name: InitExtensionFlag - * @tc.desc: Test InitExtensionFlag function when isUIAbility_ is true - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_InitExtensionFlag_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_InitExtensionFlag_0200 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::shared_ptr application = std::make_shared(); - - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->name = "MockPageAbility"; - abilityInfo->type = AbilityType::PAGE; - sptr token = sptr(new (std::nothrow) MockAbilityToken()); - std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); - - std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); - EXPECT_EQ(extension, nullptr); - abilitythread->InitExtensionFlag(abilityRecord); - - uint32_t state = AAFwk::ABILITY_STATE_FOREGROUND_NEW; - std::string methodName = "methodName"; - abilitythread->AddLifecycleEvent(state, methodName); - EXPECT_EQ(abilitythread->isUIAbility_, true); - - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_InitExtensionFlag_0200 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_InitExtensionFlag_0300 - * @tc.name: InitExtensionFlag - * @tc.desc: Test InitExtensionFlag function when isUIAbility_ is true - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_InitExtensionFlag_0300, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_InitExtensionFlag_0300 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - std::shared_ptr application = std::make_shared(); - - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->name = "MockPageAbility"; - abilityInfo->type = AbilityType::PAGE; - sptr token = sptr(new (std::nothrow) MockAbilityToken()); - std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); - - std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); - EXPECT_EQ(extension, nullptr); - abilitythread->InitExtensionFlag(abilityRecord); - - uint32_t state = AAFwk::ABILITY_STATE_BACKGROUND_NEW; - std::string methodName = "methodName"; - abilitythread->AddLifecycleEvent(state, methodName); - EXPECT_EQ(abilitythread->isUIAbility_, true); - - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_InitExtensionFlag_0300 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_HandleShareData_0100 - * @tc.name: HandleShareData - * @tc.desc: Test HandleShareData function when abilityImpl_ is null - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_HandleShareData_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleShareData_0100 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - int32_t uniqueId = 1; - abilitythread->HandleShareData(uniqueId); - EXPECT_EQ(abilitythread->abilityImpl_, nullptr); - - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleShareData_0100 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_HandleDisconnectExtension_0100 - * @tc.name: HandleDisconnectExtension - * @tc.desc: Test HandleDisconnectExtension function when extensionImpl_ is null - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_HandleDisconnectExtension_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleDisconnectExtension_0100 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - Want want; - abilitythread->extensionImpl_ = nullptr; - abilitythread->HandleDisconnectExtension(want); - - EXPECT_EQ(abilitythread->token_, nullptr); - int32_t uniqueId = 1; - abilitythread->ScheduleShareData(uniqueId); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleDisconnectExtension_0100 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_HandleDisconnectExtension_0200 - * @tc.name: HandleDisconnectExtension - * @tc.desc: Test HandleDisconnectExtension function when extensionImpl_ is null - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_HandleDisconnectExtension_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleDisconnectExtension_0200 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - Want want; - abilitythread->extensionImpl_ = nullptr; - abilitythread->HandleDisconnectExtension(want); - - abilitythread->token_ = sptr(new (std::nothrow) MockAbilityToken()); - EXPECT_NE(abilitythread->token_, nullptr); - int32_t uniqueId = 1; - EXPECT_EQ(abilitythread->abilityHandler_, nullptr); - abilitythread->ScheduleShareData(uniqueId); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleDisconnectExtension_0200 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_HandleDisconnectExtension_0300 - * @tc.name: HandleDisconnectExtension - * @tc.desc: Test HandleDisconnectExtension function when extensionImpl_ is null - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_HandleDisconnectExtension_0300, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleDisconnectExtension_0300 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - Want want; - abilitythread->extensionImpl_ = nullptr; - abilitythread->HandleDisconnectExtension(want); - - abilitythread->token_ = sptr(new (std::nothrow) MockAbilityToken()); - EXPECT_NE(abilitythread->token_, nullptr); - abilitythread->abilityHandler_ = std::make_shared(nullptr); - EXPECT_NE(abilitythread->abilityHandler_, nullptr); - int32_t uniqueId = 1; - abilitythread->ScheduleShareData(uniqueId); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleDisconnectExtension_0300 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0100 - * @tc.name: SchedulePrepareTerminateAbility - * @tc.desc: Test SchedulePrepareTerminateAbility function when extensionImpl_ is null - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0100 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - abilitythread->abilityImpl_ = nullptr; - bool ret = abilitythread->SchedulePrepareTerminateAbility(); - abilitythread->HandlePrepareTermianteAbility(); - EXPECT_EQ(ret, false); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0100 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0200 - * @tc.name: SchedulePrepareTerminateAbility - * @tc.desc: Test SchedulePrepareTerminateAbility function when extensionImpl_ is null - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0200 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - abilitythread->abilityImpl_ = std::make_shared(); - EXPECT_NE(abilitythread->abilityImpl_, nullptr); - abilitythread->abilityHandler_ = std::make_shared(nullptr); - EXPECT_NE(abilitythread->abilityHandler_, nullptr); - bool ret = abilitythread->SchedulePrepareTerminateAbility(); - EXPECT_EQ(ret, false); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0200 end"; -} - -/** - * @tc.number: AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0300 - * @tc.name: SchedulePrepareTerminateAbility - * @tc.desc: Test SchedulePrepareTerminateAbility function when extensionImpl_ is null - */ -HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0300, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0300 start"; - AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); - EXPECT_NE(abilitythread, nullptr); - - abilitythread->abilityImpl_ = std::make_shared(); - EXPECT_NE(abilitythread->abilityImpl_, nullptr); - abilitythread->abilityHandler_ = nullptr; - bool ret = abilitythread->SchedulePrepareTerminateAbility(); - abilitythread->HandlePrepareTermianteAbility(); - EXPECT_EQ(ret, false); - GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0300 end"; -} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file 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 new file mode 100644 index 0000000000..d262a2155f --- /dev/null +++ b/test/unittest/frameworks_kits_ability_native_test/fa_ability_thread_test.cpp @@ -0,0 +1,649 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#define private public +#define protected public +#include "ability_loader.h" +#include "fa_ability_thread.h" +#undef private +#undef protected +#include "ability.h" +#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" +#include "mock_ability_token.h" +#include "mock_data_ability.h" +#include "mock_data_obs_mgr_stub.h" +#include "mock_page_ability.h" +#include "mock_service_ability.h" +#include "ohos_application.h" +#include "page_ability_impl.h" +#include "uri.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +REGISTER_AA(MockDataAbility) +REGISTER_AA(MockPageAbility) +REGISTER_AA(MockServiceAbility) +static const int32_t STARTID = 0; +static const int32_t ASSERT_NUM = -1; +static const std::string DEVICE_ID = "deviceId"; +static const std::string TEST = "test"; + +class FaAbilityThreadTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() override; + void TearDown() override; +}; + +void FaAbilityThreadTest::SetUpTestCase(void) +{} + +void FaAbilityThreadTest::TearDownTestCase(void) +{} + +void FaAbilityThreadTest::SetUp(void) +{} + +void FaAbilityThreadTest::TearDown(void) +{} + +/** + * @tc.number: AaFwk_AbilityThread_DumpAbilityInfoInner_0200 + * @tc.name: DumpAbilityInfoInner + * @tc.desc: Test DumpAbilityInfoInner function when currentAbility_ is nullptr + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_DumpAbilityInfoInner_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpAbilityInfoInner_0200 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::vector params; + std::vector info; + + EXPECT_EQ(abilitythread->currentAbility_, nullptr); + abilitythread->currentExtension_ = std::make_shared(); + EXPECT_NE(abilitythread->currentExtension_, nullptr); + abilitythread->DumpAbilityInfoInner(params, info); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpAbilityInfoInner_0200 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_DumpAbilityInfoInner_0300 + * @tc.name: DumpAbilityInfoInner + * @tc.desc: Test DumpAbilityInfoInner function when currentExtension_ is nullptr + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_DumpAbilityInfoInner_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpAbilityInfoInner_0300 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::vector params; + std::vector info; + + abilitythread->currentAbility_ = std::make_shared(); + EXPECT_NE(abilitythread->currentAbility_, nullptr); + abilitythread->abilityImpl_ = std::make_shared(); + EXPECT_NE(abilitythread->abilityImpl_, nullptr); + EXPECT_EQ(abilitythread->currentExtension_, nullptr); + abilitythread->DumpAbilityInfoInner(params, info); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpAbilityInfoInner_0300 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_DumpOtherInfo_0100 + * @tc.name: DumpOtherInfo + * @tc.desc: Test DumpOtherInfo function when abilityHandler_ and currentAbility_ is not nullptr + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_DumpOtherInfo_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpOtherInfo_0100 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + abilitythread->abilityHandler_ = std::make_shared(nullptr); + EXPECT_NE(abilitythread->abilityHandler_, nullptr); + auto abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + auto setRunner = EventRunner::Create(abilityInfo->name); + abilitythread->abilityHandler_->SetEventRunner(setRunner); + auto getRunner = abilitythread->abilityHandler_->GetEventRunner(); + EXPECT_NE(getRunner, nullptr); + + std::vector info; + abilitythread->currentAbility_ = std::make_shared(); + EXPECT_NE(abilitythread->currentAbility_, nullptr); + abilitythread->DumpOtherInfo(info); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpOtherInfo_0100 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_DumpOtherInfo_0200 + * @tc.name: DumpOtherInfo + * @tc.desc: Test DumpOtherInfo function when abilityHandler_ is nullptr + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_DumpOtherInfo_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpOtherInfo_0200 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::vector info; + EXPECT_EQ(abilitythread->abilityHandler_, nullptr); + abilitythread->DumpOtherInfo(info); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpOtherInfo_0200 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_DumpOtherInfo_0300 + * @tc.name: DumpOtherInfo + * @tc.desc: Test DumpOtherInfo function when currentAbility_ is nullptr + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_DumpOtherInfo_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpOtherInfo_0300 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::vector info; + abilitythread->abilityHandler_ = std::make_shared(nullptr); + EXPECT_NE(abilitythread->abilityHandler_, nullptr); + EXPECT_EQ(abilitythread->currentAbility_, nullptr); + abilitythread->DumpOtherInfo(info); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_DumpOtherInfo_0300 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_CallRequest_0100 + * @tc.name: CallRequest + * @tc.desc: Test CallRequest function when abilityHandler_ and currentAbility_ is not nullptr + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_CallRequest_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0100 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::vector info; + abilitythread->abilityHandler_ = std::make_shared(nullptr); + EXPECT_NE(abilitythread->abilityHandler_, nullptr); + abilitythread->currentAbility_ = std::make_shared(); + EXPECT_NE(abilitythread->currentAbility_, nullptr); + abilitythread->CallRequest(); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0100 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_CallRequest_0200 + * @tc.name: CallRequest + * @tc.desc: Test CallRequest function when abilityHandler_ and currentAbility_ is not nullptr + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_CallRequest_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0200 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::vector info; + EXPECT_EQ(abilitythread->abilityHandler_, nullptr); + EXPECT_EQ(abilitythread->currentAbility_, nullptr); + abilitythread->CallRequest(); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0200 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_CreateAbilityName_0100 + * @tc.name: CreateAbilityName + * @tc.desc: Test CreateAbilityName function when parameters are application and abilityRecord + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_CreateAbilityName_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAbilityName_0100 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + + std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, nullptr); + EXPECT_EQ(abilityName, ""); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAbilityName_0100 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_CreateAbilityName_0200 + * @tc.name: CreateAbilityName + * @tc.desc: Test CreateAbilityName function when parameters are application and abilityRecord + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_CreateAbilityName_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAbilityName_0200 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::shared_ptr application = std::make_shared(); + std::string abilityName = abilitythread->CreateAbilityName(nullptr, application); + EXPECT_EQ(abilityName, ""); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAbilityName_0200 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_CreateExtensionAbilityName_0101 + * @tc.name: CreateExtensionAbilityName + * @tc.desc: Test CreateExtensionAbilityName function when parameters are application and abilityRecord + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_CreateExtensionAbilityName_0101, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateExtensionAbilityName_0101 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::shared_ptr application = std::make_shared(); + std::shared_ptr abilityInfo = std::make_shared(); + std::string abilityName = "MockPageAbility"; + abilitythread->CreateExtensionAbilityName(application, abilityInfo, abilityName); + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + std::string ret = abilitythread->CreateAbilityName(abilityRecord, application); + EXPECT_EQ(abilityName, "MockPageAbility"); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateExtensionAbilityName_0101 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_CreateExtensionAbilityName_0200 + * @tc.name: CreateExtensionAbilityName + * @tc.desc: Test CreateExtensionAbilityName function when parameters are application and abilityRecord + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_CreateExtensionAbilityName_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateExtensionAbilityName_0200 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + AppExecFwk::ExtensionAbilityInfo extensionInfo; + extensionInfo.type = AppExecFwk::ExtensionAbilityType::STATICSUBSCRIBER; + std::shared_ptr application = std::make_shared(); + std::shared_ptr abilityInfo = std::make_shared(); + std::string abilityName = ""; + abilitythread->CreateExtensionAbilityName(application, abilityInfo, abilityName); + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + std::string ret = abilitythread->CreateAbilityName(abilityRecord, application); + EXPECT_EQ(abilityName, "ServiceExtension"); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateExtensionAbilityName_0200 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_AttachExtension_0300 + * @tc.name: AttachExtension + * @tc.desc: Test AttachExtension function when application is null + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AttachExtension_0300 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + + std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); + + std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, nullptr); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + EXPECT_EQ(extension, nullptr); + + abilitythread->AttachExtension(nullptr, abilityRecord, mainRunner); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AttachExtension_0300 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_AttachExtension_0400 + * @tc.name: AttachExtension + * @tc.desc: Test AttachExtension function when abilityRecord is null + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0400, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AttachExtension_0400 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::shared_ptr application = std::make_shared(); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); + + std::string abilityName = abilitythread->CreateAbilityName(nullptr, application); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + EXPECT_EQ(extension, nullptr); + + abilitythread->AttachExtension(application, nullptr, mainRunner); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AttachExtension_0400 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_AttachExtension_0500 + * @tc.name: AttachExtension + * @tc.desc: Test AttachExtension function when mainRunner is null + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AttachExtension_0500 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::shared_ptr application = std::make_shared(); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + + std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + EXPECT_EQ(extension, nullptr); + + abilitythread->AttachExtension(application, abilityRecord, nullptr); + EXPECT_EQ(abilitythread->abilityHandler_, nullptr); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_AttachExtension_0500 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_CreateAndInitContextDeal_0500 + * @tc.name: CreateAndInitContextDeal + * @tc.desc: Test CreateAndInitContextDeal function when application is null + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_CreateAndInitContextDeal_0500, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAndInitContextDeal_0500 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::shared_ptr application = std::make_shared(); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + + std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + EXPECT_EQ(extension, nullptr); + + auto ret = abilitythread->CreateAndInitContextDeal(application, abilityRecord, nullptr); + EXPECT_EQ(ret, nullptr); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAndInitContextDeal_0500 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_CreateAndInitContextDeal_0600 + * @tc.name: CreateAndInitContextDeal + * @tc.desc: Test CreateAndInitContextDeal function when application is null + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_CreateAndInitContextDeal_0600, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAndInitContextDeal_0600 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + + std::shared_ptr abilityObject = std::make_shared(); + std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, nullptr); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + EXPECT_EQ(extension, nullptr); + + auto ret = abilitythread->CreateAndInitContextDeal(nullptr, abilityRecord, abilityObject); + EXPECT_EQ(ret, nullptr); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CreateAndInitContextDeal_0600 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_InitExtensionFlag_0200 + * @tc.name: InitExtensionFlag + * @tc.desc: Test InitExtensionFlag function when isUIAbility_ is true + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_InitExtensionFlag_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_InitExtensionFlag_0200 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::shared_ptr application = std::make_shared(); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + + std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + EXPECT_EQ(extension, nullptr); + abilitythread->InitExtensionFlag(abilityRecord); + + uint32_t state = AAFwk::ABILITY_STATE_FOREGROUND_NEW; + std::string methodName = "methodName"; + abilitythread->AddLifecycleEvent(state, methodName); + EXPECT_EQ(abilitythread->isUIAbility_, true); + + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_InitExtensionFlag_0200 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_InitExtensionFlag_0300 + * @tc.name: InitExtensionFlag + * @tc.desc: Test InitExtensionFlag function when isUIAbility_ is true + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_InitExtensionFlag_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_InitExtensionFlag_0300 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + std::shared_ptr application = std::make_shared(); + + std::shared_ptr abilityInfo = std::make_shared(); + abilityInfo->name = "MockPageAbility"; + abilityInfo->type = AbilityType::PAGE; + sptr token = sptr(new (std::nothrow) MockAbilityToken()); + std::shared_ptr abilityRecord = std::make_shared(abilityInfo, token); + + std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + EXPECT_EQ(extension, nullptr); + abilitythread->InitExtensionFlag(abilityRecord); + + uint32_t state = AAFwk::ABILITY_STATE_BACKGROUND_NEW; + std::string methodName = "methodName"; + abilitythread->AddLifecycleEvent(state, methodName); + EXPECT_EQ(abilitythread->isUIAbility_, true); + + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_InitExtensionFlag_0300 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_HandleShareData_0100 + * @tc.name: HandleShareData + * @tc.desc: Test HandleShareData function when abilityImpl_ is null + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_HandleShareData_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleShareData_0100 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + int32_t uniqueId = 1; + abilitythread->HandleShareData(uniqueId); + EXPECT_EQ(abilitythread->abilityImpl_, nullptr); + + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleShareData_0100 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_HandleDisconnectExtension_0100 + * @tc.name: HandleDisconnectExtension + * @tc.desc: Test HandleDisconnectExtension function when extensionImpl_ is null + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_HandleDisconnectExtension_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleDisconnectExtension_0100 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + Want want; + abilitythread->extensionImpl_ = nullptr; + abilitythread->HandleDisconnectExtension(want); + + EXPECT_EQ(abilitythread->token_, nullptr); + int32_t uniqueId = 1; + abilitythread->ScheduleShareData(uniqueId); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleDisconnectExtension_0100 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_HandleDisconnectExtension_0200 + * @tc.name: HandleDisconnectExtension + * @tc.desc: Test HandleDisconnectExtension function when extensionImpl_ is null + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_HandleDisconnectExtension_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleDisconnectExtension_0200 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + Want want; + abilitythread->extensionImpl_ = nullptr; + abilitythread->HandleDisconnectExtension(want); + + abilitythread->token_ = sptr(new (std::nothrow) MockAbilityToken()); + EXPECT_NE(abilitythread->token_, nullptr); + int32_t uniqueId = 1; + EXPECT_EQ(abilitythread->abilityHandler_, nullptr); + abilitythread->ScheduleShareData(uniqueId); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleDisconnectExtension_0200 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_HandleDisconnectExtension_0300 + * @tc.name: HandleDisconnectExtension + * @tc.desc: Test HandleDisconnectExtension function when extensionImpl_ is null + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_HandleDisconnectExtension_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleDisconnectExtension_0300 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + Want want; + abilitythread->extensionImpl_ = nullptr; + abilitythread->HandleDisconnectExtension(want); + + abilitythread->token_ = sptr(new (std::nothrow) MockAbilityToken()); + EXPECT_NE(abilitythread->token_, nullptr); + abilitythread->abilityHandler_ = std::make_shared(nullptr); + EXPECT_NE(abilitythread->abilityHandler_, nullptr); + int32_t uniqueId = 1; + abilitythread->ScheduleShareData(uniqueId); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_HandleDisconnectExtension_0300 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0100 + * @tc.name: SchedulePrepareTerminateAbility + * @tc.desc: Test SchedulePrepareTerminateAbility function when extensionImpl_ is null + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0100 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + abilitythread->abilityImpl_ = nullptr; + bool ret = abilitythread->SchedulePrepareTerminateAbility(); + abilitythread->HandlePrepareTermianteAbility(); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0100 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0200 + * @tc.name: SchedulePrepareTerminateAbility + * @tc.desc: Test SchedulePrepareTerminateAbility function when extensionImpl_ is null + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0200, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0200 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + abilitythread->abilityImpl_ = std::make_shared(); + EXPECT_NE(abilitythread->abilityImpl_, nullptr); + abilitythread->abilityHandler_ = std::make_shared(nullptr); + EXPECT_NE(abilitythread->abilityHandler_, nullptr); + bool ret = abilitythread->SchedulePrepareTerminateAbility(); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0200 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0300 + * @tc.name: SchedulePrepareTerminateAbility + * @tc.desc: Test SchedulePrepareTerminateAbility function when extensionImpl_ is null + */ +HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0300, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0300 start"; + AbilityRuntime::FAAbilityThread *abilitythread = new (std::nothrow) AbilityRuntime::FAAbilityThread(); + EXPECT_NE(abilitythread, nullptr); + + abilitythread->abilityImpl_ = std::make_shared(); + EXPECT_NE(abilitythread->abilityImpl_, nullptr); + abilitythread->abilityHandler_ = nullptr; + bool ret = abilitythread->SchedulePrepareTerminateAbility(); + abilitythread->HandlePrepareTermianteAbility(); + EXPECT_EQ(ret, false); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_SchedulePrepareTerminateAbility_0300 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/frameworks_kits_appkit_native_test/context_impl_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/context_impl_test.cpp index bf34a35a8d..9b6757c484 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 @@ -334,6 +334,31 @@ HWTEST_F(ContextImplTest, GetResourceDir_0100, TestSize.Level1) TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); } +HWTEST_F(ContextImplTest, GetResourceDir_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto contextImpl = std::make_shared(); + EXPECT_NE(contextImpl, nullptr); + contextImpl->hapModuleInfo_ = std::make_shared(); + auto resourceDir = contextImpl->GetResourceDir(); + EXPECT_EQ(resourceDir, ""); + + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + +HWTEST_F(ContextImplTest, GetResourceDir_0300, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "%{public}s start.", __func__); + auto contextImpl = std::make_shared(); + EXPECT_NE(contextImpl, nullptr); + contextImpl->hapModuleInfo_ = std::make_shared(); + contextImpl->hapModuleInfo_->moduleName = "moduleName"; + auto resourceDir = contextImpl->GetResourceDir(); + EXPECT_EQ(resourceDir, ""); + + TAG_LOGI(AAFwkTag::TEST, "%{public}s end.", __func__); +} + /** * @tc.name: GetFilesDir_0100 * @tc.desc: Get files directory basic test. @@ -1241,5 +1266,128 @@ HWTEST_F(ContextImplTest, GetGroupDir_0100, TestSize.Level1) res = contextImpl->GetSystemDatabaseDir("", false, systemDatabaseDir); EXPECT_EQ(res, 0); } + +HWTEST_F(ContextImplTest, GetGroupPreferencesDirWithCheck_0100, TestSize.Level1) +{ + auto contextImpl = std::make_shared(); + EXPECT_NE(contextImpl, nullptr); + std::string groupId = "groupIdtest"; + std::string preferencesDir; + contextImpl->GetGroupPreferencesDirWithCheck(groupId, true, preferencesDir); +} + +HWTEST_F(ContextImplTest, CreateModuleContext_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleContext_001 start"; + EXPECT_EQ(contextImpl_->CreateModuleContext("bundleName", "module_name"), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleContext_001 end"; +} + +HWTEST_F(ContextImplTest, CreateModuleContext_003, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleContext_001 start"; + EXPECT_EQ(contextImpl_->CreateModuleContext("", "module_name"), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleContext_001 end"; +} + +HWTEST_F(ContextImplTest, CreateModuleContext_004, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleContext_001 start"; + EXPECT_EQ(contextImpl_->CreateModuleContext("bundleName", ""), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleContext_001 end"; +} + +HWTEST_F(ContextImplTest, CreateModuleContext_005, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleContext_005 start"; + EXPECT_EQ(contextImpl_->CreateModuleContext(contextImpl_->GetBundleName(), "entry"), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleContext_005 end"; +} + +HWTEST_F(ContextImplTest, CreateModuleResourceManager_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleResourceManager_001 start"; + EXPECT_EQ(contextImpl_->CreateModuleResourceManager("", "entry"), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleResourceManager_001 end"; +} + +HWTEST_F(ContextImplTest, CreateModuleResourceManager_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleResourceManager_002 start"; + EXPECT_EQ(contextImpl_->CreateModuleResourceManager("bundleName", ""), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleResourceManager_002 end"; +} + +HWTEST_F(ContextImplTest, CreateModuleResourceManager_003, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleResourceManager_003 start"; + EXPECT_EQ(contextImpl_->CreateModuleResourceManager("bundleName", "entry"), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleResourceManager_003 end"; +} + +HWTEST_F(ContextImplTest, CreateModuleResourceManager_004, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleResourceManager_004 start"; + EXPECT_EQ(contextImpl_->CreateModuleResourceManager(contextImpl_->GetBundleName(), "entry"), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleResourceManager_004 end"; +} + +HWTEST_F(ContextImplTest, GetBundleInfo_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleInfo_001 start"; + std::string bundleName = "bundleName"; + AppExecFwk::BundleInfo bundleInfo; + contextImpl_->GetBundleInfo(bundleName, bundleInfo, false); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleInfo_001 end"; +} + +HWTEST_F(ContextImplTest, GetBundleInfo_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleInfo_002 start"; + AppExecFwk::BundleInfo bundleInfo; + contextImpl_->GetBundleInfo(contextImpl_->GetBundleName(), bundleInfo, false); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleInfo_002 end"; +} + +HWTEST_F(ContextImplTest, GetBundleInfo_003, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleInfo_003 start"; + AppExecFwk::BundleInfo bundleInfo; + bundleInfo.name = contextImpl_->GetBundleName(); + contextImpl_->GetBundleInfo(contextImpl_->GetBundleName(), bundleInfo, false); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleInfo_003 end"; +} + +HWTEST_F(ContextImplTest, CreateBundleContext_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateBundleContext_001 start"; + EXPECT_EQ(contextImpl_->CreateBundleContext(contextImpl_->GetBundleName()), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateBundleContext_001 end"; +} + +HWTEST_F(ContextImplTest, CreateBundleContext_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateBundleContext_002 start"; + auto parentContext = std::make_shared(); + contextImpl_->SetParentContext(parentContext); + EXPECT_EQ(contextImpl_->CreateBundleContext(contextImpl_->GetBundleName()), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateBundleContext_002 end"; +} + +HWTEST_F(ContextImplTest, CreateBundleContext_003, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateBundleContext_003 start"; + auto parentContext = std::make_shared(); + contextImpl_->SetParentContext(parentContext); + EXPECT_EQ(contextImpl_->CreateBundleContext(""), nullptr); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateBundleContext_003 end"; +} + +HWTEST_F(ContextImplTest, SetSupportedProcessCacheSelf_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetSupportedProcessCacheSelf_001 start"; + EXPECT_NE(contextImpl_->SetSupportedProcessCacheSelf(true), 0); + GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetSupportedProcessCacheSelf_001 end"; +} } // namespace AppExecFwk } diff --git a/test/unittest/resident_process_manager_test/resident_process_manager_test.cpp b/test/unittest/resident_process_manager_test/resident_process_manager_test.cpp index 77d29d02c6..48072d8287 100755 --- a/test/unittest/resident_process_manager_test/resident_process_manager_test.cpp +++ b/test/unittest/resident_process_manager_test/resident_process_manager_test.cpp @@ -237,5 +237,40 @@ HWTEST_F(ResidentProcessManagerTest, CheckMainElement_006, TestSize.Level1) EXPECT_FALSE(res); manager.reset(); } + +/* + * Feature: ResidentProcessManager + * Function: SetResidentProcessEnabled + * SubFunction: NA + * FunctionPoints:ResidentProcessManager SetResidentProcessEnabled + * EnvConditions: NA + * CaseDescription: Verify SetResidentProcessEnabled + */ +HWTEST_F(ResidentProcessManagerTest, SetResidentProcessEnable_001, TestSize.Level1) +{ + auto manager = std::make_shared(); + ASSERT_NE(manager, nullptr); + std::string bundleName = "com.example.resident.process"; + std::string callerName; + EXPECT_EQ(manager->SetResidentProcessEnabled(bundleName, callerName, false), INVALID_PARAMETERS_ERR); +} + +/* + * Feature: ResidentProcessManager + * Function: ResidentProcessManager + * SubFunction: NA + * FunctionPoints:ResidentProcessManager ResidentProcessManager + * EnvConditions: NA + * CaseDescription: Verify ResidentProcessManager + */ +HWTEST_F(ResidentProcessManagerTest, SetResidentProcessEnable_002, TestSize.Level1) +{ + auto manager = std::make_shared(); + ASSERT_NE(manager, nullptr); + + std::string bundleName = "com.example.resident.process"; + std::string callerName = "resident.process.manager.test"; + EXPECT_EQ(manager->SetResidentProcessEnabled(bundleName, callerName, false), ERR_NO_RESIDENT_PERMISSION); +} } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/services/ability_util_test/BUILD.gn b/test/unittest/services/ability_util_test/BUILD.gn index a9861f851c..4767444913 100644 --- a/test/unittest/services/ability_util_test/BUILD.gn +++ b/test/unittest/services/ability_util_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022 Huawei Device Co., Ltd. +# Copyright (c) 2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -42,6 +42,7 @@ ohos_unittest("ability_util_test") { "bundle_framework:appexecfwk_base", "common_event_service:cesfwk_innerkits", "hilog:libhilog", + "hitrace:hitrace_meter", ] } diff --git a/test/unittest/start_other_app_interceptor_test/BUILD.gn b/test/unittest/start_other_app_interceptor_test/BUILD.gn index 530d21d715..0de8fc9bdc 100644 --- a/test/unittest/start_other_app_interceptor_test/BUILD.gn +++ b/test/unittest/start_other_app_interceptor_test/BUILD.gn @@ -50,6 +50,7 @@ ohos_unittest("start_other_app_interceptor_test") { "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "c_utils:utils", "eventhandler:libeventhandler", "ffrt:libffrt", diff --git a/test/unittest/start_other_app_interceptor_test/start_other_app_interceptor_test.cpp b/test/unittest/start_other_app_interceptor_test/start_other_app_interceptor_test.cpp index 0a9ef31a64..2d7390e3ca 100644 --- a/test/unittest/start_other_app_interceptor_test/start_other_app_interceptor_test.cpp +++ b/test/unittest/start_other_app_interceptor_test/start_other_app_interceptor_test.cpp @@ -86,6 +86,20 @@ HWTEST_F(StartOtherAppInterceptorTest, GetApplicationInfo_001, TestSize.Level1) EXPECT_FALSE(res); } +/** + * @tc.name: GetApplicationInfo_002 + * @tc.desc: test function GetApplicationInfo when callerToken is nullptr + * @tc.type: FUNC + */ +HWTEST_F(StartOtherAppInterceptorTest, GetApplicationInfo_002, TestSize.Level1) +{ + auto interceptor = std::make_shared(); + AppExecFwk::ApplicationInfo applicationInfo; + sptr callerToken; + bool res = interceptor->GetApplicationInfo(callerToken, applicationInfo); + EXPECT_FALSE(res); +} + /** * @tc.name: CheckAncoShellCall_001 * @tc.desc: test function CheckAncoShellCall when caller is anco shell @@ -207,5 +221,46 @@ HWTEST_F(StartOtherAppInterceptorTest, DoProcess_002, TestSize.Level1) int32_t res = interceptor->DoProcess(param); EXPECT_EQ(res, ERR_OK); } + +/** + * @tc.name: CheckTargetIsSystemApp_001 + * @tc.desc: test function CheckTargetIsSystemApp when applicationInfo is true + * @tc.type: FUNC + */ +HWTEST_F(StartOtherAppInterceptorTest, CheckTargetIsSystemApp_001, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + AppExecFwk::ApplicationInfo applicationInfo; + applicationInfo.isSystemApp = true; + bool res = interceptor->CheckTargetIsSystemApp(applicationInfo); + EXPECT_EQ(res, true); +} + +/** + * @tc.name: CheckTargetIsSystemApp_002 + * @tc.desc: test function CheckTargetIsSystemApp when applicationInfo is false + * @tc.type: FUNC + */ +HWTEST_F(StartOtherAppInterceptorTest, CheckTargetIsSystemApp_002, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + AppExecFwk::ApplicationInfo applicationInfo; + applicationInfo.isSystemApp = false; + bool res = interceptor->CheckTargetIsSystemApp(applicationInfo); + EXPECT_EQ(res, false); +} + +/** + * @tc.name: IsDelegatorCall_001 + * @tc.desc: test function IsDelegatorCall when applicationInfo is true + * @tc.type: FUNC + */ +HWTEST_F(StartOtherAppInterceptorTest, IsDelegatorCall_001, TestSize.Level1) +{ + std::shared_ptr interceptor = std::make_shared(); + Want want; + bool res = interceptor->IsDelegatorCall(want); + EXPECT_EQ(res, false); +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/uri_permission_impl_test/mock/include/mock_my_flag.h b/test/unittest/uri_permission_impl_test/mock/include/mock_my_flag.h index e8d80c0844..1f90b164cd 100644 --- a/test/unittest/uri_permission_impl_test/mock/include/mock_my_flag.h +++ b/test/unittest/uri_permission_impl_test/mock/include/mock_my_flag.h @@ -63,6 +63,7 @@ public: static bool permissionAllMedia_; static bool permissionProxyAuthorization_; static bool permissionAll_; + static bool permissionPrivileged_; static TokenInfoMap tokenInfos; }; 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 452fc6acca..a9d3556cfc 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 @@ -237,6 +237,12 @@ public: return E_OK; } + virtual int32_t MountDfsDocs(int32_t userId, const std::string &relativePath, + const std::string &networkId, const std::string &deviceId) override + { + return E_OK; + } + virtual std::vector CreateShareFile(const std::vector &uriList, uint32_t tokenId, uint32_t flag) override { diff --git a/test/unittest/uri_permission_impl_test/mock/src/mock_my_flag.cpp b/test/unittest/uri_permission_impl_test/mock/src/mock_my_flag.cpp index 6afd60c3e3..9c7e6c081b 100644 --- a/test/unittest/uri_permission_impl_test/mock/src/mock_my_flag.cpp +++ b/test/unittest/uri_permission_impl_test/mock/src/mock_my_flag.cpp @@ -26,6 +26,7 @@ bool MyFlag::permissionWriteAudio_ = false; bool MyFlag::permissionReadAudio_ = false; bool MyFlag::permissionProxyAuthorization_ = false; bool MyFlag::permissionAll_ = false; +bool MyFlag::permissionPrivileged_ = false; TokenInfoMap MyFlag::tokenInfos = {}; } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/uri_permission_impl_test/mock/src/mock_permission_verification.cpp b/test/unittest/uri_permission_impl_test/mock/src/mock_permission_verification.cpp index 25174ab60a..a10c1a030a 100644 --- a/test/unittest/uri_permission_impl_test/mock/src/mock_permission_verification.cpp +++ b/test/unittest/uri_permission_impl_test/mock/src/mock_permission_verification.cpp @@ -24,6 +24,7 @@ constexpr const char* PERMISSION_READ_IMAGEVIDEO = "ohos.permission.READ_IMAGEVI constexpr const char* PERMISSION_WRITE_AUDIO = "ohos.permission.WRITE_AUDIO"; constexpr const char* PERMISSION_READ_AUDIO = "ohos.permission.READ_AUDIO"; constexpr const char* PERMISSION_PROXY_AUTHORIZATION_URI = "ohos.permission.PROXY_AUTHORIZATION_URI"; +constexpr const char* PERMISSION_GRANT_URI_PERMISSION_PRIVILEGED = "ohos.permission.GRANT_URI_PERMISSION_PRIVILEGED"; } // namespace bool PermissionVerification::VerifyPermissionByTokenId(const int &tokenId, const std::string &permissionName) const @@ -49,6 +50,9 @@ bool PermissionVerification::VerifyPermissionByTokenId(const int &tokenId, const if (permissionName == PERMISSION_PROXY_AUTHORIZATION_URI) { return MyFlag::permissionProxyAuthorization_; } + if (permissionName == PERMISSION_GRANT_URI_PERMISSION_PRIVILEGED) { + return MyFlag::permissionPrivileged_; + } return false; } bool PermissionVerification::VerifyCallingPermission(const std::string &permissionName) const diff --git a/test/unittest/uri_permission_impl_test/uri_permission_impl_test.cpp b/test/unittest/uri_permission_impl_test/uri_permission_impl_test.cpp index 11f9944897..02236b1acb 100755 --- a/test/unittest/uri_permission_impl_test/uri_permission_impl_test.cpp +++ b/test/unittest/uri_permission_impl_test/uri_permission_impl_test.cpp @@ -597,7 +597,7 @@ HWTEST_F(UriPermissionImplTest, Upms_CheckUriPermission_004, TestSize.Level1) * Feature: UriPermissionManagerStubImpl * Function: RevokeAllUriPermission * SubFunction: NA - * FunctionPoints: RevokeAllUriPermission not called by SA or SystemApp. + * FunctionPoints: RevokeAllUriPermission called by SA or SystemApp. */ HWTEST_F(UriPermissionImplTest, RevokeAllUriPermission_001, TestSize.Level1) { @@ -609,5 +609,269 @@ HWTEST_F(UriPermissionImplTest, RevokeAllUriPermission_001, TestSize.Level1) auto ret = upms->RevokeAllUriPermissions(1002); EXPECT_EQ(ret, ERR_OK); } + +/* + * Feature: UriPermissionManagerStubImpl + * Function: RevokeAllUriPermission + * SubFunction: NA + * FunctionPoints: RevokeAllUriPermission not called by SA or SystemApp. +*/ +HWTEST_F(UriPermissionImplTest, RevokeAllUriPermission_002, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + MyFlag::flag_ &= (~MyFlag::IS_SA_CALL); + MyFlag::tokenInfos[1001] = TokenInfo(1001, MyATokenTypeEnum::TOKEN_NATIVE, "tempProcess"); + IPCSkeleton::callerTokenId = 1001; + auto ret = upms->RevokeAllUriPermissions(1002); + EXPECT_EQ(ret, CHECK_PERMISSION_FAILED); +} + +/* + * Feature: UriPermissionManagerStubImpl + * Function: GrantUriPermissionPrivileged + * SubFunction: NA + * FunctionPoints: do not have permission to call GrantUriPermissionPrivileged. +*/ +HWTEST_F(UriPermissionImplTest, GrantUriPermissionPrivileged_001, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + + MyFlag::tokenInfos[1001] = TokenInfo(1001, MyATokenTypeEnum::TOKEN_NATIVE, "tempProcess"); + IPCSkeleton::callerTokenId = 1001; + MyFlag::permissionPrivileged_ = false; + + auto uri1 = Uri("file://com.example.app1001/data/storage/el2/base/haps/entry/files/test_001.txt"); + std::string targetBundleName = "com.example.app1002"; + uint32_t flag = 1; + const std::vector uris = { uri1 }; + auto ret = upms->GrantUriPermissionPrivileged(uris, flag, targetBundleName, 0); + EXPECT_EQ(ret, CHECK_PERMISSION_FAILED); +} + +/* + * Feature: UriPermissionManagerStubImpl + * Function: GrantUriPermissionPrivileged + * SubFunction: NA + * FunctionPoints: flag is 0. +*/ +HWTEST_F(UriPermissionImplTest, GrantUriPermissionPrivileged_002, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + + MyFlag::tokenInfos[1001] = TokenInfo(1001, MyATokenTypeEnum::TOKEN_NATIVE, "foundation"); + IPCSkeleton::callerTokenId = 1001; + MyFlag::permissionPrivileged_ = true; + + auto uri1 = Uri("file://com.example.app1001/data/storage/el2/base/haps/entry/files/test_001.txt"); + std::string targetBundleName = "com.example.app1002"; + uint32_t flag = 0; + const std::vector uris = { uri1 }; + auto ret = upms->GrantUriPermissionPrivileged(uris, flag, targetBundleName, 0); + MyFlag::permissionPrivileged_ = false; + EXPECT_EQ(ret, ERR_CODE_INVALID_URI_FLAG); +} + +/* + * Feature: UriPermissionManagerStubImpl + * Function: GrantUriPermissionPrivileged + * SubFunction: NA + * FunctionPoints: targetBundleName is invalid. +*/ +HWTEST_F(UriPermissionImplTest, GrantUriPermissionPrivileged_003, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + + MyFlag::tokenInfos[1001] = TokenInfo(1001, MyATokenTypeEnum::TOKEN_NATIVE, "foundation"); + IPCSkeleton::callerTokenId = 1001; + MyFlag::permissionPrivileged_ = true; + + auto uri1 = Uri("file://com.example.app1001/data/storage/el2/base/haps/entry/files/test_001.txt"); + std::string targetBundleName = "com.example.invalid"; + uint32_t flag = 1; + const std::vector uris = { uri1 }; + auto ret = upms->GrantUriPermissionPrivileged(uris, flag, targetBundleName, 0); + MyFlag::permissionPrivileged_ = false; + EXPECT_EQ(ret, GET_BUNDLE_INFO_FAILED); +} + +/* + * Feature: UriPermissionManagerStubImpl + * Function: GrantUriPermissionPrivileged + * SubFunction: NA + * FunctionPoints: type of uri is invalid. +*/ +HWTEST_F(UriPermissionImplTest, GrantUriPermissionPrivileged_004, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + + MyFlag::tokenInfos[1001] = TokenInfo(1001, MyATokenTypeEnum::TOKEN_NATIVE, "foundation"); + IPCSkeleton::callerTokenId = 1001; + MyFlag::permissionPrivileged_ = true; + + auto uri1 = Uri("http://com.example.app1001/data/storage/el2/base/haps/entry/files/test_001.txt"); + std::string targetBundleName = "com.example.app1002"; + uint32_t flag = 1; + const std::vector uris = { uri1 }; + auto ret = upms->GrantUriPermissionPrivileged(uris, flag, targetBundleName, 0); + MyFlag::permissionPrivileged_ = false; + EXPECT_EQ(ret, ERR_CODE_INVALID_URI_TYPE); +} + +/* + * Feature: UriPermissionManagerStubImpl + * Function: GrantUriPermissionPrivileged + * SubFunction: NA + * FunctionPoints: Create Share File failed. +*/ +HWTEST_F(UriPermissionImplTest, GrantUriPermissionPrivileged_005, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + + MyFlag::tokenInfos[1001] = TokenInfo(1001, MyATokenTypeEnum::TOKEN_NATIVE, "foundation"); + IPCSkeleton::callerTokenId = 1001; + MyFlag::permissionPrivileged_ = true; + + auto uri1 = Uri("file://com.example.app1001/data/storage/el2/base/haps/entry/files/test_001.txt"); + std::string targetBundleName = "com.example.app1002"; + uint32_t flag = 1; + const std::vector uris = { uri1 }; + upms->storageManager_ = new StorageManager::StorageManagerServiceMock(); + StorageManager::StorageManagerServiceMock::isZero = false; + auto ret = upms->GrantUriPermissionPrivileged(uris, flag, targetBundleName, 0); + MyFlag::permissionPrivileged_ = false; + EXPECT_EQ(ret, INNER_ERR); +} + +/* + * Feature: UriPermissionManagerStubImpl + * Function: GrantUriPermissionPrivileged + * SubFunction: NA + * FunctionPoints: Grant Uri permission success. +*/ +HWTEST_F(UriPermissionImplTest, GrantUriPermissionPrivileged_006, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + + MyFlag::tokenInfos[1001] = TokenInfo(1001, MyATokenTypeEnum::TOKEN_NATIVE, "foundation"); + IPCSkeleton::callerTokenId = 1001; + MyFlag::permissionPrivileged_ = true; + + auto uri1 = Uri("file://com.example.app1001/data/storage/el2/base/haps/entry/files/test_001.txt"); + std::string targetBundleName = "com.example.app1002"; + uint32_t flag = 1; + const std::vector uris = { uri1 }; + upms->storageManager_ = new StorageManager::StorageManagerServiceMock(); + StorageManager::StorageManagerServiceMock::isZero = true; + auto ret = upms->GrantUriPermissionPrivileged(uris, flag, targetBundleName, 0); + MyFlag::permissionPrivileged_ = false; + EXPECT_EQ(ret, ERR_OK); +} + +/* + * Feature: UriPermissionManagerStubImpl + * Function: CheckUriAuthorization + * SubFunction: NA + * FunctionPoints: CheckUriAuthorization not called by SA or SystemApp. +*/ +HWTEST_F(UriPermissionImplTest, CheckUriAuthorization_001, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + MyFlag::flag_ &= (~MyFlag::IS_SA_CALL); + std::string uri = "file://com.example.app1001/data/storage/el2/base/haps/entry/files/test_001.txt"; + const std::vector uris = { uri }; + uint32_t flag = 1; + uint32_t tokenId = 1001; + auto res = upms->CheckUriAuthorization(uris, flag, tokenId); + std::vector expectRes(1, false); + EXPECT_EQ(res, expectRes); +} + +/* + * Feature: UriPermissionManagerStubImpl + * Function: CheckUriAuthorization + * SubFunction: NA + * FunctionPoints: flag is 0. +*/ +HWTEST_F(UriPermissionImplTest, CheckUriAuthorization_002, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + MyFlag::flag_ |= MyFlag::IS_SA_CALL; + std::string uri = "file://com.example.app1001/data/storage/el2/base/haps/entry/files/test_001.txt"; + const std::vector uris = { uri }; + uint32_t flag = 0; + uint32_t tokenId = 1001; + auto res = upms->CheckUriAuthorization(uris, flag, tokenId); + std::vector expectRes(1, false); + EXPECT_EQ(res, expectRes); +} + +/* + * Feature: UriPermissionManagerStubImpl + * Function: CheckUriAuthorization + * SubFunction: NA + * FunctionPoints: uri is invalid. +*/ +HWTEST_F(UriPermissionImplTest, CheckUriAuthorization_003, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + MyFlag::flag_ |= MyFlag::IS_SA_CALL; + std::string uri = "http://com.example.app1001/data/storage/el2/base/haps/entry/files/test_001.txt"; + const std::vector uris = { uri }; + uint32_t flag = 1; + uint32_t tokenId = 1001; + auto res = upms->CheckUriAuthorization(uris, flag, tokenId); + std::vector expectRes(1, false); + EXPECT_EQ(res, expectRes); +} + +/* + * Feature: UriPermissionManagerStubImpl + * Function: CheckUriAuthorization + * SubFunction: NA + * FunctionPoints: check uri authorization failed, have no permission. +*/ +HWTEST_F(UriPermissionImplTest, CheckUriAuthorization_004, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + MyFlag::flag_ |= MyFlag::IS_SA_CALL; + std::string uri = "file://com.example.app1001/data/storage/el2/base/haps/entry/files/test_001.txt"; + const std::vector uris = { uri }; + uint32_t flag = 1; + uint32_t tokenId = 1002; + auto res = upms->CheckUriAuthorization(uris, flag, tokenId); + std::vector expectRes(1, false); + EXPECT_EQ(res, expectRes); +} + +/* + * Feature: UriPermissionManagerStubImpl + * Function: CheckUriAuthorization + * SubFunction: NA + * FunctionPoints: check uri authorization success. +*/ +HWTEST_F(UriPermissionImplTest, CheckUriAuthorization_005, TestSize.Level1) +{ + auto upms = std::make_unique(); + ASSERT_NE(upms, nullptr); + MyFlag::flag_ |= MyFlag::IS_SA_CALL; + std::string uri = "file://com.example.app1001/data/storage/el2/base/haps/entry/files/test_001.txt"; + const std::vector uris = { uri }; + uint32_t flag = 1; + uint32_t tokenId = 1001; + auto res = upms->CheckUriAuthorization(uris, flag, tokenId); + std::vector expectRes(1, true); + EXPECT_EQ(res, expectRes); +} } // namespace AAFwk } // namespace OHOS diff --git a/tools/aa/include/ability_command.h b/tools/aa/include/ability_command.h index 64905ad22b..e5818f9d6a 100644 --- a/tools/aa/include/ability_command.h +++ b/tools/aa/include/ability_command.h @@ -70,7 +70,7 @@ const std::string HELP_MSG_START = "usage: aa start \n" "options list:\n" " -h, --help list available commands\n" - " [-d ] [-a -b ] [-m ] [-D] [-S] " + " [-d ] [-a -b ] [-m ] [-p ] [-D] [-S] [-N] [-R]" " [--ps ] " " [--pi ] " " [--pb ] " diff --git a/tools/aa/src/ability_command.cpp b/tools/aa/src/ability_command.cpp index d050d25642..ade10c056d 100644 --- a/tools/aa/src/ability_command.cpp +++ b/tools/aa/src/ability_command.cpp @@ -47,7 +47,7 @@ constexpr int OPTION_PARAMETER_NULL_STRING = 260; 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:CDSN"; +const std::string SHORT_OPTIONS = "ch:d:a:b:e:t:p:s:m:A:U:CDSNR"; constexpr struct option LONG_OPTIONS[] = { {"help", no_argument, nullptr, 'h'}, {"device", required_argument, nullptr, 'd'}, @@ -59,6 +59,7 @@ constexpr struct option LONG_OPTIONS[] = { {"cold-start", no_argument, nullptr, 'C'}, {"debug", no_argument, nullptr, 'D'}, {"native-debug", no_argument, nullptr, 'N'}, + {"mutil-thread", no_argument, nullptr, 'R'}, {"action", required_argument, nullptr, 'A'}, {"URI", required_argument, nullptr, 'U'}, {"entity", required_argument, nullptr, 'e'}, @@ -1398,6 +1399,7 @@ ErrCode AbilityManagerShellCommand::MakeWantFromCmd(Want& want, std::string& win bool isContinuation = false; bool isSandboxApp = false; bool isNativeDebug = false; + bool isMultiThread = false; while (true) { counter++; @@ -1796,6 +1798,10 @@ ErrCode AbilityManagerShellCommand::MakeWantFromCmd(Want& want, std::string& win isNativeDebug = true; break; } + case 'R': { + isMultiThread = true; + TAG_LOGD(AAFwkTag::AA_TOOL, "isMultiThread"); + } case 0: { break; } @@ -1858,6 +1864,9 @@ ErrCode AbilityManagerShellCommand::MakeWantFromCmd(Want& want, std::string& win if (!typeVal.empty()) { want.SetType(typeVal); } + if (isMultiThread) { + want.SetParam("multiThread", isMultiThread); + } } }