• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 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 "main_thread.h"
17 
18 #include <malloc.h>
19 #include <new>
20 #include <regex>
21 #include <sys/prctl.h>
22 #include <unistd.h>
23 
24 #include "constants.h"
25 #include "ability_delegator.h"
26 #include "ability_delegator_registry.h"
27 #include "ability_loader.h"
28 #include "ability_thread.h"
29 #include "ability_util.h"
30 #include "app_loader.h"
31 #include "app_recovery.h"
32 #include "appfreeze_inner.h"
33 #include "application_data_manager.h"
34 #include "application_env_impl.h"
35 #include "bundle_mgr_proxy.h"
36 #include "hitrace_meter.h"
37 #include "configuration_convertor.h"
38 #include "common_event_manager.h"
39 #include "context_deal.h"
40 #include "context_impl.h"
41 #include "extension_ability_info.h"
42 #include "extension_module_loader.h"
43 #include "extension_plugin_info.h"
44 #include "extract_resource_manager.h"
45 #include "file_path_utils.h"
46 #include "hilog_wrapper.h"
47 #ifdef SUPPORT_GRAPHICS
48 #include "locale_config.h"
49 #endif
50 #include "app_mgr_client.h"
51 #include "if_system_ability_manager.h"
52 #include "iservice_registry.h"
53 #include "js_runtime.h"
54 #include "mix_stack_dumper.h"
55 #include "ohos_application.h"
56 #include "overlay_module_info.h"
57 #include "parameters.h"
58 #include "resource_manager.h"
59 #include "runtime.h"
60 #include "sys_mgr_client.h"
61 #include "system_ability_definition.h"
62 #include "task_handler_client.h"
63 #include "uncaught_exception_callback.h"
64 #include "hisysevent.h"
65 #include "js_runtime_utils.h"
66 #include "context/application_context.h"
67 
68 #if defined(NWEB)
69 #include <thread>
70 #include "app_mgr_client.h"
71 #include "nweb_pre_dns_adapter.h"
72 #include "nweb_helper.h"
73 #endif
74 
75 #ifdef IMAGE_PURGEABLE_PIXELMAP
76 #include "purgeable_resource_manager.h"
77 #endif
78 
79 #if defined(ABILITY_LIBRARY_LOADER) || defined(APPLICATION_LIBRARY_LOADER)
80 #include <dirent.h>
81 #include <dlfcn.h>
82 #endif
83 namespace OHOS {
84 namespace AppExecFwk {
85 using namespace OHOS::AbilityBase::Constants;
86 std::weak_ptr<OHOSApplication> MainThread::applicationForDump_;
87 std::shared_ptr<EventHandler> MainThread::signalHandler_ = nullptr;
88 std::shared_ptr<MainThread::MainHandler> MainThread::mainHandler_ = nullptr;
89 static std::shared_ptr<MixStackDumper> mixStackDumper_ = nullptr;
90 const std::string PERFCMD_PROFILE = "profile";
91 const std::string PERFCMD_DUMPHEAP = "dumpheap";
92 namespace {
93 #ifdef APP_USE_ARM
94 constexpr char FORM_RENDER_LIB_PATH[] = "/system/lib/libformrender.z.so";
95 #else
96 constexpr char FORM_RENDER_LIB_PATH[] = "/system/lib64/libformrender.z.so";
97 #endif
98 
99 constexpr int32_t DELIVERY_TIME = 200;
100 constexpr int32_t DISTRIBUTE_TIME = 100;
101 constexpr int32_t UNSPECIFIED_USERID = -2;
102 constexpr int SIGNAL_JS_HEAP = 39;
103 constexpr int SIGNAL_JS_HEAP_PRIV = 40;
104 
105 constexpr char EVENT_KEY_PACKAGE_NAME[] = "PACKAGE_NAME";
106 constexpr char EVENT_KEY_VERSION[] = "VERSION";
107 constexpr char EVENT_KEY_TYPE[] = "TYPE";
108 constexpr char EVENT_KEY_HAPPEN_TIME[] = "HAPPEN_TIME";
109 constexpr char EVENT_KEY_REASON[] = "REASON";
110 constexpr char EVENT_KEY_JSVM[] = "JSVM";
111 constexpr char EVENT_KEY_SUMMARY[] = "SUMMARY";
112 
113 const int32_t JSCRASH_TYPE = 3;
114 const std::string JSVM_TYPE = "ARK";
115 const std::string SIGNAL_HANDLER = "SignalHandler";
116 
117 constexpr uint32_t CHECK_MAIN_THREAD_IS_ALIVE = 1;
118 
119 const std::string OVERLAY_STATE_CHANGED = "usual.event.OVERLAY_STATE_CHANGED";
120 
GetLibPath(const std::string & hapPath,bool isPreInstallApp)121 std::string GetLibPath(const std::string &hapPath, bool isPreInstallApp)
122 {
123     std::string libPath = LOCAL_CODE_PATH;
124     if (isPreInstallApp) {
125         auto pos = hapPath.rfind("/");
126         libPath = hapPath.substr(0, pos);
127     }
128     return libPath;
129 }
130 
GetHapSoPath(const HapModuleInfo & hapInfo,AppLibPathMap & appLibPaths,bool isPreInstallApp)131 void GetHapSoPath(const HapModuleInfo &hapInfo, AppLibPathMap &appLibPaths, bool isPreInstallApp)
132 {
133     if (hapInfo.nativeLibraryPath.empty()) {
134         HILOG_DEBUG("Lib path of %{public}s is empty, lib isn't isolated or compressed.", hapInfo.moduleName.c_str());
135         return;
136     }
137 
138     std::string appLibPathKey = hapInfo.bundleName + "/" + hapInfo.moduleName;
139     std::string libPath = LOCAL_CODE_PATH;
140     if (!hapInfo.compressNativeLibs) {
141         HILOG_DEBUG("Lib of %{public}s will not be extracted from hap.", hapInfo.moduleName.c_str());
142         libPath = GetLibPath(hapInfo.hapPath, isPreInstallApp);
143     }
144 
145     libPath += (libPath.back() == '/') ? hapInfo.nativeLibraryPath : "/" + hapInfo.nativeLibraryPath;
146     HILOG_INFO("appLibPathKey: %{private}s, lib path: %{private}s", appLibPathKey.c_str(), libPath.c_str());
147     appLibPaths[appLibPathKey].emplace_back(libPath);
148 }
149 
GetHspNativeLibPath(const BaseSharedBundleInfo & hspInfo,AppLibPathMap & appLibPaths,bool isPreInstallApp)150 void GetHspNativeLibPath(const BaseSharedBundleInfo &hspInfo, AppLibPathMap &appLibPaths, bool isPreInstallApp)
151 {
152     if (hspInfo.nativeLibraryPath.empty()) {
153         return;
154     }
155 
156     std::string appLibPathKey = hspInfo.bundleName + "/" + hspInfo.moduleName;
157     std::string libPath = LOCAL_CODE_PATH;
158     if (!hspInfo.compressNativeLibs) {
159         libPath = GetLibPath(hspInfo.hapPath, isPreInstallApp);
160         libPath = libPath.back() == '/' ? libPath : libPath + "/";
161         if (isPreInstallApp) {
162             libPath += hspInfo.nativeLibraryPath;
163         } else {
164             libPath += hspInfo.bundleName + "/" + hspInfo.moduleName + "/" + hspInfo.nativeLibraryPath;
165         }
166     } else {
167         libPath = libPath.back() == '/' ? libPath : libPath + "/";
168         libPath += hspInfo.bundleName + "/" + hspInfo.nativeLibraryPath;
169     }
170 
171     HILOG_DEBUG("appLibPathKey: %{private}s, libPath: %{private}s", appLibPathKey.c_str(), libPath.c_str());
172     appLibPaths[appLibPathKey].emplace_back(libPath);
173 }
174 
GetPatchNativeLibPath(const HapModuleInfo & hapInfo,std::string & patchNativeLibraryPath,AppLibPathMap & appLibPaths)175 void GetPatchNativeLibPath(const HapModuleInfo &hapInfo, std::string &patchNativeLibraryPath,
176     AppLibPathMap &appLibPaths)
177 {
178     if (hapInfo.isLibIsolated) {
179         patchNativeLibraryPath = hapInfo.hqfInfo.nativeLibraryPath;
180     }
181 
182     if (patchNativeLibraryPath.empty()) {
183         HILOG_DEBUG("Patch lib path of %{public}s is empty.", hapInfo.moduleName.c_str());
184         return;
185     }
186 
187     if (hapInfo.compressNativeLibs && !hapInfo.isLibIsolated) {
188         HILOG_DEBUG("Lib of %{public}s has compressed and isn't isolated, no need to set.", hapInfo.moduleName.c_str());
189         return;
190     }
191 
192     std::string appLibPathKey = hapInfo.bundleName + "/" + hapInfo.moduleName;
193     std::string patchLibPath = LOCAL_CODE_PATH;
194     patchLibPath += (patchLibPath.back() == '/') ? patchNativeLibraryPath : "/" + patchNativeLibraryPath;
195     HILOG_INFO("appLibPathKey: %{public}s, patch lib path: %{private}s", appLibPathKey.c_str(), patchLibPath.c_str());
196     appLibPaths[appLibPathKey].emplace_back(patchLibPath);
197 }
198 } // namespace
199 
GetNativeLibPath(const BundleInfo & bundleInfo,const HspList & hspList,AppLibPathMap & appLibPaths)200 void MainThread::GetNativeLibPath(const BundleInfo &bundleInfo, const HspList &hspList, AppLibPathMap &appLibPaths)
201 {
202     std::string patchNativeLibraryPath = bundleInfo.applicationInfo.appQuickFix.deployedAppqfInfo.nativeLibraryPath;
203     if (!patchNativeLibraryPath.empty()) {
204         // libraries in patch lib path has a higher priority when loading.
205         std::string patchLibPath = LOCAL_CODE_PATH;
206         patchLibPath += (patchLibPath.back() == '/') ? patchNativeLibraryPath : "/" + patchNativeLibraryPath;
207         HILOG_INFO("napi patch lib path = %{private}s", patchLibPath.c_str());
208         appLibPaths["default"].emplace_back(patchLibPath);
209     }
210 
211     std::string nativeLibraryPath = bundleInfo.applicationInfo.nativeLibraryPath;
212     if (!nativeLibraryPath.empty()) {
213         if (nativeLibraryPath.back() == '/') {
214             nativeLibraryPath.pop_back();
215         }
216         std::string libPath = LOCAL_CODE_PATH;
217         libPath += (libPath.back() == '/') ? nativeLibraryPath : "/" + nativeLibraryPath;
218         HILOG_INFO("napi lib path = %{private}s", libPath.c_str());
219         appLibPaths["default"].emplace_back(libPath);
220     }
221 
222     for (auto &hapInfo : bundleInfo.hapModuleInfos) {
223         HILOG_DEBUG("moduleName: %{public}s, isLibIsolated: %{public}d, compressNativeLibs: %{public}d.",
224             hapInfo.moduleName.c_str(), hapInfo.isLibIsolated, hapInfo.compressNativeLibs);
225         GetPatchNativeLibPath(hapInfo, patchNativeLibraryPath, appLibPaths);
226         GetHapSoPath(hapInfo, appLibPaths, hapInfo.hapPath.find(ABS_CODE_PATH));
227     }
228 
229     for (auto &hspInfo : hspList) {
230         HILOG_DEBUG("bundle:%s, module:%s, nativeLibraryPath:%s", hspInfo.bundleName.c_str(),
231             hspInfo.moduleName.c_str(), hspInfo.nativeLibraryPath.c_str());
232         GetHspNativeLibPath(hspInfo, appLibPaths, hspInfo.hapPath.find(ABS_CODE_PATH) != 0u);
233     }
234 }
235 
236 #define ACEABILITY_LIBRARY_LOADER
237 #ifdef ABILITY_LIBRARY_LOADER
238     const std::string acelibdir("libace.z.so");
239 #endif
240 
241 /**
242  *
243  * @brief Notify the AppMgrDeathRecipient that the remote is dead.
244  *
245  * @param remote The remote which is dead.
246  */
OnRemoteDied(const wptr<IRemoteObject> & remote)247 void AppMgrDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
248 {
249     HILOG_ERROR("MainThread::AppMgrDeathRecipient remote died receive");
250 }
251 
MainThread()252 MainThread::MainThread()
253 {
254     HILOG_INFO("MainThread");
255 #ifdef ABILITY_LIBRARY_LOADER
256     fileEntries_.clear();
257     nativeFileEntries_.clear();
258     handleAbilityLib_.clear();
259 #endif  // ABILITY_LIBRARY_LOADER
260 }
261 
~MainThread()262 MainThread::~MainThread()
263 {
264     HILOG_INFO("~MainThread");
265     if (watchdog_ != nullptr && !watchdog_->IsStopWatchdog()) {
266         watchdog_->Stop();
267         watchdog_ = nullptr;
268     }
269 }
270 
271 /**
272  *
273  * @brief Get the current MainThreadState.
274  *
275  * @return Returns the current MainThreadState.
276  */
GetMainThreadState() const277 MainThreadState MainThread::GetMainThreadState() const
278 {
279     return mainThreadState_;
280 }
281 
282 /**
283  *
284  * @brief Set the runner state of mainthread.
285  *
286  * @param runnerStart whether the runner is started.
287  */
SetRunnerStarted(bool runnerStart)288 void MainThread::SetRunnerStarted(bool runnerStart)
289 {
290     isRunnerStarted_ = runnerStart;
291 }
292 
293 /**
294  *
295  * @brief Get the runner state of mainthread.
296  *
297  * @return Returns the runner state of mainthread.
298  */
GetRunnerStarted() const299 bool MainThread::GetRunnerStarted() const
300 {
301     return isRunnerStarted_;
302 }
303 
304 /**
305  *
306  * @brief Get the newThreadId.
307  *
308  * @return Returns the newThreadId.
309  */
GetNewThreadId()310 int MainThread::GetNewThreadId()
311 {
312     return newThreadId_++;
313 }
314 
315 /**
316  *
317  * @brief Get the application.
318  *
319  * @return Returns the application.
320  */
GetApplication() const321 std::shared_ptr<OHOSApplication> MainThread::GetApplication() const
322 {
323     return application_;
324 }
325 
326 /**
327  *
328  * @brief Get the applicationInfo.
329  *
330  * @return Returns the applicationInfo.
331  */
GetApplicationInfo() const332 std::shared_ptr<ApplicationInfo> MainThread::GetApplicationInfo() const
333 {
334     return applicationInfo_;
335 }
336 
337 /**
338  *
339  * @brief Get the applicationImpl.
340  *
341  * @return Returns the applicationImpl.
342  */
GetApplicationImpl()343 std::shared_ptr<ApplicationImpl> MainThread::GetApplicationImpl()
344 {
345     return applicationImpl_;
346 }
347 
348 /**
349  *
350  * @brief Connect the mainthread to the AppMgr.
351  *
352  */
ConnectToAppMgr()353 bool MainThread::ConnectToAppMgr()
354 {
355     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
356     HILOG_DEBUG("MainThread ConnectToAppMgr start.");
357     auto object = OHOS::DelayedSingleton<SysMrgClient>::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID);
358     if (object == nullptr) {
359         HILOG_ERROR("failed to get app manager service");
360         return false;
361     }
362     deathRecipient_ = new (std::nothrow) AppMgrDeathRecipient();
363     if (deathRecipient_ == nullptr) {
364         HILOG_ERROR("failed to new AppMgrDeathRecipient");
365         return false;
366     }
367 
368     if (!object->AddDeathRecipient(deathRecipient_)) {
369         HILOG_ERROR("failed to AddDeathRecipient");
370         return false;
371     }
372 
373     appMgr_ = iface_cast<IAppMgr>(object);
374     if (appMgr_ == nullptr) {
375         HILOG_ERROR("failed to iface_cast object to appMgr_");
376         return false;
377     }
378     appMgr_->AttachApplication(this);
379     HILOG_DEBUG("MainThread::connectToAppMgr end");
380     return true;
381 }
382 
383 /**
384  *
385  * @brief Attach the mainthread to the AppMgr.
386  *
387  */
Attach()388 void MainThread::Attach()
389 {
390     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
391     HILOG_DEBUG("Attach");
392     if (!ConnectToAppMgr()) {
393         HILOG_ERROR("attachApplication failed");
394         return;
395     }
396     mainThreadState_ = MainThreadState::ATTACH;
397 }
398 
399 /**
400  *
401  * @brief remove the deathRecipient from appMgr.
402  *
403  */
RemoveAppMgrDeathRecipient()404 void MainThread::RemoveAppMgrDeathRecipient()
405 {
406     HILOG_DEBUG("RemoveAppMgrDeathRecipient");
407     if (appMgr_ == nullptr) {
408         HILOG_ERROR("MainThread::RemoveAppMgrDeathRecipient failed");
409         return;
410     }
411 
412     sptr<IRemoteObject> object = appMgr_->AsObject();
413     if (object != nullptr) {
414         object->RemoveDeathRecipient(deathRecipient_);
415     } else {
416         HILOG_ERROR("appMgr_->AsObject() failed");
417     }
418 }
419 
420 /**
421  *
422  * @brief Get the eventHandler of mainthread.
423  *
424  * @return Returns the eventHandler of mainthread.
425  */
GetMainHandler() const426 std::shared_ptr<EventHandler> MainThread::GetMainHandler() const
427 {
428     return mainHandler_;
429 }
430 
431 /**
432  *
433  * @brief Schedule the foreground lifecycle of application.
434  *
435  */
ScheduleForegroundApplication()436 void MainThread::ScheduleForegroundApplication()
437 {
438     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
439     HILOG_DEBUG("ScheduleForegroundApplication");
440     wptr<MainThread> weak = this;
441     auto task = [weak]() {
442         auto appThread = weak.promote();
443         if (appThread == nullptr) {
444             HILOG_ERROR("appThread is nullptr, HandleForegroundApplication failed.");
445             return;
446         }
447         appThread->HandleForegroundApplication();
448     };
449     if (!mainHandler_->PostTask(task)) {
450         HILOG_ERROR("PostTask task failed");
451     }
452     watchdog_->SetBackgroundStatus(false);
453 }
454 
455 /**
456  *
457  * @brief Schedule the background lifecycle of application.
458  *
459  */
ScheduleBackgroundApplication()460 void MainThread::ScheduleBackgroundApplication()
461 {
462     HILOG_DEBUG("ScheduleBackgroundApplication");
463     wptr<MainThread> weak = this;
464     auto task = [weak]() {
465         auto appThread = weak.promote();
466         if (appThread == nullptr) {
467             HILOG_ERROR("appThread is nullptr, HandleBackgroundApplication failed.");
468             return;
469         }
470         appThread->HandleBackgroundApplication();
471     };
472     if (!mainHandler_->PostTask(task)) {
473         HILOG_ERROR("MainThread::ScheduleBackgroundApplication PostTask task failed");
474     }
475     watchdog_->SetBackgroundStatus(true);
476 }
477 
478 /**
479  *
480  * @brief Schedule the terminate lifecycle of application.
481  *
482  */
ScheduleTerminateApplication()483 void MainThread::ScheduleTerminateApplication()
484 {
485     HILOG_DEBUG("ScheduleTerminateApplication");
486     wptr<MainThread> weak = this;
487     auto task = [weak]() {
488         auto appThread = weak.promote();
489         if (appThread == nullptr) {
490             HILOG_ERROR("appThread is nullptr, HandleTerminateApplication failed.");
491             return;
492         }
493         appThread->HandleTerminateApplication();
494     };
495     if (!mainHandler_->PostTask(task)) {
496         HILOG_ERROR("MainThread::ScheduleTerminateApplication PostTask task failed");
497     }
498 }
499 
500 /**
501  *
502  * @brief Shrink the memory which used by application.
503  *
504  * @param level Indicates the memory trim level, which shows the current memory usage status.
505  */
ScheduleShrinkMemory(const int level)506 void MainThread::ScheduleShrinkMemory(const int level)
507 {
508     HILOG_DEBUG("scheduleShrinkMemory level: %{public}d", level);
509     wptr<MainThread> weak = this;
510     auto task = [weak, level]() {
511         auto appThread = weak.promote();
512         if (appThread == nullptr) {
513             HILOG_ERROR("appThread is nullptr, HandleShrinkMemory failed.");
514             return;
515         }
516         appThread->HandleShrinkMemory(level);
517     };
518     if (!mainHandler_->PostTask(task)) {
519         HILOG_ERROR("MainThread::ScheduleShrinkMemory PostTask task failed");
520     }
521 }
522 
523 /**
524  *
525  * @brief Notify the memory level.
526  *
527  * @param level Indicates the memory trim level, which shows the current memory usage status.
528  */
ScheduleMemoryLevel(const int level)529 void MainThread::ScheduleMemoryLevel(const int level)
530 {
531     HILOG_DEBUG("ScheduleMemoryLevel level: %{public}d", level);
532     wptr<MainThread> weak = this;
533     auto task = [weak, level]() {
534         auto appThread = weak.promote();
535         if (appThread == nullptr) {
536             HILOG_ERROR("appThread is nullptr, HandleMemoryLevel failed.");
537             return;
538         }
539         appThread->HandleMemoryLevel(level);
540     };
541     if (!mainHandler_->PostTask(task)) {
542         HILOG_ERROR("MainThread::ScheduleMemoryLevel PostTask task failed");
543     }
544 }
545 
546 /**
547  *
548  * @brief Get the application's memory allocation info.
549  *
550  * @param pid, pid input.
551  * @param mallocInfo, dynamic storage information output.
552  */
ScheduleHeapMemory(const int32_t pid,OHOS::AppExecFwk::MallocInfo & mallocInfo)553 void MainThread::ScheduleHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)
554 {
555     struct mallinfo mi = mallinfo();
556     int usmblks = mi.usmblks; // 当前从分配器中分配的总的堆内存大小
557     int uordblks = mi.uordblks; // 当前已释放给分配器,分配缓存了未释放给系统的内存大小
558     int fordblks = mi.fordblks; // 当前未释放的大小
559     HILOG_DEBUG("The pid of the app we want to dump memory allocation information is: %{public}i", pid);
560     HILOG_DEBUG("usmblks: %{public}i, uordblks: %{public}i, fordblks: %{public}i", usmblks, uordblks, fordblks);
561     mallocInfo.usmblks = usmblks;
562     mallocInfo.uordblks = uordblks;
563     mallocInfo.fordblks = fordblks;
564 }
565 
566 /**
567  *
568  * @brief Schedule the application process exit safely.
569  *
570  */
ScheduleProcessSecurityExit()571 void MainThread::ScheduleProcessSecurityExit()
572 {
573     HILOG_DEBUG("ScheduleProcessSecurityExit called");
574     wptr<MainThread> weak = this;
575     auto task = [weak]() {
576         auto appThread = weak.promote();
577         if (appThread == nullptr) {
578             HILOG_ERROR("appThread is nullptr, ScheduleProcessSecurityExit failed.");
579             return;
580         }
581         appThread->HandleProcessSecurityExit();
582     };
583     bool result = mainHandler_->PostTask(task);
584     if (!result) {
585         HILOG_ERROR("ScheduleProcessSecurityExit post task failed");
586     }
587 }
588 
589 /**
590  *
591  * @brief Low the memory which used by application.
592  *
593  */
ScheduleLowMemory()594 void MainThread::ScheduleLowMemory()
595 {
596     HILOG_DEBUG("MainThread::scheduleLowMemory called");
597 }
598 
599 /**
600  *
601  * @brief Launch the application.
602  *
603  * @param data The launchdata of the application witch launced.
604  *
605  */
ScheduleLaunchApplication(const AppLaunchData & data,const Configuration & config)606 void MainThread::ScheduleLaunchApplication(const AppLaunchData &data, const Configuration &config)
607 {
608     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
609     HILOG_DEBUG("MainThread schedule launch application start.");
610     wptr<MainThread> weak = this;
611     auto task = [weak, data, config]() {
612         auto appThread = weak.promote();
613         if (appThread == nullptr) {
614             HILOG_ERROR("appThread is nullptr, HandleLaunchApplication failed.");
615             return;
616         }
617         appThread->HandleLaunchApplication(data, config);
618     };
619     if (!mainHandler_->PostTask(task)) {
620         HILOG_ERROR("MainThread::ScheduleLaunchApplication PostTask task failed");
621     }
622 }
623 
624 /**
625  *
626  * @brief update the application info after new module installed.
627  *
628  * @param appInfo The latest application info obtained from bms for update abilityRuntimeContext.
629  *
630  */
ScheduleUpdateApplicationInfoInstalled(const ApplicationInfo & appInfo)631 void MainThread::ScheduleUpdateApplicationInfoInstalled(const ApplicationInfo &appInfo)
632 {
633     HILOG_DEBUG("ScheduleUpdateApplicationInfoInstalled");
634     wptr<MainThread> weak = this;
635     auto task = [weak, appInfo]() {
636         auto appThread = weak.promote();
637         if (appThread == nullptr) {
638             HILOG_ERROR("appThread is nullptr, HandleUpdateApplicationInfoInstalled failed.");
639             return;
640         }
641         appThread->HandleUpdateApplicationInfoInstalled(appInfo);
642     };
643     if (!mainHandler_->PostTask(task)) {
644         HILOG_ERROR("MainThread::ScheduleUpdateApplicationInfoInstalled PostTask task failed");
645     }
646 }
647 
ScheduleAbilityStage(const HapModuleInfo & abilityStage)648 void MainThread::ScheduleAbilityStage(const HapModuleInfo &abilityStage)
649 {
650     HILOG_DEBUG("ScheduleAbilityStage");
651     wptr<MainThread> weak = this;
652     auto task = [weak, abilityStage]() {
653         auto appThread = weak.promote();
654         if (appThread == nullptr) {
655             HILOG_ERROR("appThread is nullptr, HandleShrinkMemory failed.");
656             return;
657         }
658         appThread->HandleAbilityStage(abilityStage);
659     };
660     if (!mainHandler_->PostTask(task)) {
661         HILOG_ERROR("MainThread::ScheduleAbilityStageInfo PostTask task failed");
662     }
663 }
664 
ScheduleLaunchAbility(const AbilityInfo & info,const sptr<IRemoteObject> & token,const std::shared_ptr<AAFwk::Want> & want)665 void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr<IRemoteObject> &token,
666     const std::shared_ptr<AAFwk::Want> &want)
667 {
668     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
669     HILOG_DEBUG("schedule launch ability %{public}s, type is %{public}d.", info.name.c_str(), info.type);
670 
671     AAFwk::Want newWant(*want);
672     newWant.CloseAllFd();
673     std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>(info);
674     std::shared_ptr<AbilityLocalRecord> abilityRecord = std::make_shared<AbilityLocalRecord>(abilityInfo, token);
675     abilityRecord->SetWant(want);
676 
677     wptr<MainThread> weak = this;
678     auto task = [weak, abilityRecord]() {
679         auto appThread = weak.promote();
680         if (appThread == nullptr) {
681             HILOG_ERROR("appThread is nullptr, HandleLaunchAbility failed.");
682             return;
683         }
684         appThread->HandleLaunchAbility(abilityRecord);
685     };
686     if (!mainHandler_->PostTask(task)) {
687         HILOG_ERROR("MainThread::ScheduleLaunchAbility PostTask task failed");
688     }
689 }
690 
691 /**
692  *
693  * @brief clean the ability by token.
694  *
695  * @param token The token belong to the ability which want to be cleaned.
696  *
697  */
ScheduleCleanAbility(const sptr<IRemoteObject> & token)698 void MainThread::ScheduleCleanAbility(const sptr<IRemoteObject> &token)
699 {
700     HILOG_DEBUG("Schedule clean ability called.");
701     wptr<MainThread> weak = this;
702     auto task = [weak, token]() {
703         auto appThread = weak.promote();
704         if (appThread == nullptr) {
705             HILOG_ERROR("appThread is nullptr, HandleCleanAbility failed.");
706             return;
707         }
708         appThread->HandleCleanAbility(token);
709     };
710     if (!mainHandler_->PostTask(task)) {
711         HILOG_ERROR("MainThread::ScheduleCleanAbility PostTask task failed");
712     }
713 }
714 
715 /**
716  *
717  * @brief send the new profile.
718  *
719  * @param profile The updated profile.
720  *
721  */
ScheduleProfileChanged(const Profile & profile)722 void MainThread::ScheduleProfileChanged(const Profile &profile)
723 {
724     HILOG_DEBUG("MainThread::scheduleProfileChanged profile name: %{public}s", profile.GetName().c_str());
725 }
726 
727 /**
728  *
729  * @brief send the new config to the application.
730  *
731  * @param config The updated config.
732  *
733  */
ScheduleConfigurationUpdated(const Configuration & config)734 void MainThread::ScheduleConfigurationUpdated(const Configuration &config)
735 {
736     HILOG_DEBUG("ScheduleConfigurationUpdated");
737     wptr<MainThread> weak = this;
738     auto task = [weak, config]() {
739         auto appThread = weak.promote();
740         if (appThread == nullptr) {
741             HILOG_ERROR("appThread is nullptr, HandleConfigurationUpdated failed.");
742             return;
743         }
744         appThread->HandleConfigurationUpdated(config);
745     };
746     if (!mainHandler_->PostTask(task)) {
747         HILOG_ERROR("MainThread::ScheduleConfigurationUpdated PostTask task failed");
748     }
749 }
750 
CheckLaunchApplicationParam(const AppLaunchData & appLaunchData) const751 bool MainThread::CheckLaunchApplicationParam(const AppLaunchData &appLaunchData) const
752 {
753     ApplicationInfo appInfo = appLaunchData.GetApplicationInfo();
754     ProcessInfo processInfo = appLaunchData.GetProcessInfo();
755 
756     if (appInfo.name.empty()) {
757         HILOG_ERROR("MainThread::checkLaunchApplicationParam applicationName is empty");
758         return false;
759     }
760 
761     if (processInfo.GetProcessName().empty()) {
762         HILOG_ERROR("MainThread::checkLaunchApplicationParam processName is empty");
763         return false;
764     }
765     return true;
766 }
767 
768 /**
769  *
770  * @brief Check whether the record is legal.
771  *
772  * @param record The record should be checked.
773  *
774  * @return if the record is legal, return true. else return false.
775  */
CheckAbilityItem(const std::shared_ptr<AbilityLocalRecord> & record) const776 bool MainThread::CheckAbilityItem(const std::shared_ptr<AbilityLocalRecord> &record) const
777 {
778     if (record == nullptr) {
779         HILOG_ERROR("MainThread::checkAbilityItem record is null");
780         return false;
781     }
782 
783     std::shared_ptr<AbilityInfo> abilityInfo = record->GetAbilityInfo();
784     sptr<IRemoteObject> token = record->GetToken();
785 
786     if (abilityInfo == nullptr) {
787         HILOG_ERROR("MainThread::checkAbilityItem abilityInfo is null");
788         return false;
789     }
790 
791     if (token == nullptr) {
792         HILOG_ERROR("MainThread::checkAbilityItem token is null");
793         return false;
794     }
795     return true;
796 }
797 
798 /**
799  *
800  * @brief Terminate the application but don't notify ams.
801  *
802  */
HandleTerminateApplicationLocal()803 void MainThread::HandleTerminateApplicationLocal()
804 {
805     HILOG_DEBUG("HandleTerminateApplicationLocal");
806     if (application_ == nullptr) {
807         HILOG_ERROR("MainThread::HandleTerminateApplicationLocal error!");
808         return;
809     }
810     applicationImpl_->PerformTerminateStrong();
811 
812     std::shared_ptr<EventRunner> signalRunner = signalHandler_->GetEventRunner();
813     if (signalRunner) {
814         signalRunner->Stop();
815     }
816 
817     std::shared_ptr<EventRunner> runner = mainHandler_->GetEventRunner();
818     if (runner == nullptr) {
819         HILOG_ERROR("MainThread::HandleTerminateApplicationLocal get manHandler error");
820         return;
821     }
822 
823     if (watchdog_ != nullptr && !watchdog_->IsStopWatchdog()) {
824         watchdog_->Stop();
825         watchdog_ = nullptr;
826     }
827 
828     int ret = runner->Stop();
829     if (ret != ERR_OK) {
830         HILOG_ERROR("MainThread::HandleTerminateApplicationLocal failed. runner->Run failed ret = %{public}d", ret);
831     }
832     HILOG_DEBUG("runner is stopped");
833     SetRunnerStarted(false);
834 }
835 
836 /**
837  *
838  * @brief Schedule the application process exit safely.
839  *
840  */
HandleProcessSecurityExit()841 void MainThread::HandleProcessSecurityExit()
842 {
843     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
844     HILOG_DEBUG("HandleProcessSecurityExit");
845     if (abilityRecordMgr_ == nullptr) {
846         HILOG_ERROR("MainThread::HandleProcessSecurityExit abilityRecordMgr_ is null");
847         return;
848     }
849 
850     std::vector<sptr<IRemoteObject>> tokens = (abilityRecordMgr_->GetAllTokens());
851 
852     for (auto iter = tokens.begin(); iter != tokens.end(); ++iter) {
853         HandleCleanAbilityLocal(*iter);
854     }
855 
856     HandleTerminateApplicationLocal();
857 }
858 
InitCreate(std::shared_ptr<ContextDeal> & contextDeal,ApplicationInfo & appInfo,ProcessInfo & processInfo)859 bool MainThread::InitCreate(
860     std::shared_ptr<ContextDeal> &contextDeal, ApplicationInfo &appInfo, ProcessInfo &processInfo)
861 {
862     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
863     // get application shared point
864     application_ = std::shared_ptr<OHOSApplication>(ApplicationLoader::GetInstance().GetApplicationByName());
865     if (application_ == nullptr) {
866         HILOG_ERROR("InitCreate application create failed");
867         return false;
868     }
869 
870     applicationInfo_ = std::make_shared<ApplicationInfo>(appInfo);
871     if (applicationInfo_ == nullptr) {
872         HILOG_ERROR("MainThread::InitCreate create applicationInfo_ failed");
873         return false;
874     }
875 
876     processInfo_ = std::make_shared<ProcessInfo>(processInfo);
877     if (processInfo_ == nullptr) {
878         HILOG_ERROR("MainThread::InitCreate create processInfo_ failed");
879         return false;
880     }
881 
882     applicationImpl_ = std::make_shared<ApplicationImpl>();
883     if (applicationImpl_ == nullptr) {
884         HILOG_ERROR("MainThread::InitCreate create applicationImpl_ failed");
885         return false;
886     }
887 
888     abilityRecordMgr_ = std::make_shared<AbilityRecordMgr>();
889     if (abilityRecordMgr_ == nullptr) {
890         HILOG_ERROR("MainThread::InitCreate create AbilityRecordMgr failed");
891         return false;
892     }
893 
894     contextDeal = std::make_shared<ContextDeal>();
895     if (contextDeal == nullptr) {
896         HILOG_ERROR("MainThread::InitCreate create contextDeal failed");
897         return false;
898     }
899     AppExecFwk::AppfreezeInner::GetInstance()->SetApplicationInfo(applicationInfo_);
900 
901     application_->SetProcessInfo(processInfo_);
902     contextDeal->SetApplicationInfo(applicationInfo_);
903     contextDeal->SetBundleCodePath(applicationInfo_->codePath);  // BMS need to add cpath
904 
905     return true;
906 }
907 
CheckForHandleLaunchApplication(const AppLaunchData & appLaunchData)908 bool MainThread::CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData)
909 {
910     if (application_ != nullptr) {
911         HILOG_ERROR("MainThread::handleLaunchApplication already create application");
912         return false;
913     }
914 
915     if (!CheckLaunchApplicationParam(appLaunchData)) {
916         HILOG_ERROR("MainThread::handleLaunchApplication appLaunchData invalid");
917         return false;
918     }
919     return true;
920 }
921 
InitResourceManager(std::shared_ptr<Global::Resource::ResourceManager> & resourceManager,const AppExecFwk::HapModuleInfo & entryHapModuleInfo,const std::string & bundleName,bool multiProjects,const Configuration & config)922 bool MainThread::InitResourceManager(std::shared_ptr<Global::Resource::ResourceManager> &resourceManager,
923     const AppExecFwk::HapModuleInfo &entryHapModuleInfo, const std::string &bundleName,
924     bool multiProjects, const Configuration &config)
925 {
926     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
927     bool isStageBased = entryHapModuleInfo.isStageBasedModel;
928     if (isStageBased && multiProjects) {
929         HILOG_INFO("MainThread::InitResourceManager for multiProjects.");
930     } else {
931         std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + bundleName);
932         std::string loadPath =
933             (!entryHapModuleInfo.hapPath.empty()) ? entryHapModuleInfo.hapPath : entryHapModuleInfo.resourcePath;
934         if (!loadPath.empty()) {
935             loadPath = std::regex_replace(loadPath, pattern, std::string(LOCAL_CODE_PATH));
936             HILOG_DEBUG("ModuleResPath: %{public}s", loadPath.c_str());
937             // getOverlayPath
938             auto res = GetOverlayModuleInfos(bundleName, entryHapModuleInfo.moduleName, overlayModuleInfos_);
939             if (res != ERR_OK) {
940                 HILOG_WARN("Get overlay paths from bms failed.");
941             }
942             if (overlayModuleInfos_.size() == 0) {
943                 if (!resourceManager->AddResource(loadPath.c_str())) {
944                     HILOG_ERROR("AddResource failed");
945                 }
946             } else {
947                 std::vector<std::string> overlayPaths;
948                 for (auto it : overlayModuleInfos_) {
949                     if (std::regex_search(it.hapPath, std::regex(bundleName))) {
950                         it.hapPath = std::regex_replace(it.hapPath, pattern, std::string(LOCAL_CODE_PATH));
951                     } else {
952                         it.hapPath = std::regex_replace(it.hapPath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES);
953                     }
954                     if (it.state == OverlayState::OVERLAY_ENABLE) {
955                         HILOG_DEBUG("InitResourceManager hapPath: %{public}s", it.hapPath.c_str());
956                         overlayPaths.emplace_back(it.hapPath);
957                     }
958                 }
959                 HILOG_DEBUG("OverlayPaths size:%{public}zu.", overlayPaths.size());
960                 if (!resourceManager->AddResource(loadPath, overlayPaths)) {
961                     HILOG_ERROR("AddResource failed");
962                 }
963                 // add listen overlay change
964                 EventFwk::MatchingSkills matchingSkills;
965                 matchingSkills.AddEvent(OVERLAY_STATE_CHANGED);
966                 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
967                 subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
968                 wptr<MainThread> weak = this;
969                 auto callback = [weak, resourceManager, bundleName, moduleName = entryHapModuleInfo.moduleName,
970                     loadPath](const EventFwk::CommonEventData &data) {
971                     HILOG_DEBUG("On overlay changed.");
972                     auto appThread = weak.promote();
973                     if (appThread == nullptr) {
974                         HILOG_ERROR("abilityThread is nullptr, SetRunnerStarted failed.");
975                         return;
976                     }
977                     appThread->OnOverlayChanged(data, resourceManager, bundleName, moduleName, loadPath);
978                 };
979                 auto subscriber = std::make_shared<OverlayEventSubscriber>(subscribeInfo, callback);
980                 bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber);
981                 HILOG_DEBUG("Overlay event subscriber register result is %{public}d", subResult);
982             }
983         }
984     }
985 
986     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
987 #ifdef SUPPORT_GRAPHICS
988     UErrorCode status = U_ZERO_ERROR;
989     icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status);
990     resConfig->SetLocaleInfo(locale);
991     const icu::Locale *localeInfo = resConfig->GetLocaleInfo();
992     if (localeInfo != nullptr) {
993         HILOG_INFO("Language: %{public}s, script: %{public}s, region: %{public}s",
994             localeInfo->getLanguage(), localeInfo->getScript(), localeInfo->getCountry());
995     }
996 #endif
997     std::string colormode = config.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
998     HILOG_DEBUG("Colormode is %{public}s.", colormode.c_str());
999     resConfig->SetColorMode(ConvertColorMode(colormode));
1000 
1001     std::string hasPointerDevice = config.GetItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
1002     HILOG_DEBUG("HasPointerDevice is %{public}s.", hasPointerDevice.c_str());
1003     resConfig->SetInputDevice(ConvertHasPointerDevice(hasPointerDevice));
1004 
1005     std::string deviceType = config.GetItem(AAFwk::GlobalConfigurationKey::DEVICE_TYPE);
1006     HILOG_DEBUG("deviceType is %{public}s <---->  %{public}d.", deviceType.c_str(), ConvertDeviceType(deviceType));
1007     resConfig->SetDeviceType(ConvertDeviceType(deviceType));
1008     resourceManager->UpdateResConfig(*resConfig);
1009     return true;
1010 }
1011 
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)1012 void MainThread::OnOverlayChanged(const EventFwk::CommonEventData &data,
1013     const std::shared_ptr<Global::Resource::ResourceManager> &resourceManager, const std::string &bundleName,
1014     const std::string &moduleName, const std::string &loadPath)
1015 {
1016     HILOG_DEBUG("OnOverlayChanged begin.");
1017     if (mainHandler_ == nullptr) {
1018         HILOG_ERROR("mainHandler is nullptr.");
1019         return;
1020     }
1021     wptr<MainThread> weak = this;
1022     auto task = [weak, data, resourceManager, bundleName, moduleName, loadPath]() {
1023         auto appThread = weak.promote();
1024         if (appThread == nullptr) {
1025             HILOG_ERROR("abilityThread is nullptr, SetRunnerStarted failed.");
1026             return;
1027         }
1028         appThread->HandleOnOverlayChanged(data, resourceManager, bundleName, moduleName, loadPath);
1029     };
1030     if (!mainHandler_->PostTask(task)) {
1031         HILOG_ERROR("MainThread::ScheduleConfigurationUpdated PostTask task failed");
1032     }
1033 }
1034 
HandleOnOverlayChanged(const EventFwk::CommonEventData & data,const std::shared_ptr<Global::Resource::ResourceManager> & resourceManager,const std::string & bundleName,const std::string & moduleName,const std::string & loadPath)1035 void MainThread::HandleOnOverlayChanged(const EventFwk::CommonEventData &data,
1036     const std::shared_ptr<Global::Resource::ResourceManager> &resourceManager, const std::string &bundleName,
1037     const std::string &moduleName, const std::string &loadPath)
1038 {
1039     HILOG_DEBUG("HandleOnOverlayChanged begin.");
1040     auto want = data.GetWant();
1041     std::string action = want.GetAction();
1042     if (action != OVERLAY_STATE_CHANGED) {
1043         HILOG_DEBUG("Not this subscribe, action: %{public}s.", action.c_str());
1044         return;
1045     }
1046     bool isEnable = data.GetWant().GetBoolParam(Constants::OVERLAY_STATE, false);
1047     // 1.get overlay hapPath
1048     if (resourceManager == nullptr) {
1049         HILOG_ERROR("resourceManager is nullptr");
1050         return;
1051     }
1052     std::vector<OverlayModuleInfo> overlayModuleInfos;
1053     auto res = GetOverlayModuleInfos(bundleName, moduleName, overlayModuleInfos);
1054     if (res != ERR_OK) {
1055         return;
1056     }
1057 
1058     // 2.add/remove overlay hapPath
1059     if (loadPath.empty() || overlayModuleInfos.size() == 0) {
1060         HILOG_WARN("There is not any hapPath in overlayModuleInfo");
1061     } else {
1062         if (isEnable) {
1063             std::vector<std::string> overlayPaths = GetAddOverlayPaths(overlayModuleInfos);
1064             if (!resourceManager->AddResource(loadPath, overlayPaths)) {
1065                 HILOG_ERROR("AddResource failed");
1066             }
1067         } else {
1068             std::vector<std::string> overlayPaths = GetRemoveOverlayPaths(overlayModuleInfos);
1069             if (!resourceManager->RemoveResource(loadPath, overlayPaths)) {
1070                 HILOG_ERROR("RemoveResource failed");
1071             }
1072         }
1073     }
1074 }
GetNativeStrFromJsTaggedObj(NativeObject * obj,const char * key)1075 [[maybe_unused]] static std::string GetNativeStrFromJsTaggedObj(NativeObject* obj, const char* key)
1076 {
1077     if (obj == nullptr) {
1078         HILOG_ERROR("Failed to get value from key:%{public}s, Null NativeObject", key);
1079         return "";
1080     }
1081 
1082     NativeValue* value = obj->GetProperty(key);
1083     NativeString* valueStr = AbilityRuntime::ConvertNativeValueTo<NativeString>(value);
1084     if (valueStr == nullptr) {
1085         HILOG_ERROR("Failed to convert value from key:%{public}s", key);
1086         return "";
1087     }
1088     size_t valueStrBufLength = valueStr->GetLength();
1089     size_t valueStrLength = 0;
1090     char* valueCStr = new (std::nothrow) char[valueStrBufLength + 1];
1091     if (valueCStr == nullptr) {
1092         HILOG_ERROR("Failed to new valueCStr");
1093         return "";
1094     }
1095     valueStr->GetCString(valueCStr, valueStrBufLength + 1, &valueStrLength);
1096     std::string ret(valueCStr, valueStrLength);
1097     delete []valueCStr;
1098     HILOG_DEBUG("GetNativeStrFromJsTaggedObj Success %{public}s:%{public}s", key, ret.c_str());
1099     return ret;
1100 }
1101 
IsNeedLoadLibrary(const std::string & bundleName)1102 bool IsNeedLoadLibrary(const std::string &bundleName)
1103 {
1104     std::vector<std::string> needLoadLibraryBundleNames{
1105         "com.ohos.contactsdataability",
1106         "com.ohos.medialibrary.medialibrarydata",
1107         "com.ohos.telephonydataability",
1108         "com.ohos.FusionSearch",
1109         "com.ohos.formrenderservice"
1110     };
1111 
1112     for (const auto &item : needLoadLibraryBundleNames) {
1113         if (item == bundleName) {
1114             return true;
1115         }
1116     }
1117     return false;
1118 }
1119 
GetBundleForLaunchApplication(sptr<IBundleMgr> bundleMgr,const std::string & bundleName,int32_t appIndex,BundleInfo & bundleInfo)1120 bool GetBundleForLaunchApplication(sptr<IBundleMgr> bundleMgr, const std::string &bundleName,
1121     int32_t appIndex, BundleInfo &bundleInfo)
1122 {
1123     bool queryResult;
1124     if (appIndex != 0) {
1125         HILOG_INFO("bundleName = %{public}s", bundleName.c_str());
1126         queryResult = (bundleMgr->GetSandboxBundleInfo(bundleName,
1127             appIndex, UNSPECIFIED_USERID, bundleInfo) == 0);
1128     } else {
1129         HILOG_INFO("bundleName = %{public}s", bundleName.c_str());
1130         queryResult = (bundleMgr->GetBundleInfoForSelf(
1131             (static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) +
1132             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) +
1133             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE) +
1134             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) +
1135             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) +
1136             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY) +
1137             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_METADATA)), bundleInfo) == ERR_OK);
1138     }
1139     return queryResult;
1140 }
1141 
1142 /**
1143  *
1144  * @brief Launch the application.
1145  *
1146  * @param appLaunchData The launchdata of the application witch launced.
1147  *
1148  */
HandleLaunchApplication(const AppLaunchData & appLaunchData,const Configuration & config)1149 void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, const Configuration &config)
1150 {
1151     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1152     HILOG_DEBUG("MainThread handle launch application start.");
1153     if (!CheckForHandleLaunchApplication(appLaunchData)) {
1154         HILOG_ERROR("MainThread::handleLaunchApplication CheckForHandleLaunchApplication failed");
1155         return;
1156     }
1157 
1158     auto appInfo = appLaunchData.GetApplicationInfo();
1159     ProcessInfo processInfo = appLaunchData.GetProcessInfo();
1160     HILOG_DEBUG("MainThread handle launch application, InitCreate Start.");
1161     std::shared_ptr<ContextDeal> contextDeal;
1162     if (!InitCreate(contextDeal, appInfo, processInfo)) {
1163         HILOG_ERROR("MainThread::handleLaunchApplication InitCreate failed");
1164         return;
1165     }
1166     sptr<IBundleMgr> bundleMgr = contextDeal->GetBundleManager();
1167     if (bundleMgr == nullptr) {
1168         HILOG_ERROR("MainThread::handleLaunchApplication GetBundleManager is nullptr");
1169         return;
1170     }
1171 
1172     auto bundleName = appInfo.bundleName;
1173     BundleInfo bundleInfo;
1174     if (!GetBundleForLaunchApplication(bundleMgr, bundleName, appLaunchData.GetAppIndex(), bundleInfo)) {
1175         HILOG_ERROR("HandleLaunchApplication GetBundleInfo failed!");
1176         return;
1177     }
1178 
1179     if (IsNeedLoadLibrary(bundleName)) {
1180         std::vector<std::string> localPaths;
1181         ChangeToLocalPath(bundleName, appInfo.moduleSourceDirs, localPaths);
1182         LoadAbilityLibrary(localPaths);
1183         LoadNativeLiabrary(bundleInfo, appInfo.nativeLibraryPath);
1184     }
1185     if (appInfo.needAppDetail) {
1186         HILOG_DEBUG("MainThread::handleLaunchApplication %{public}s need add app detail ability library path",
1187             bundleName.c_str());
1188         LoadAppDetailAbilityLibrary(appInfo.appDetailAbilityLibraryPath);
1189     }
1190     LoadAppLibrary();
1191 
1192     applicationForDump_ = application_;
1193     mixStackDumper_ = std::make_shared<MixStackDumper>();
1194     if (!mixStackDumper_->IsInstalled()) {
1195         mixStackDumper_->InstallDumpHandler(application_, signalHandler_);
1196     }
1197 
1198     bool moduelJson = false;
1199     bool isStageBased = false;
1200     bool findEntryHapModuleInfo = false;
1201     AppExecFwk::HapModuleInfo entryHapModuleInfo;
1202     if (!bundleInfo.hapModuleInfos.empty()) {
1203         for (auto hapModuleInfo : bundleInfo.hapModuleInfos) {
1204             if (hapModuleInfo.moduleType == AppExecFwk::ModuleType::ENTRY) {
1205                 findEntryHapModuleInfo = true;
1206                 entryHapModuleInfo = hapModuleInfo;
1207                 break;
1208             }
1209         }
1210         if (!findEntryHapModuleInfo) {
1211             HILOG_WARN("HandleLaunchApplication find entry hap module info failed!");
1212             entryHapModuleInfo = bundleInfo.hapModuleInfos.back();
1213         }
1214         moduelJson = entryHapModuleInfo.isModuleJson;
1215         isStageBased = entryHapModuleInfo.isStageBasedModel;
1216     }
1217     if (isStageBased) {
1218         AppRecovery::GetInstance().InitApplicationInfo(GetMainHandler(), GetApplicationInfo());
1219     }
1220     HILOG_DEBUG("stageBased:%{public}d moduleJson:%{public}d size:%{public}zu",
1221         isStageBased, moduelJson, bundleInfo.hapModuleInfos.size());
1222 
1223     // create contextImpl
1224     std::shared_ptr<AbilityRuntime::ContextImpl> contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
1225     contextImpl->SetApplicationInfo(std::make_shared<ApplicationInfo>(appInfo));
1226     std::shared_ptr<AbilityRuntime::ApplicationContext> applicationContext =
1227         AbilityRuntime::ApplicationContext::GetInstance();
1228     applicationContext->AttachContextImpl(contextImpl);
1229     application_->SetApplicationContext(applicationContext);
1230 
1231     HspList hspList;
1232     ErrCode ret = bundleMgr->GetBaseSharedBundleInfos(appInfo.bundleName, hspList);
1233     if (ret != ERR_OK) {
1234         HILOG_ERROR("GetBaseSharedBundleInfos failed: %{public}d", ret);
1235     }
1236     AppLibPathMap appLibPaths {};
1237     GetNativeLibPath(bundleInfo, hspList, appLibPaths);
1238     bool isSystemApp = bundleInfo.applicationInfo.isSystemApp;
1239     HILOG_DEBUG("the application isSystemApp: %{public}d", isSystemApp);
1240     AbilityRuntime::JsRuntime::SetAppLibPath(appLibPaths, isSystemApp);
1241 
1242     if (isStageBased) {
1243         // Create runtime
1244         auto hapPath = entryHapModuleInfo.hapPath;
1245         auto moduleName = entryHapModuleInfo.moduleName;
1246         AbilityRuntime::Runtime::Options options;
1247         options.bundleName = appInfo.bundleName;
1248         options.codePath = LOCAL_CODE_PATH;
1249         options.hapPath = hapPath;
1250         options.moduleName = moduleName;
1251         options.eventRunner = mainHandler_->GetEventRunner();
1252         options.loadAce = true;
1253         options.isBundle = (entryHapModuleInfo.compileMode != AppExecFwk::CompileMode::ES_MODULE);
1254         options.isDebugVersion = bundleInfo.applicationInfo.debug;
1255         options.arkNativeFilePath = bundleInfo.applicationInfo.arkNativeFilePath;
1256         options.uid = bundleInfo.applicationInfo.uid;
1257         options.apiTargetVersion = appInfo.apiTargetVersion;
1258         auto runtime = AbilityRuntime::Runtime::Create(options);
1259         if (!runtime) {
1260             HILOG_ERROR("Failed to create runtime");
1261             return;
1262         }
1263         auto& jsEngine = (static_cast<AbilityRuntime::JsRuntime&>(*runtime)).GetNativeEngine();
1264         auto bundleName = appInfo.bundleName;
1265         auto versionCode = appInfo.versionCode;
1266         JsEnv::UncaughtExceptionInfo uncaughtExceptionInfo;
1267         uncaughtExceptionInfo.hapPath = hapPath;
1268         wptr<MainThread> weak = this;
1269         uncaughtExceptionInfo.uncaughtTask = [weak, bundleName, versionCode]
1270             (std::string summary, const JsEnv::ErrorObject errorObj) {
1271             auto appThread = weak.promote();
1272             if (appThread == nullptr) {
1273                 HILOG_ERROR("appThread is nullptr.");
1274                 return;
1275             }
1276             time_t timet;
1277             time(&timet);
1278             HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, "JS_ERROR",
1279                 OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
1280                 EVENT_KEY_PACKAGE_NAME, bundleName,
1281                 EVENT_KEY_VERSION, std::to_string(versionCode),
1282                 EVENT_KEY_TYPE, JSCRASH_TYPE,
1283                 EVENT_KEY_HAPPEN_TIME, timet,
1284                 EVENT_KEY_REASON, errorObj.name,
1285                 EVENT_KEY_JSVM, JSVM_TYPE,
1286                 EVENT_KEY_SUMMARY, summary);
1287             ErrorObject appExecErrorObj = {
1288                 .name = errorObj.name,
1289                 .message = errorObj.message,
1290                 .stack = errorObj.stack
1291             };
1292             FaultData faultData;
1293             faultData.faultType = FaultDataType::JS_ERROR;
1294             faultData.errorObject = appExecErrorObj;
1295             DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->NotifyAppFault(faultData);
1296             if (ApplicationDataManager::GetInstance().NotifyUnhandledException(summary) &&
1297                 ApplicationDataManager::GetInstance().NotifyExceptionObject(appExecErrorObj)) {
1298                 return;
1299             }
1300             // if app's callback has been registered, let app decide whether exit or not.
1301             HILOG_ERROR("\n%{public}s is about to exit due to RuntimeError\nError type:%{public}s\n%{public}s",
1302                 bundleName.c_str(), errorObj.name.c_str(), summary.c_str());
1303             DelayedSingleton<AbilityManagerClient>::GetInstance()->RecordAppExitReason(REASON_JS_ERROR);
1304             appThread->ScheduleProcessSecurityExit();
1305         };
1306         (static_cast<AbilityRuntime::JsRuntime&>(*runtime)).RegisterUncaughtExceptionHandler(uncaughtExceptionInfo);
1307         application_->SetRuntime(std::move(runtime));
1308 
1309         std::weak_ptr<OHOSApplication> wpApplication = application_;
1310         AbilityLoader::GetInstance().RegisterAbility("Ability",
1311             [wpApplication]() -> Ability* {
1312             auto app = wpApplication.lock();
1313             if (app != nullptr) {
1314                 return Ability::Create(app->GetRuntime());
1315             }
1316             HILOG_ERROR("AbilityLoader::GetAbilityByName failed.");
1317             return nullptr;
1318         });
1319         if (application_ != nullptr) {
1320             LoadAllExtensions(jsEngine);
1321         }
1322 
1323         IdleTimeCallback callback = [wpApplication](int32_t idleTime) {
1324             auto app = wpApplication.lock();
1325             if (app == nullptr) {
1326                 HILOG_ERROR("app is nullptr.");
1327                 return;
1328             }
1329             auto &runtime = app->GetRuntime();
1330             if (runtime == nullptr) {
1331                 HILOG_ERROR("runtime is nullptr.");
1332                 return;
1333             }
1334             auto& nativeEngine = (static_cast<AbilityRuntime::JsRuntime&>(*runtime)).GetNativeEngine();
1335             nativeEngine.NotifyIdleTime(idleTime);
1336         };
1337         idleTime_ = std::make_shared<IdleTime>(mainHandler_, callback);
1338         idleTime_->Start();
1339 
1340         IdleNotifyStatusCallback cb = idleTime_->GetIdleNotifyFunc();
1341         jsEngine.NotifyIdleStatusControl(cb);
1342     }
1343 
1344     auto usertestInfo = appLaunchData.GetUserTestInfo();
1345     if (usertestInfo) {
1346         if (!PrepareAbilityDelegator(usertestInfo, isStageBased, entryHapModuleInfo)) {
1347             HILOG_ERROR("Failed to prepare ability delegator");
1348             return;
1349         }
1350     }
1351 
1352     // init resourceManager.
1353     HILOG_DEBUG("MainThread handle launch application, CreateResourceManager Start.");
1354     std::shared_ptr<Global::Resource::ResourceManager> resourceManager(Global::Resource::CreateResourceManager());
1355     if (resourceManager == nullptr) {
1356         HILOG_ERROR("MainThread::handleLaunchApplication create resourceManager failed");
1357         return;
1358     }
1359 
1360     if (!InitResourceManager(resourceManager, entryHapModuleInfo, bundleInfo.name,
1361         bundleInfo.applicationInfo.multiProjects, config)) {
1362         HILOG_ERROR("MainThread::handleLaunchApplication InitResourceManager failed");
1363         return;
1364     }
1365     contextImpl->SetResourceManager(resourceManager);
1366     AbilityBase::ExtractResourceManager::GetExtractResourceManager().SetGlobalObject(resourceManager);
1367 
1368     contextDeal->initResourceManager(resourceManager);
1369     contextDeal->SetApplicationContext(application_);
1370     application_->AttachBaseContext(contextDeal);
1371     application_->SetAbilityRecordMgr(abilityRecordMgr_);
1372     application_->SetConfiguration(config);
1373     contextImpl->SetConfiguration(application_->GetConfiguration());
1374 
1375     applicationImpl_->SetRecordId(appLaunchData.GetRecordId());
1376     applicationImpl_->SetApplication(application_);
1377     mainThreadState_ = MainThreadState::READY;
1378     if (!applicationImpl_->PerformAppReady()) {
1379         HILOG_ERROR("HandleLaunchApplication::application applicationImpl_->PerformAppReady failed");
1380         return;
1381     }
1382     // L1 needs to add corresponding interface
1383     ApplicationEnvImpl *pAppEvnIml = ApplicationEnvImpl::GetInstance();
1384 
1385     if (pAppEvnIml) {
1386         pAppEvnIml->SetAppInfo(*applicationInfo_.get());
1387     } else {
1388         HILOG_ERROR("HandleLaunchApplication::application pAppEvnIml is null");
1389     }
1390 
1391 #if defined(NWEB)
1392     // pre dns for nweb
1393     std::thread(&OHOS::NWeb::PreDnsInThread).detach();
1394 
1395     // start nwebspawn process
1396     std::weak_ptr<OHOSApplication> weakApp = application_;
1397     wptr<IAppMgr> weakMgr = appMgr_;
1398     std::thread([weakApp, weakMgr] {
1399         auto app = weakApp.lock();
1400         auto appmgr = weakMgr.promote();
1401         if (app == nullptr || appmgr == nullptr) {
1402             HILOG_ERROR("HandleLaunchApplication app or appmgr is null");
1403             return;
1404         }
1405 
1406         if (prctl(PR_SET_NAME, "preStartNWeb") < 0) {
1407             HILOG_WARN("Set thread name failed with %{public}d", errno);
1408         }
1409 
1410         std::string nwebPath = app->GetAppContext()->GetCacheDir() + "/web";
1411         bool isFirstStartUpWeb = (access(nwebPath.c_str(), F_OK) != 0);
1412         if (!isFirstStartUpWeb) {
1413             appmgr->PreStartNWebSpawnProcess();
1414         }
1415         OHOS::NWeb::NWebHelper::TryPreReadLib(isFirstStartUpWeb, app->GetAppContext()->GetBundleCodeDir());
1416     }).detach();
1417 #endif
1418 }
1419 
1420 #ifdef ABILITY_LIBRARY_LOADER
CalcNativeLiabraryEntries(const BundleInfo & bundleInfo,std::string & nativeLibraryPath)1421 void MainThread::CalcNativeLiabraryEntries(const BundleInfo &bundleInfo, std::string &nativeLibraryPath)
1422 {
1423     bool loadSoFromDir = bundleInfo.hapModuleInfos.empty();
1424     std::vector<std::string> nativeFileEntries;
1425     for (const auto &item: bundleInfo.hapModuleInfos) {
1426         if (!item.compressNativeLibs) {
1427             HILOG_DEBUG("handle entries for: %{public}s, with path: %{public}s", item.moduleName.c_str(),
1428                 item.nativeLibraryPath.c_str());
1429             if (item.nativeLibraryPath.empty()) {
1430                 HILOG_DEBUG("nativeLibraryPath empty: %{public}s", item.moduleName.c_str());
1431                 continue;
1432             }
1433             std::string libPath = GetLibPath(item.hapPath, bundleInfo.isPreInstallApp);
1434             libPath += (libPath.back() == '/') ? item.nativeLibraryPath : "/" + item.nativeLibraryPath;
1435             HILOG_INFO("module lib path: %{public}s", libPath.c_str());
1436             if (libPath.back() != '/') {
1437                 libPath.push_back('/');
1438             }
1439             for (const auto &entryName : item.nativeLibraryFileNames) {
1440                 HILOG_DEBUG("add entry: %{public}s.", entryName.c_str());
1441                 nativeFileEntries.emplace_back(libPath + entryName);
1442             }
1443         } else {
1444             HILOG_DEBUG("compressNativeLibs flag true for: %{public}s.", item.moduleName.c_str());
1445             loadSoFromDir = true;
1446         }
1447     }
1448 
1449     if (loadSoFromDir) {
1450         if (nativeLibraryPath.empty()) {
1451             HILOG_WARN("Native library path is empty.");
1452             return;
1453         }
1454 
1455         if (nativeLibraryPath.back() == '/') {
1456             nativeLibraryPath.pop_back();
1457         }
1458         std::string libPath = LOCAL_CODE_PATH;
1459         libPath += (libPath.back() == '/') ? nativeLibraryPath : "/" + nativeLibraryPath;
1460         HILOG_DEBUG("native library path = %{public}s", libPath.c_str());
1461 
1462         if (!ScanDir(libPath, nativeFileEntries_)) {
1463             HILOG_WARN("%{public}s scanDir %{public}s not exits", __func__, libPath.c_str());
1464         }
1465     }
1466 
1467     if (!nativeFileEntries.empty()) {
1468         nativeFileEntries_.insert(nativeFileEntries_.end(), nativeFileEntries.begin(), nativeFileEntries.end());
1469     }
1470 }
1471 
LoadNativeLiabrary(const BundleInfo & bundleInfo,std::string & nativeLibraryPath)1472 void MainThread::LoadNativeLiabrary(const BundleInfo &bundleInfo, std::string &nativeLibraryPath)
1473 {
1474     CalcNativeLiabraryEntries(bundleInfo, nativeLibraryPath);
1475     if (nativeFileEntries_.empty()) {
1476         HILOG_WARN("No native library");
1477         return;
1478     }
1479 
1480     void *handleAbilityLib = nullptr;
1481     for (auto fileEntry : nativeFileEntries_) {
1482         if (fileEntry.empty()) {
1483             continue;
1484         }
1485         handleAbilityLib = dlopen(fileEntry.c_str(), RTLD_NOW | RTLD_GLOBAL);
1486         if (handleAbilityLib == nullptr) {
1487             if (fileEntry.find("libformrender.z.so") == std::string::npos) {
1488                 HILOG_ERROR("%{public}s Fail to dlopen %{public}s, [%{public}s]",
1489                     __func__, fileEntry.c_str(), dlerror());
1490                 exit(-1);
1491             } else {
1492                 HILOG_DEBUG("Load libformrender.z.so from native lib path.");
1493                 handleAbilityLib = dlopen(FORM_RENDER_LIB_PATH, RTLD_NOW | RTLD_GLOBAL);
1494                 if (handleAbilityLib == nullptr) {
1495                     HILOG_ERROR("%{public}s Fail to dlopen %{public}s, [%{public}s]",
1496                         __func__, FORM_RENDER_LIB_PATH, dlerror());
1497                     exit(-1);
1498                 }
1499                 fileEntry = FORM_RENDER_LIB_PATH;
1500             }
1501         }
1502         HILOG_DEBUG("%{public}s Success to dlopen %{public}s", __func__, fileEntry.c_str());
1503         handleAbilityLib_.emplace_back(handleAbilityLib);
1504     }
1505 }
1506 #endif
1507 
ChangeToLocalPath(const std::string & bundleName,const std::vector<std::string> & sourceDirs,std::vector<std::string> & localPath)1508 void MainThread::ChangeToLocalPath(const std::string &bundleName,
1509     const std::vector<std::string> &sourceDirs, std::vector<std::string> &localPath)
1510 {
1511     std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + bundleName
1512         + std::string(FILE_SEPARATOR));
1513     for (auto item : sourceDirs) {
1514         if (item.empty()) {
1515             continue;
1516         }
1517         localPath.emplace_back(
1518             std::regex_replace(item, pattern, std::string(LOCAL_CODE_PATH) + std::string(FILE_SEPARATOR)));
1519     }
1520 }
1521 
ChangeToLocalPath(const std::string & bundleName,const std::string & sourceDir,std::string & localPath)1522 void MainThread::ChangeToLocalPath(const std::string &bundleName,
1523     const std::string &sourceDir, std::string &localPath)
1524 {
1525     std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + bundleName);
1526     if (sourceDir.empty()) {
1527         return;
1528     }
1529     if (std::regex_search(localPath, std::regex(bundleName))) {
1530         localPath = std::regex_replace(localPath, pattern, std::string(LOCAL_CODE_PATH));
1531     } else {
1532         localPath = std::regex_replace(localPath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES);
1533     }
1534 }
1535 
HandleUpdateApplicationInfoInstalled(const ApplicationInfo & appInfo)1536 void MainThread::HandleUpdateApplicationInfoInstalled(const ApplicationInfo &appInfo)
1537 {
1538     HILOG_DEBUG("MainThread::HandleUpdateApplicationInfoInstalled");
1539     if (!application_) {
1540         HILOG_ERROR("application_ is nullptr");
1541         return;
1542     }
1543     application_->UpdateApplicationInfoInstalled(appInfo);
1544 
1545     if (!appMgr_ || !applicationImpl_) {
1546         HILOG_ERROR("appMgr_ is nullptr");
1547         return;
1548     }
1549 }
1550 
HandleAbilityStage(const HapModuleInfo & abilityStage)1551 void MainThread::HandleAbilityStage(const HapModuleInfo &abilityStage)
1552 {
1553     HILOG_DEBUG("MainThread::HandleAbilityStageInfo");
1554     if (!application_) {
1555         HILOG_ERROR("application_ is nullptr");
1556         return;
1557     }
1558 
1559     application_->AddAbilityStage(abilityStage);
1560 
1561     if (!appMgr_ || !applicationImpl_) {
1562         HILOG_ERROR("appMgr_ is nullptr");
1563         return;
1564     }
1565 
1566     appMgr_->AddAbilityStageDone(applicationImpl_->GetRecordId());
1567 }
1568 
LoadAllExtensions(NativeEngine & nativeEngine)1569 void MainThread::LoadAllExtensions(NativeEngine &nativeEngine)
1570 {
1571     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1572     HILOG_DEBUG("LoadAllExtensions.");
1573     if (!extensionConfigMgr_) {
1574         HILOG_ERROR("ExtensionConfigMgr is invalid");
1575         return;
1576     }
1577 
1578     auto extensionPlugins = AbilityRuntime::ExtensionPluginInfo::GetInstance().GetExtensionPlugins();
1579     if (extensionPlugins.empty()) {
1580         HILOG_ERROR("no extension type map.");
1581         return;
1582     }
1583 
1584     std::map<int32_t, std::string> extensionTypeMap;
1585     for (auto& item : extensionPlugins) {
1586         extensionTypeMap.insert(std::pair<int32_t, std::string>(item.extensionType, item.extensionName));
1587         AddExtensionBlockItem(item.extensionName, item.extensionType);
1588 
1589         std::string file = item.extensionLibFile;
1590         std::weak_ptr<OHOSApplication> wApp = application_;
1591         AbilityLoader::GetInstance().RegisterExtension(item.extensionName,
1592             [wApp, file]() -> AbilityRuntime::Extension* {
1593             auto app = wApp.lock();
1594             if (app != nullptr) {
1595                 return AbilityRuntime::ExtensionModuleLoader::GetLoader(file.c_str()).Create(app->GetRuntime());
1596             }
1597             HILOG_ERROR("AbilityLoader::GetExtensionByName failed.");
1598             return nullptr;
1599         });
1600     }
1601     application_->SetExtensionTypeMap(extensionTypeMap);
1602 }
1603 
PrepareAbilityDelegator(const std::shared_ptr<UserTestRecord> & record,bool isStageBased,const AppExecFwk::HapModuleInfo & entryHapModuleInfo)1604 bool MainThread::PrepareAbilityDelegator(const std::shared_ptr<UserTestRecord> &record, bool isStageBased,
1605     const AppExecFwk::HapModuleInfo &entryHapModuleInfo)
1606 {
1607     HILOG_DEBUG("enter, isStageBased = %{public}d", isStageBased);
1608     if (!record) {
1609         HILOG_ERROR("Invalid UserTestRecord");
1610         return false;
1611     }
1612     auto args = std::make_shared<AbilityDelegatorArgs>(record->want);
1613     if (isStageBased) { // Stage model
1614         HILOG_DEBUG("PrepareAbilityDelegator for Stage model.");
1615         auto testRunner = TestRunner::Create(application_->GetRuntime(), args, false);
1616         auto delegator = std::make_shared<AbilityDelegator>(
1617             application_->GetAppContext(), std::move(testRunner), record->observer);
1618         AbilityDelegatorRegistry::RegisterInstance(delegator, args);
1619         delegator->Prepare();
1620     } else { // FA model
1621         HILOG_DEBUG("PrepareAbilityDelegator for FA model.");
1622         AbilityRuntime::Runtime::Options options;
1623         options.codePath = LOCAL_CODE_PATH;
1624         options.eventRunner = mainHandler_->GetEventRunner();
1625         options.hapPath = entryHapModuleInfo.hapPath;
1626         options.loadAce = false;
1627         options.isStageModel = false;
1628         options.isTestFramework = true;
1629         if (applicationInfo_) {
1630             options.apiTargetVersion = applicationInfo_->apiTargetVersion;
1631         }
1632         if (entryHapModuleInfo.abilityInfos.empty()) {
1633             HILOG_ERROR("Failed to abilityInfos");
1634             return false;
1635         }
1636         bool isFaJsModel = entryHapModuleInfo.abilityInfos.front().srcLanguage == "js" ? true : false;
1637         static auto runtime = AbilityRuntime::Runtime::Create(options);
1638         auto testRunner = TestRunner::Create(runtime, args, isFaJsModel);
1639         if (testRunner == nullptr) {
1640             HILOG_ERROR("Failed to Create testRunner");
1641             return false;
1642         }
1643         if (!testRunner->Initialize()) {
1644             HILOG_ERROR("Failed to Initialize testRunner");
1645             return false;
1646         }
1647         auto delegator = std::make_shared<AbilityDelegator>(
1648             application_->GetAppContext(), std::move(testRunner), record->observer);
1649         AbilityDelegatorRegistry::RegisterInstance(delegator, args);
1650         delegator->Prepare();
1651     }
1652     return true;
1653 }
1654 
1655 /**
1656  *
1657  * @brief launch the ability.
1658  *
1659  * @param abilityRecord The abilityRecord which belongs to the ability launched.
1660  *
1661  */
HandleLaunchAbility(const std::shared_ptr<AbilityLocalRecord> & abilityRecord)1662 void MainThread::HandleLaunchAbility(const std::shared_ptr<AbilityLocalRecord> &abilityRecord)
1663 {
1664     CHECK_POINTER_LOG(abilityRecord, "MainThread::HandleLaunchAbility parameter(abilityRecord) is null");
1665     std::string connector = "##";
1666     std::string traceName = __PRETTY_FUNCTION__ + connector;
1667     if (abilityRecord->GetWant() != nullptr) {
1668         traceName += abilityRecord->GetWant()->GetElement().GetBundleName();
1669     } else {
1670         HILOG_ERROR("Want is nullptr, cant not get abilityName.");
1671     }
1672     HITRACE_METER_NAME(HITRACE_TAG_APP, traceName);
1673     HILOG_DEBUG("HandleLaunchAbility called start.");
1674     CHECK_POINTER_LOG(applicationImpl_, "MainThread::HandleLaunchAbility applicationImpl_ is null");
1675     CHECK_POINTER_LOG(abilityRecordMgr_, "MainThread::HandleLaunchAbility abilityRecordMgr_ is null");
1676 
1677     auto abilityToken = abilityRecord->GetToken();
1678     CHECK_POINTER_LOG(abilityToken, "MainThread::HandleLaunchAbility failed. abilityRecord->GetToken failed");
1679 
1680     abilityRecordMgr_->SetToken(abilityToken);
1681     abilityRecordMgr_->AddAbilityRecord(abilityToken, abilityRecord);
1682 
1683     if (!IsApplicationReady()) {
1684         HILOG_ERROR("MainThread::handleLaunchAbility not init OHOSApplication, should launch application first");
1685         return;
1686     }
1687 
1688     if (!CheckAbilityItem(abilityRecord)) {
1689         HILOG_ERROR("MainThread::handleLaunchAbility record is invalid");
1690         return;
1691     }
1692 
1693     auto& runtime = application_->GetRuntime();
1694     auto appInfo = application_->GetApplicationInfo();
1695     auto want = abilityRecord->GetWant();
1696     if (appInfo == nullptr) {
1697         HILOG_ERROR("appInfo is nullptr");
1698         return;
1699     }
1700 
1701     if (runtime && want && appInfo->debug) {
1702         auto perfCmd = want->GetStringParam("perfCmd");
1703         if (perfCmd.find(PERFCMD_PROFILE) != std::string::npos ||
1704             perfCmd.find(PERFCMD_DUMPHEAP) != std::string::npos) {
1705             HILOG_DEBUG("perfCmd is %{public}s", perfCmd.c_str());
1706             runtime->StartProfiler(perfCmd);
1707         } else {
1708             runtime->StartDebugMode(want->GetBoolParam("debugApp", false));
1709         }
1710     }
1711 
1712     std::vector<HqfInfo> hqfInfos = appInfo->appQuickFix.deployedAppqfInfo.hqfInfos;
1713     std::map<std::string, std::string> modulePaths;
1714     if (runtime && !hqfInfos.empty()) {
1715         for (auto it = hqfInfos.begin(); it != hqfInfos.end(); it++) {
1716             HILOG_INFO("moudelName: %{private}s, hqfFilePath: %{private}s.",
1717                 it->moduleName.c_str(), it->hqfFilePath.c_str());
1718             modulePaths.insert(std::make_pair(it->moduleName, it->hqfFilePath));
1719         }
1720         runtime->RegisterQuickFixQueryFunc(modulePaths);
1721     }
1722 
1723     mainThreadState_ = MainThreadState::RUNNING;
1724     std::shared_ptr<AbilityRuntime::Context> stageContext = application_->AddAbilityStage(abilityRecord);
1725     SetProcessExtensionType(abilityRecord);
1726     UpdateRuntimeModuleChecker(runtime);
1727 #ifdef APP_ABILITY_USE_TWO_RUNNER
1728     AbilityThread::AbilityThreadMain(application_, abilityRecord, stageContext);
1729 #else
1730     AbilityThread::AbilityThreadMain(application_, abilityRecord, mainHandler_->GetEventRunner(), stageContext);
1731 #endif
1732 }
1733 
1734 /**
1735  *
1736  * @brief Clean the ability but don't notify ams.
1737  *
1738  * @param token The token which belongs to the ability launched.
1739  *
1740  */
HandleCleanAbilityLocal(const sptr<IRemoteObject> & token)1741 void MainThread::HandleCleanAbilityLocal(const sptr<IRemoteObject> &token)
1742 {
1743     HILOG_DEBUG("start.");
1744     if (!IsApplicationReady()) {
1745         HILOG_ERROR("not init OHOSApplication, should launch application first");
1746         return;
1747     }
1748 
1749     if (token == nullptr) {
1750         HILOG_ERROR("token is null");
1751         return;
1752     }
1753 
1754     std::shared_ptr<AbilityLocalRecord> record = abilityRecordMgr_->GetAbilityItem(token);
1755     if (record == nullptr) {
1756         HILOG_ERROR("abilityRecord not found");
1757         return;
1758     }
1759     std::shared_ptr<AbilityInfo> abilityInfo = record->GetAbilityInfo();
1760     if (abilityInfo == nullptr) {
1761         HILOG_ERROR("record->GetAbilityInfo() failed");
1762         return;
1763     }
1764     HILOG_INFO("ability name: %{public}s", abilityInfo->name.c_str());
1765 
1766     abilityRecordMgr_->RemoveAbilityRecord(token);
1767     application_->CleanAbilityStage(token, abilityInfo);
1768 #ifdef APP_ABILITY_USE_TWO_RUNNER
1769     std::shared_ptr<EventRunner> runner = record->GetEventRunner();
1770     if (runner != nullptr) {
1771         int ret = runner->Stop();
1772         if (ret != ERR_OK) {
1773             HILOG_ERROR("MainThread::main failed. ability runner->Run failed ret = %{public}d", ret);
1774         }
1775         abilityRecordMgr_->RemoveAbilityRecord(token);
1776         application_->CleanAbilityStage(token, abilityInfo);
1777     } else {
1778         HILOG_WARN("runner not found");
1779     }
1780 #endif
1781 }
1782 
1783 /**
1784  *
1785  * @brief Clean the ability.
1786  *
1787  * @param token The token which belongs to the ability launched.
1788  *
1789  */
HandleCleanAbility(const sptr<IRemoteObject> & token)1790 void MainThread::HandleCleanAbility(const sptr<IRemoteObject> &token)
1791 {
1792     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1793     if (applicationInfo_ == nullptr) {
1794         HILOG_ERROR("applicationInfo is null");
1795         return;
1796     }
1797     HILOG_DEBUG("Handle clean ability start, app is %{public}s.", applicationInfo_->name.c_str());
1798 
1799     if (!IsApplicationReady()) {
1800         HILOG_ERROR("not init OHOSApplication, should launch application first");
1801         return;
1802     }
1803 
1804     if (token == nullptr) {
1805         HILOG_ERROR("token is null");
1806         return;
1807     }
1808 
1809     std::shared_ptr<AbilityLocalRecord> record = abilityRecordMgr_->GetAbilityItem(token);
1810     if (record == nullptr) {
1811         HILOG_ERROR("abilityRecord not found");
1812         return;
1813     }
1814     std::shared_ptr<AbilityInfo> abilityInfo = record->GetAbilityInfo();
1815     if (abilityInfo == nullptr) {
1816         HILOG_ERROR("record->GetAbilityInfo() failed");
1817         return;
1818     }
1819 
1820 #ifdef SUPPORT_GRAPHICS
1821     if (abilityInfo->type == AbilityType::PAGE && abilityInfo->isStageBasedModel) {
1822         AppRecovery::GetInstance().RemoveAbility(token);
1823     }
1824 #endif
1825 
1826     abilityRecordMgr_->RemoveAbilityRecord(token);
1827     application_->CleanAbilityStage(token, abilityInfo);
1828 #ifdef APP_ABILITY_USE_TWO_RUNNER
1829     std::shared_ptr<EventRunner> runner = record->GetEventRunner();
1830     if (runner != nullptr) {
1831         int ret = runner->Stop();
1832         if (ret != ERR_OK) {
1833             HILOG_ERROR("MainThread::main failed. ability runner->Run failed ret = %{public}d", ret);
1834         }
1835         abilityRecordMgr_->RemoveAbilityRecord(token);
1836         application_->CleanAbilityStage(token, abilityInfo);
1837     } else {
1838         HILOG_WARN("runner not found");
1839     }
1840 #endif
1841     appMgr_->AbilityCleaned(token);
1842     HILOG_INFO("Handle clean ability end, app: %{public}s, ability: %{public}s.",
1843         applicationInfo_->name.c_str(), abilityInfo->name.c_str());
1844 }
1845 
1846 /**
1847  *
1848  * @brief Foreground the application.
1849  *
1850  */
HandleForegroundApplication()1851 void MainThread::HandleForegroundApplication()
1852 {
1853     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1854     HILOG_DEBUG("MainThread handle application to foreground called.");
1855     if ((application_ == nullptr) || (appMgr_ == nullptr)) {
1856         HILOG_ERROR("MainThread::handleForegroundApplication error!");
1857         return;
1858     }
1859 #ifdef IMAGE_PURGEABLE_PIXELMAP
1860     PurgeableMem::PurgeableResourceManager::GetInstance().BeginAccessPurgeableMem();
1861 #endif
1862     if (!applicationImpl_->PerformForeground()) {
1863         HILOG_ERROR("MainThread::handleForegroundApplication error!, applicationImpl_->PerformForeground() failed");
1864         return;
1865     }
1866 
1867     HILOG_DEBUG("to foreground success, recordId is %{public}d", applicationImpl_->GetRecordId());
1868     appMgr_->ApplicationForegrounded(applicationImpl_->GetRecordId());
1869 }
1870 
1871 /**
1872  *
1873  * @brief Background the application.
1874  *
1875  */
HandleBackgroundApplication()1876 void MainThread::HandleBackgroundApplication()
1877 {
1878     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1879     HILOG_DEBUG("MainThread::handleBackgroundApplication called start.");
1880 
1881     if ((application_ == nullptr) || (appMgr_ == nullptr)) {
1882         HILOG_ERROR("MainThread::handleBackgroundApplication error!");
1883         return;
1884     }
1885 
1886     if (!applicationImpl_->PerformBackground()) {
1887         HILOG_ERROR("MainThread::handleForegroundApplication error!, applicationImpl_->PerformBackground() failed");
1888         return;
1889     }
1890     appMgr_->ApplicationBackgrounded(applicationImpl_->GetRecordId());
1891 }
1892 
1893 /**
1894  *
1895  * @brief Terminate the application.
1896  *
1897  */
HandleTerminateApplication()1898 void MainThread::HandleTerminateApplication()
1899 {
1900     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1901     HILOG_DEBUG("MainThread::handleTerminateApplication called start.");
1902     if ((application_ == nullptr) || (appMgr_ == nullptr)) {
1903         HILOG_ERROR("MainThread::handleTerminateApplication error!");
1904         return;
1905     }
1906 
1907     if (!applicationImpl_->PerformTerminate()) {
1908         HILOG_WARN("%{public}s: applicationImpl_->PerformTerminate() failed.", __func__);
1909     }
1910 
1911     std::shared_ptr<EventRunner> signalRunner = signalHandler_->GetEventRunner();
1912     if (signalRunner) {
1913         signalRunner->Stop();
1914     }
1915 
1916     std::shared_ptr<EventRunner> runner = mainHandler_->GetEventRunner();
1917     if (runner == nullptr) {
1918         HILOG_ERROR("MainThread::handleTerminateApplication get manHandler error");
1919         return;
1920     }
1921 
1922     if (watchdog_ != nullptr && !watchdog_->IsStopWatchdog()) {
1923         watchdog_->Stop();
1924         watchdog_ = nullptr;
1925     }
1926 
1927     int ret = runner->Stop();
1928     if (ret != ERR_OK) {
1929         HILOG_ERROR("MainThread::handleTerminateApplication failed. runner->Run failed ret = %{public}d", ret);
1930     }
1931     SetRunnerStarted(false);
1932     appMgr_->ApplicationTerminated(applicationImpl_->GetRecordId());
1933 }
1934 
1935 /**
1936  *
1937  * @brief Shrink the memory which used by application.
1938  *
1939  * @param level Indicates the memory trim level, which shows the current memory usage status.
1940  *
1941  */
HandleShrinkMemory(const int level)1942 void MainThread::HandleShrinkMemory(const int level)
1943 {
1944     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1945     HILOG_DEBUG("MainThread::HandleShrinkMemory called start.");
1946 
1947     if (applicationImpl_ == nullptr) {
1948         HILOG_ERROR("MainThread::HandleShrinkMemory error! applicationImpl_ is null");
1949         return;
1950     }
1951 
1952     applicationImpl_->PerformMemoryLevel(level);
1953 }
1954 
1955 /**
1956  *
1957  * @brief Handle NotifyMemoryLevel.
1958  *
1959  * @param level Indicates the memory trim level, which shows the current memory usage status.
1960  *
1961  */
HandleMemoryLevel(int level)1962 void MainThread::HandleMemoryLevel(int level)
1963 {
1964     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1965     HILOG_DEBUG("MainThread::HandleMemoryLevel called start.");
1966 
1967     if (application_ == nullptr) {
1968         HILOG_ERROR("MainThread::HandleMemoryLevel error! application_ is null");
1969         return;
1970     }
1971 
1972     application_->OnMemoryLevel(level);
1973 }
1974 
1975 /**
1976  *
1977  * @brief send the new config to the application.
1978  *
1979  * @param config The updated config.
1980  *
1981  */
HandleConfigurationUpdated(const Configuration & config)1982 void MainThread::HandleConfigurationUpdated(const Configuration &config)
1983 {
1984     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1985     HILOG_DEBUG("MainThread::HandleConfigurationUpdated called start.");
1986 
1987     if (applicationImpl_ == nullptr) {
1988         HILOG_ERROR("MainThread::HandleConfigurationUpdated error! applicationImpl_ is null");
1989         return;
1990     }
1991 
1992     applicationImpl_->PerformConfigurationUpdated(config);
1993 }
1994 
TaskTimeoutDetected(const std::shared_ptr<EventRunner> & runner)1995 void MainThread::TaskTimeoutDetected(const std::shared_ptr<EventRunner> &runner)
1996 {
1997     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1998     HILOG_DEBUG("MainThread::TaskTimeoutDetected called start.");
1999 
2000     auto deliveryTimeoutCallback = []() {
2001         HILOG_DEBUG("MainThread::TaskTimeoutDetected delivery timeout");
2002     };
2003     auto distributeTimeoutCallback = []() {
2004         HILOG_DEBUG("MainThread::TaskTimeoutDetected distribute timeout");
2005     };
2006 
2007     if (runner !=nullptr && mainHandler_ != nullptr) {
2008         runner->SetDeliveryTimeout(DELIVERY_TIME);
2009         mainHandler_->SetDeliveryTimeoutCallback(deliveryTimeoutCallback);
2010 
2011         runner->SetDistributeTimeout(DISTRIBUTE_TIME);
2012         mainHandler_->SetDistributeTimeoutCallback(distributeTimeoutCallback);
2013     }
2014 }
2015 
Init(const std::shared_ptr<EventRunner> & runner)2016 void MainThread::Init(const std::shared_ptr<EventRunner> &runner)
2017 {
2018     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2019     HILOG_DEBUG("MainThread:Init Start");
2020     mainHandler_ = std::make_shared<MainHandler>(runner, this);
2021     watchdog_ = std::make_shared<Watchdog>();
2022     signalHandler_ = std::make_shared<EventHandler>(EventRunner::Create(SIGNAL_HANDLER));
2023     extensionConfigMgr_ = std::make_unique<AbilityRuntime::ExtensionConfigMgr>();
2024     wptr<MainThread> weak = this;
2025     auto task = [weak]() {
2026         auto appThread = weak.promote();
2027         if (appThread == nullptr) {
2028             HILOG_ERROR("abilityThread is nullptr, SetRunnerStarted failed.");
2029             return;
2030         }
2031         appThread->SetRunnerStarted(true);
2032     };
2033     if (!mainHandler_->PostTask(task)) {
2034         HILOG_ERROR("MainThread::Init PostTask task failed");
2035     }
2036     TaskTimeoutDetected(runner);
2037 
2038     watchdog_->Init(mainHandler_);
2039     AppExecFwk::AppfreezeInner::GetInstance()->SetMainHandler(mainHandler_);
2040     extensionConfigMgr_->Init();
2041 }
2042 
HandleSignal(int signal)2043 void MainThread::HandleSignal(int signal)
2044 {
2045     switch (signal) {
2046         case SIGNAL_JS_HEAP: {
2047             auto heapFunc = std::bind(&MainThread::HandleDumpHeap, false);
2048             signalHandler_->PostTask(heapFunc);
2049             break;
2050         }
2051         case SIGNAL_JS_HEAP_PRIV: {
2052             auto privateHeapFunc = std::bind(&MainThread::HandleDumpHeap, true);
2053             signalHandler_->PostTask(privateHeapFunc);
2054             break;
2055         }
2056         default:
2057             break;
2058     }
2059 }
2060 
HandleDumpHeap(bool isPrivate)2061 void MainThread::HandleDumpHeap(bool isPrivate)
2062 {
2063     HILOG_DEBUG("Dump heap start.");
2064     if (mainHandler_ == nullptr) {
2065         HILOG_ERROR("HandleDumpHeap failed, mainHandler is nullptr");
2066         return;
2067     }
2068 
2069     auto task = [isPrivate] {
2070         auto app = applicationForDump_.lock();
2071         if (app == nullptr || app->GetRuntime() == nullptr) {
2072             HILOG_ERROR("runtime is nullptr.");
2073             return;
2074         }
2075         app->GetRuntime()->DumpHeapSnapshot(isPrivate);
2076     };
2077     mainHandler_->PostTask(task);
2078 }
2079 
Start()2080 void MainThread::Start()
2081 {
2082     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2083     HILOG_DEBUG("MainThread start come.");
2084     std::shared_ptr<EventRunner> runner = EventRunner::GetMainEventRunner();
2085     if (runner == nullptr) {
2086         HILOG_ERROR("MainThread::main failed, runner is nullptr");
2087         return;
2088     }
2089     sptr<MainThread> thread = sptr<MainThread>(new (std::nothrow) MainThread());
2090     if (thread == nullptr) {
2091         HILOG_ERROR("MainThread::static failed. new MainThread failed");
2092         return;
2093     }
2094 
2095     struct sigaction sigAct;
2096     sigemptyset(&sigAct.sa_mask);
2097     sigAct.sa_flags = 0;
2098     sigAct.sa_handler = &MainThread::HandleSignal;
2099     sigaction(SIGUSR1, &sigAct, NULL);
2100     sigaction(SIGNAL_JS_HEAP, &sigAct, NULL);
2101     sigaction(SIGNAL_JS_HEAP_PRIV, &sigAct, NULL);
2102 
2103     thread->Init(runner);
2104 
2105     thread->Attach();
2106 
2107     int ret = runner->Run();
2108     if (ret != ERR_OK) {
2109         HILOG_ERROR("MainThread::main failed. runner->Run failed ret = %{public}d", ret);
2110     }
2111 
2112     thread->RemoveAppMgrDeathRecipient();
2113 }
2114 
PreloadExtensionPlugin()2115 void MainThread::PreloadExtensionPlugin()
2116 {
2117     AbilityRuntime::ExtensionPluginInfo::GetInstance().Preload();
2118 }
2119 
MainHandler(const std::shared_ptr<EventRunner> & runner,const sptr<MainThread> & thread)2120 MainThread::MainHandler::MainHandler(const std::shared_ptr<EventRunner> &runner, const sptr<MainThread> &thread)
2121     : AppExecFwk::EventHandler(runner), mainThreadObj_(thread)
2122 {}
2123 
2124 /**
2125  *
2126  * @brief Process the event.
2127  *
2128  * @param event the event want to be processed.
2129  *
2130  */
ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer & event)2131 void MainThread::MainHandler::ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer &event)
2132 {
2133     auto eventId = event->GetInnerEventId();
2134     if (eventId == CHECK_MAIN_THREAD_IS_ALIVE) {
2135         auto mt = mainThreadObj_.promote();
2136         if (mt != nullptr) {
2137             mt->CheckMainThreadIsAlive();
2138         }
2139     }
2140 }
2141 
2142 /**
2143  *
2144  * @brief Check whether the OHOSApplication is ready.
2145  *
2146  * @return if the record is legal, return true. else return false.
2147  *
2148  */
IsApplicationReady() const2149 bool MainThread::IsApplicationReady() const
2150 {
2151     HILOG_DEBUG("MainThread::IsApplicationReady called start");
2152     if (application_ == nullptr || applicationImpl_ == nullptr) {
2153         HILOG_WARN("MainThread::IsApplicationReady called. application_=null or applicationImpl_=null");
2154         return false;
2155     }
2156 
2157     return true;
2158 }
2159 
2160 #ifdef ABILITY_LIBRARY_LOADER
2161 /**
2162  *
2163  * @brief Load the ability library.
2164  *
2165  * @param libraryPaths the library paths.
2166  *
2167  */
LoadAbilityLibrary(const std::vector<std::string> & libraryPaths)2168 void MainThread::LoadAbilityLibrary(const std::vector<std::string> &libraryPaths)
2169 {
2170     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2171 #ifdef ABILITY_LIBRARY_LOADER
2172     HILOG_DEBUG("MainThread load ability library start.");
2173 #ifdef ACEABILITY_LIBRARY_LOADER
2174     void *AceAbilityLib = nullptr;
2175     AceAbilityLib = dlopen(acelibdir.c_str(), RTLD_NOW | RTLD_GLOBAL);
2176     if (AceAbilityLib == nullptr) {
2177         HILOG_ERROR("Fail to dlopen %{public}s, [%{public}s]", acelibdir.c_str(), dlerror());
2178     } else {
2179         HILOG_DEBUG("Success to dlopen %{public}s", acelibdir.c_str());
2180         handleAbilityLib_.emplace_back(AceAbilityLib);
2181     }
2182 #endif  // ACEABILITY_LIBRARY_LOADER
2183     size_t size = libraryPaths.size();
2184     for (size_t index = 0; index < size; index++) {
2185         std::string libraryPath = libraryPaths[index];
2186         HILOG_DEBUG("Try to scanDir %{public}s", libraryPath.c_str());
2187         if (!ScanDir(libraryPath, fileEntries_)) {
2188             HILOG_WARN("scanDir %{public}s not exits", libraryPath.c_str());
2189         }
2190         libraryPath = libraryPath + "/libs";
2191         if (!ScanDir(libraryPath, fileEntries_)) {
2192             HILOG_WARN("scanDir %{public}s not exits", libraryPath.c_str());
2193         }
2194     }
2195 
2196     if (fileEntries_.empty()) {
2197         HILOG_WARN("No ability library");
2198         return;
2199     }
2200 
2201     char resolvedPath[PATH_MAX] = {0};
2202     void *handleAbilityLib = nullptr;
2203     for (const auto& fileEntry : fileEntries_) {
2204         if (fileEntry.empty() || fileEntry.size() >= PATH_MAX) {
2205             continue;
2206         }
2207         if (realpath(fileEntry.c_str(), resolvedPath) == nullptr) {
2208             HILOG_ERROR("Failed to get realpath, errno = %{public}d", errno);
2209             continue;
2210         }
2211 
2212         handleAbilityLib = dlopen(resolvedPath, RTLD_NOW | RTLD_GLOBAL);
2213         if (handleAbilityLib == nullptr) {
2214             HILOG_ERROR("Fail to dlopen %{public}s, [%{public}s]",
2215                 resolvedPath, dlerror());
2216             exit(-1);
2217         }
2218         HILOG_INFO("Success to dlopen %{public}s", fileEntry.c_str());
2219         handleAbilityLib_.emplace_back(handleAbilityLib);
2220     }
2221 #endif  // ABILITY_LIBRARY_LOADER
2222 }
2223 
LoadAppLibrary()2224 void MainThread::LoadAppLibrary()
2225 {
2226     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2227 #ifdef APPLICATION_LIBRARY_LOADER
2228     std::string appPath = applicationLibraryPath;
2229     HILOG_INFO("calling dlopen. appPath=%{public}s", appPath.c_str());
2230     handleAppLib_ = dlopen(appPath.c_str(), RTLD_NOW | RTLD_GLOBAL);
2231     if (handleAppLib_ == nullptr) {
2232         HILOG_ERROR("Fail to dlopen %{public}s, [%{public}s]", appPath.c_str(), dlerror());
2233         exit(-1);
2234     }
2235 #endif  // APPLICATION_LIBRARY_LOADER
2236 }
2237 
LoadAppDetailAbilityLibrary(std::string & nativeLibraryPath)2238 void MainThread::LoadAppDetailAbilityLibrary(std::string &nativeLibraryPath)
2239 {
2240     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2241 #ifdef ABILITY_LIBRARY_LOADER
2242     HILOG_DEBUG("LoadAppDetailAbilityLibrary try to scanDir %{public}s", nativeLibraryPath.c_str());
2243     std::vector<std::string> fileEntries;
2244     if (!ScanDir(nativeLibraryPath, fileEntries)) {
2245         HILOG_WARN("scanDir %{public}s not exits", nativeLibraryPath.c_str());
2246     }
2247     if (fileEntries.empty()) {
2248         HILOG_WARN("No ability library");
2249         return;
2250     }
2251     char resolvedPath[PATH_MAX] = {0};
2252     void *handleAbilityLib = nullptr;
2253     for (const auto& fileEntry : fileEntries) {
2254         if (fileEntry.empty() || fileEntry.size() >= PATH_MAX) {
2255             continue;
2256         }
2257         if (realpath(fileEntry.c_str(), resolvedPath) == nullptr) {
2258             HILOG_ERROR("Failed to get realpath, errno = %{public}d", errno);
2259             continue;
2260         }
2261 
2262         handleAbilityLib = dlopen(resolvedPath, RTLD_NOW | RTLD_GLOBAL);
2263         if (handleAbilityLib == nullptr) {
2264             HILOG_ERROR("Fail to dlopen %{public}s, [%{public}s]",
2265                 resolvedPath, dlerror());
2266             exit(-1);
2267         }
2268         HILOG_INFO("Success to dlopen %{public}s", fileEntry.c_str());
2269         handleAbilityLib_.emplace_back(handleAbilityLib);
2270     }
2271 #endif // ABILITY_LIBRARY_LOADER
2272 }
2273 
ScanDir(const std::string & dirPath,std::vector<std::string> & files)2274 bool MainThread::ScanDir(const std::string &dirPath, std::vector<std::string> &files)
2275 {
2276     DIR *dirp = opendir(dirPath.c_str());
2277     if (dirp == nullptr) {
2278         HILOG_ERROR("MainThread::ScanDir open dir:%{public}s fail", dirPath.c_str());
2279         return false;
2280     }
2281     struct dirent *df = nullptr;
2282     for (;;) {
2283         df = readdir(dirp);
2284         if (df == nullptr) {
2285             break;
2286         }
2287 
2288         std::string currentName(df->d_name);
2289         if (currentName.compare(".") == 0 || currentName.compare("..") == 0) {
2290             continue;
2291         }
2292 
2293         if (CheckFileType(currentName, abilityLibraryType_)) {
2294             files.emplace_back(dirPath + pathSeparator_ + currentName);
2295         }
2296     }
2297 
2298     if (closedir(dirp) == -1) {
2299         HILOG_WARN("close dir fail");
2300     }
2301     return true;
2302 }
2303 
2304 /**
2305  *
2306  * @brief Check the fileType.
2307  *
2308  * @param fileName The fileName of the lib.
2309  * @param extensionName The extensionName of the lib.
2310  *
2311  * @return if the FileType is legal, return true. else return false.
2312  *
2313  */
CheckFileType(const std::string & fileName,const std::string & extensionName)2314 bool MainThread::CheckFileType(const std::string &fileName, const std::string &extensionName)
2315 {
2316     HILOG_DEBUG("MainThread::CheckFileType path is %{public}s, support suffix is %{public}s",
2317         fileName.c_str(),
2318         extensionName.c_str());
2319 
2320     if (fileName.empty()) {
2321         HILOG_ERROR("the file name is empty");
2322         return false;
2323     }
2324 
2325     auto position = fileName.rfind('.');
2326     if (position == std::string::npos) {
2327         HILOG_WARN("filename no extension name");
2328         return false;
2329     }
2330 
2331     std::string suffixStr = fileName.substr(position);
2332     return LowerStr(suffixStr) == extensionName;
2333 }
2334 
HandleScheduleAcceptWant(const AAFwk::Want & want,const std::string & moduleName)2335 void MainThread::HandleScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName)
2336 {
2337     HILOG_DEBUG("MainThread::HandleScheduleAcceptWant");
2338     if (!application_) {
2339         HILOG_ERROR("application_ is nullptr");
2340         return;
2341     }
2342 
2343     std::string specifiedFlag;
2344     application_->ScheduleAcceptWant(want, moduleName, specifiedFlag);
2345 
2346     if (!appMgr_ || !applicationImpl_) {
2347         HILOG_ERROR("appMgr_ is nullptr");
2348         return;
2349     }
2350 
2351     appMgr_->ScheduleAcceptWantDone(applicationImpl_->GetRecordId(), want, specifiedFlag);
2352 }
2353 
ScheduleAcceptWant(const AAFwk::Want & want,const std::string & moduleName)2354 void MainThread::ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName)
2355 {
2356     HILOG_DEBUG("start");
2357     wptr<MainThread> weak = this;
2358     auto task = [weak, want, moduleName]() {
2359         auto appThread = weak.promote();
2360         if (appThread == nullptr) {
2361             HILOG_ERROR("abilityThread is nullptr, HandleScheduleAcceptWant failed.");
2362             return;
2363         }
2364         appThread->HandleScheduleAcceptWant(want, moduleName);
2365     };
2366     if (!mainHandler_->PostTask(task)) {
2367         HILOG_ERROR("PostTask task failed");
2368     }
2369 }
2370 
CheckMainThreadIsAlive()2371 void MainThread::CheckMainThreadIsAlive()
2372 {
2373     watchdog_->SetAppMainThreadState(true);
2374     watchdog_->AllowReportEvent();
2375 }
2376 #endif  // ABILITY_LIBRARY_LOADER
2377 
ScheduleNotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback,const int32_t recordId)2378 int32_t MainThread::ScheduleNotifyLoadRepairPatch(const std::string &bundleName,
2379     const sptr<IQuickFixCallback> &callback, const int32_t recordId)
2380 {
2381     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2382     HILOG_DEBUG("ScheduleNotifyLoadRepairPatch function called.");
2383     wptr<MainThread> weak = this;
2384     auto task = [weak, bundleName, callback, recordId]() {
2385         auto appThread = weak.promote();
2386         if (appThread == nullptr || appThread->application_ == nullptr || callback == nullptr) {
2387             HILOG_ERROR("ScheduleNotifyLoadRepairPatch, parameter is nullptr.");
2388             return;
2389         }
2390 
2391         bool ret = true;
2392         std::vector<std::pair<std::string, std::string>> hqfFilePair;
2393         if (appThread->GetHqfFileAndHapPath(bundleName, hqfFilePair)) {
2394             for (auto it = hqfFilePair.begin(); it != hqfFilePair.end(); it++) {
2395                 HILOG_INFO("ScheduleNotifyLoadRepairPatch, LoadPatch, hqfFile: %{private}s, hapPath: %{private}s.",
2396                     it->first.c_str(), it->second.c_str());
2397                 ret = appThread->application_->NotifyLoadRepairPatch(it->first, it->second);
2398             }
2399         } else {
2400             HILOG_DEBUG("ScheduleNotifyLoadRepairPatch, There's no hqfFile need to load.");
2401         }
2402 
2403         callback->OnLoadPatchDone(ret ? NO_ERROR : ERR_INVALID_OPERATION, recordId);
2404     };
2405     if (mainHandler_ == nullptr || !mainHandler_->PostTask(task)) {
2406         HILOG_ERROR("ScheduleNotifyLoadRepairPatch, Post task failed.");
2407         return ERR_INVALID_VALUE;
2408     }
2409 
2410     return NO_ERROR;
2411 }
2412 
ScheduleNotifyHotReloadPage(const sptr<IQuickFixCallback> & callback,const int32_t recordId)2413 int32_t MainThread::ScheduleNotifyHotReloadPage(const sptr<IQuickFixCallback> &callback, const int32_t recordId)
2414 {
2415     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2416     HILOG_DEBUG("function called.");
2417     wptr<MainThread> weak = this;
2418     auto task = [weak, callback, recordId]() {
2419         auto appThread = weak.promote();
2420         if (appThread == nullptr || appThread->application_ == nullptr || callback == nullptr) {
2421             HILOG_ERROR("parameter is nullptr.");
2422             return;
2423         }
2424         auto ret = appThread->application_->NotifyHotReloadPage();
2425         callback->OnReloadPageDone(ret ? NO_ERROR : ERR_INVALID_OPERATION, recordId);
2426     };
2427     if (mainHandler_ == nullptr || !mainHandler_->PostTask(task)) {
2428         HILOG_ERROR("Post task failed.");
2429         return ERR_INVALID_VALUE;
2430     }
2431 
2432     return NO_ERROR;
2433 }
2434 
GetHqfFileAndHapPath(const std::string & bundleName,std::vector<std::pair<std::string,std::string>> & fileMap)2435 bool MainThread::GetHqfFileAndHapPath(const std::string &bundleName,
2436     std::vector<std::pair<std::string, std::string>> &fileMap)
2437 {
2438     HILOG_DEBUG("function called.");
2439     auto bundleObj = DelayedSingleton<SysMrgClient>::GetInstance()->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
2440     if (bundleObj == nullptr) {
2441         HILOG_ERROR("Failed to get bundle manager service.");
2442         return false;
2443     }
2444 
2445     sptr<IBundleMgr> bundleMgr = iface_cast<IBundleMgr>(bundleObj);
2446     if (bundleMgr == nullptr) {
2447         HILOG_ERROR("Bundle manager is nullptr.");
2448         return false;
2449     }
2450 
2451     BundleInfo bundleInfo;
2452     if (bundleMgr->GetBundleInfoForSelf(
2453         (static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) +
2454         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY) +
2455         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) +
2456         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE) +
2457         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) +
2458         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) +
2459         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_METADATA)), bundleInfo) != ERR_OK) {
2460         HILOG_ERROR("Get bundle info of %{public}s failed.", bundleName.c_str());
2461         return false;
2462     }
2463 
2464     for (auto hapInfo : bundleInfo.hapModuleInfos) {
2465         if ((processInfo_ != nullptr) && (processInfo_->GetProcessName() == hapInfo.process) &&
2466             (!hapInfo.hqfInfo.hqfFilePath.empty())) {
2467             std::string resolvedHapPath(AbilityBase::GetLoadPath(hapInfo.hapPath));
2468             std::string resolvedHqfFile(AbilityBase::GetLoadPath(hapInfo.hqfInfo.hqfFilePath));
2469             HILOG_INFO("bundleName: %{public}s, moduleName: %{public}s, processName: %{private}s, "
2470                 "hqf file: %{private}s, hap path: %{private}s.", bundleName.c_str(), hapInfo.moduleName.c_str(),
2471                 hapInfo.process.c_str(), resolvedHqfFile.c_str(), resolvedHapPath.c_str());
2472             fileMap.push_back(std::pair<std::string, std::string>(resolvedHqfFile, resolvedHapPath));
2473         }
2474     }
2475 
2476     return true;
2477 }
2478 
ScheduleNotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback,const int32_t recordId)2479 int32_t MainThread::ScheduleNotifyUnLoadRepairPatch(const std::string &bundleName,
2480     const sptr<IQuickFixCallback> &callback, const int32_t recordId)
2481 {
2482     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2483     HILOG_DEBUG("ScheduleNotifyUnLoadRepairPatch function called.");
2484     wptr<MainThread> weak = this;
2485     auto task = [weak, bundleName, callback, recordId]() {
2486         auto appThread = weak.promote();
2487         if (appThread == nullptr || appThread->application_ == nullptr || callback == nullptr) {
2488             HILOG_ERROR("ScheduleNotifyUnLoadRepairPatch, parameter is nullptr.");
2489             return;
2490         }
2491 
2492         bool ret = true;
2493         std::vector<std::pair<std::string, std::string>> hqfFilePair;
2494         if (appThread->GetHqfFileAndHapPath(bundleName, hqfFilePair)) {
2495             for (auto it = hqfFilePair.begin(); it != hqfFilePair.end(); it++) {
2496                 HILOG_INFO("ScheduleNotifyUnLoadRepairPatch, UnloadPatch, hqfFile: %{private}s.", it->first.c_str());
2497                 ret = appThread->application_->NotifyUnLoadRepairPatch(it->first);
2498             }
2499         } else {
2500             HILOG_DEBUG("ScheduleNotifyUnLoadRepairPatch, There's no hqfFile need to unload.");
2501         }
2502 
2503         callback->OnUnloadPatchDone(ret ? NO_ERROR : ERR_INVALID_OPERATION, recordId);
2504     };
2505     if (mainHandler_ == nullptr || !mainHandler_->PostTask(task)) {
2506         HILOG_ERROR("ScheduleNotifyUnLoadRepairPatch, Post task failed.");
2507         return ERR_INVALID_VALUE;
2508     }
2509 
2510     return NO_ERROR;
2511 }
2512 
ScheduleNotifyAppFault(const FaultData & faultData)2513 int32_t MainThread::ScheduleNotifyAppFault(const FaultData &faultData)
2514 {
2515     if (mainHandler_ == nullptr) {
2516         HILOG_ERROR("mainHandler is nullptr");
2517         return ERR_INVALID_VALUE;
2518     }
2519 
2520     if (faultData.faultType == FaultDataType::APP_FREEZE) {
2521         return AppExecFwk::AppfreezeInner::GetInstance()->AppfreezeHandle(faultData, false);
2522     }
2523 
2524     wptr<MainThread> weak = this;
2525     auto task = [weak, faultData] {
2526         auto appThread = weak.promote();
2527         if (appThread == nullptr) {
2528             HILOG_ERROR("appThread is nullptr, NotifyAppFault failed.");
2529             return;
2530         }
2531         appThread->NotifyAppFault(faultData);
2532     };
2533     mainHandler_->PostTask(task);
2534     return NO_ERROR;
2535 }
2536 
NotifyAppFault(const FaultData & faultData)2537 void MainThread::NotifyAppFault(const FaultData &faultData)
2538 {
2539     if (faultData.notifyApp) {
2540         ErrorObject faultErrorObj = {
2541             .name = faultData.errorObject.name,
2542             .message = faultData.errorObject.message,
2543             .stack = faultData.errorObject.stack
2544         };
2545         ApplicationDataManager::GetInstance().NotifyExceptionObject(faultErrorObj);
2546     }
2547 }
2548 
SetProcessExtensionType(const std::shared_ptr<AbilityLocalRecord> & abilityRecord)2549 void MainThread::SetProcessExtensionType(const std::shared_ptr<AbilityLocalRecord> &abilityRecord)
2550 {
2551     if (!extensionConfigMgr_) {
2552         HILOG_ERROR("AddExtensionBlockItem failed, extensionConfigMgr_ is null");
2553         return;
2554     }
2555     if (!abilityRecord) {
2556         HILOG_ERROR("AddExtensionBlockItem failed, abilityRecord is null");
2557         return;
2558     }
2559     if (!abilityRecord->GetAbilityInfo()) {
2560         HILOG_ERROR("AddExtensionBlockItem failed, abilityInfo is null");
2561         return;
2562     }
2563     HILOG_INFO("SetProcessExtensionType, type = %{public}d",
2564         static_cast<int32_t>(abilityRecord->GetAbilityInfo()->extensionAbilityType));
2565     extensionConfigMgr_->SetProcessExtensionType(
2566         static_cast<int32_t>(abilityRecord->GetAbilityInfo()->extensionAbilityType));
2567 }
2568 
AddExtensionBlockItem(const std::string & extensionName,int32_t type)2569 void MainThread::AddExtensionBlockItem(const std::string &extensionName, int32_t type)
2570 {
2571     if (!extensionConfigMgr_) {
2572         HILOG_ERROR("AddExtensionBlockItem failed, extensionConfigMgr_ is null");
2573         return;
2574     }
2575     extensionConfigMgr_->AddBlockListItem(extensionName, type);
2576 }
2577 
UpdateRuntimeModuleChecker(const std::unique_ptr<AbilityRuntime::Runtime> & runtime)2578 void MainThread::UpdateRuntimeModuleChecker(const std::unique_ptr<AbilityRuntime::Runtime> &runtime)
2579 {
2580     if (!extensionConfigMgr_) {
2581         HILOG_ERROR("UpdateRuntimeModuleChecker failed, extensionConfigMgr_ is null");
2582         return;
2583     }
2584     extensionConfigMgr_->UpdateRuntimeModuleChecker(runtime);
2585 }
2586 
GetOverlayModuleInfos(const std::string & bundleName,const std::string & moduleName,std::vector<OverlayModuleInfo> & overlayModuleInfos) const2587 int MainThread::GetOverlayModuleInfos(const std::string &bundleName, const std::string &moduleName,
2588     std::vector<OverlayModuleInfo> &overlayModuleInfos) const
2589 {
2590     sptr<AppExecFwk::IBundleMgr> bundleMgr = AAFwk::AbilityUtil::GetBundleManager();
2591     if (bundleMgr == nullptr) {
2592         HILOG_ERROR("ContextImpl::CreateBundleContext GetBundleManager is nullptr");
2593         return ERR_INVALID_VALUE;
2594     }
2595 
2596     auto overlayMgrProxy = bundleMgr->GetOverlayManagerProxy();
2597     if (overlayMgrProxy == nullptr) {
2598         HILOG_ERROR("GetOverlayManagerProxy failed.");
2599         return ERR_INVALID_VALUE;
2600     }
2601 
2602     auto ret = overlayMgrProxy->GetTargetOverlayModuleInfo(moduleName, overlayModuleInfos);
2603     if (ret != ERR_OK) {
2604         HILOG_ERROR("GetOverlayModuleInfo form bms failed.");
2605         return ret;
2606     }
2607     std::sort(overlayModuleInfos.begin(), overlayModuleInfos.end(),
2608         [](const OverlayModuleInfo& lhs, const OverlayModuleInfo& rhs) -> bool {
2609         return lhs.priority > rhs.priority;
2610     });
2611     HILOG_DEBUG("GetOverlayPath end, the size of overlay is: %{public}zu", overlayModuleInfos.size());
2612     return ERR_OK;
2613 }
2614 
GetAddOverlayPaths(const std::vector<OverlayModuleInfo> & overlayModuleInfos)2615 std::vector<std::string> MainThread::GetAddOverlayPaths(const std::vector<OverlayModuleInfo> &overlayModuleInfos)
2616 {
2617     std::vector<std::string> addPaths;
2618     for (auto it : overlayModuleInfos) {
2619         auto iter = std::find_if(
2620             overlayModuleInfos_.begin(), overlayModuleInfos_.end(), [it](OverlayModuleInfo item) {
2621                 return it.moduleName == item.moduleName;
2622             });
2623         if ((iter != overlayModuleInfos_.end()) && (it.state == AppExecFwk::OverlayState::OVERLAY_ENABLE)) {
2624             iter->state = it.state;
2625             ChangeToLocalPath(iter->bundleName, iter->hapPath, iter->hapPath);
2626             HILOG_DEBUG("add path:%{public}s.", iter->hapPath.c_str());
2627             addPaths.emplace_back(iter->hapPath);
2628         }
2629     }
2630     return addPaths;
2631 }
2632 
GetRemoveOverlayPaths(const std::vector<OverlayModuleInfo> & overlayModuleInfos)2633 std::vector<std::string> MainThread::GetRemoveOverlayPaths(const std::vector<OverlayModuleInfo> &overlayModuleInfos)
2634 {
2635     std::vector<std::string> removePaths;
2636     for (auto it : overlayModuleInfos) {
2637         auto iter = std::find_if(
2638             overlayModuleInfos_.begin(), overlayModuleInfos_.end(), [it](OverlayModuleInfo item) {
2639                 return it.moduleName == item.moduleName;
2640             });
2641         if ((iter != overlayModuleInfos_.end()) && (it.state != AppExecFwk::OverlayState::OVERLAY_ENABLE)) {
2642             iter->state = it.state;
2643             ChangeToLocalPath(iter->bundleName, iter->hapPath, iter->hapPath);
2644             HILOG_DEBUG("remove path:%{public}s.", iter->hapPath.c_str());
2645             removePaths.emplace_back(iter->hapPath);
2646         }
2647     }
2648 
2649     return removePaths;
2650 }
2651 }  // namespace AppExecFwk
2652 }  // namespace OHOS
2653