• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "context_impl.h"
17 
18 #include <cerrno>
19 #include <regex>
20 
21 #include "ability_manager_client.h"
22 #include "app_mgr_client.h"
23 #include "application_context.h"
24 #include "bundle_mgr_helper.h"
25 #include "bundle_mgr_proxy.h"
26 #include "common_event_manager.h"
27 #include "configuration_convertor.h"
28 #include "constants.h"
29 #include "directory_ex.h"
30 #include "file_ex.h"
31 #include "hilog_tag_wrapper.h"
32 #include "hitrace_meter.h"
33 #include "ipc_object_proxy.h"
34 #include "ipc_singleton.h"
35 #include "js_runtime_utils.h"
36 #ifdef SUPPORT_SCREEN
37 #include "locale_config.h"
38 #endif
39 #include "os_account_manager_wrapper.h"
40 #include "overlay_event_subscriber.h"
41 #include "overlay_module_info.h"
42 #include "parameters.h"
43 #include "running_process_info.h"
44 #include "sys_mgr_client.h"
45 #include "system_ability_definition.h"
46 
47 namespace OHOS {
48 namespace AbilityRuntime {
49 #ifdef SUPPORT_GRAPHICS
50 std::mutex ContextImpl::getDisplayConfigCallbackMutex_;
51 GetDisplayConfigCallback ContextImpl::getDisplayConfigCallback_ = nullptr;
52 #endif
53 using namespace OHOS::AbilityBase::Constants;
54 
55 const std::string PATTERN_VERSION = std::string(FILE_SEPARATOR) + "v\\d+" + FILE_SEPARATOR;
56 
57 const size_t Context::CONTEXT_TYPE_ID(std::hash<const char*> {} ("Context"));
58 const int64_t ContextImpl::CONTEXT_CREATE_BY_SYSTEM_APP(0x00000001);
59 const mode_t MODE = 0770;
60 const mode_t GROUP_MODE = 02770;
61 const std::string ContextImpl::CONTEXT_DATA_APP("/data/app/");
62 const std::string ContextImpl::CONTEXT_BUNDLE("/bundle/");
63 const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE("/mnt/hmdfs/");
64 const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE("/device_view/local/data/");
65 const std::string ContextImpl::CONTEXT_DISTRIBUTEDFILES("distributedfiles");
66 const std::string ContextImpl::CONTEXT_CLOUDFILE("cloud");
67 const std::string ContextImpl::CONTEXT_FILE_SEPARATOR("/");
68 const std::string ContextImpl::CONTEXT_DATA("/data/");
69 const std::string ContextImpl::CONTEXT_DATA_STORAGE("/data/storage/");
70 const std::string ContextImpl::CONTEXT_BASE("base");
71 const std::string ContextImpl::CONTEXT_CACHE("cache");
72 const std::string ContextImpl::CONTEXT_PREFERENCES("preferences");
73 const std::string ContextImpl::CONTEXT_GROUP("group");
74 const std::string ContextImpl::CONTEXT_DATABASE("database");
75 const std::string ContextImpl::CONTEXT_TEMP("/temp");
76 const std::string ContextImpl::CONTEXT_FILES("/files");
77 const std::string ContextImpl::CONTEXT_HAPS("/haps");
78 const std::string ContextImpl::CONTEXT_ELS[] = {"el1", "el2", "el3", "el4", "el5"};
79 const std::string ContextImpl::CONTEXT_RESOURCE_END = "/resources/resfile";
80 Global::Resource::DeviceType ContextImpl::deviceType_ = Global::Resource::DeviceType::DEVICE_NOT_SET;
81 const std::string OVERLAY_STATE_CHANGED = "usual.event.OVERLAY_STATE_CHANGED";
82 const int32_t TYPE_RESERVE = 1;
83 const int32_t TYPE_OTHERS = 2;
84 const int32_t API11 = 11;
85 const int32_t API_VERSION_MOD = 100;
86 const int32_t ERR_ABILITY_RUNTIME_EXTERNAL_NOT_SYSTEM_HSP = 16400001;
87 const int AREA2 = 2;
88 const int AREA3 = 3;
89 const int AREA4 = 4;
90 
~ContextImpl()91 ContextImpl::~ContextImpl()
92 {
93     UnsubscribeToOverlayEvents();
94 }
95 
GetBundleName() const96 std::string ContextImpl::GetBundleName() const
97 {
98     if (parentContext_ != nullptr) {
99         return parentContext_->GetBundleName();
100     }
101     return (applicationInfo_ != nullptr) ? applicationInfo_->bundleName : "";
102 }
103 
GetBundleNameWithContext(std::shared_ptr<Context> inputContext) const104 std::string ContextImpl::GetBundleNameWithContext(std::shared_ptr<Context> inputContext) const
105 {
106     if (inputContext) {
107         return inputContext->GetBundleName();
108     }
109     return GetBundleName();
110 }
111 
GetBundleCodeDir()112 std::string ContextImpl::GetBundleCodeDir()
113 {
114     auto appInfo = GetApplicationInfo();
115     if (appInfo == nullptr) {
116         return "";
117     }
118 
119     std::string dir;
120     if (IsCreateBySystemApp()) {
121         dir = std::regex_replace(appInfo->codePath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES);
122     } else {
123         dir = LOCAL_CODE_PATH;
124     }
125     CreateDirIfNotExist(dir, MODE);
126     TAG_LOGD(AAFwkTag::APPKIT, "dir:%{public}s", dir.c_str());
127     return dir;
128 }
129 
GetCacheDir()130 std::string ContextImpl::GetCacheDir()
131 {
132     std::string dir = GetBaseDir() + CONTEXT_FILE_SEPARATOR + CONTEXT_CACHE;
133     CreateDirIfNotExist(dir, MODE);
134     TAG_LOGD(AAFwkTag::APPKIT, "dir:%{public}s", dir.c_str());
135     return dir;
136 }
137 
IsUpdatingConfigurations()138 bool ContextImpl::IsUpdatingConfigurations()
139 {
140     return false;
141 }
142 
PrintDrawnCompleted()143 bool ContextImpl::PrintDrawnCompleted()
144 {
145     return false;
146 }
147 
CreateDirIfNotExistWithCheck(const std::string & dirPath,const mode_t & mode,bool checkExist)148 void ContextImpl::CreateDirIfNotExistWithCheck(const std::string &dirPath, const mode_t &mode, bool checkExist)
149 {
150     if (checkExist) {
151         CreateDirIfNotExist(dirPath, mode);
152         return;
153     }
154     // Check if the dirPath exists on the first call
155     std::lock_guard<std::mutex> lock(checkedDirSetLock_);
156     if (checkedDirSet_.find(dirPath) != checkedDirSet_.end()) {
157         return;
158     }
159     checkedDirSet_.emplace(dirPath);
160     CreateDirIfNotExist(dirPath, mode);
161 }
162 
GetDatabaseDirWithCheck(bool checkExist,std::string & databaseDir)163 int32_t ContextImpl::GetDatabaseDirWithCheck(bool checkExist, std::string &databaseDir)
164 {
165     if (IsCreateBySystemApp()) {
166         databaseDir = CONTEXT_DATA_APP + currArea_ + CONTEXT_FILE_SEPARATOR + std::to_string(GetCurrentAccountId())
167                       + CONTEXT_FILE_SEPARATOR + CONTEXT_DATABASE + CONTEXT_FILE_SEPARATOR + GetBundleName();
168     } else {
169         databaseDir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_FILE_SEPARATOR + CONTEXT_DATABASE;
170     }
171     if (parentContext_ != nullptr) {
172         databaseDir = databaseDir + CONTEXT_FILE_SEPARATOR +
173                       ((GetHapModuleInfo() == nullptr) ? "" : GetHapModuleInfo()->moduleName);
174     }
175     CreateDirIfNotExistWithCheck(databaseDir, 0, checkExist);
176     return ERR_OK;
177 }
178 
GetGroupDatabaseDirWithCheck(const std::string & groupId,bool checkExist,std::string & databaseDir)179 int32_t ContextImpl::GetGroupDatabaseDirWithCheck(const std::string &groupId, bool checkExist, std::string &databaseDir)
180 {
181     int32_t ret = GetGroupDirWithCheck(groupId, checkExist, databaseDir);
182     if (ret != ERR_OK) {
183         return ret;
184     }
185     databaseDir = databaseDir + CONTEXT_FILE_SEPARATOR + CONTEXT_DATABASE;
186     CreateDirIfNotExistWithCheck(databaseDir, GROUP_MODE, checkExist);
187     return ERR_OK;
188 }
189 
GetSystemDatabaseDir(const std::string & groupId,bool checkExist,std::string & databaseDir)190 int32_t ContextImpl::GetSystemDatabaseDir(const std::string &groupId, bool checkExist, std::string &databaseDir)
191 {
192     int32_t ret;
193     if (groupId.empty()) {
194         ret = GetDatabaseDirWithCheck(checkExist, databaseDir);
195     } else {
196         ret = GetGroupDatabaseDirWithCheck(groupId, checkExist, databaseDir);
197     }
198     TAG_LOGD(AAFwkTag::APPKIT, "databaseDir: %{public}s", databaseDir.c_str());
199     return ret;
200 }
201 
GetDatabaseDir()202 std::string ContextImpl::GetDatabaseDir()
203 {
204     std::string dir;
205     GetDatabaseDirWithCheck(true, dir);
206     TAG_LOGD(AAFwkTag::APPKIT, "databaseDir: %{public}s", dir.c_str());
207     return dir;
208 }
209 
GetPreferencesDirWithCheck(bool checkExist,std::string & preferencesDir)210 int32_t ContextImpl::GetPreferencesDirWithCheck(bool checkExist, std::string &preferencesDir)
211 {
212     preferencesDir = GetBaseDir() + CONTEXT_FILE_SEPARATOR + CONTEXT_PREFERENCES;
213     CreateDirIfNotExistWithCheck(preferencesDir, MODE, checkExist);
214     return ERR_OK;
215 }
216 
GetGroupPreferencesDirWithCheck(const std::string & groupId,bool checkExist,std::string & preferencesDir)217 int32_t ContextImpl::GetGroupPreferencesDirWithCheck(const std::string &groupId, bool checkExist,
218     std::string &preferencesDir)
219 {
220     int32_t ret = GetGroupDirWithCheck(groupId, checkExist, preferencesDir);
221     if (ret != ERR_OK) {
222         return ret;
223     }
224     preferencesDir = preferencesDir + CONTEXT_FILE_SEPARATOR + CONTEXT_PREFERENCES;
225     CreateDirIfNotExistWithCheck(preferencesDir, GROUP_MODE, checkExist);
226     return ERR_OK;
227 }
228 
GetSystemPreferencesDir(const std::string & groupId,bool checkExist,std::string & preferencesDir)229 int32_t ContextImpl::GetSystemPreferencesDir(const std::string &groupId, bool checkExist, std::string &preferencesDir)
230 {
231     int32_t ret;
232     if (groupId.empty()) {
233         ret = GetPreferencesDirWithCheck(checkExist, preferencesDir);
234     } else {
235         ret = GetGroupPreferencesDirWithCheck(groupId, checkExist, preferencesDir);
236     }
237     TAG_LOGD(AAFwkTag::APPKIT, "preferencesDir: %{public}s", preferencesDir.c_str());
238     return ret;
239 }
240 
GetPreferencesDir()241 std::string ContextImpl::GetPreferencesDir()
242 {
243     std::string dir;
244     GetPreferencesDirWithCheck(true, dir);
245     TAG_LOGD(AAFwkTag::APPKIT, "preferencesDir: %{public}s", dir.c_str());
246     return dir;
247 }
248 
GetGroupDirWithCheck(const std::string & groupId,bool checkExist,std::string & groupDir)249 int32_t ContextImpl::GetGroupDirWithCheck(const std::string &groupId, bool checkExist, std::string &groupDir)
250 {
251     if (currArea_ == CONTEXT_ELS[0]) {
252         TAG_LOGE(AAFwkTag::APPKIT, "groupDir currently not supports el1 level");
253         return ERR_INVALID_VALUE;
254     }
255     int errCode = GetBundleManager();
256     if (errCode != ERR_OK) {
257         TAG_LOGE(AAFwkTag::APPKIT, "failed, errCode: %{public}d", errCode);
258         return errCode;
259     }
260     std::string groupDirGet;
261     bool ret = bundleMgr_->GetGroupDir(groupId, groupDirGet);
262     if (!ret || groupDirGet.empty()) {
263         TAG_LOGE(AAFwkTag::APPKIT, "getGroupDir failed or groupDirGet empty");
264         return ERR_INVALID_VALUE;
265     }
266     std::string uuid = groupDirGet.substr(groupDirGet.rfind('/'));
267     groupDir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_FILE_SEPARATOR + CONTEXT_GROUP + uuid;
268     CreateDirIfNotExistWithCheck(groupDir, MODE, true);
269     return ERR_OK;
270 }
271 
GetGroupDir(std::string groupId)272 std::string ContextImpl::GetGroupDir(std::string groupId)
273 {
274     std::string dir;
275     GetGroupDirWithCheck(groupId, true, dir);
276     TAG_LOGD(AAFwkTag::APPKIT, "GroupDir:%{public}s", dir.c_str());
277     return dir;
278 }
279 
GetTempDir()280 std::string ContextImpl::GetTempDir()
281 {
282     std::string dir = GetBaseDir() + CONTEXT_TEMP;
283     CreateDirIfNotExist(dir, MODE);
284     TAG_LOGD(AAFwkTag::APPKIT, "dir:%{public}s", dir.c_str());
285     return dir;
286 }
287 
GetResourceDir()288 std::string ContextImpl::GetResourceDir()
289 {
290     std::shared_ptr<AppExecFwk::HapModuleInfo> hapModuleInfoPtr = GetHapModuleInfo();
291     if (hapModuleInfoPtr == nullptr || hapModuleInfoPtr->moduleName.empty()) {
292         return "";
293     }
294     std::string dir = std::string(LOCAL_CODE_PATH) + CONTEXT_FILE_SEPARATOR +
295         hapModuleInfoPtr->moduleName + CONTEXT_RESOURCE_END;
296     if (OHOS::FileExists(dir)) {
297         return dir;
298     }
299     return "";
300 }
301 
GetAllTempDir(std::vector<std::string> & tempPaths)302 void ContextImpl::GetAllTempDir(std::vector<std::string> &tempPaths)
303 {
304     // Application temp dir
305     auto appTemp = GetTempDir();
306     if (OHOS::FileExists(appTemp)) {
307         tempPaths.push_back(appTemp);
308     }
309     // Module dir
310     if (applicationInfo_ == nullptr) {
311         TAG_LOGE(AAFwkTag::APPKIT, "null applicationInfo");
312         return;
313     }
314 
315     std::string baseDir;
316     if (IsCreateBySystemApp()) {
317         baseDir = CONTEXT_DATA_APP + currArea_ + CONTEXT_FILE_SEPARATOR + std::to_string(GetCurrentAccountId()) +
318             CONTEXT_FILE_SEPARATOR + CONTEXT_BASE + CONTEXT_FILE_SEPARATOR + GetBundleName();
319     } else {
320         baseDir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_FILE_SEPARATOR + CONTEXT_BASE;
321     }
322     for (const auto &moudleItem: applicationInfo_->moduleInfos) {
323         auto moudleTemp = baseDir + CONTEXT_HAPS + CONTEXT_FILE_SEPARATOR + moudleItem.moduleName + CONTEXT_TEMP;
324         if (!OHOS::FileExists(moudleTemp)) {
325             TAG_LOGW(AAFwkTag::APPKIT, "module [%{public}s] temp path not exist,path: %{public}s",
326                 moudleItem.moduleName.c_str(), moudleTemp.c_str());
327             continue;
328         }
329         tempPaths.push_back(moudleTemp);
330     }
331 }
332 
GetFilesDir()333 std::string ContextImpl::GetFilesDir()
334 {
335     std::string dir = GetBaseDir() + CONTEXT_FILES;
336     CreateDirIfNotExist(dir, MODE);
337     TAG_LOGD(AAFwkTag::APPKIT, "dir:%{public}s", dir.c_str());
338     return dir;
339 }
340 
GetDistributedFilesDir()341 std::string ContextImpl::GetDistributedFilesDir()
342 {
343     TAG_LOGD(AAFwkTag::APPKIT, "called");
344     std::string dir;
345     if (IsCreateBySystemApp()) {
346         dir = CONTEXT_DISTRIBUTEDFILES_BASE_BEFORE + std::to_string(GetCurrentAccountId()) +
347             CONTEXT_DISTRIBUTEDFILES_BASE_MIDDLE + GetBundleName();
348     } else {
349         if (currArea_ == CONTEXT_ELS[1] || currArea_ == CONTEXT_ELS[AREA2] || currArea_ == CONTEXT_ELS[AREA3] ||
350             currArea_ == CONTEXT_ELS[AREA4]) {
351             // when areamode swith to el3/el4/el5, the distributedfiles dir should be always el2's
352             // distributedfilesdir dir
353             dir = CONTEXT_DATA_STORAGE + CONTEXT_ELS[1] + CONTEXT_FILE_SEPARATOR + CONTEXT_DISTRIBUTEDFILES;
354         } else {
355             dir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_FILE_SEPARATOR + CONTEXT_DISTRIBUTEDFILES;
356         }
357     }
358     CreateDirIfNotExist(dir, 0);
359     TAG_LOGD(AAFwkTag::APPKIT, "dir:%{public}s", dir.c_str());
360     return dir;
361 }
362 
GetCloudFileDir()363 std::string ContextImpl::GetCloudFileDir()
364 {
365     std::string dir = CONTEXT_DATA_STORAGE + CONTEXT_ELS[1] + CONTEXT_FILE_SEPARATOR + CONTEXT_CLOUDFILE;
366     CreateDirIfNotExist(dir, MODE);
367     return dir;
368 }
369 
SwitchArea(int mode)370 void ContextImpl::SwitchArea(int mode)
371 {
372     TAG_LOGD(AAFwkTag::APPKIT, "mode:%{public}d", mode);
373     if (mode < 0 || mode >= (int)(sizeof(CONTEXT_ELS) / sizeof(CONTEXT_ELS[0]))) {
374         TAG_LOGE(AAFwkTag::APPKIT, "mode invalid");
375         return;
376     }
377     currArea_ = CONTEXT_ELS[mode];
378     TAG_LOGD(AAFwkTag::APPKIT, "currArea:%{public}s", currArea_.c_str());
379 }
380 
SetMcc(std::string mcc)381 void ContextImpl::SetMcc(std::string mcc)
382 {
383     TAG_LOGD(AAFwkTag::APPKIT, "mcc:%{public}s", mcc.c_str());
384     if (config_) {
385         config_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_MCC, mcc);
386     }
387 }
388 
SetMnc(std::string mnc)389 void ContextImpl::SetMnc(std::string mnc)
390 {
391     TAG_LOGD(AAFwkTag::APPKIT, "mnc:%{public}s", mnc.c_str());
392     if (config_) {
393         config_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_MNC, mnc);
394     }
395 }
396 
CreateModuleContext(const std::string & moduleName,std::shared_ptr<Context> inputContext)397 std::shared_ptr<Context> ContextImpl::CreateModuleContext(const std::string &moduleName,
398     std::shared_ptr<Context> inputContext)
399 {
400     return CreateModuleContext(GetBundleNameWithContext(inputContext), moduleName, inputContext);
401 }
402 
CreateModuleContext(const std::string & bundleName,const std::string & moduleName,std::shared_ptr<Context> inputContext)403 std::shared_ptr<Context> ContextImpl::CreateModuleContext(const std::string &bundleName, const std::string &moduleName,
404     std::shared_ptr<Context> inputContext)
405 {
406     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
407     if (bundleName.empty() || moduleName.empty()) {
408         return nullptr;
409     }
410 
411     TAG_LOGD(AAFwkTag::APPKIT, "bundleName: %{public}s", bundleName.c_str());
412 
413     AppExecFwk::BundleInfo bundleInfo;
414     GetBundleInfo(bundleName, bundleInfo, inputContext);
415     if (bundleInfo.name.empty() || bundleInfo.applicationInfo.name.empty()) {
416         TAG_LOGE(AAFwkTag::APPKIT, "GetBundleInfo error");
417         ErrCode ret = bundleMgr_->GetDependentBundleInfo(bundleName, bundleInfo,
418             AppExecFwk::GetDependentBundleInfoFlag::GET_ALL_DEPENDENT_BUNDLE_INFO);
419         if (ret != ERR_OK) {
420             TAG_LOGE(AAFwkTag::APPKIT, "GetDependentBundleInfo failed:%{public}d", ret);
421             return nullptr;
422         }
423     }
424 
425     auto appContext = std::make_shared<ContextImpl>();
426     if (bundleInfo.applicationInfo.codePath != std::to_string(TYPE_RESERVE) &&
427         bundleInfo.applicationInfo.codePath != std::to_string(TYPE_OTHERS)) {
428         TAG_LOGD(AAFwkTag::APPKIT, "modulename: %{public}s, bundleName: %{public}s",
429             moduleName.c_str(), bundleName.c_str());
430         auto info = std::find_if(bundleInfo.hapModuleInfos.begin(), bundleInfo.hapModuleInfos.end(),
431             [&moduleName](const AppExecFwk::HapModuleInfo &hapModuleInfo) {
432                 return hapModuleInfo.moduleName == moduleName;
433             });
434         if (info == bundleInfo.hapModuleInfos.end()) {
435             TAG_LOGE(AAFwkTag::APPKIT, "moduleName error");
436             return nullptr;
437         }
438         appContext->InitHapModuleInfo(*info);
439     }
440 
441     appContext->SetConfiguration(config_);
442     appContext->SetProcessName(processName_);
443     bool self = false;
444     if (inputContext) {
445         self = (bundleName == inputContext->GetBundleName());
446     } else {
447         self = bundleName == GetBundleName();
448     }
449     InitResourceManager(bundleInfo, appContext, self, moduleName, inputContext);
450     appContext->SetApplicationInfo(std::make_shared<AppExecFwk::ApplicationInfo>(bundleInfo.applicationInfo));
451     return appContext;
452 }
453 
CreateModuleContext(const std::string & moduleName)454 std::shared_ptr<Context> ContextImpl::CreateModuleContext(const std::string &moduleName)
455 {
456     return CreateModuleContext(GetBundleName(), moduleName, nullptr);
457 }
458 
CreateModuleContext(const std::string & bundleName,const std::string & moduleName)459 std::shared_ptr<Context> ContextImpl::CreateModuleContext(const std::string &bundleName, const std::string &moduleName)
460 {
461     return CreateModuleContext(bundleName, moduleName, nullptr);
462 }
463 
CreateModuleResourceManager(const std::string & bundleName,const std::string & moduleName)464 std::shared_ptr<Global::Resource::ResourceManager> ContextImpl::CreateModuleResourceManager(
465     const std::string &bundleName, const std::string &moduleName)
466 {
467     TAG_LOGD(AAFwkTag::APPKIT, "begin, bundleName: %{public}s, moduleName: %{public}s",
468         bundleName.c_str(), moduleName.c_str());
469     if (bundleName.empty() || moduleName.empty()) {
470         TAG_LOGE(AAFwkTag::APPKIT, "bundleName: %{public}s, moduleName: %{public}s",
471             bundleName.c_str(), moduleName.c_str());
472         return nullptr;
473     }
474 
475     AppExecFwk::BundleInfo bundleInfo;
476     bool currentBundle = false;
477     if (GetBundleInfo(bundleName, bundleInfo, currentBundle) != ERR_OK) {
478         TAG_LOGE(AAFwkTag::APPKIT, "GetBundleInfo failed, bundleName: %{public}s", bundleName.c_str());
479         return nullptr;
480     }
481 
482     if (bundleInfo.applicationInfo.codePath == std::to_string(TYPE_RESERVE) ||
483         bundleInfo.applicationInfo.codePath == std::to_string(TYPE_OTHERS)) {
484         std::shared_ptr<Global::Resource::ResourceManager> resourceManager = InitOthersResourceManagerInner(
485             bundleInfo, currentBundle, moduleName);
486         if (resourceManager == nullptr) {
487             TAG_LOGE(AAFwkTag::APPKIT, "null resourceManager");
488         }
489         return resourceManager;
490     }
491 
492     std::shared_ptr<Global::Resource::ResourceManager> resourceManager = InitResourceManagerInner(
493         bundleInfo, currentBundle, moduleName);
494     if (resourceManager == nullptr) {
495         TAG_LOGE(AAFwkTag::APPKIT, "null resourceManager");
496         return nullptr;
497     }
498     UpdateResConfig(GetResourceManager(), resourceManager);
499     return resourceManager;
500 }
501 
CreateSystemHspModuleResourceManager(const std::string & bundleName,const std::string & moduleName,std::shared_ptr<Global::Resource::ResourceManager> & resourceManager)502 int32_t ContextImpl::CreateSystemHspModuleResourceManager(const std::string &bundleName,
503     const std::string &moduleName, std::shared_ptr<Global::Resource::ResourceManager> &resourceManager)
504 {
505     TAG_LOGD(AAFwkTag::APPKIT, "begin, bundleName: %{public}s, moduleName: %{public}s",
506         bundleName.c_str(), moduleName.c_str());
507     if (bundleName.empty() || moduleName.empty()) {
508         TAG_LOGE(AAFwkTag::APPKIT, "bundleName: %{public}s, moduleName: %{public}s",
509             bundleName.c_str(), moduleName.c_str());
510         return ERR_INVALID_VALUE;
511     }
512 
513     AppExecFwk::BundleInfo bundleInfo;
514     GetBundleInfo(bundleName, bundleInfo);
515     if (bundleInfo.name.empty() || bundleInfo.applicationInfo.name.empty()) {
516         TAG_LOGW(AAFwkTag::APPKIT, "GetBundleInfo error");
517         ErrCode ret = bundleMgr_->GetDependentBundleInfo(bundleName, bundleInfo,
518             AppExecFwk::GetDependentBundleInfoFlag::GET_ALL_DEPENDENT_BUNDLE_INFO);
519         if (ret != ERR_OK) {
520             TAG_LOGE(AAFwkTag::APPKIT, "GetDependentBundleInfo failed:%{public}d", ret);
521             return ERR_INVALID_VALUE;
522         }
523     }
524 
525     if (bundleInfo.applicationInfo.bundleType != AppExecFwk::BundleType::APP_SERVICE_FWK) {
526         TAG_LOGE(AAFwkTag::APPKIT, "input bundleName:%{public}s not system hsp", bundleName.c_str());
527         return ERR_ABILITY_RUNTIME_EXTERNAL_NOT_SYSTEM_HSP;
528     }
529 
530     std::string selfBundleName = GetBundleName();
531     if (bundleInfo.applicationInfo.codePath == std::to_string(TYPE_RESERVE) ||
532         bundleInfo.applicationInfo.codePath == std::to_string(TYPE_OTHERS)) {
533         resourceManager = InitOthersResourceManagerInner(bundleInfo, selfBundleName == bundleName, moduleName);
534         if (resourceManager == nullptr) {
535             TAG_LOGE(AAFwkTag::APPKIT, "null resourceManager");
536         }
537         return ERR_INVALID_VALUE;
538     }
539 
540     resourceManager = InitResourceManagerInner(bundleInfo, selfBundleName == bundleName, moduleName);
541     if (resourceManager == nullptr) {
542         TAG_LOGE(AAFwkTag::APPKIT, "null resourceManager");
543         return ERR_INVALID_VALUE;
544     }
545     UpdateResConfig(GetResourceManager(), resourceManager);
546     return ERR_OK;
547 }
548 
GetBundleInfo(const std::string & bundleName,AppExecFwk::BundleInfo & bundleInfo,bool & currentBundle)549 int32_t ContextImpl::GetBundleInfo(const std::string &bundleName, AppExecFwk::BundleInfo &bundleInfo,
550     bool &currentBundle)
551 {
552     std::string currentBundleName;
553     auto appContext = ApplicationContext::GetInstance();
554     if (appContext != nullptr) {
555         currentBundleName = appContext->GetBundleName();
556     }
557     currentBundle = bundleName == currentBundleName;
558 
559     int errCode = GetBundleManager();
560     if (errCode != ERR_OK) {
561         TAG_LOGE(AAFwkTag::APPKIT, "errCode: %{public}d", errCode);
562         return errCode;
563     }
564 
565     if (currentBundle) {
566         bundleMgr_->GetBundleInfoForSelf((
567             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) +
568             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY) +
569             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) +
570             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE) +
571             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) +
572             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) +
573             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_METADATA)), bundleInfo);
574     } else {
575         int accountId = GetCurrentAccountId();
576         if (accountId == 0) {
577             accountId = GetCurrentActiveAccountId();
578         }
579         bundleMgr_->GetBundleInfoV9(bundleName,
580             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) +
581             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE),
582             bundleInfo, accountId);
583     }
584 
585     if (bundleInfo.name.empty() || bundleInfo.applicationInfo.name.empty()) {
586         TAG_LOGW(AAFwkTag::APPKIT, "bundleInfo empty");
587         ErrCode ret = bundleMgr_->GetUninstalledBundleInfo(bundleName, bundleInfo);
588         if (ret != ERR_OK) {
589             TAG_LOGE(AAFwkTag::APPKIT, "GetUninstalledBundleInfo failed:%{public}d", ret);
590             return ret;
591         }
592     }
593     return ERR_OK;
594 }
595 
GetBundleInfo(const std::string & bundleName,AppExecFwk::BundleInfo & bundleInfo,std::shared_ptr<Context> inputContext)596 void ContextImpl::GetBundleInfo(const std::string &bundleName, AppExecFwk::BundleInfo &bundleInfo,
597     std::shared_ptr<Context> inputContext)
598 {
599     TAG_LOGD(AAFwkTag::APPKIT, "begin");
600     if (bundleMgr_ == nullptr) {
601         int errCode = GetBundleManager();
602         if (errCode != ERR_OK) {
603             TAG_LOGE(AAFwkTag::APPKIT, "failed, errCode: %{public}d", errCode);
604             return;
605         }
606     }
607 
608     if (bundleName == GetBundleNameWithContext(inputContext)) {
609         bundleMgr_->GetBundleInfoForSelf(
610             (static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) +
611             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION)), bundleInfo);
612     } else {
613         int accountId = GetCurrentAccountId();
614         if (accountId == 0) {
615             accountId = GetCurrentActiveAccountId();
616         }
617         bundleMgr_->GetBundleInfoV9(bundleName,
618             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) +
619             static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE),
620             bundleInfo, accountId);
621     }
622 }
623 
GetArea()624 int ContextImpl::GetArea()
625 {
626     TAG_LOGD(AAFwkTag::APPKIT, "begin");
627     int mode = -1;
628     for (int i = 0; i < (int)(sizeof(CONTEXT_ELS) / sizeof(CONTEXT_ELS[0])); i++) {
629         if (currArea_ == CONTEXT_ELS[i]) {
630             mode = i;
631             break;
632         }
633     }
634     if (mode == -1) {
635         TAG_LOGE(AAFwkTag::APPKIT, "not find mode");
636         return EL_DEFAULT;
637     }
638     TAG_LOGD(AAFwkTag::APPKIT, "end");
639     return mode;
640 }
641 
GetProcessName()642 std::string ContextImpl::GetProcessName()
643 {
644     return processName_;
645 }
646 
GetBaseDir() const647 std::string ContextImpl::GetBaseDir() const
648 {
649     std::string baseDir;
650     if (IsCreateBySystemApp()) {
651         baseDir = CONTEXT_DATA_APP + currArea_ + CONTEXT_FILE_SEPARATOR + std::to_string(GetCurrentAccountId()) +
652             CONTEXT_FILE_SEPARATOR + CONTEXT_BASE + CONTEXT_FILE_SEPARATOR + GetBundleName();
653     } else {
654         baseDir = CONTEXT_DATA_STORAGE + currArea_ + CONTEXT_FILE_SEPARATOR + CONTEXT_BASE;
655     }
656     if (parentContext_ != nullptr) {
657         baseDir = baseDir + CONTEXT_HAPS + CONTEXT_FILE_SEPARATOR +
658             ((GetHapModuleInfo() == nullptr) ? "" : GetHapModuleInfo()->moduleName);
659     }
660 
661     TAG_LOGD(AAFwkTag::APPKIT, "Dir:%{public}s", baseDir.c_str());
662     return baseDir;
663 }
664 
GetCurrentAccountId() const665 int ContextImpl::GetCurrentAccountId() const
666 {
667     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
668     int userId = 0;
669     auto instance = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance();
670     if (instance == nullptr) {
671         TAG_LOGE(AAFwkTag::APPKIT, "null instance");
672         return userId;
673     }
674     instance->GetOsAccountLocalIdFromProcess(userId);
675     TAG_LOGD(AAFwkTag::APPKIT, "userId: %{public}d", userId);
676     return userId;
677 }
678 
GetCurrentActiveAccountId() const679 int ContextImpl::GetCurrentActiveAccountId() const
680 {
681     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
682     std::vector<int> accountIds;
683     auto instance = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance();
684     if (instance == nullptr) {
685         TAG_LOGE(AAFwkTag::APPKIT, "null instance");
686         return 0;
687     }
688     ErrCode ret = instance->QueryActiveOsAccountIds(accountIds);
689     if (ret != ERR_OK) {
690         TAG_LOGE(AAFwkTag::APPKIT, "ContextImpl::GetCurrentActiveAccountId error. ret: %{public}d", ret);
691         return 0;
692     }
693 
694     if (accountIds.size() == 0) {
695         TAG_LOGE(AAFwkTag::APPKIT, "no accounts");
696         return 0;
697     }
698     TAG_LOGD(AAFwkTag::APPKIT, "accountId: %{public}d", accountIds[0]);
699     return accountIds[0];
700 }
701 
CreateBundleContext(std::shared_ptr<Context> & context,const std::string & bundleName,std::shared_ptr<Context> inputContext)702 int32_t ContextImpl::CreateBundleContext(std::shared_ptr<Context> &context, const std::string &bundleName,
703     std::shared_ptr<Context> inputContext)
704 {
705     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
706 
707     if (bundleName.empty()) {
708         TAG_LOGE(AAFwkTag::APPKIT, "bundleName empty");
709         return ERR_INVALID_VALUE;
710     }
711 
712     int errCode = GetBundleManager();
713     if (errCode != ERR_OK) {
714         TAG_LOGE(AAFwkTag::APPKIT, "failed, errCode: %{public}d", errCode);
715         return ERR_INVALID_VALUE;
716     }
717 
718     AppExecFwk::BundleInfo bundleInfo;
719     int accountId = GetCurrentAccountId();
720     if (accountId == 0) {
721         accountId = GetCurrentActiveAccountId();
722     }
723 
724     TAG_LOGD(AAFwkTag::APPKIT, "length: %{public}zu, bundleName: %{public}s",
725         (size_t)bundleName.length(), bundleName.c_str());
726     bundleMgr_->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, accountId);
727 
728     if (bundleInfo.name.empty() || bundleInfo.applicationInfo.name.empty()) {
729         TAG_LOGE(AAFwkTag::APPKIT, "bundleInfo empty");
730         return ERR_INVALID_VALUE;
731     }
732 
733     std::shared_ptr<ContextImpl> appContext = std::make_shared<ContextImpl>();
734     appContext->SetFlags(CONTEXT_CREATE_BY_SYSTEM_APP);
735     appContext->SetConfiguration(config_);
736     appContext->SetProcessName(processName_);
737 
738     // init resourceManager.
739     InitResourceManager(bundleInfo, appContext, false, "", inputContext);
740 
741     appContext->SetApplicationInfo(std::make_shared<AppExecFwk::ApplicationInfo>(bundleInfo.applicationInfo));
742     context = appContext;
743     return ERR_OK;
744 }
745 
CreateBundleContext(const std::string & bundleName)746 std::shared_ptr<Context> ContextImpl::CreateBundleContext(const std::string &bundleName)
747 {
748     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
749     TAG_LOGD(AAFwkTag::APPKIT, "begin");
750     if (parentContext_ != nullptr) {
751         return parentContext_->CreateBundleContext(bundleName);
752     }
753 
754     if (bundleName.empty()) {
755         TAG_LOGE(AAFwkTag::APPKIT, "bundleName empty");
756         return nullptr;
757     }
758 
759     int errCode = GetBundleManager();
760     if (errCode != ERR_OK) {
761         TAG_LOGE(AAFwkTag::APPKIT, "failed, errCode: %{public}d", errCode);
762         return nullptr;
763     }
764 
765     AppExecFwk::BundleInfo bundleInfo;
766     int accountId = GetCurrentAccountId();
767     if (accountId == 0) {
768         accountId = GetCurrentActiveAccountId();
769     }
770     TAG_LOGD(AAFwkTag::APPKIT, "length: %{public}zu, bundleName: %{public}s",
771         (size_t)bundleName.length(), bundleName.c_str());
772     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "bundleMgr_->GetBundleInfo");
773     bundleMgr_->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, accountId);
774 
775     if (bundleInfo.name.empty() || bundleInfo.applicationInfo.name.empty()) {
776         TAG_LOGE(AAFwkTag::APPKIT, "bundleInfo empty");
777         return nullptr;
778     }
779 
780     std::shared_ptr<ContextImpl> appContext = std::make_shared<ContextImpl>();
781     appContext->SetFlags(CONTEXT_CREATE_BY_SYSTEM_APP);
782     appContext->SetConfiguration(config_);
783     appContext->SetProcessName(processName_);
784 
785     // init resourceManager.
786     InitResourceManager(bundleInfo, appContext);
787     appContext->SetApplicationInfo(std::make_shared<AppExecFwk::ApplicationInfo>(bundleInfo.applicationInfo));
788     return appContext;
789 }
790 
InitResourceManager(const AppExecFwk::BundleInfo & bundleInfo,const std::shared_ptr<ContextImpl> & appContext,bool currentBundle,const std::string & moduleName,std::shared_ptr<Context> inputContext)791 void ContextImpl::InitResourceManager(const AppExecFwk::BundleInfo &bundleInfo,
792     const std::shared_ptr<ContextImpl> &appContext, bool currentBundle, const std::string& moduleName,
793     std::shared_ptr<Context> inputContext)
794 {
795     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
796     TAG_LOGD(AAFwkTag::APPKIT, "begin, bundleName:%{public}s, moduleName:%{public}s",
797         bundleInfo.name.c_str(), moduleName.c_str());
798 
799     if (appContext == nullptr) {
800         TAG_LOGE(AAFwkTag::APPKIT, "null appContext");
801         return;
802     }
803     if (bundleInfo.applicationInfo.codePath == std::to_string(TYPE_RESERVE) ||
804         bundleInfo.applicationInfo.codePath == std::to_string(TYPE_OTHERS)) {
805         std::shared_ptr<Global::Resource::ResourceManager> resourceManager = InitOthersResourceManagerInner(
806             bundleInfo, currentBundle, moduleName);
807         if (resourceManager == nullptr) {
808             TAG_LOGE(AAFwkTag::APPKIT, "null resourceManager");
809             return;
810         }
811         appContext->SetResourceManager(resourceManager);
812         return;
813     }
814 
815     std::shared_ptr<Global::Resource::ResourceManager> resourceManager = InitResourceManagerInner(
816         bundleInfo, currentBundle, moduleName, inputContext);
817     if (resourceManager == nullptr) {
818         return;
819     }
820     std::shared_ptr<Global::Resource::ResourceManager> src = nullptr;
821     if (inputContext) {
822         src = inputContext->GetResourceManager();
823     }
824     UpdateResConfig(src, resourceManager);
825     appContext->SetResourceManager(resourceManager);
826 }
827 
InitOthersResourceManagerInner(const AppExecFwk::BundleInfo & bundleInfo,bool currentBundle,const std::string & moduleName)828 std::shared_ptr<Global::Resource::ResourceManager> ContextImpl::InitOthersResourceManagerInner(
829     const AppExecFwk::BundleInfo &bundleInfo, bool currentBundle, const std::string& moduleName)
830 {
831     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
832     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
833     std::string hapPath;
834     std::vector<std::string> overlayPaths;
835     int32_t appType;
836     if (bundleInfo.applicationInfo.codePath == std::to_string(TYPE_RESERVE)) {
837         appType = TYPE_RESERVE;
838     } else if (bundleInfo.applicationInfo.codePath == std::to_string(TYPE_OTHERS)) {
839         appType = TYPE_OTHERS;
840     } else {
841         appType = 0;
842     }
843     std::shared_ptr<Global::Resource::ResourceManager> resourceManager(Global::Resource::CreateResourceManager(
844         bundleInfo.name, moduleName, hapPath, overlayPaths, *resConfig, appType));
845     return resourceManager;
846 }
847 
InitResourceManagerInner(const AppExecFwk::BundleInfo & bundleInfo,bool currentBundle,const std::string & moduleName,std::shared_ptr<Context> inputContext)848 std::shared_ptr<Global::Resource::ResourceManager> ContextImpl::InitResourceManagerInner(
849     const AppExecFwk::BundleInfo &bundleInfo, bool currentBundle, const std::string& moduleName,
850     std::shared_ptr<Context> inputContext)
851 {
852     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
853     std::shared_ptr<Global::Resource::ResourceManager> resourceManager = InitOthersResourceManagerInner(
854         bundleInfo, currentBundle, moduleName);
855     if (resourceManager == nullptr) {
856         TAG_LOGE(AAFwkTag::APPKIT, "null resourceManager");
857         return resourceManager;
858     }
859     if (!moduleName.empty() || !bundleInfo.applicationInfo.multiProjects) {
860         TAG_LOGD(AAFwkTag::APPKIT, "hapModuleInfos count: %{public}zu", bundleInfo.hapModuleInfos.size());
861         std::regex inner_pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR)
862             + GetBundleNameWithContext(inputContext));
863         std::regex outer_pattern(ABS_CODE_PATH);
864         std::regex hsp_pattern(std::string(ABS_CODE_PATH) + FILE_SEPARATOR + bundleInfo.name + PATTERN_VERSION);
865         std::string hsp_sandbox = std::string(LOCAL_CODE_PATH) + FILE_SEPARATOR + bundleInfo.name + FILE_SEPARATOR;
866         {
867             HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "for (auto hapModuleInfo : bundleInfo.hapModuleInfos)");
868             for (auto hapModuleInfo : bundleInfo.hapModuleInfos) {
869                 TAG_LOGD(AAFwkTag::APPKIT, "hapModuleInfo abilityInfo size: %{public}zu",
870                     hapModuleInfo.abilityInfos.size());
871                 if (!moduleName.empty() && hapModuleInfo.moduleName != moduleName) {
872                     continue;
873                 }
874                 std::string loadPath =
875                     hapModuleInfo.hapPath.empty() ? hapModuleInfo.resourcePath : hapModuleInfo.hapPath;
876                 if (loadPath.empty()) {
877                     TAG_LOGD(AAFwkTag::APPKIT, "loadPath is empty");
878                     continue;
879                 }
880                 if (currentBundle) {
881                     loadPath = std::regex_replace(loadPath, inner_pattern, LOCAL_CODE_PATH);
882                 } else if (bundleInfo.applicationInfo.bundleType == AppExecFwk::BundleType::SHARED) {
883                     loadPath = std::regex_replace(loadPath, hsp_pattern, hsp_sandbox);
884                 } else if (bundleInfo.applicationInfo.bundleType == AppExecFwk::BundleType::APP_SERVICE_FWK) {
885                     loadPath = std::regex_replace(loadPath, hsp_pattern, hsp_sandbox);
886                 } else {
887                     loadPath = std::regex_replace(loadPath, outer_pattern, LOCAL_BUNDLES);
888                 }
889 
890                 TAG_LOGD(AAFwkTag::APPKIT, "loadPath: %{private}s", loadPath.c_str());
891                 GetOverlayPath(resourceManager, bundleInfo.name, hapModuleInfo.moduleName, loadPath, currentBundle,
892                     inputContext);
893                 AddPatchResource(resourceManager, loadPath, hapModuleInfo.hqfInfo.hqfFilePath,
894                     bundleInfo.applicationInfo.debug, inputContext);
895             }
896         }
897     }
898     return resourceManager;
899 }
900 
AddPatchResource(std::shared_ptr<Global::Resource::ResourceManager> & resourceManager,const std::string & loadPath,const std::string & hqfPath,bool isDebug,std::shared_ptr<Context> inputContext)901 void ContextImpl::AddPatchResource(std::shared_ptr<Global::Resource::ResourceManager> &resourceManager,
902     const std::string &loadPath, const std::string &hqfPath, bool isDebug, std::shared_ptr<Context> inputContext)
903 {
904     std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR)
905         + GetBundleNameWithContext(inputContext));
906     if (!hqfPath.empty() && isDebug) {
907         std::string realHqfPath = std::regex_replace(hqfPath, pattern, LOCAL_CODE_PATH);
908         TAG_LOGI(AAFwkTag::APPKIT, "AddPatchResource hapPath:%{public}s, patchPath:%{public}s",
909             loadPath.c_str(), realHqfPath.c_str());
910         if (!resourceManager->AddPatchResource(loadPath.c_str(), realHqfPath.c_str())) {
911             TAG_LOGE(AAFwkTag::APPKIT, "AddPatchResource failed");
912         }
913     }
914 }
915 
GetOverlayPath(std::shared_ptr<Global::Resource::ResourceManager> & resourceManager,const std::string & bundleName,const std::string & moduleName,std::string & loadPath,bool currentBundle,std::shared_ptr<Context> inputContext)916 void ContextImpl::GetOverlayPath(std::shared_ptr<Global::Resource::ResourceManager> &resourceManager,
917     const std::string &bundleName, const std::string &moduleName, std::string &loadPath, bool currentBundle,
918     std::shared_ptr<Context> inputContext)
919 {
920     // getOverlayPath
921     std::vector<AppExecFwk::OverlayModuleInfo> overlayModuleInfos;
922     auto res = GetOverlayModuleInfos(bundleName, moduleName, overlayModuleInfos);
923     if (res != ERR_OK) {
924         TAG_LOGD(AAFwkTag::APPKIT, "Get overlay paths from bms failed.");
925     }
926     if (overlayModuleInfos.size() == 0) {
927         if (!resourceManager->AddResource(loadPath.c_str())) {
928             TAG_LOGE(AAFwkTag::APPKIT, "moduleResPath: %{private}s", loadPath.c_str());
929         }
930     } else {
931         std::vector<std::string> overlayPaths;
932         for (auto it : overlayModuleInfos) {
933             if (std::regex_search(it.hapPath, std::regex(GetBundleNameWithContext(inputContext)))) {
934                 it.hapPath = std::regex_replace(it.hapPath, std::regex(std::string(ABS_CODE_PATH) +
935         std::string(FILE_SEPARATOR) + GetBundleNameWithContext(inputContext)), LOCAL_CODE_PATH);
936             } else {
937                 it.hapPath = std::regex_replace(it.hapPath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES);
938             }
939             if (it.state == AppExecFwk::OverlayState::OVERLAY_ENABLE) {
940                 TAG_LOGD(AAFwkTag::APPKIT, "hapPath: %{private}s", it.hapPath.c_str());
941                 overlayPaths.emplace_back(it.hapPath);
942             }
943         }
944         TAG_LOGD(AAFwkTag::APPKIT, "OverlayPaths size:%{public}zu.", overlayPaths.size());
945         if (!resourceManager->AddResource(loadPath, overlayPaths)) {
946             TAG_LOGE(AAFwkTag::APPKIT, "AddResource failed");
947         }
948 
949         if (currentBundle) {
950             SubscribeToOverlayEvents(resourceManager, bundleName, moduleName, loadPath, overlayModuleInfos);
951         }
952     }
953 }
954 
SubscribeToOverlayEvents(std::shared_ptr<Global::Resource::ResourceManager> & resourceManager,const std::string & name,const std::string & hapModuleName,std::string & loadPath,std::vector<AppExecFwk::OverlayModuleInfo> overlayModuleInfos)955 void ContextImpl::SubscribeToOverlayEvents(std::shared_ptr<Global::Resource::ResourceManager> &resourceManager,
956     const std::string &name, const std::string &hapModuleName, std::string &loadPath,
957     std::vector<AppExecFwk::OverlayModuleInfo> overlayModuleInfos)
958 {
959     std::lock_guard<std::mutex> lock(overlaySubscriberMutex_);
960     if (overlaySubscriber_ != nullptr) {
961         return;
962     }
963     // add listen overlay change
964     overlayModuleInfos_ = overlayModuleInfos;
965     EventFwk::MatchingSkills matchingSkills;
966     matchingSkills.AddEvent(OVERLAY_STATE_CHANGED);
967     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
968     subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
969     auto callback = [this, resourceManager, bundleName = name, moduleName =
970     hapModuleName, loadPath](const EventFwk::CommonEventData &data) {
971         TAG_LOGI(AAFwkTag::APPKIT, "on overlay changed");
972         this->OnOverlayChanged(data, resourceManager, bundleName, moduleName, loadPath);
973     };
974     overlaySubscriber_ = std::make_shared<AppExecFwk::OverlayEventSubscriber>(subscribeInfo, callback);
975     bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(overlaySubscriber_);
976     TAG_LOGI(AAFwkTag::APPKIT, "Overlay event subscriber register result is %{public}d", subResult);
977 }
978 
UnsubscribeToOverlayEvents()979 void ContextImpl::UnsubscribeToOverlayEvents()
980 {
981     std::lock_guard<std::mutex> lock(overlaySubscriberMutex_);
982     if (overlaySubscriber_ != nullptr) {
983         EventFwk::CommonEventManager::UnSubscribeCommonEvent(overlaySubscriber_);
984         overlaySubscriber_ = nullptr;
985     }
986 }
987 
UpdateResConfig(std::shared_ptr<Global::Resource::ResourceManager> & resourceManager)988 void ContextImpl::UpdateResConfig(std::shared_ptr<Global::Resource::ResourceManager> &resourceManager)
989 {
990     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
991     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
992     if (resConfig == nullptr) {
993         TAG_LOGE(AAFwkTag::APPKIT, "null resConfig");
994         return;
995     }
996 
997     if (GetHapModuleInfo() != nullptr && GetApplicationInfo() != nullptr) {
998         std::vector<AppExecFwk::Metadata> metadata = GetHapModuleInfo()->metadata;
999         bool load = std::any_of(metadata.begin(), metadata.end(), [](const auto &metadataItem) {
1000             return metadataItem.name == "ContextResourceConfigLoadFromParentTemp" && metadataItem.value == "true";
1001         });
1002         if (load && GetApplicationInfo()->apiTargetVersion % API_VERSION_MOD >= API11) {
1003             std::shared_ptr<Global::Resource::ResourceManager> currentResMgr = GetResourceManager();
1004             if (currentResMgr != nullptr) {
1005                 TAG_LOGD(AAFwkTag::APPKIT, "apiVersion: %{public}d, load parent config",
1006                     GetApplicationInfo()->apiTargetVersion);
1007                 currentResMgr->GetResConfig(*resConfig);
1008             }
1009         }
1010     }
1011 #ifdef SUPPORT_SCREEN
1012     UErrorCode status = U_ZERO_ERROR;
1013     icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetEffectiveLanguage(), status);
1014     resConfig->SetLocaleInfo(locale);
1015     if (resConfig->GetLocaleInfo() == nullptr) {
1016         TAG_LOGE(AAFwkTag::APPKIT, "null LocaleInfo");
1017     }
1018 #endif
1019     resConfig->SetDeviceType(GetDeviceType());
1020     if (config_) {
1021         std::string mcc = config_->GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_MCC);
1022         std::string mnc = config_->GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_MNC);
1023         try {
1024             resConfig->SetMcc(static_cast<uint32_t>(std::stoi(mcc)));
1025             resConfig->SetMnc(static_cast<uint32_t>(std::stoi(mnc)));
1026         } catch (...) {
1027             TAG_LOGD(AAFwkTag::APPKIT, "Set mcc,mnc failed mcc:%{public}s mnc:%{public}s", mcc.c_str(), mnc.c_str());
1028         }
1029     }
1030     resourceManager->UpdateResConfig(*resConfig);
1031 }
1032 
UpdateResConfig(std::shared_ptr<Global::Resource::ResourceManager> src,std::shared_ptr<Global::Resource::ResourceManager> & resourceManager)1033 void ContextImpl::UpdateResConfig(std::shared_ptr<Global::Resource::ResourceManager> src,
1034     std::shared_ptr<Global::Resource::ResourceManager> &resourceManager)
1035 {
1036     if (src == nullptr) {
1037         UpdateResConfig(resourceManager);
1038         return;
1039     }
1040     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1041     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1042     if (resConfig == nullptr) {
1043         TAG_LOGE(AAFwkTag::APPKIT, "null resConfig");
1044         return;
1045     }
1046     src->GetResConfig(*resConfig);
1047     resourceManager->UpdateResConfig(*resConfig);
1048 }
1049 
GetBundleManager()1050 ErrCode ContextImpl::GetBundleManager()
1051 {
1052     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1053     std::lock_guard<std::mutex> lock(bundleManagerMutex_);
1054     if (bundleMgr_ != nullptr && !resetFlag_) {
1055         return ERR_OK;
1056     }
1057 
1058     bundleMgr_ = DelayedSingleton<AppExecFwk::BundleMgrHelper>::GetInstance();
1059     if (bundleMgr_ == nullptr) {
1060         TAG_LOGE(AAFwkTag::APPKIT, "null bundleMgr_");
1061         return ERR_NULL_OBJECT;
1062     }
1063 
1064     TAG_LOGD(AAFwkTag::APPKIT, "Success");
1065     return ERR_OK;
1066 }
1067 
SetApplicationInfo(const std::shared_ptr<AppExecFwk::ApplicationInfo> & info)1068 void ContextImpl::SetApplicationInfo(const std::shared_ptr<AppExecFwk::ApplicationInfo> &info)
1069 {
1070     if (info == nullptr) {
1071         TAG_LOGE(AAFwkTag::APPKIT, "null info");
1072         return;
1073     }
1074     applicationInfo_ = info;
1075 }
1076 
SetResourceManager(const std::shared_ptr<Global::Resource::ResourceManager> & resourceManager)1077 void ContextImpl::SetResourceManager(const std::shared_ptr<Global::Resource::ResourceManager> &resourceManager)
1078 {
1079     resourceManager_ = resourceManager;
1080 }
1081 
GetResourceManager() const1082 std::shared_ptr<Global::Resource::ResourceManager> ContextImpl::GetResourceManager() const
1083 {
1084     if (resourceManager_) {
1085         return resourceManager_;
1086     }
1087 
1088     return parentContext_ != nullptr ? parentContext_->GetResourceManager() : nullptr;
1089 }
1090 
GetApplicationInfo() const1091 std::shared_ptr<AppExecFwk::ApplicationInfo> ContextImpl::GetApplicationInfo() const
1092 {
1093     if (parentContext_ != nullptr) {
1094         return parentContext_->GetApplicationInfo();
1095     }
1096 
1097     return applicationInfo_;
1098 }
1099 
SetParentContext(const std::shared_ptr<Context> & context)1100 void ContextImpl::SetParentContext(const std::shared_ptr<Context> &context)
1101 {
1102     parentContext_ = context;
1103 }
1104 
GetBundleCodePath() const1105 std::string ContextImpl::GetBundleCodePath() const
1106 {
1107     if (parentContext_ != nullptr) {
1108         return parentContext_->GetBundleCodePath();
1109     }
1110     return (applicationInfo_ != nullptr) ? applicationInfo_->codePath : "";
1111 }
1112 
InitHapModuleInfo(const std::shared_ptr<AppExecFwk::AbilityInfo> & abilityInfo)1113 void ContextImpl::InitHapModuleInfo(const std::shared_ptr<AppExecFwk::AbilityInfo> &abilityInfo)
1114 {
1115     if (hapModuleInfo_ != nullptr || abilityInfo == nullptr) {
1116         return;
1117     }
1118     int errCode = GetBundleManager();
1119     if (errCode != ERR_OK) {
1120         TAG_LOGE(AAFwkTag::APPKIT, "failed, errCode: %{public}d", errCode);
1121         return ;
1122     }
1123 
1124     hapModuleInfo_ = std::make_shared<AppExecFwk::HapModuleInfo>();
1125     if (!bundleMgr_->GetHapModuleInfo(*abilityInfo.get(), *hapModuleInfo_)) {
1126         TAG_LOGE(AAFwkTag::APPKIT, "will retval false");
1127     }
1128 }
1129 
InitHapModuleInfo(const AppExecFwk::HapModuleInfo & hapModuleInfo)1130 void ContextImpl::InitHapModuleInfo(const AppExecFwk::HapModuleInfo &hapModuleInfo)
1131 {
1132     hapModuleInfo_ = std::make_shared<AppExecFwk::HapModuleInfo>(hapModuleInfo);
1133 }
1134 
GetHapModuleInfo() const1135 std::shared_ptr<AppExecFwk::HapModuleInfo> ContextImpl::GetHapModuleInfo() const
1136 {
1137     if (hapModuleInfo_ == nullptr) {
1138         TAG_LOGD(AAFwkTag::APPKIT, "hapModuleInfo is empty");
1139     }
1140     return hapModuleInfo_;
1141 }
1142 
GetHapModuleInfoWithContext(std::shared_ptr<Context> inputContext) const1143 std::shared_ptr<AppExecFwk::HapModuleInfo> ContextImpl::GetHapModuleInfoWithContext(
1144     std::shared_ptr<Context> inputContext) const
1145 {
1146     if (inputContext) {
1147         return inputContext->GetHapModuleInfo();
1148     }
1149     return GetHapModuleInfo();
1150 }
1151 
SetFlags(int64_t flags)1152 void ContextImpl::SetFlags(int64_t flags)
1153 {
1154     flags_ = static_cast<uint64_t>(flags_) | static_cast<uint64_t>(CONTEXT_CREATE_BY_SYSTEM_APP);
1155 }
1156 
IsCreateBySystemApp() const1157 bool ContextImpl::IsCreateBySystemApp() const
1158 {
1159     return (static_cast<uint64_t>(flags_) & static_cast<uint64_t>(CONTEXT_CREATE_BY_SYSTEM_APP)) == 1;
1160 }
1161 
1162 std::shared_ptr<ApplicationContext> Context::applicationContext_ = nullptr;
1163 std::mutex Context::contextMutex_;
1164 
GetApplicationContext()1165 std::shared_ptr<ApplicationContext> Context::GetApplicationContext()
1166 {
1167     std::lock_guard<std::mutex> lock(contextMutex_);
1168     return applicationContext_;
1169 }
1170 
SetToken(const sptr<IRemoteObject> & token)1171 void ContextImpl::SetToken(const sptr<IRemoteObject> &token)
1172 {
1173     if (token == nullptr) {
1174         TAG_LOGD(AAFwkTag::APPKIT, "null token");
1175         return;
1176     }
1177     token_ = token;
1178     if (GetBundleName() == "com.ohos.callui") {
1179         PrintTokenInfo();
1180     }
1181 }
1182 
GetToken()1183 sptr<IRemoteObject> ContextImpl::GetToken()
1184 {
1185     return token_;
1186 }
1187 
CreateDirIfNotExist(const std::string & dirPath,const mode_t & mode) const1188 void ContextImpl::CreateDirIfNotExist(const std::string& dirPath, const mode_t& mode) const
1189 {
1190     if (!OHOS::FileExists(dirPath)) {
1191         TAG_LOGD(AAFwkTag::APPKIT, "ForceCreateDirectory, dir: %{public}s", dirPath.c_str());
1192         bool createDir = OHOS::ForceCreateDirectory(dirPath);
1193         if (!createDir) {
1194             TAG_LOGE(AAFwkTag::APPKIT, "create dir %{public}s failed, errno is %{public}d", dirPath.c_str(), errno);
1195             return;
1196         }
1197         if (mode != 0) {
1198             chmod(dirPath.c_str(), mode);
1199         }
1200     }
1201 }
1202 
SetConfiguration(const std::shared_ptr<AppExecFwk::Configuration> & config)1203 void ContextImpl::SetConfiguration(const std::shared_ptr<AppExecFwk::Configuration> &config)
1204 {
1205     config_ = config;
1206 }
1207 
AppHasDarkRes(bool & darkRes)1208 void ContextImpl::AppHasDarkRes(bool &darkRes)
1209 {
1210     std::shared_ptr<Global::Resource::ResourceManager> currentResMgr = GetResourceManager();
1211     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1212     if (currentResMgr == nullptr || resConfig == nullptr) {
1213         TAG_LOGE(AAFwkTag::APPKIT, "null resMgr or resConfig");
1214         return;
1215     }
1216     currentResMgr->GetResConfig(*resConfig);
1217     darkRes = resConfig->GetAppDarkRes();
1218     TAG_LOGD(AAFwkTag::APPKIT, "darkRes %{public}d", darkRes);
1219 }
1220 
SetProcessName(const std::string & processName)1221 void ContextImpl::SetProcessName(const std::string &processName)
1222 {
1223     processName_ = processName;
1224 }
1225 
KillProcessBySelf(const bool clearPageStack)1226 void ContextImpl::KillProcessBySelf(const bool clearPageStack)
1227 {
1228     TAG_LOGI(AAFwkTag::APPKIT, "call");
1229     auto appMgrClient = DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance();
1230     appMgrClient->KillApplicationSelf(clearPageStack);
1231 }
1232 
GetProcessRunningInformation(AppExecFwk::RunningProcessInfo & info)1233 int32_t ContextImpl::GetProcessRunningInformation(AppExecFwk::RunningProcessInfo &info)
1234 {
1235     auto appMgrClient = DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance();
1236     auto result = appMgrClient->GetProcessRunningInformation(info);
1237     TAG_LOGD(AAFwkTag::APPKIT, "result is %{public}d", result);
1238     return result;
1239 }
1240 
GetAllRunningInstanceKeys(std::vector<std::string> & instanceKeys)1241 int32_t ContextImpl::GetAllRunningInstanceKeys(std::vector<std::string> &instanceKeys)
1242 {
1243     auto appMgrClient = DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance();
1244     auto result = appMgrClient->GetAllRunningInstanceKeysBySelf(instanceKeys);
1245     TAG_LOGD(AAFwkTag::APPKIT, "result is %{public}d", result);
1246     return result;
1247 }
1248 
RestartApp(const AAFwk::Want & want)1249 int32_t ContextImpl::RestartApp(const AAFwk::Want& want)
1250 {
1251     auto result = OHOS::AAFwk::AbilityManagerClient::GetInstance()->RestartApp(want);
1252     TAG_LOGD(AAFwkTag::APPKIT, "result is %{public}d", result);
1253     return result;
1254 }
1255 
GetConfiguration() const1256 std::shared_ptr<AppExecFwk::Configuration> ContextImpl::GetConfiguration() const
1257 {
1258     return config_;
1259 }
1260 
GetDeviceType() const1261 Global::Resource::DeviceType ContextImpl::GetDeviceType() const
1262 {
1263     if (deviceType_ != Global::Resource::DeviceType::DEVICE_NOT_SET) {
1264         return deviceType_;
1265     }
1266 
1267     auto config = GetConfiguration();
1268     if (config != nullptr) {
1269         auto deviceType = config->GetItem(AAFwk::GlobalConfigurationKey::DEVICE_TYPE);
1270         TAG_LOGD(AAFwkTag::APPKIT, "deviceType is %{public}s", deviceType.c_str());
1271         deviceType_ = AppExecFwk::ConvertDeviceType(deviceType);
1272     }
1273 
1274     if (deviceType_ == Global::Resource::DeviceType::DEVICE_NOT_SET) {
1275         deviceType_ = Global::Resource::DeviceType::DEVICE_PHONE;
1276     }
1277     TAG_LOGD(AAFwkTag::APPKIT, "deviceType is %{public}d", deviceType_);
1278     return deviceType_;
1279 }
1280 
GetOverlayMgrProxy()1281 ErrCode ContextImpl::GetOverlayMgrProxy()
1282 {
1283     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1284     int errCode = GetBundleManager();
1285     if (errCode != ERR_OK) {
1286         TAG_LOGE(AAFwkTag::APPKIT, "failed, errCode: %{public}d", errCode);
1287         return errCode;
1288     }
1289 
1290     std::lock_guard<std::mutex> lock(overlayMgrProxyMutex_);
1291     if (overlayMgrProxy_ != nullptr) {
1292         return ERR_OK;
1293     }
1294 
1295     overlayMgrProxy_ = bundleMgr_->GetOverlayManagerProxy();
1296     if (overlayMgrProxy_ == nullptr) {
1297             TAG_LOGE(AAFwkTag::APPKIT, "null overlayMgrProxy");
1298         return ERR_NULL_OBJECT;
1299     }
1300 
1301     TAG_LOGD(AAFwkTag::APPKIT, "Success.");
1302     return ERR_OK;
1303 }
1304 
GetOverlayModuleInfos(const std::string & bundleName,const std::string & moduleName,std::vector<AppExecFwk::OverlayModuleInfo> & overlayModuleInfos)1305 int ContextImpl::GetOverlayModuleInfos(const std::string &bundleName, const std::string &moduleName,
1306     std::vector<AppExecFwk::OverlayModuleInfo> &overlayModuleInfos)
1307 {
1308     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1309     int errCode = GetOverlayMgrProxy();
1310     if (errCode != ERR_OK) {
1311         TAG_LOGE(AAFwkTag::APPKIT, "failed, errCode: %{public}d", errCode);
1312         return errCode;
1313     }
1314     {
1315         HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "overlayMgrProxy_->GetTargetOverlayModuleInfo");
1316         auto ret = overlayMgrProxy_->GetTargetOverlayModuleInfo(moduleName, overlayModuleInfos);
1317         if (ret != ERR_OK) {
1318             TAG_LOGD(AAFwkTag::APPKIT, "GetOverlayModuleInfo form bms failed");
1319             return ret;
1320         }
1321     }
1322     std::sort(overlayModuleInfos.begin(), overlayModuleInfos.end(),
1323         [](const AppExecFwk::OverlayModuleInfo& lhs, const AppExecFwk::OverlayModuleInfo& rhs) -> bool {
1324         return lhs.priority > rhs.priority;
1325     });
1326     TAG_LOGD(AAFwkTag::APPKIT, "the size of overlay is: %{public}zu", overlayModuleInfos.size());
1327     return ERR_OK;
1328 }
1329 
GetAddOverlayPaths(const std::vector<AppExecFwk::OverlayModuleInfo> & overlayModuleInfos)1330 std::vector<std::string> ContextImpl::GetAddOverlayPaths(
1331     const std::vector<AppExecFwk::OverlayModuleInfo> &overlayModuleInfos)
1332 {
1333     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1334     std::vector<std::string> addPaths;
1335     for (auto it : overlayModuleInfos) {
1336         auto iter = std::find_if(
1337             overlayModuleInfos_.begin(), overlayModuleInfos_.end(), [it](AppExecFwk::OverlayModuleInfo item) {
1338                 return it.moduleName == item.moduleName;
1339             });
1340         if ((iter != overlayModuleInfos_.end()) && (it.state == AppExecFwk::OverlayState::OVERLAY_ENABLE)) {
1341             iter->state = it.state;
1342             ChangeToLocalPath(iter->bundleName, iter->hapPath, iter->hapPath);
1343             TAG_LOGD(AAFwkTag::APPKIT, "add path:%{private}s", iter->hapPath.c_str());
1344             addPaths.emplace_back(iter->hapPath);
1345         }
1346     }
1347 
1348     return addPaths;
1349 }
1350 
GetRemoveOverlayPaths(const std::vector<AppExecFwk::OverlayModuleInfo> & overlayModuleInfos)1351 std::vector<std::string> ContextImpl::GetRemoveOverlayPaths(
1352     const std::vector<AppExecFwk::OverlayModuleInfo> &overlayModuleInfos)
1353 {
1354     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1355     std::vector<std::string> removePaths;
1356     for (auto it : overlayModuleInfos) {
1357         auto iter = std::find_if(
1358             overlayModuleInfos_.begin(), overlayModuleInfos_.end(), [it](AppExecFwk::OverlayModuleInfo item) {
1359                 return it.moduleName == item.moduleName;
1360             });
1361         if ((iter != overlayModuleInfos_.end()) && (it.state != AppExecFwk::OverlayState::OVERLAY_ENABLE)) {
1362             iter->state = it.state;
1363             ChangeToLocalPath(iter->bundleName, iter->hapPath, iter->hapPath);
1364             TAG_LOGD(AAFwkTag::APPKIT, "remove path:%{private}s", iter->hapPath.c_str());
1365             removePaths.emplace_back(iter->hapPath);
1366         }
1367     }
1368 
1369     return removePaths;
1370 }
1371 
OnOverlayChanged(const EventFwk::CommonEventData & data,const std::shared_ptr<Global::Resource::ResourceManager> & resourceManager,const std::string & bundleName,const std::string & moduleName,const std::string & loadPath)1372 void ContextImpl::OnOverlayChanged(const EventFwk::CommonEventData &data,
1373     const std::shared_ptr<Global::Resource::ResourceManager> &resourceManager, const std::string &bundleName,
1374     const std::string &moduleName, const std::string &loadPath)
1375 {
1376     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1377     TAG_LOGD(AAFwkTag::APPKIT, "begin");
1378     auto want = data.GetWant();
1379     std::string action = want.GetAction();
1380     if (action != OVERLAY_STATE_CHANGED) {
1381         TAG_LOGD(AAFwkTag::APPKIT, "Not this subscribe, action: %{public}s", action.c_str());
1382         return;
1383     }
1384     if (GetBundleName() != bundleName) {
1385         TAG_LOGD(AAFwkTag::APPKIT, "Not this app, bundleName: %{public}s", bundleName.c_str());
1386         return;
1387     }
1388     bool isEnable = data.GetWant().GetBoolParam(AppExecFwk::Constants::OVERLAY_STATE, false);
1389     // 1.get overlay hapPath
1390     if (resourceManager == nullptr) {
1391         TAG_LOGE(AAFwkTag::APPKIT, "null resourceManager");
1392         return;
1393     }
1394     if (overlayModuleInfos_.size() == 0) {
1395         TAG_LOGE(AAFwkTag::APPKIT, "overlayModuleInfos empty");
1396         return;
1397     }
1398     std::vector<AppExecFwk::OverlayModuleInfo> overlayModuleInfos;
1399     auto res = GetOverlayModuleInfos(bundleName, moduleName, overlayModuleInfos);
1400     if (res != ERR_OK) {
1401         return;
1402     }
1403 
1404     // 2.add/remove overlay hapPath
1405     if (loadPath.empty() || overlayModuleInfos.size() == 0) {
1406         TAG_LOGW(AAFwkTag::APPKIT, "empty hapPath in overlayModuleInfo");
1407     } else {
1408         if (isEnable) {
1409             std::vector<std::string> overlayPaths = GetAddOverlayPaths(overlayModuleInfos);
1410             if (!resourceManager->AddResource(loadPath, overlayPaths)) {
1411                 TAG_LOGE(AAFwkTag::APPKIT, "AddResource error");
1412             }
1413         } else {
1414             std::vector<std::string> overlayPaths = GetRemoveOverlayPaths(overlayModuleInfos);
1415             if (!resourceManager->RemoveResource(loadPath, overlayPaths)) {
1416                 TAG_LOGE(AAFwkTag::APPKIT, "RemoveResource error");
1417             }
1418         }
1419     }
1420 }
1421 
ChangeToLocalPath(const std::string & bundleName,const std::string & sourceDir,std::string & localPath)1422 void ContextImpl::ChangeToLocalPath(const std::string& bundleName, const std::string& sourceDir, std::string& localPath)
1423 {
1424     std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + bundleName);
1425     if (sourceDir.empty()) {
1426         return;
1427     }
1428     bool isExist = false;
1429     try {
1430         isExist = std::regex_search(localPath, std::regex(bundleName));
1431     } catch (...) {
1432         TAG_LOGE(AAFwkTag::APPKIT, "ChangeToLocalPath error localPath:%{public}s bundleName:%{public}s",
1433             localPath.c_str(), bundleName.c_str());
1434     }
1435     if (isExist) {
1436         localPath = std::regex_replace(localPath, pattern, std::string(LOCAL_CODE_PATH));
1437     } else {
1438         localPath = std::regex_replace(localPath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES);
1439     }
1440 }
1441 
ClearUpApplicationData()1442 void ContextImpl::ClearUpApplicationData()
1443 {
1444     int errCode = DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->ClearUpApplicationDataBySelf();
1445     if (errCode != ERR_OK) {
1446         TAG_LOGE(AAFwkTag::APPKIT, "delete bundle side user data by self failed");
1447         return;
1448     }
1449 }
1450 
SetSupportedProcessCacheSelf(bool isSupport)1451 int32_t ContextImpl::SetSupportedProcessCacheSelf(bool isSupport)
1452 {
1453     TAG_LOGD(AAFwkTag::APPKIT, "Called");
1454     auto appMgrClient = DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance();
1455     if (appMgrClient == nullptr) {
1456         TAG_LOGE(AAFwkTag::APPKIT, "null appMgrClient");
1457         return ERR_INVALID_VALUE;
1458     }
1459     return appMgrClient->SetSupportedProcessCacheSelf(isSupport);
1460 }
1461 
PrintTokenInfo() const1462 void ContextImpl::PrintTokenInfo() const
1463 {
1464     if (token_ == nullptr) {
1465         TAG_LOGI(AAFwkTag::EXT, "null token");
1466         return;
1467     }
1468     if (!token_->IsProxyObject()) {
1469         TAG_LOGI(AAFwkTag::EXT, "token not proxy");
1470         return;
1471     }
1472     IPCObjectProxy *tokenProxyObject = reinterpret_cast<IPCObjectProxy *>(token_.GetRefPtr());
1473     if (tokenProxyObject != nullptr) {
1474         std::string remoteDescriptor = Str16ToStr8(tokenProxyObject->GetInterfaceDescriptor());
1475         TAG_LOGI(AAFwkTag::EXT, "handle: %{public}d, descriptor: %{public}s",
1476             tokenProxyObject->GetHandle(), remoteDescriptor.c_str());
1477     }
1478 }
1479 
ShallowCopySelf(std::shared_ptr<ContextImpl> & contextImpl)1480 void ContextImpl::ShallowCopySelf(std::shared_ptr<ContextImpl> &contextImpl)
1481 {
1482     contextImpl->token_ = token_;
1483     contextImpl->applicationInfo_ = applicationInfo_;
1484     contextImpl->parentContext_ = parentContext_;
1485     contextImpl->resourceManager_ = resourceManager_;
1486     contextImpl->hapModuleInfo_ = hapModuleInfo_;
1487     contextImpl->config_ = config_;
1488     contextImpl->currArea_ = currArea_;
1489     contextImpl->overlayModuleInfos_ = overlayModuleInfos_;
1490     {
1491         std::lock_guard<std::mutex> lock(checkedDirSetLock_);
1492         contextImpl->checkedDirSet_ = checkedDirSet_;
1493     }
1494     {
1495         std::lock_guard<std::mutex> lock(bundleManagerMutex_);
1496         contextImpl->bundleMgr_ = bundleMgr_;
1497     }
1498     {
1499         std::lock_guard<std::mutex> lock(overlayMgrProxyMutex_);
1500         contextImpl->overlayMgrProxy_ = overlayMgrProxy_;
1501     }
1502     contextImpl->resetFlag_ = resetFlag_;
1503     contextImpl->processName_ = processName_;
1504 }
1505 
CreateAreaModeContext(int areaMode)1506 std::shared_ptr<Context> ContextImpl::CreateAreaModeContext(int areaMode)
1507 {
1508     std::shared_ptr<ContextImpl> contextImpl = std::make_shared<ContextImpl>();
1509     if (contextImpl == nullptr) {
1510         TAG_LOGE(AAFwkTag::APPKIT, "failed to create contextImpl");
1511         return nullptr;
1512     }
1513     ShallowCopySelf(contextImpl);
1514     contextImpl->SwitchArea(areaMode);
1515     return contextImpl;
1516 }
1517 
CreateHspModuleResourceManager(const std::string & bundleName,const std::string & moduleName,std::shared_ptr<Global::Resource::ResourceManager> & resourceManager)1518 int32_t ContextImpl::CreateHspModuleResourceManager(const std::string &bundleName,
1519     const std::string &moduleName, std::shared_ptr<Global::Resource::ResourceManager> &resourceManager)
1520 {
1521     if (bundleName.empty() || moduleName.empty()) {
1522         TAG_LOGE(AAFwkTag::APPKIT, "bundleName is %{public}s, moduleName is %{public}s",
1523             bundleName.c_str(), moduleName.c_str());
1524         return ERR_INVALID_VALUE;
1525     }
1526 
1527     int errCode = GetBundleManager();
1528     if (errCode != ERR_OK) {
1529         TAG_LOGE(AAFwkTag::APPKIT, "The bundleMgr_ is nullptr");
1530         return ERR_INVALID_VALUE;
1531     }
1532 
1533     AppExecFwk::BundleInfo bundleInfo;
1534     ErrCode ret = bundleMgr_->GetDependentBundleInfo(bundleName, bundleInfo,
1535         AppExecFwk::GetDependentBundleInfoFlag::GET_ALL_DEPENDENT_BUNDLE_INFO);
1536     if (ret != ERR_OK) {
1537         TAG_LOGE(AAFwkTag::APPKIT, "GetDependentBundleInfo failed:%{public}d", ret);
1538         return ERR_INVALID_VALUE;
1539     }
1540 
1541     std::string selfBundleName = GetBundleName();
1542     if (bundleInfo.applicationInfo.codePath == std::to_string(TYPE_RESERVE) ||
1543         bundleInfo.applicationInfo.codePath == std::to_string(TYPE_OTHERS)) {
1544         resourceManager = InitOthersResourceManagerInner(bundleInfo, selfBundleName == bundleName, moduleName);
1545         if (resourceManager == nullptr) {
1546             TAG_LOGE(AAFwkTag::APPKIT, "InitOthersResourceManagerInner create resourceManager failed");
1547         }
1548         return ERR_INVALID_VALUE;
1549     }
1550 
1551     resourceManager = InitResourceManagerInner(bundleInfo, selfBundleName == bundleName, moduleName);
1552     if (resourceManager == nullptr) {
1553         TAG_LOGE(AAFwkTag::APPKIT, "InitResourceManagerInner create resourceManager failed");
1554         return ERR_INVALID_VALUE;
1555     }
1556 
1557     UpdateResConfig(GetResourceManager(), resourceManager);
1558     return ERR_OK;
1559 }
UpdateDisplayConfiguration(std::shared_ptr<ContextImpl> & contextImpl,uint64_t displayId,float density,std::string direction)1560 bool ContextImpl::UpdateDisplayConfiguration(std::shared_ptr<ContextImpl> &contextImpl, uint64_t displayId,
1561     float density, std::string direction)
1562 {
1563     if (contextImpl == nullptr) {
1564         TAG_LOGE(AAFwkTag::APPKIT, "null contextImpl");
1565         return false;
1566     }
1567 
1568     std::shared_ptr<AppExecFwk::Configuration> newConfiguration = nullptr;
1569     if (config_ == nullptr) {
1570         newConfiguration = std::make_shared<AppExecFwk::Configuration>();
1571     } else {
1572         newConfiguration = std::make_shared<AppExecFwk::Configuration>(*config_);
1573     }
1574     if (newConfiguration == nullptr) {
1575         TAG_LOGE(AAFwkTag::APPKIT, "failed to create configuration");
1576         return false;
1577     }
1578     newConfiguration->AddItem(AppExecFwk::ConfigurationInner::APPLICATION_DISPLAYID, std::to_string(displayId));
1579     newConfiguration->AddItem(displayId, AppExecFwk::ConfigurationInner::APPLICATION_DENSITYDPI,
1580         AppExecFwk::GetDensityStr(density));
1581     newConfiguration->AddItem(displayId, AppExecFwk::ConfigurationInner::APPLICATION_DIRECTION, direction);
1582     contextImpl->config_ = newConfiguration;
1583 
1584     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1585     if (resConfig == nullptr) {
1586         TAG_LOGE(AAFwkTag::APPKIT, "null resConfig");
1587         return false;
1588     }
1589     auto resourceManager = GetResourceManager();
1590     if (resourceManager == nullptr) {
1591         TAG_LOGE(AAFwkTag::APPKIT, "null resource manager");
1592         return false;
1593     }
1594     resourceManager->GetResConfig(*resConfig);
1595     resConfig->SetScreenDensity(density);
1596     resConfig->SetDirection(AppExecFwk::ConvertDirection(direction));
1597     if (contextImpl->resourceManager_ == nullptr) {
1598         TAG_LOGE(AAFwkTag::APPKIT, "null resource manager");
1599         return false;
1600     }
1601     contextImpl->resourceManager_->UpdateResConfig(*resConfig);
1602     return true;
1603 }
1604 
1605 #ifdef SUPPORT_GRAPHICS
CreateDisplayContext(uint64_t displayId)1606 std::shared_ptr<Context> ContextImpl::CreateDisplayContext(uint64_t displayId)
1607 {
1608     float density;
1609     std::string direction;
1610     if (!GetDisplayConfig(displayId, density, direction)) {
1611         TAG_LOGE(AAFwkTag::APPKIT, "failed to get display config");
1612         return nullptr;
1613     }
1614     std::shared_ptr<ContextImpl> contextImpl = std::make_shared<ContextImpl>();
1615     if (contextImpl == nullptr) {
1616         TAG_LOGE(AAFwkTag::APPKIT, "failed to create contextImpl");
1617         return nullptr;
1618     }
1619     ShallowCopySelf(contextImpl);
1620 
1621     auto appContext = ApplicationContext::GetInstance();
1622     if (appContext == nullptr) {
1623         TAG_LOGE(AAFwkTag::APPKIT, "failed to get application context");
1624         return nullptr;
1625     }
1626     std::string currentBundleName = appContext->GetBundleName();
1627     AppExecFwk::BundleInfo bundleInfo;
1628     bool currentBundle = true;
1629     auto result = GetBundleInfo(currentBundleName, bundleInfo, currentBundle);
1630     if (result != ERR_OK) {
1631         TAG_LOGE(AAFwkTag::APPKIT, "failed to get bundle info");
1632         return nullptr;
1633     }
1634     InitResourceManager(bundleInfo, contextImpl, true);
1635     if (contextImpl->resourceManager_ == nullptr) {
1636         TAG_LOGE(AAFwkTag::APPKIT, "failed to init resource manager");
1637         return nullptr;
1638     }
1639     if (!UpdateDisplayConfiguration(contextImpl, displayId, density, direction)) {
1640         TAG_LOGE(AAFwkTag::APPKIT, "failed to Update display configuration");
1641         return nullptr;
1642     }
1643     return contextImpl;
1644 }
1645 
RegisterGetDisplayConfig(GetDisplayConfigCallback getDisplayConfigCallback)1646 void ContextImpl::RegisterGetDisplayConfig(GetDisplayConfigCallback getDisplayConfigCallback)
1647 {
1648     std::lock_guard<std::mutex> lock(getDisplayConfigCallbackMutex_);
1649     getDisplayConfigCallback_ = getDisplayConfigCallback;
1650 }
1651 
GetDisplayConfig(uint64_t displayId,float & density,std::string & directionStr)1652 bool ContextImpl::GetDisplayConfig(uint64_t displayId, float &density, std::string &directionStr)
1653 {
1654     std::lock_guard<std::mutex> lock(getDisplayConfigCallbackMutex_);
1655     if (getDisplayConfigCallback_ == nullptr) {
1656         TAG_LOGE(AAFwkTag::APPKIT, "null ability GetDisplayConfig callback");
1657         return false;
1658     }
1659     return getDisplayConfigCallback_(displayId, density, directionStr);
1660 }
1661 #endif
1662 }  // namespace AbilityRuntime
1663 }  // namespace OHOS
1664