1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "main_thread.h"
17 
18 #include <malloc.h>
19 #include <new>
20 #include <regex>
21 #include <sys/prctl.h>
22 #include <sys/wait.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25 
26 #include "ability_manager_client.h"
27 #include "constants.h"
28 #include "ability_delegator.h"
29 #include "ability_delegator_registry.h"
30 #include "ability_loader.h"
31 #include "ability_thread.h"
32 #include "ability_util.h"
33 #include "app_loader.h"
34 #include "app_recovery.h"
35 #include "appfreeze_inner.h"
36 #include "appfreeze_state.h"
37 #include "application_data_manager.h"
38 #include "application_env_impl.h"
39 #include "bundle_mgr_proxy.h"
40 #include "hitrace_meter.h"
41 #include "child_main_thread.h"
42 #include "child_process_manager.h"
43 #include "configuration_convertor.h"
44 #include "common_event_manager.h"
45 #include "global_constant.h"
46 #include "context_deal.h"
47 #include "context_impl.h"
48 #include "dump_ffrt_helper.h"
49 #include "dump_ipc_helper.h"
50 #include "dump_runtime_helper.h"
51 #include "exit_reason.h"
52 #include "extension_ability_info.h"
53 #include "extension_module_loader.h"
54 #include "extension_plugin_info.h"
55 #include "extract_resource_manager.h"
56 #include "ffrt.h"
57 #include "file_path_utils.h"
58 #include "freeze_util.h"
59 #include "hilog_tag_wrapper.h"
60 #include "resource_config_helper.h"
61 #ifdef SUPPORT_SCREEN
62 #include "locale_config.h"
63 #include "ace_forward_compatibility.h"
64 #include "form_constants.h"
65 #include "include/private/EGL/cache.h"
66 #ifdef SUPPORT_APP_PREFERRED_LANGUAGE
67 #include "preferred_language.h"
68 #endif
69 #endif
70 #include "app_mgr_client.h"
71 #include "if_system_ability_manager.h"
72 #include "iservice_registry.h"
73 #include "js_runtime.h"
74 #ifdef CJ_FRONTEND
75 #include "cj_runtime.h"
76 #endif
77 #include "native_lib_util.h"
78 #include "nlohmann/json.hpp"
79 #include "ohos_application.h"
80 #include "overlay_module_info.h"
81 #include "parameters.h"
82 #include "resource_manager.h"
83 #include "runtime.h"
84 #include "sys_mgr_client.h"
85 #include "system_ability_definition.h"
86 #include "task_handler_client.h"
87 #include "time_util.h"
88 #include "uncaught_exception_callback.h"
89 #include "hisysevent.h"
90 #include "js_runtime_utils.h"
91 #include "context/application_context.h"
92 #include "os_account_manager_wrapper.h"
93 
94 #if defined(NWEB)
95 #include <thread>
96 #include "app_mgr_client.h"
97 #include "nweb_helper.h"
98 #endif
99 
100 #ifdef IMAGE_PURGEABLE_PIXELMAP
101 #include "purgeable_resource_manager.h"
102 #endif
103 
104 #if defined(ABILITY_LIBRARY_LOADER) || defined(APPLICATION_LIBRARY_LOADER)
105 #include <dirent.h>
106 #include <dlfcn.h>
107 #endif
108 namespace OHOS {
109 using AbilityRuntime::FreezeUtil;
110 namespace AppExecFwk {
111 using namespace OHOS::AbilityBase::Constants;
112 std::weak_ptr<OHOSApplication> MainThread::applicationForDump_;
113 std::shared_ptr<MainThread::MainHandler> MainThread::mainHandler_ = nullptr;
114 const std::string PERFCMD_PROFILE = "profile";
115 const std::string PERFCMD_DUMPHEAP = "dumpheap";
116 namespace {
117 #ifdef APP_USE_ARM
118 constexpr char FORM_RENDER_LIB_PATH[] = "/system/lib/libformrender.z.so";
119 #elif defined(APP_USE_X86_64)
120 constexpr char FORM_RENDER_LIB_PATH[] = "/system/lib64/libformrender.z.so";
121 #else
122 constexpr char FORM_RENDER_LIB_PATH[] = "/system/lib64/libformrender.z.so";
123 #endif
124 
125 constexpr int32_t DELIVERY_TIME = 200;
126 constexpr int32_t DISTRIBUTE_TIME = 100;
127 constexpr int32_t START_HIGH_SENSITIVE = 1;
128 constexpr int32_t EXIT_HIGH_SENSITIVE = 2;
129 constexpr int32_t UNSPECIFIED_USERID = -2;
130 constexpr int32_t JS_ERROR_EXIT = -2;
131 constexpr int32_t TIME_OUT = 120;
132 constexpr int32_t DEFAULT_SLEEP_TIME = 100000;
133 
134 enum class SignalType {
135     SIGNAL_JSHEAP_OLD,
136     SIGNAL_JSHEAP,
137     SIGNAL_JSHEAP_PRIV,
138     SIGNAL_NO_TRIGGERID,
139     SIGNAL_NO_TRIGGERID_PRIV,
140     SIGNAL_FORCE_FULLGC,
141 };
142 
143 constexpr char EVENT_KEY_PACKAGE_NAME[] = "PACKAGE_NAME";
144 constexpr char EVENT_KEY_VERSION[] = "VERSION";
145 constexpr char EVENT_KEY_TYPE[] = "TYPE";
146 constexpr char EVENT_KEY_HAPPEN_TIME[] = "HAPPEN_TIME";
147 constexpr char EVENT_KEY_REASON[] = "REASON";
148 constexpr char EVENT_KEY_JSVM[] = "JSVM";
149 constexpr char EVENT_KEY_SUMMARY[] = "SUMMARY";
150 constexpr char EVENT_KEY_PNAME[] = "PNAME";
151 constexpr char EVENT_KEY_APP_RUNING_UNIQUE_ID[] = "APP_RUNNING_UNIQUE_ID";
152 constexpr char DEVELOPER_MODE_STATE[] = "const.security.developermode.state";
153 constexpr char PRODUCT_ASSERT_FAULT_DIALOG_ENABLED[] = "persisit.sys.abilityms.support_assert_fault_dialog";
154 constexpr char KILL_REASON[] = "Kill Reason:Js Error";
155 
156 const int32_t JSCRASH_TYPE = 3;
157 const std::string JSVM_TYPE = "ARK";
158 const std::string SIGNAL_HANDLER = "OS_SignalHandler";
159 
160 constexpr uint32_t CHECK_MAIN_THREAD_IS_ALIVE = 1;
161 
162 const std::string OVERLAY_STATE_CHANGED = "usual.event.OVERLAY_STATE_CHANGED";
163 const std::string JSON_KEY_APP_FONT_SIZE_SCALE = "fontSizeScale";
164 const std::string JSON_KEY_APP_FONT_MAX_SCALE = "fontSizeMaxScale";
165 const std::string JSON_KEY_APP_CONFIGURATION = "configuration";
166 const std::string DEFAULT_APP_FONT_SIZE_SCALE = "nonFollowSystem";
167 const std::string SYSTEM_DEFAULT_FONTSIZE_SCALE = "1.0";
168 const int32_t TYPE_RESERVE = 1;
169 const int32_t TYPE_OTHERS = 2;
170 
171 extern "C" int DFX_SetAppRunningUniqueId(const char* appRunningId, size_t len) __attribute__((weak));
172 } // namespace
173 
GetNativeLibPath(const BundleInfo &bundleInfo, const HspList &hspList, AppLibPathMap &appLibPaths)174 void MainThread::GetNativeLibPath(const BundleInfo &bundleInfo, const HspList &hspList, AppLibPathMap &appLibPaths)
175 {
176     std::string patchNativeLibraryPath = bundleInfo.applicationInfo.appQuickFix.deployedAppqfInfo.nativeLibraryPath;
177     if (!patchNativeLibraryPath.empty()) {
178         // libraries in patch lib path has a higher priority when loading.
179         std::string patchLibPath = LOCAL_CODE_PATH;
180         patchLibPath += (patchLibPath.back() == '/') ? patchNativeLibraryPath : "/" + patchNativeLibraryPath;
181         TAG_LOGD(AAFwkTag::APPKIT, "lib path = %{private}s", patchLibPath.c_str());
182         appLibPaths["default"].emplace_back(patchLibPath);
183     }
184 
185     std::string nativeLibraryPath = bundleInfo.applicationInfo.nativeLibraryPath;
186     if (!nativeLibraryPath.empty()) {
187         if (nativeLibraryPath.back() == '/') {
188             nativeLibraryPath.pop_back();
189         }
190         std::string libPath = LOCAL_CODE_PATH;
191         libPath += (libPath.back() == '/') ? nativeLibraryPath : "/" + nativeLibraryPath;
192         TAG_LOGD(AAFwkTag::APPKIT, "lib path = %{private}s", libPath.c_str());
193         appLibPaths["default"].emplace_back(libPath);
194     }
195 
196     for (auto &hapInfo : bundleInfo.hapModuleInfos) {
197         TAG_LOGD(AAFwkTag::APPKIT,
198             "moduleName: %{public}s, isLibIsolated: %{public}d, compressNativeLibs: %{public}d.",
199             hapInfo.moduleName.c_str(), hapInfo.isLibIsolated, hapInfo.compressNativeLibs);
200         GetPatchNativeLibPath(hapInfo, patchNativeLibraryPath, appLibPaths);
201         GetHapSoPath(hapInfo, appLibPaths, hapInfo.hapPath.find(ABS_CODE_PATH));
202     }
203 
204     for (auto &hspInfo : hspList) {
205         TAG_LOGD(AAFwkTag::APPKIT, "bundle:%s, module:%s, nativeLibraryPath:%s", hspInfo.bundleName.c_str(),
206             hspInfo.moduleName.c_str(), hspInfo.nativeLibraryPath.c_str());
207         GetHspNativeLibPath(hspInfo, appLibPaths, hspInfo.hapPath.find(ABS_CODE_PATH) != 0u);
208     }
209 }
210 
211 /**
212  *
213  * @brief Notify the AppMgrDeathRecipient that the remote is dead.
214  *
215  * @param remote The remote which is dead.
216  */
OnRemoteDied(const wptr<IRemoteObject> &remote)217 void AppMgrDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
218 {
219     TAG_LOGE(AAFwkTag::APPKIT, "remote died receive");
220 }
221 
MainThread()222 MainThread::MainThread()
223 {
224 #ifdef ABILITY_LIBRARY_LOADER
225     fileEntries_.clear();
226     nativeFileEntries_.clear();
227     handleAbilityLib_.clear();
228 #endif  // ABILITY_LIBRARY_LOADER
229 }
230 
~MainThread()231 MainThread::~MainThread()
232 {
233     TAG_LOGD(AAFwkTag::APPKIT, "called");
234     if (watchdog_ != nullptr && !watchdog_->IsStopWatchdog()) {
235         watchdog_->Stop();
236         watchdog_ = nullptr;
237     }
238 }
239 
240 /**
241  *
242  * @brief Get the current MainThreadState.
243  *
244  * @return Returns the current MainThreadState.
245  */
GetMainThreadState() const246 MainThreadState MainThread::GetMainThreadState() const
247 {
248     return mainThreadState_;
249 }
250 
251 /**
252  *
253  * @brief Set the runner state of mainthread.
254  *
255  * @param runnerStart whether the runner is started.
256  */
SetRunnerStarted(bool runnerStart)257 void MainThread::SetRunnerStarted(bool runnerStart)
258 {
259     isRunnerStarted_ = runnerStart;
260 }
261 
262 /**
263  *
264  * @brief Get the runner state of mainthread.
265  *
266  * @return Returns the runner state of mainthread.
267  */
GetRunnerStarted() const268 bool MainThread::GetRunnerStarted() const
269 {
270     return isRunnerStarted_;
271 }
272 
273 /**
274  *
275  * @brief Get the newThreadId.
276  *
277  * @return Returns the newThreadId.
278  */
GetNewThreadId()279 int MainThread::GetNewThreadId()
280 {
281     return newThreadId_++;
282 }
283 
284 /**
285  *
286  * @brief Get the application.
287  *
288  * @return Returns the application.
289  */
GetApplication() const290 std::shared_ptr<OHOSApplication> MainThread::GetApplication() const
291 {
292     return application_;
293 }
294 
295 /**
296  *
297  * @brief Get the applicationInfo.
298  *
299  * @return Returns the applicationInfo.
300  */
GetApplicationInfo() const301 std::shared_ptr<ApplicationInfo> MainThread::GetApplicationInfo() const
302 {
303     return applicationInfo_;
304 }
305 
306 /**
307  *
308  * @brief Get the applicationImpl.
309  *
310  * @return Returns the applicationImpl.
311  */
GetApplicationImpl()312 std::shared_ptr<ApplicationImpl> MainThread::GetApplicationImpl()
313 {
314     return applicationImpl_;
315 }
316 
317 /**
318  *
319  * @brief Connect the mainthread to the AppMgr.
320  *
321  */
ConnectToAppMgr()322 bool MainThread::ConnectToAppMgr()
323 {
324     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
325     TAG_LOGD(AAFwkTag::APPKIT, "%{public}s start.", __func__);
326     auto object = OHOS::DelayedSingleton<SysMrgClient>::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID);
327     if (object == nullptr) {
328         TAG_LOGE(AAFwkTag::APPKIT, "failed to get app manager service");
329         return false;
330     }
331     deathRecipient_ = new (std::nothrow) AppMgrDeathRecipient();
332     if (deathRecipient_ == nullptr) {
333         TAG_LOGE(AAFwkTag::APPKIT, "failed to new AppMgrDeathRecipient");
334         return false;
335     }
336 
337     if (!object->AddDeathRecipient(deathRecipient_)) {
338         TAG_LOGE(AAFwkTag::APPKIT, "failed to AddDeathRecipient");
339         return false;
340     }
341 
342     appMgr_ = iface_cast<IAppMgr>(object);
343     if (appMgr_ == nullptr) {
344         TAG_LOGE(AAFwkTag::APPKIT, "failed to iface_cast object to appMgr_");
345         return false;
346     }
347     TAG_LOGI(AAFwkTag::APPKIT, "attach to appMGR.");
348     appMgr_->AttachApplication(this);
349     TAG_LOGD(AAFwkTag::APPKIT, "end");
350     return true;
351 }
352 
353 /**
354  *
355  * @brief Attach the mainthread to the AppMgr.
356  *
357  */
Attach()358 void MainThread::Attach()
359 {
360     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
361     TAG_LOGD(AAFwkTag::APPKIT, "Attach");
362     if (!ConnectToAppMgr()) {
363         TAG_LOGE(AAFwkTag::APPKIT, "attachApplication failed");
364         return;
365     }
366     mainThreadState_ = MainThreadState::ATTACH;
367     isDeveloperMode_ = system::GetBoolParameter(DEVELOPER_MODE_STATE, false);
368     auto bundleMgrHelper = DelayedSingleton<BundleMgrHelper>::GetInstance();
369     if (bundleMgrHelper == nullptr) {
370         TAG_LOGE(AAFwkTag::APPKIT, "The bundleMgrHelper is nullptr");
371         return;
372     }
373     bundleMgrHelper->PreConnect();
374 }
375 
376 /**
377  *
378  * @brief remove the deathRecipient from appMgr.
379  *
380  */
RemoveAppMgrDeathRecipient()381 void MainThread::RemoveAppMgrDeathRecipient()
382 {
383     TAG_LOGD(AAFwkTag::APPKIT, "called");
384     if (appMgr_ == nullptr) {
385         TAG_LOGE(AAFwkTag::APPKIT, "failed");
386         return;
387     }
388 
389     sptr<IRemoteObject> object = appMgr_->AsObject();
390     if (object != nullptr) {
391         object->RemoveDeathRecipient(deathRecipient_);
392     } else {
393         TAG_LOGE(AAFwkTag::APPKIT, "appMgr_->AsObject() failed");
394     }
395 }
396 
397 /**
398  *
399  * @brief Get the eventHandler of mainthread.
400  *
401  * @return Returns the eventHandler of mainthread.
402  */
GetMainHandler() const403 std::shared_ptr<EventHandler> MainThread::GetMainHandler() const
404 {
405     return mainHandler_;
406 }
407 
408 /**
409  *
410  * @brief Schedule the foreground lifecycle of application.
411  *
412  */
ScheduleForegroundApplication()413 bool MainThread::ScheduleForegroundApplication()
414 {
415     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
416     FreezeUtil::GetInstance().AddAppLifecycleEvent(0, "ScheduleForegroundApplication");
417     TAG_LOGD(AAFwkTag::APPKIT, "called");
418     wptr<MainThread> weak = this;
419     auto task = [weak]() {
420         auto appThread = weak.promote();
421         if (appThread == nullptr) {
422             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr.");
423             return;
424         }
425         appThread->HandleForegroundApplication();
426     };
427     if (!mainHandler_->PostTask(task, "MainThread:ForegroundApplication")) {
428         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
429     }
430     auto tmpWatchdog = watchdog_;
431     if (tmpWatchdog == nullptr) {
432         TAG_LOGE(AAFwkTag::APPKIT, "Watch dog is nullptr.");
433     } else {
434         tmpWatchdog->SetBackgroundStatus(false);
435     }
436     return true;
437 }
438 
439 /**
440  *
441  * @brief Schedule the background lifecycle of application.
442  *
443  */
ScheduleBackgroundApplication()444 void MainThread::ScheduleBackgroundApplication()
445 {
446     TAG_LOGI(AAFwkTag::APPKIT, "called");
447     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
448     wptr<MainThread> weak = this;
449     auto task = [weak]() {
450         auto appThread = weak.promote();
451         if (appThread == nullptr) {
452             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
453             return;
454         }
455         appThread->HandleBackgroundApplication();
456     };
457     if (!mainHandler_->PostTask(task, "MainThread:BackgroundApplication")) {
458         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
459     }
460 
461     auto tmpWatchdog = watchdog_;
462     if (tmpWatchdog == nullptr) {
463         TAG_LOGE(AAFwkTag::APPKIT, "Watch dog is nullptr.");
464         return;
465     }
466     tmpWatchdog->SetBackgroundStatus(true);
467     tmpWatchdog = nullptr;
468 }
469 
470 /**
471  *
472  * @brief Schedule the terminate lifecycle of application.
473  *
474  * @param isLastProcess When it is the last application process, pass in true.
475  */
ScheduleTerminateApplication(bool isLastProcess)476 void MainThread::ScheduleTerminateApplication(bool isLastProcess)
477 {
478     TAG_LOGD(AAFwkTag::APPKIT, "called");
479     wptr<MainThread> weak = this;
480     auto task = [weak, isLastProcess]() {
481         auto appThread = weak.promote();
482         if (appThread == nullptr) {
483             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
484             return;
485         }
486         appThread->HandleTerminateApplication(isLastProcess);
487     };
488     if (!mainHandler_->PostTask(task, "MainThread:TerminateApplication")) {
489         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
490     }
491 }
492 
493 /**
494  *
495  * @brief Shrink the memory which used by application.
496  *
497  * @param level Indicates the memory trim level, which shows the current memory usage status.
498  */
ScheduleShrinkMemory(const int level)499 void MainThread::ScheduleShrinkMemory(const int level)
500 {
501     TAG_LOGD(AAFwkTag::APPKIT, "level: %{public}d", level);
502     wptr<MainThread> weak = this;
503     auto task = [weak, level]() {
504         auto appThread = weak.promote();
505         if (appThread == nullptr) {
506             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
507             return;
508         }
509         appThread->HandleShrinkMemory(level);
510     };
511     if (!mainHandler_->PostTask(task, "MainThread:ShrinkMemory")) {
512         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
513     }
514 }
515 
516 /**
517  *
518  * @brief Notify the memory level.
519  *
520  * @param level Indicates the memory trim level, which shows the current memory usage status.
521  */
ScheduleMemoryLevel(const int level)522 void MainThread::ScheduleMemoryLevel(const int level)
523 {
524     TAG_LOGD(AAFwkTag::APPKIT, "level: %{public}d", level);
525     wptr<MainThread> weak = this;
526     auto task = [weak, level]() {
527         auto appThread = weak.promote();
528         if (appThread == nullptr) {
529             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
530             return;
531         }
532         appThread->HandleMemoryLevel(level);
533     };
534     if (!mainHandler_->PostTask(task, "MainThread:MemoryLevel")) {
535         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
536     }
537 }
538 
539 /**
540  *
541  * @brief Get the application's memory allocation info.
542  *
543  * @param pid, pid input.
544  * @param mallocInfo, dynamic storage information output.
545  */
ScheduleHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)546 void MainThread::ScheduleHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)
547 {
548     struct mallinfo mi = mallinfo();
549     int usmblks = mi.usmblks; // 当前从分配器中分配的总的堆内存大小
550     int uordblks = mi.uordblks; // 当前已释放给分配器,分配缓存了未释放给系统的内存大小
551     int fordblks = mi.fordblks; // 当前未释放的大小
552     int hblkhd = mi.hblkhd; // 堆内存的总共占用大小
553     TAG_LOGD(AAFwkTag::APPKIT, "The pid of the app we want to dump memory allocation information is: %{public}i", pid);
554     TAG_LOGD(AAFwkTag::APPKIT, "usmblks: %{public}i, uordblks: %{public}i, fordblks: %{public}i, hblkhd: %{public}i",
555         usmblks, uordblks, fordblks, hblkhd);
556     mallocInfo.usmblks = usmblks;
557     mallocInfo.uordblks = uordblks;
558     mallocInfo.fordblks = fordblks;
559     mallocInfo.hblkhd = hblkhd;
560 }
561 
562 /**
563  *
564  * @brief the application triggerGC and dump jsheap memory.
565  *
566  * @param info, pid, tid, needGC, needSnapshot.
567  */
ScheduleJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info)568 void MainThread::ScheduleJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info)
569 {
570     TAG_LOGI(AAFwkTag::APPKIT, "pid: %{public}d, tid: %{public}d, needGc: %{public}d, needSnapshot: %{public}d,\n"
571         "needLeakobj: %{public}d", info.pid, info.tid, info.needGc, info.needSnapshot, info.needLeakobj);
572     wptr<MainThread> weak = this;
573     auto task = [weak, info]() {
574         auto appThread = weak.promote();
575         if (appThread == nullptr) {
576             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
577             return;
578         }
579         appThread->HandleJsHeapMemory(info);
580     };
581     if (!mainHandler_->PostTask(task, "MainThread:HandleJsHeapMemory")) {
582         TAG_LOGE(AAFwkTag::APPKIT, "PostTask HandleJsHeapMemory failed");
583     }
584 }
585 
586 /**
587  *
588  * @brief Schedule the application process exit safely.
589  *
590  */
ScheduleProcessSecurityExit()591 void MainThread::ScheduleProcessSecurityExit()
592 {
593     wptr<MainThread> weak = this;
594     auto task = [weak]() {
595         auto appThread = weak.promote();
596         if (appThread == nullptr) {
597             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
598             return;
599         }
600         appThread->HandleProcessSecurityExit();
601     };
602     bool result = mainHandler_->PostTask(task, "MainThread:ProcessSecurityExit");
603     if (!result) {
604         TAG_LOGE(AAFwkTag::APPKIT, "post task failed");
605     }
606 }
607 
608 /**
609  *
610  * @brief Schedule the application clear recovery page stack.
611  *
612  */
ScheduleClearPageStack()613 void MainThread::ScheduleClearPageStack()
614 {
615     TAG_LOGI(AAFwkTag::APPKIT, "ScheduleClearPageStack called");
616     if (applicationInfo_ == nullptr) {
617         TAG_LOGE(AAFwkTag::APPKIT, "applicationInfo_ is nullptr");
618         return;
619     }
620 
621     auto bundleName = applicationInfo_->bundleName;
622     AppRecovery::GetInstance().ClearPageStack(bundleName);
623 }
624 
625 /**
626  *
627  * @brief Low the memory which used by application.
628  *
629  */
ScheduleLowMemory()630 void MainThread::ScheduleLowMemory()
631 {}
632 
633 /**
634  *
635  * @brief Launch the application.
636  *
637  * @param data The launchdata of the application witch launced.
638  *
639  */
ScheduleLaunchApplication(const AppLaunchData &data, const Configuration &config)640 void MainThread::ScheduleLaunchApplication(const AppLaunchData &data, const Configuration &config)
641 {
642     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
643     TAG_LOGD(AAFwkTag::APPKIT, "called");
644     FreezeUtil::GetInstance().AddAppLifecycleEvent(0, "ScheduleLaunchApplication");
645     wptr<MainThread> weak = this;
646     auto task = [weak, data, config]() {
647         auto appThread = weak.promote();
648         if (appThread == nullptr) {
649             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
650             return;
651         }
652         appThread->HandleInitAssertFaultTask(data.GetDebugApp(), data.GetApplicationInfo().debug);
653         appThread->HandleLaunchApplication(data, config);
654     };
655     if (!mainHandler_->PostTask(task, "MainThread:LaunchApplication")) {
656         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
657     }
658 }
659 
660 /**
661  *
662  * @brief update the application info after new module installed.
663  *
664  * @param appInfo The latest application info obtained from bms for update abilityRuntimeContext.
665  *
666  */
ScheduleUpdateApplicationInfoInstalled(const ApplicationInfo &appInfo)667 void MainThread::ScheduleUpdateApplicationInfoInstalled(const ApplicationInfo &appInfo)
668 {
669     TAG_LOGD(AAFwkTag::APPKIT, "ScheduleUpdateApplicationInfoInstalled");
670     wptr<MainThread> weak = this;
671     auto task = [weak, appInfo]() {
672         auto appThread = weak.promote();
673         if (appThread == nullptr) {
674             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
675             return;
676         }
677         appThread->HandleUpdateApplicationInfoInstalled(appInfo);
678     };
679     if (!mainHandler_->PostTask(task, "MainThread:UpdateApplicationInfoInstalled")) {
680         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
681     }
682 }
683 
ScheduleAbilityStage(const HapModuleInfo &abilityStage)684 void MainThread::ScheduleAbilityStage(const HapModuleInfo &abilityStage)
685 {
686     TAG_LOGD(AAFwkTag::APPKIT, "called");
687     wptr<MainThread> weak = this;
688     auto task = [weak, abilityStage]() {
689         auto appThread = weak.promote();
690         if (appThread == nullptr) {
691             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
692             return;
693         }
694         appThread->HandleAbilityStage(abilityStage);
695     };
696     if (!mainHandler_->PostTask(task, "MainThread:AbilityStage")) {
697         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
698     }
699 }
700 
IsBgWorkingThread(const AbilityInfo &info)701 bool MainThread::IsBgWorkingThread(const AbilityInfo &info)
702 {
703     return info.extensionAbilityType == ExtensionAbilityType::BACKUP;
704 }
705 
ScheduleLaunchAbility(const AbilityInfo &info, const sptr<IRemoteObject> &token, const std::shared_ptr<AAFwk::Want> &want, int32_t abilityRecordId)706 void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr<IRemoteObject> &token,
707     const std::shared_ptr<AAFwk::Want> &want, int32_t abilityRecordId)
708 {
709     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
710     TAG_LOGI(AAFwkTag::APPKIT, "%{public}s called, ability %{public}s, type is %{public}d.",
711         __func__, info.name.c_str(), info.type);
712 
713     if (want != nullptr) {
714         AAFwk::Want newWant(*want);
715         newWant.CloseAllFd();
716     }
717     std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>(info);
718     auto abilityRecord = std::make_shared<AbilityLocalRecord>(abilityInfo, token, want, abilityRecordId);
719     auto tmpWatchdog = watchdog_;
720     if (tmpWatchdog != nullptr) {
721         tmpWatchdog->SetBgWorkingThreadStatus(IsBgWorkingThread(info));
722         tmpWatchdog = nullptr;
723     }
724     FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::LOAD };
725     std::string entry = "MainThread::ScheduleLaunchAbility; the load lifecycle.";
726     FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
727 
728     wptr<MainThread> weak = this;
729     auto task = [weak, abilityRecord]() {
730         auto appThread = weak.promote();
731         if (appThread == nullptr) {
732             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
733             return;
734         }
735         appThread->HandleLaunchAbility(abilityRecord);
736     };
737     if (!mainHandler_->PostTask(task, "MainThread:LaunchAbility")) {
738         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
739     }
740 }
741 
742 /**
743  *
744  * @brief clean the ability by token.
745  *
746  * @param token The token belong to the ability which want to be cleaned.
747  *
748  */
ScheduleCleanAbility(const sptr<IRemoteObject> &token, bool isCacheProcess)749 void MainThread::ScheduleCleanAbility(const sptr<IRemoteObject> &token, bool isCacheProcess)
750 {
751     TAG_LOGD(AAFwkTag::APPKIT, "called, with isCacheProcess =%{public}d.", isCacheProcess);
752     FreezeUtil::GetInstance().DeleteAppLifecycleEvent(0);
753     FreezeUtil::GetInstance().DeleteLifecycleEvent(token);
754     wptr<MainThread> weak = this;
755     auto task = [weak, token, isCacheProcess]() {
756         auto appThread = weak.promote();
757         if (appThread == nullptr) {
758             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
759             return;
760         }
761         appThread->HandleCleanAbility(token, isCacheProcess);
762     };
763     if (!mainHandler_->PostTask(task, "MainThread:CleanAbility")) {
764         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
765     }
766 }
767 
768 /**
769  *
770  * @brief send the new profile.
771  *
772  * @param profile The updated profile.
773  *
774  */
ScheduleProfileChanged(const Profile &profile)775 void MainThread::ScheduleProfileChanged(const Profile &profile)
776 {
777     TAG_LOGD(AAFwkTag::APPKIT, "profile name: %{public}s", profile.GetName().c_str());
778 }
779 
780 /**
781  *
782  * @brief send the new config to the application.
783  *
784  * @param config The updated config.
785  *
786  */
ScheduleConfigurationUpdated(const Configuration &config)787 void MainThread::ScheduleConfigurationUpdated(const Configuration &config)
788 {
789     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
790     TAG_LOGD(AAFwkTag::APPKIT, "called");
791     wptr<MainThread> weak = this;
792     auto task = [weak, config]() {
793         auto appThread = weak.promote();
794         if (appThread == nullptr) {
795             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
796             return;
797         }
798         appThread->HandleConfigurationUpdated(config);
799     };
800     if (!mainHandler_->PostTask(task, "MainThread:ConfigurationUpdated")) {
801         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
802     }
803 }
804 
CheckLaunchApplicationParam(const AppLaunchData &appLaunchData) const805 bool MainThread::CheckLaunchApplicationParam(const AppLaunchData &appLaunchData) const
806 {
807     if (appLaunchData.GetApplicationInfo().name.empty()) {
808         TAG_LOGE(AAFwkTag::APPKIT, "applicationName is empty");
809         return false;
810     }
811 
812     if (appLaunchData.GetProcessInfo().GetProcessName().empty()) {
813         TAG_LOGE(AAFwkTag::APPKIT, "processName is empty");
814         return false;
815     }
816     return true;
817 }
818 
819 /**
820  *
821  * @brief Check whether the record is legal.
822  *
823  * @param record The record should be checked.
824  *
825  * @return if the record is legal, return true. else return false.
826  */
CheckAbilityItem(const std::shared_ptr<AbilityLocalRecord> &record) const827 bool MainThread::CheckAbilityItem(const std::shared_ptr<AbilityLocalRecord> &record) const
828 {
829     if (record == nullptr) {
830         TAG_LOGE(AAFwkTag::APPKIT, "record is null");
831         return false;
832     }
833 
834     std::shared_ptr<AbilityInfo> abilityInfo = record->GetAbilityInfo();
835     sptr<IRemoteObject> token = record->GetToken();
836 
837     if (abilityInfo == nullptr) {
838         TAG_LOGE(AAFwkTag::APPKIT, "abilityInfo is null");
839         return false;
840     }
841 
842     if (token == nullptr) {
843         TAG_LOGE(AAFwkTag::APPKIT, "token is null");
844         return false;
845     }
846     return true;
847 }
848 
849 /**
850  *
851  * @brief Terminate the application but don't notify ams.
852  *
853  */
HandleTerminateApplicationLocal()854 void MainThread::HandleTerminateApplicationLocal()
855 {
856     TAG_LOGD(AAFwkTag::APPKIT, "called");
857     if (applicationImpl_ == nullptr) {
858         TAG_LOGE(AAFwkTag::APPKIT, "error!");
859         return;
860     }
861     applicationImpl_->PerformTerminateStrong();
862 
863     std::shared_ptr<EventRunner> runner = mainHandler_->GetEventRunner();
864     if (runner == nullptr) {
865         TAG_LOGE(AAFwkTag::APPKIT, "get manHandler error");
866         return;
867     }
868 
869     if (watchdog_ != nullptr && !watchdog_->IsStopWatchdog()) {
870         watchdog_->Stop();
871         watchdog_ = nullptr;
872     }
873 
874     int ret = runner->Stop();
875     if (ret != ERR_OK) {
876         TAG_LOGE(AAFwkTag::APPKIT, "runner->Run failed ret = %{public}d", ret);
877     }
878 
879     TAG_LOGD(AAFwkTag::APPKIT, "runner is stopped");
880     SetRunnerStarted(false);
881     HandleCancelAssertFaultTask();
882 }
883 
HandleJsHeapMemory(const OHOS::AppExecFwk::JsHeapDumpInfo &info)884 void MainThread::HandleJsHeapMemory(const OHOS::AppExecFwk::JsHeapDumpInfo &info)
885 {
886     TAG_LOGD(AAFwkTag::APPKIT, "called");
887     if (mainHandler_ == nullptr) {
888         TAG_LOGE(AAFwkTag::APPKIT, "null mainHandler");
889         return;
890     }
891     auto app = applicationForDump_.lock();
892     if (app == nullptr) {
893         TAG_LOGE(AAFwkTag::APPKIT, "null app");
894         return;
895     }
896     auto helper = std::make_shared<DumpRuntimeHelper>(app);
897     helper->DumpJsHeap(info);
898 }
899 
900 /**
901  *
902  * @brief Schedule the application process exit safely.
903  *
904  */
HandleProcessSecurityExit()905 void MainThread::HandleProcessSecurityExit()
906 {
907     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
908     TAG_LOGD(AAFwkTag::APPKIT, "HandleProcessSecurityExit");
909     if (abilityRecordMgr_ == nullptr) {
910         TAG_LOGE(AAFwkTag::APPKIT, "abilityRecordMgr_ is null");
911         return;
912     }
913     if (application_ == nullptr) {
914         TAG_LOGE(AAFwkTag::APPKIT, "application_ is null");
915         return;
916     }
917     std::vector<sptr<IRemoteObject>> tokens = abilityRecordMgr_->GetAllTokens();
918 
919     for (auto iter = tokens.begin(); iter != tokens.end(); ++iter) {
920         HandleCleanAbilityLocal(*iter);
921     }
922 
923     // in process cache state, there can be abilityStage with no abilities
924     application_->CleanEmptyAbilityStage();
925 
926     HandleTerminateApplicationLocal();
927 }
928 
InitCreate( std::shared_ptr<ContextDeal> &contextDeal, ApplicationInfo &appInfo, ProcessInfo &processInfo)929 bool MainThread::InitCreate(
930     std::shared_ptr<ContextDeal> &contextDeal, ApplicationInfo &appInfo, ProcessInfo &processInfo)
931 {
932     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
933     // get application shared point
934     application_ = std::shared_ptr<OHOSApplication>(ApplicationLoader::GetInstance().GetApplicationByName());
935     if (application_ == nullptr) {
936         TAG_LOGE(AAFwkTag::APPKIT, "create failed");
937         return false;
938     }
939 
940     applicationInfo_ = std::make_shared<ApplicationInfo>(appInfo);
941     if (applicationInfo_ == nullptr) {
942         TAG_LOGE(AAFwkTag::APPKIT, "create applicationInfo_ failed");
943         return false;
944     }
945 
946     processInfo_ = std::make_shared<ProcessInfo>(processInfo);
947     if (processInfo_ == nullptr) {
948         TAG_LOGE(AAFwkTag::APPKIT, "create processInfo_ failed");
949         return false;
950     }
951 
952     applicationImpl_ = std::make_shared<ApplicationImpl>();
953     if (applicationImpl_ == nullptr) {
954         TAG_LOGE(AAFwkTag::APPKIT, "create applicationImpl_ failed");
955         return false;
956     }
957 
958     abilityRecordMgr_ = std::make_shared<AbilityRecordMgr>();
959     if (abilityRecordMgr_ == nullptr) {
960         TAG_LOGE(AAFwkTag::APPKIT, "create AbilityRecordMgr failed");
961         return false;
962     }
963 
964     contextDeal = std::make_shared<ContextDeal>();
965     if (contextDeal == nullptr) {
966         TAG_LOGE(AAFwkTag::APPKIT, "create contextDeal failed");
967         return false;
968     }
969     AppExecFwk::AppfreezeInner::GetInstance()->SetApplicationInfo(applicationInfo_);
970 
971     application_->SetProcessInfo(processInfo_);
972     contextDeal->SetApplicationInfo(applicationInfo_);
973     contextDeal->SetBundleCodePath(applicationInfo_->codePath);  // BMS need to add cpath
974 
975     return true;
976 }
977 
CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData)978 bool MainThread::CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData)
979 {
980     if (!CheckLaunchApplicationParam(appLaunchData)) {
981         TAG_LOGE(AAFwkTag::APPKIT, "appLaunchData invalid");
982         return false;
983     }
984     return true;
985 }
986 
InitResourceManager(std::shared_ptr<Global::Resource::ResourceManager> &resourceManager, const AppExecFwk::HapModuleInfo &entryHapModuleInfo, const std::string &bundleName, const Configuration &config, const ApplicationInfo &appInfo)987 bool MainThread::InitResourceManager(std::shared_ptr<Global::Resource::ResourceManager> &resourceManager,
988     const AppExecFwk::HapModuleInfo &entryHapModuleInfo, const std::string &bundleName,
989     const Configuration &config, const ApplicationInfo &appInfo)
990 {
991     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
992     bool isStageBased = entryHapModuleInfo.isStageBasedModel;
993     if (isStageBased && appInfo.multiProjects) {
994         TAG_LOGI(AAFwkTag::APPKIT, "multiProjects");
995     } else {
996         OnStartAbility(bundleName, resourceManager, entryHapModuleInfo, appInfo.debug);
997     }
998 
999     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1000 #if defined(SUPPORT_GRAPHICS) && defined(SUPPORT_APP_PREFERRED_LANGUAGE)
1001     UErrorCode status = U_ZERO_ERROR;
1002     icu::Locale systemLocale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLocale(), status);
1003     resConfig->SetLocaleInfo(systemLocale);
1004 
1005     if (Global::I18n::PreferredLanguage::IsSetAppPreferredLanguage()) {
1006         icu::Locale preferredLocale =
1007             icu::Locale::forLanguageTag(Global::I18n::PreferredLanguage::GetAppPreferredLanguage(), status);
1008         resConfig->SetPreferredLocaleInfo(preferredLocale);
1009     }
1010 #endif
1011     std::string colormode = config.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
1012     TAG_LOGD(AAFwkTag::APPKIT, "Colormode is %{public}s", colormode.c_str());
1013     resConfig->SetColorMode(ConvertColorMode(colormode));
1014 
1015     std::string hasPointerDevice = config.GetItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
1016     TAG_LOGD(AAFwkTag::APPKIT, "HasPointerDevice is %{public}s", hasPointerDevice.c_str());
1017     resConfig->SetInputDevice(ConvertHasPointerDevice(hasPointerDevice));
1018 
1019     std::string deviceType = config.GetItem(AAFwk::GlobalConfigurationKey::DEVICE_TYPE);
1020     TAG_LOGD(AAFwkTag::APPKIT, "deviceType is %{public}s <---->  %{public}d", deviceType.c_str(),
1021         ConvertDeviceType(deviceType));
1022     resConfig->SetDeviceType(ConvertDeviceType(deviceType));
1023 
1024     std::string mcc = config.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_MCC);
1025     TAG_LOGD(AAFwkTag::APPKIT, "mcc is %{public}s", mcc.c_str());
1026     uint32_t mccNum = 0;
1027     if (AbilityRuntime::ResourceConfigHelper::ConvertStringToUint32(mcc, mccNum)) {
1028         resConfig->SetMcc(mccNum);
1029     }
1030 
1031     std::string mnc = config.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_MNC);
1032     TAG_LOGD(AAFwkTag::APPKIT, "mnc is %{public}s", mnc.c_str());
1033     uint32_t mncNum = 0;
1034     if (AbilityRuntime::ResourceConfigHelper::ConvertStringToUint32(mnc, mncNum)) {
1035         resConfig->SetMnc(mncNum);
1036     }
1037 
1038     resourceManager->UpdateResConfig(*resConfig);
1039     return true;
1040 }
1041 
OnStartAbility(const std::string &bundleName, std::shared_ptr<Global::Resource::ResourceManager> &resourceManager, const AppExecFwk::HapModuleInfo &entryHapModuleInfo, const bool isDebugApp)1042 void MainThread::OnStartAbility(const std::string &bundleName,
1043     std::shared_ptr<Global::Resource::ResourceManager> &resourceManager,
1044     const AppExecFwk::HapModuleInfo &entryHapModuleInfo, const bool isDebugApp)
1045 {
1046     std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + bundleName);
1047     std::string loadPath =
1048         (!entryHapModuleInfo.hapPath.empty()) ? entryHapModuleInfo.hapPath : entryHapModuleInfo.resourcePath;
1049     if (!loadPath.empty()) {
1050         loadPath = std::regex_replace(loadPath, pattern, std::string(LOCAL_CODE_PATH));
1051         TAG_LOGD(AAFwkTag::APPKIT, "ModuleResPath: %{public}s", loadPath.c_str());
1052         // getOverlayPath
1053         if (overlayModuleInfos_.empty()) {
1054             if (!resourceManager->AddResource(loadPath.c_str())) {
1055                 TAG_LOGE(AAFwkTag::APPKIT, "AddResource failed");
1056             }
1057         } else {
1058             std::vector<std::string> overlayPaths = GetOverlayPaths(bundleName, overlayModuleInfos_);
1059             TAG_LOGD(AAFwkTag::APPKIT, "OverlayPaths size:%{public}zu", overlayPaths.size());
1060             if (!resourceManager->AddResource(loadPath, overlayPaths)) {
1061                 TAG_LOGE(AAFwkTag::APPKIT, "AddResource failed");
1062             }
1063             SubscribeOverlayChange(bundleName, loadPath, resourceManager, entryHapModuleInfo);
1064         }
1065         std::string hqfPath = entryHapModuleInfo.hqfInfo.hqfFilePath;
1066         if (!hqfPath.empty() && isDebugApp) {
1067             hqfPath = std::regex_replace(hqfPath, pattern, std::string(LOCAL_CODE_PATH));
1068             TAG_LOGI(AAFwkTag::APPKIT, "AddPatchResource hapPath:%{public}s, patchPath:%{public}s",
1069                 loadPath.c_str(), hqfPath.c_str());
1070             if (!resourceManager->AddPatchResource(loadPath.c_str(), hqfPath.c_str())) {
1071                 TAG_LOGE(AAFwkTag::APPKIT, "AddPatchResource failed");
1072             }
1073         }
1074     }
1075 }
1076 
GetOverlayPaths(const std::string &bundleName, const std::vector<OverlayModuleInfo> &overlayModuleInfos)1077 std::vector<std::string> MainThread::GetOverlayPaths(const std::string &bundleName,
1078     const std::vector<OverlayModuleInfo> &overlayModuleInfos)
1079 {
1080     std::vector<std::string> overlayPaths;
1081     for (auto &it : overlayModuleInfos_) {
1082         if (std::regex_search(it.hapPath, std::regex(bundleName))) {
1083             it.hapPath = std::regex_replace(it.hapPath, std::regex(std::string(ABS_CODE_PATH) +
1084                 std::string(FILE_SEPARATOR) + bundleName), std::string(LOCAL_CODE_PATH));
1085         } else {
1086             it.hapPath = std::regex_replace(it.hapPath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES);
1087         }
1088         if (it.state == OverlayState::OVERLAY_ENABLE) {
1089             TAG_LOGD(AAFwkTag::APPKIT, "hapPath: %{public}s", it.hapPath.c_str());
1090             overlayPaths.emplace_back(it.hapPath);
1091         }
1092     }
1093     return overlayPaths;
1094 }
1095 
SubscribeOverlayChange(const std::string &bundleName, const std::string &loadPath, std::shared_ptr<Global::Resource::ResourceManager> &resourceManager, const AppExecFwk::HapModuleInfo &entryHapModuleInfo)1096 void MainThread::SubscribeOverlayChange(const std::string &bundleName, const std::string &loadPath,
1097     std::shared_ptr<Global::Resource::ResourceManager> &resourceManager,
1098     const AppExecFwk::HapModuleInfo &entryHapModuleInfo)
1099 {
1100     // add listen overlay change
1101     EventFwk::MatchingSkills matchingSkills;
1102     matchingSkills.AddEvent(OVERLAY_STATE_CHANGED);
1103     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
1104     subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
1105     wptr<MainThread> weak = this;
1106     auto callback = [weak, resourceManager, bundleName, moduleName = entryHapModuleInfo.moduleName,
1107         loadPath](const EventFwk::CommonEventData &data) {
1108         TAG_LOGD(AAFwkTag::APPKIT, "On overlay changed");
1109         auto appThread = weak.promote();
1110         if (appThread == nullptr) {
1111             TAG_LOGE(AAFwkTag::APPKIT, "abilityThread is nullptr, SetRunnerStarted failed");
1112             return;
1113         }
1114         appThread->OnOverlayChanged(data, resourceManager, bundleName, moduleName, loadPath);
1115     };
1116     auto subscriber = std::make_shared<OverlayEventSubscriber>(subscribeInfo, callback);
1117     bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber);
1118     TAG_LOGD(AAFwkTag::APPKIT, "Overlay event subscriber register result is %{public}d", subResult);
1119 }
1120 
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)1121 void MainThread::OnOverlayChanged(const EventFwk::CommonEventData &data,
1122     const std::shared_ptr<Global::Resource::ResourceManager> &resourceManager, const std::string &bundleName,
1123     const std::string &moduleName, const std::string &loadPath)
1124 {
1125     if (mainHandler_ == nullptr) {
1126         TAG_LOGE(AAFwkTag::APPKIT, "mainHandler is nullptr");
1127         return;
1128     }
1129     wptr<MainThread> weak = this;
1130     auto task = [weak, data, resourceManager, bundleName, moduleName, loadPath]() {
1131         auto appThread = weak.promote();
1132         if (appThread == nullptr) {
1133             TAG_LOGE(AAFwkTag::APPKIT, "abilityThread is nullptr");
1134             return;
1135         }
1136         appThread->HandleOnOverlayChanged(data, resourceManager, bundleName, moduleName, loadPath);
1137     };
1138     if (!mainHandler_->PostTask(task, "MainThread:OnOverlayChanged")) {
1139         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
1140     }
1141 }
1142 
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)1143 void MainThread::HandleOnOverlayChanged(const EventFwk::CommonEventData &data,
1144     const std::shared_ptr<Global::Resource::ResourceManager> &resourceManager, const std::string &bundleName,
1145     const std::string &moduleName, const std::string &loadPath)
1146 {
1147     TAG_LOGD(AAFwkTag::APPKIT, "begin");
1148     auto want = data.GetWant();
1149     std::string action = want.GetAction();
1150     if (action != OVERLAY_STATE_CHANGED) {
1151         TAG_LOGD(AAFwkTag::APPKIT, "Not this subscribe, action: %{public}s", action.c_str());
1152         return;
1153     }
1154     bool isEnable = data.GetWant().GetBoolParam(Constants::OVERLAY_STATE, false);
1155     // 1.get overlay hapPath
1156     if (resourceManager == nullptr) {
1157         TAG_LOGE(AAFwkTag::APPKIT, "resourceManager is nullptr");
1158         return;
1159     }
1160     std::vector<OverlayModuleInfo> overlayModuleInfos;
1161     auto res = GetOverlayModuleInfos(bundleName, moduleName, overlayModuleInfos);
1162     if (res != ERR_OK) {
1163         return;
1164     }
1165 
1166     // 2.add/remove overlay hapPath
1167     if (loadPath.empty() || overlayModuleInfos.empty()) {
1168         TAG_LOGW(AAFwkTag::APPKIT, "There is not any hapPath in overlayModuleInfo");
1169     } else {
1170         if (isEnable) {
1171             std::vector<std::string> overlayPaths = GetAddOverlayPaths(overlayModuleInfos);
1172             if (!resourceManager->AddResource(loadPath, overlayPaths)) {
1173                 TAG_LOGE(AAFwkTag::APPKIT, "AddResource failed");
1174             }
1175         } else {
1176             std::vector<std::string> overlayPaths = GetRemoveOverlayPaths(overlayModuleInfos);
1177             if (!resourceManager->RemoveResource(loadPath, overlayPaths)) {
1178                 TAG_LOGE(AAFwkTag::APPKIT, "RemoveResource failed");
1179             }
1180         }
1181     }
1182 }
1183 
IsNeedLoadLibrary(const std::string &bundleName)1184 bool IsNeedLoadLibrary(const std::string &bundleName)
1185 {
1186     std::vector<std::string> needLoadLibraryBundleNames{
1187         "com.ohos.contactsdataability",
1188         "com.ohos.medialibrary.medialibrarydata",
1189         "com.ohos.ringtonelibrary.ringtonelibrarydata",
1190         "com.ohos.telephonydataability",
1191         "com.ohos.FusionSearch",
1192         "com.ohos.formrenderservice"
1193     };
1194 
1195     return std::find(needLoadLibraryBundleNames.begin(), needLoadLibraryBundleNames.end(), bundleName)
1196         != needLoadLibraryBundleNames.end();
1197 }
1198 
GetBundleForLaunchApplication(std::shared_ptr<BundleMgrHelper> bundleMgrHelper, const std::string &bundleName, int32_t appIndex, BundleInfo &bundleInfo)1199 bool GetBundleForLaunchApplication(std::shared_ptr<BundleMgrHelper> bundleMgrHelper, const std::string &bundleName,
1200     int32_t appIndex, BundleInfo &bundleInfo)
1201 {
1202     bool queryResult;
1203     if (appIndex > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
1204         TAG_LOGD(AAFwkTag::APPKIT, "The bundleName = %{public}s", bundleName.c_str());
1205         queryResult = (bundleMgrHelper->GetSandboxBundleInfo(bundleName,
1206             appIndex, UNSPECIFIED_USERID, bundleInfo) == 0);
1207     } else {
1208         TAG_LOGD(AAFwkTag::APPKIT, "The bundleName = %{public}s", bundleName.c_str());
1209         queryResult = (bundleMgrHelper->GetBundleInfoForSelf(
1210             (static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) +
1211             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) +
1212             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE) +
1213             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) +
1214             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) +
1215             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY) +
1216 #ifdef SUPPORT_GRAPHICS
1217             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION) +
1218 #endif
1219             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_METADATA)), bundleInfo) == ERR_OK);
1220     }
1221     return queryResult;
1222 }
1223 #ifdef CJ_FRONTEND
CreateCjExceptionInfo(const std::string &bundleName, uint32_t versionCode, const std::string &hapPath)1224 CJUncaughtExceptionInfo MainThread::CreateCjExceptionInfo(const std::string &bundleName,
1225     uint32_t versionCode, const std::string &hapPath)
1226 {
1227     CJUncaughtExceptionInfo uncaughtExceptionInfo;
1228     wptr<MainThread> weak_this = this;
1229     uncaughtExceptionInfo.hapPath = hapPath.c_str();
1230     uncaughtExceptionInfo.uncaughtTask = [weak_this, bundleName, versionCode]
1231         (std::string summary, const CJErrorObject errorObj) {
1232             auto appThread = weak_this.promote();
1233             if (appThread == nullptr) {
1234                 TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
1235                 return;
1236             }
1237             time_t timet;
1238             time(&timet);
1239             std::string errName = errorObj.name ? errorObj.name : "[none]";
1240             std::string errMsg = errorObj.message ? errorObj.message : "[none]";
1241             std::string errStack = errorObj.stack ? errorObj.stack : "[none]";
1242             HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, "CJ_ERROR",
1243                 OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
1244                 EVENT_KEY_PACKAGE_NAME, bundleName,
1245                 EVENT_KEY_VERSION, std::to_string(versionCode),
1246                 EVENT_KEY_TYPE, JSCRASH_TYPE,
1247                 EVENT_KEY_HAPPEN_TIME, timet,
1248                 EVENT_KEY_REASON, errName,
1249                 EVENT_KEY_JSVM, JSVM_TYPE,
1250                 EVENT_KEY_SUMMARY, summary);
1251             ErrorObject appExecErrorObj = {
1252                 .name = errName,
1253                 .message = errMsg,
1254                 .stack = errStack
1255             };
1256             FaultData faultData;
1257             faultData.faultType = FaultDataType::CJ_ERROR;
1258             faultData.errorObject = appExecErrorObj;
1259             DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->NotifyAppFault(faultData);
1260             if (ApplicationDataManager::GetInstance().NotifyCJUnhandledException(summary) &&
1261                 ApplicationDataManager::GetInstance().NotifyCJExceptionObject(appExecErrorObj)) {
1262                 return;
1263             }
1264             // if app's callback has been registered, let app decide whether exit or not.
1265             TAG_LOGE(AAFwkTag::APPKIT,
1266                 "\n%{public}s is about to exit due to RuntimeError\nError type:%{public}s\n%{public}s\n"
1267                 "message: %{public}s\n"
1268                 "stack: %{public}s",
1269                 bundleName.c_str(), errName.c_str(), summary.c_str(), errMsg.c_str(), errStack.c_str());
1270             AAFwk::ExitReason exitReason = { REASON_CJ_ERROR, errName };
1271             AbilityManagerClient::GetInstance()->RecordAppExitReason(exitReason);
1272             appThread->ScheduleProcessSecurityExit();
1273         };
1274     return uncaughtExceptionInfo;
1275 }
1276 #endif
1277 /**
1278  *
1279  * @brief Launch the application.
1280  *
1281  * @param appLaunchData The launchdata of the application witch launced.
1282  *
1283  */
HandleLaunchApplication(const AppLaunchData &appLaunchData, const Configuration &config)1284 void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, const Configuration &config)
1285 {
1286     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1287     FreezeUtil::GetInstance().AddAppLifecycleEvent(0, "HandleLaunchApplication:begin");
1288     if (!CheckForHandleLaunchApplication(appLaunchData)) {
1289         TAG_LOGE(AAFwkTag::APPKIT, "CheckForHandleLaunchApplication failed");
1290         return;
1291     }
1292 
1293     if (appLaunchData.GetDebugApp() && watchdog_ != nullptr && !watchdog_->IsStopWatchdog()) {
1294         SetAppDebug(AbilityRuntime::AppFreezeState::AppFreezeFlag::DEBUG_LAUNCH_MODE, true);
1295         watchdog_->Stop();
1296         watchdog_.reset();
1297     }
1298 
1299     auto appInfo = appLaunchData.GetApplicationInfo();
1300     ProcessInfo processInfo = appLaunchData.GetProcessInfo();
1301     TAG_LOGD(AAFwkTag::APPKIT, "InitCreate Start");
1302     std::shared_ptr<ContextDeal> contextDeal;
1303     if (!InitCreate(contextDeal, appInfo, processInfo)) {
1304         TAG_LOGE(AAFwkTag::APPKIT, "InitCreate failed");
1305         return;
1306     }
1307     auto bundleMgrHelper = contextDeal->GetBundleManager();
1308     if (bundleMgrHelper == nullptr) {
1309         TAG_LOGE(AAFwkTag::APPKIT, "The bundleMgrHelper is nullptr");
1310         return;
1311     }
1312 
1313     auto bundleName = appInfo.bundleName;
1314     auto tmpWatchdog = watchdog_;
1315     if (tmpWatchdog != nullptr) {
1316         tmpWatchdog->SetBundleInfo(bundleName, appInfo.versionName);
1317         tmpWatchdog = nullptr;
1318     }
1319     BundleInfo bundleInfo;
1320     if (!GetBundleForLaunchApplication(bundleMgrHelper, bundleName, appLaunchData.GetAppIndex(), bundleInfo)) {
1321         TAG_LOGE(AAFwkTag::APPKIT, "Failed to get bundle info");
1322         return;
1323     }
1324 
1325     bool moduelJson = false;
1326     bool isStageBased = false;
1327     bool findEntryHapModuleInfo = false;
1328 #ifdef CJ_FRONTEND
1329     bool isCJApp = false;
1330 #endif
1331     AppExecFwk::HapModuleInfo entryHapModuleInfo;
1332     if (!bundleInfo.hapModuleInfos.empty()) {
1333         for (auto hapModuleInfo : bundleInfo.hapModuleInfos) {
1334             if (hapModuleInfo.moduleType == AppExecFwk::ModuleType::ENTRY) {
1335                 findEntryHapModuleInfo = true;
1336                 entryHapModuleInfo = hapModuleInfo;
1337                 break;
1338             }
1339         }
1340         if (!findEntryHapModuleInfo) {
1341             TAG_LOGW(AAFwkTag::APPKIT, "HandleLaunchApplication find entry hap module info failed");
1342             entryHapModuleInfo = bundleInfo.hapModuleInfos.back();
1343         }
1344 #ifdef CJ_FRONTEND
1345         if (!entryHapModuleInfo.abilityInfos.empty()) {
1346             auto srcEntrancenName = entryHapModuleInfo.abilityInfos.front().srcEntrance;
1347             isCJApp = AbilityRuntime::CJRuntime::IsCJAbility(srcEntrancenName);
1348             AbilityRuntime::CJRuntime::SetPackageName(srcEntrancenName);
1349         }
1350 #endif
1351         moduelJson = entryHapModuleInfo.isModuleJson;
1352         isStageBased = entryHapModuleInfo.isStageBasedModel;
1353     }
1354 
1355 #ifdef SUPPORT_SCREEN
1356     std::vector<OHOS::AppExecFwk::Metadata> metaData = entryHapModuleInfo.metadata;
1357     bool isFullUpdate = std::any_of(metaData.begin(), metaData.end(), [](const auto &metaDataItem) {
1358         return metaDataItem.name == "ArkTSPartialUpdate" && metaDataItem.value == "false";
1359     });
1360     bool isReqForm = std::any_of(bundleInfo.reqPermissions.begin(), bundleInfo.reqPermissions.end(),
1361         [] (const auto &reqPermission) {
1362         return reqPermission == OHOS::AppExecFwk::Constants::PERMISSION_REQUIRE_FORM;
1363     });
1364     {
1365         HITRACE_METER_NAME(HITRACE_TAG_APP, "Ace::AceForwardCompatibility::Init");
1366         Ace::AceForwardCompatibility::Init(bundleName, appInfo.apiCompatibleVersion, (isFullUpdate || isReqForm));
1367     }
1368 #endif
1369 
1370     if (IsNeedLoadLibrary(bundleName)) {
1371         std::vector<std::string> localPaths;
1372         ChangeToLocalPath(bundleName, appInfo.moduleSourceDirs, localPaths);
1373         LoadAbilityLibrary(localPaths);
1374         LoadNativeLibrary(bundleInfo, appInfo.nativeLibraryPath);
1375 #ifdef SUPPORT_SCREEN
1376     } else if (Ace::AceForwardCompatibility::PipelineChanged()) {
1377         std::vector<std::string> localPaths;
1378         ChangeToLocalPath(bundleName, appInfo.moduleSourceDirs, localPaths);
1379         LoadAbilityLibrary(localPaths);
1380 #endif
1381     }
1382     if (appInfo.needAppDetail) {
1383         TAG_LOGD(AAFwkTag::APPKIT,
1384             "MainThread::handleLaunchApplication %{public}s need add app detail ability library path",
1385             bundleName.c_str());
1386         LoadAppDetailAbilityLibrary(appInfo.appDetailAbilityLibraryPath);
1387     }
1388     LoadAppLibrary();
1389 
1390     applicationForDump_ = application_;
1391 
1392     if (isStageBased) {
1393         AppRecovery::GetInstance().InitApplicationInfo(GetMainHandler(), GetApplicationInfo());
1394     }
1395     TAG_LOGD(AAFwkTag::APPKIT, "stageBased:%{public}d moduleJson:%{public}d size:%{public}zu",
1396         isStageBased, moduelJson, bundleInfo.hapModuleInfos.size());
1397 
1398     // create contextImpl
1399     std::shared_ptr<AbilityRuntime::ContextImpl> contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
1400     contextImpl->SetApplicationInfo(std::make_shared<ApplicationInfo>(appInfo));
1401     std::shared_ptr<AbilityRuntime::ApplicationContext> applicationContext =
1402         AbilityRuntime::ApplicationContext::GetInstance();
1403     int32_t appIndex = appLaunchData.GetAppIndex();
1404     std::string instanceKey = appLaunchData.GetInstanceKey();
1405     applicationContext->SetCurrentAppCloneIndex(appIndex);
1406     applicationContext->SetCurrentInstanceKey(instanceKey);
1407     applicationContext->SetCurrentAppMode(static_cast<int32_t>(appInfo.multiAppMode.multiAppModeType));
1408     applicationContext->AttachContextImpl(contextImpl);
1409     auto appRunningId = appLaunchData.GetAppRunningUniqueId();
1410     applicationContext->SetAppRunningUniqueId(appRunningId);
1411     if (DFX_SetAppRunningUniqueId != nullptr) {
1412         DFX_SetAppRunningUniqueId(appRunningId.c_str(), appRunningId.length());
1413     }
1414     application_->SetApplicationContext(applicationContext);
1415 
1416 #ifdef SUPPORT_SCREEN
1417     OHOS::EglSetCacheDir(applicationContext->GetCacheDir());
1418 #endif
1419 
1420     HspList hspList;
1421     ErrCode ret = bundleMgrHelper->GetBaseSharedBundleInfos(appInfo.bundleName, hspList,
1422         AppExecFwk::GetDependentBundleInfoFlag::GET_ALL_DEPENDENT_BUNDLE_INFO);
1423     if (ret != ERR_OK) {
1424         TAG_LOGE(AAFwkTag::APPKIT, "Get base shared bundle infos failed: %{public}d", ret);
1425     }
1426 
1427     std::map<std::string, std::string> pkgContextInfoJsonStringMap;
1428     for (auto hapModuleInfo : bundleInfo.hapModuleInfos) {
1429         pkgContextInfoJsonStringMap[hapModuleInfo.moduleName] = hapModuleInfo.hapPath;
1430     }
1431 
1432     AppLibPathMap appLibPaths {};
1433     GetNativeLibPath(bundleInfo, hspList, appLibPaths);
1434     bool isSystemApp = bundleInfo.applicationInfo.isSystemApp;
1435     TAG_LOGD(AAFwkTag::APPKIT, "the application isSystemApp: %{public}d", isSystemApp);
1436 #ifdef CJ_FRONTEND
1437     if (isCJApp) {
1438         AbilityRuntime::CJRuntime::SetAppLibPath(appLibPaths);
1439         if (appInfo.asanEnabled) {
1440             AbilityRuntime::CJRuntime::SetSanitizerVersion(SanitizerKind::ASAN);
1441         } else if (appInfo.tsanEnabled) {
1442             AbilityRuntime::CJRuntime::SetSanitizerVersion(SanitizerKind::TSAN);
1443         } else if (appInfo.hwasanEnabled) {
1444             AbilityRuntime::CJRuntime::SetSanitizerVersion(SanitizerKind::HWASAN);
1445         }
1446     } else {
1447 #endif
1448         AbilityRuntime::JsRuntime::SetAppLibPath(appLibPaths, isSystemApp);
1449 #ifdef CJ_FRONTEND
1450     }
1451 #endif
1452 
1453     if (isStageBased) {
1454         // Create runtime
1455         auto hapPath = entryHapModuleInfo.hapPath;
1456         auto moduleName = entryHapModuleInfo.moduleName;
1457         AbilityRuntime::Runtime::Options options;
1458         options.bundleName = appInfo.bundleName;
1459         options.codePath = LOCAL_CODE_PATH;
1460         options.hapPath = hapPath;
1461         options.moduleName = moduleName;
1462         options.eventRunner = mainHandler_->GetEventRunner();
1463         options.loadAce = true;
1464         options.isBundle = (entryHapModuleInfo.compileMode != AppExecFwk::CompileMode::ES_MODULE);
1465         options.isDebugVersion = bundleInfo.applicationInfo.debug;
1466         options.arkNativeFilePath = bundleInfo.applicationInfo.arkNativeFilePath;
1467         options.uid = bundleInfo.applicationInfo.uid;
1468         options.apiTargetVersion = appInfo.apiTargetVersion;
1469         options.pkgContextInfoJsonStringMap = pkgContextInfoJsonStringMap;
1470 #ifdef CJ_FRONTEND
1471         options.lang = isCJApp ? AbilityRuntime::Runtime::Language::CJ : AbilityRuntime::Runtime::Language::JS;
1472 #endif
1473         if (applicationInfo_->appProvisionType == Constants::APP_PROVISION_TYPE_DEBUG) {
1474             TAG_LOGD(AAFwkTag::APPKIT, "multi-thread mode: %{public}d", appLaunchData.GetMultiThread());
1475             options.isMultiThread = appLaunchData.GetMultiThread();
1476             TAG_LOGD(AAFwkTag::JSRUNTIME, "Start Error-Info-Enhance Mode: %{public}d.",
1477                 appLaunchData.GetErrorInfoEnhance());
1478             options.isErrorInfoEnhance = appLaunchData.GetErrorInfoEnhance();
1479         }
1480         options.jitEnabled = appLaunchData.IsJITEnabled();
1481         AbilityRuntime::ChildProcessManager::GetInstance().SetForkProcessJITEnabled(appLaunchData.IsJITEnabled());
1482         TAG_LOGD(AAFwkTag::APPKIT, "isStartWithDebug:%{public}d, debug:%{public}d, isNativeStart:%{public}d",
1483             appLaunchData.GetDebugApp(), appInfo.debug, appLaunchData.isNativeStart());
1484         AbilityRuntime::ChildProcessManager::GetInstance().SetForkProcessDebugOption(appInfo.bundleName,
1485             appLaunchData.GetDebugApp(), appInfo.debug, appLaunchData.isNativeStart());
1486         if (!bundleInfo.hapModuleInfos.empty()) {
1487             for (auto hapModuleInfo : bundleInfo.hapModuleInfos) {
1488                 options.hapModulePath[hapModuleInfo.moduleName] = hapModuleInfo.hapPath;
1489                 options.packageNameList[hapModuleInfo.moduleName] = hapModuleInfo.packageName;
1490                 options.aotCompileStatusMap[hapModuleInfo.moduleName] =
1491                     static_cast<int32_t>(hapModuleInfo.aotCompileStatus);
1492             }
1493         }
1494         auto runtime = AbilityRuntime::Runtime::Create(options);
1495         if (!runtime) {
1496             TAG_LOGE(AAFwkTag::APPKIT, "Failed to create runtime");
1497             return;
1498         }
1499 
1500         if (appInfo.debug && appLaunchData.GetDebugApp()) {
1501             wptr<MainThread> weak = this;
1502             auto cb = [weak]() {
1503                 auto appThread = weak.promote();
1504                 if (appThread == nullptr) {
1505                     TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
1506                     return false;
1507                 }
1508                 return appThread->NotifyDeviceDisConnect();
1509             };
1510             runtime->SetDeviceDisconnectCallback(cb);
1511         }
1512 
1513         auto perfCmd = appLaunchData.GetPerfCmd();
1514 
1515         int32_t pid = -1;
1516         std::string processName = "";
1517         if (processInfo_ != nullptr) {
1518             pid = processInfo_->GetPid();
1519             processName = processInfo_->GetProcessName();
1520             TAG_LOGD(AAFwkTag::APPKIT, "pid is %{public}d, processName is %{public}s", pid, processName.c_str());
1521         }
1522         AbilityRuntime::Runtime::DebugOption debugOption;
1523         debugOption.isStartWithDebug = appLaunchData.GetDebugApp();
1524         debugOption.processName = processName;
1525         debugOption.isDebugApp = appInfo.debug;
1526         debugOption.isStartWithNative = appLaunchData.isNativeStart();
1527         if (perfCmd.find(PERFCMD_PROFILE) != std::string::npos ||
1528             perfCmd.find(PERFCMD_DUMPHEAP) != std::string::npos) {
1529             TAG_LOGD(AAFwkTag::APPKIT, "perfCmd is %{public}s", perfCmd.c_str());
1530             debugOption.perfCmd = perfCmd;
1531             runtime->StartProfiler(debugOption);
1532         } else {
1533             if (isDeveloperMode_) {
1534                 runtime->StartDebugMode(debugOption);
1535             }
1536         }
1537 
1538         std::vector<HqfInfo> hqfInfos = appInfo.appQuickFix.deployedAppqfInfo.hqfInfos;
1539         std::map<std::string, std::string> modulePaths;
1540         if (!hqfInfos.empty()) {
1541             for (auto it = hqfInfos.begin(); it != hqfInfos.end(); it++) {
1542                 TAG_LOGI(AAFwkTag::APPKIT, "moudelName: %{private}s, hqfFilePath: %{private}s",
1543                     it->moduleName.c_str(), it->hqfFilePath.c_str());
1544                 modulePaths.insert(std::make_pair(it->moduleName, it->hqfFilePath));
1545             }
1546             runtime->RegisterQuickFixQueryFunc(modulePaths);
1547         }
1548 
1549         auto bundleName = appInfo.bundleName;
1550         auto versionCode = appInfo.versionCode;
1551 #ifdef CJ_FRONTEND
1552         if (!isCJApp) {
1553 #endif
1554             JsEnv::UncaughtExceptionInfo uncaughtExceptionInfo;
1555             uncaughtExceptionInfo.hapPath = hapPath;
1556             wptr<MainThread> weak = this;
1557             uncaughtExceptionInfo.uncaughtTask = [weak, bundleName, versionCode, appRunningId = std::move(appRunningId),
1558                 pid, processName] (std::string summary, const JsEnv::ErrorObject errorObj) {
1559                 auto appThread = weak.promote();
1560                 if (appThread == nullptr) {
1561                     TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
1562                     return;
1563                 }
1564                 time_t timet;
1565                 time(&timet);
1566                 HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, "JS_ERROR",
1567                     OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
1568                     EVENT_KEY_PACKAGE_NAME, bundleName,
1569                     EVENT_KEY_VERSION, std::to_string(versionCode),
1570                     EVENT_KEY_TYPE, JSCRASH_TYPE,
1571                     EVENT_KEY_HAPPEN_TIME, timet,
1572                     EVENT_KEY_REASON, errorObj.name,
1573                     EVENT_KEY_JSVM, JSVM_TYPE,
1574                     EVENT_KEY_SUMMARY, summary,
1575                     EVENT_KEY_PNAME, processName,
1576                     EVENT_KEY_APP_RUNING_UNIQUE_ID, appRunningId);
1577                 ErrorObject appExecErrorObj = {
1578                     .name = errorObj.name,
1579                     .message = errorObj.message,
1580                     .stack = errorObj.stack
1581                 };
1582                 FaultData faultData;
1583                 faultData.faultType = FaultDataType::JS_ERROR;
1584                 faultData.errorObject = appExecErrorObj;
1585                 DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->NotifyAppFault(faultData);
1586                 int result = HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::FRAMEWORK, "PROCESS_KILL",
1587                     HiviewDFX::HiSysEvent::EventType::FAULT, "PID", pid, "PROCESS_NAME", processName,
1588                     "MSG", KILL_REASON);
1589                 TAG_LOGW(AAFwkTag::APPKIT, "hisysevent write result=%{public}d, send event [FRAMEWORK,PROCESS_KILL],"
1590                     " pid=%{public}d, processName=%{public}s, msg=%{public}s", result, pid, processName.c_str(),
1591                     KILL_REASON);
1592 
1593                 if (ApplicationDataManager::GetInstance().NotifyUnhandledException(summary) &&
1594                     ApplicationDataManager::GetInstance().NotifyExceptionObject(appExecErrorObj)) {
1595                     return;
1596                 }
1597                 // if app's callback has been registered, let app decide whether exit or not.
1598                 TAG_LOGE(AAFwkTag::APPKIT,
1599                     "\n%{public}s is about to exit due to RuntimeError\nError type:%{public}s\n%{public}s",
1600                     bundleName.c_str(), errorObj.name.c_str(), summary.c_str());
1601                 AAFwk::ExitReason exitReason = { REASON_JS_ERROR, errorObj.name };
1602                 AbilityManagerClient::GetInstance()->RecordAppExitReason(exitReason);
1603                 _exit(JS_ERROR_EXIT);
1604             };
1605             (static_cast<AbilityRuntime::JsRuntime&>(*runtime)).RegisterUncaughtExceptionHandler(uncaughtExceptionInfo);
1606 #ifdef CJ_FRONTEND
1607         } else {
1608             auto expectionInfo = CreateCjExceptionInfo(bundleName, versionCode, hapPath);
1609             (static_cast<AbilityRuntime::CJRuntime&>(*runtime)).RegisterUncaughtExceptionHandler(expectionInfo);
1610         }
1611 #endif
1612         wptr<MainThread> weak = this;
1613         auto callback = [weak](const AAFwk::ExitReason &exitReason) {
1614             auto appThread = weak.promote();
1615             if (appThread == nullptr) {
1616                 TAG_LOGE(AAFwkTag::APPKIT, "Main thread is nullptr");
1617             }
1618             AbilityManagerClient::GetInstance()->RecordAppExitReason(exitReason);
1619             appThread->ScheduleProcessSecurityExit();
1620         };
1621         applicationContext->RegisterProcessSecurityExit(callback);
1622 
1623         application_->SetRuntime(std::move(runtime));
1624 
1625         std::weak_ptr<OHOSApplication> wpApplication = application_;
1626         AbilityLoader::GetInstance().RegisterUIAbility("UIAbility",
1627             [wpApplication]() -> AbilityRuntime::UIAbility* {
1628             auto app = wpApplication.lock();
1629             if (app != nullptr) {
1630                 return AbilityRuntime::UIAbility::Create(app->GetRuntime());
1631             }
1632             TAG_LOGE(AAFwkTag::APPKIT, "failed");
1633             return nullptr;
1634         });
1635 #ifdef CJ_FRONTEND
1636         if (!isCJApp) {
1637 #endif
1638             auto& jsEngine = (static_cast<AbilityRuntime::JsRuntime&>(*application_->GetRuntime())).GetNativeEngine();
1639             if (application_ != nullptr) {
1640                 LoadAllExtensions(jsEngine);
1641             }
1642 
1643             IdleTimeCallback callback = [wpApplication](int32_t idleTime) {
1644                 auto app = wpApplication.lock();
1645                 if (app == nullptr) {
1646                     TAG_LOGE(AAFwkTag::APPKIT, "app is nullptr");
1647                     return;
1648                 }
1649                 auto &runtime = app->GetRuntime();
1650                 if (runtime == nullptr) {
1651                     TAG_LOGE(AAFwkTag::APPKIT, "runtime is nullptr");
1652                     return;
1653                 }
1654                 auto& nativeEngine = (static_cast<AbilityRuntime::JsRuntime&>(*runtime)).GetNativeEngine();
1655                 nativeEngine.NotifyIdleTime(idleTime);
1656             };
1657             idleTime_ = std::make_shared<IdleTime>(mainHandler_, callback);
1658             idleTime_->Start();
1659 
1660             IdleNotifyStatusCallback cb = idleTime_->GetIdleNotifyFunc();
1661             jsEngine.NotifyIdleStatusControl(cb);
1662 
1663             auto helper = std::make_shared<DumpRuntimeHelper>(application_);
1664             helper->SetAppFreezeFilterCallback();
1665         }
1666 #ifdef CJ_FRONTEND
1667     }
1668 #endif
1669 
1670     auto usertestInfo = appLaunchData.GetUserTestInfo();
1671     if (usertestInfo) {
1672         if (!PrepareAbilityDelegator(usertestInfo, isStageBased, entryHapModuleInfo)) {
1673             TAG_LOGE(AAFwkTag::APPKIT, "Failed to prepare ability delegator");
1674             return;
1675         }
1676     }
1677 
1678     // init resourceManager.
1679     auto moduleName = entryHapModuleInfo.moduleName;
1680     std::string loadPath =
1681         entryHapModuleInfo.hapPath.empty() ? entryHapModuleInfo.resourcePath : entryHapModuleInfo.hapPath;
1682     std::regex inner_pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + bundleInfo.name);
1683     loadPath = std::regex_replace(loadPath, inner_pattern, LOCAL_CODE_PATH);
1684     auto res = GetOverlayModuleInfos(bundleInfo.name, moduleName, overlayModuleInfos_);
1685     std::vector<std::string> overlayPaths;
1686     if (res == ERR_OK) {
1687         overlayPaths = GetAddOverlayPaths(overlayModuleInfos_);
1688     }
1689     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1690     int32_t appType;
1691     if (bundleInfo.applicationInfo.codePath == std::to_string(TYPE_RESERVE)) {
1692         appType = TYPE_RESERVE;
1693     } else if (bundleInfo.applicationInfo.codePath == std::to_string(TYPE_OTHERS)) {
1694         appType = TYPE_OTHERS;
1695     } else {
1696         appType = 0;
1697     }
1698     std::shared_ptr<Global::Resource::ResourceManager> resourceManager(Global::Resource::CreateResourceManager(
1699         bundleInfo.name, moduleName, loadPath, overlayPaths, *resConfig, appType));
1700 
1701     if (resourceManager == nullptr) {
1702         TAG_LOGE(AAFwkTag::APPKIT, "create resourceManager failed");
1703         return;
1704     }
1705 
1706     Configuration appConfig = config;
1707     ParseAppConfigurationParams(bundleInfo.applicationInfo.configuration, appConfig);
1708     std::string systemSizeScale = appConfig.GetItem(AAFwk::GlobalConfigurationKey::APP_FONT_SIZE_SCALE);
1709     if (!systemSizeScale.empty() && systemSizeScale.compare(DEFAULT_APP_FONT_SIZE_SCALE) == 0) {
1710         appConfig.AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_FONT_SIZE_SCALE, SYSTEM_DEFAULT_FONTSIZE_SCALE);
1711     }
1712 
1713     if (!InitResourceManager(resourceManager, entryHapModuleInfo, bundleInfo.name,
1714         appConfig, bundleInfo.applicationInfo)) {
1715         TAG_LOGE(AAFwkTag::APPKIT, "InitResourceManager failed");
1716         return;
1717     }
1718     contextImpl->SetResourceManager(resourceManager);
1719     AbilityBase::ExtractResourceManager::GetExtractResourceManager().SetGlobalObject(resourceManager);
1720 
1721     contextDeal->initResourceManager(resourceManager);
1722     contextDeal->SetApplicationContext(application_);
1723     application_->AttachBaseContext(contextDeal);
1724     application_->SetAbilityRecordMgr(abilityRecordMgr_);
1725     application_->SetConfiguration(appConfig);
1726     contextImpl->SetConfiguration(application_->GetConfiguration());
1727 
1728     applicationImpl_->SetRecordId(appLaunchData.GetRecordId());
1729     applicationImpl_->SetApplication(application_);
1730     mainThreadState_ = MainThreadState::READY;
1731     if (!applicationImpl_->PerformAppReady()) {
1732         TAG_LOGE(AAFwkTag::APPKIT, "applicationImpl_->PerformAppReady failed");
1733         return;
1734     }
1735     FreezeUtil::GetInstance().AddAppLifecycleEvent(0, "HandleLaunchApplication:end");
1736     // L1 needs to add corresponding interface
1737     ApplicationEnvImpl *pAppEvnIml = ApplicationEnvImpl::GetInstance();
1738 
1739     if (pAppEvnIml) {
1740         pAppEvnIml->SetAppInfo(*applicationInfo_.get());
1741     } else {
1742         TAG_LOGE(AAFwkTag::APPKIT, "pAppEvnIml is null");
1743     }
1744 
1745 #if defined(NWEB)
1746     // start nwebspawn process
1747     std::weak_ptr<OHOSApplication> weakApp = application_;
1748     wptr<IAppMgr> weakMgr = appMgr_;
1749     std::thread([weakApp, weakMgr] {
1750         auto app = weakApp.lock();
1751         auto appmgr = weakMgr.promote();
1752         if (app == nullptr || appmgr == nullptr) {
1753             TAG_LOGE(AAFwkTag::APPKIT, "app or appmgr is null");
1754             return;
1755         }
1756 
1757         if (prctl(PR_SET_NAME, "preStartNWeb") < 0) {
1758             TAG_LOGW(AAFwkTag::APPKIT, "Set thread name failed with %{public}d", errno);
1759         }
1760 
1761         std::string nwebPath = app->GetAppContext()->GetCacheDir() + "/web";
1762         bool isFirstStartUpWeb = (access(nwebPath.c_str(), F_OK) != 0);
1763         if (!isFirstStartUpWeb) {
1764             appmgr->PreStartNWebSpawnProcess();
1765         }
1766         OHOS::NWeb::NWebHelper::TryPreReadLib(isFirstStartUpWeb, app->GetAppContext()->GetBundleCodeDir());
1767     }).detach();
1768 #endif
1769 }
1770 
1771 #ifdef ABILITY_LIBRARY_LOADER
CalcNativeLiabraryEntries(const BundleInfo &bundleInfo, std::string &nativeLibraryPath)1772 void MainThread::CalcNativeLiabraryEntries(const BundleInfo &bundleInfo, std::string &nativeLibraryPath)
1773 {
1774     bool loadSoFromDir = bundleInfo.hapModuleInfos.empty();
1775     std::vector<std::string> nativeFileEntries;
1776     for (const auto &item: bundleInfo.hapModuleInfos) {
1777         if (!item.compressNativeLibs) {
1778             TAG_LOGD(AAFwkTag::APPKIT, "handle entries for: %{public}s, with path: %{public}s",
1779                 item.moduleName.c_str(), item.nativeLibraryPath.c_str());
1780             if (item.nativeLibraryPath.empty()) {
1781                 TAG_LOGD(AAFwkTag::APPKIT, "nativeLibraryPath empty: %{public}s", item.moduleName.c_str());
1782                 continue;
1783             }
1784             std::string libPath = GetLibPath(item.hapPath, bundleInfo.isPreInstallApp);
1785             libPath += (libPath.back() == '/') ? item.nativeLibraryPath : "/" + item.nativeLibraryPath;
1786             TAG_LOGI(AAFwkTag::APPKIT, "module lib path: %{public}s", libPath.c_str());
1787             if (libPath.back() != '/') {
1788                 libPath.push_back('/');
1789             }
1790             for (const auto &entryName : item.nativeLibraryFileNames) {
1791                 TAG_LOGD(AAFwkTag::APPKIT, "add entry: %{public}s", entryName.c_str());
1792                 nativeFileEntries.emplace_back(libPath + entryName);
1793             }
1794         } else {
1795             TAG_LOGD(AAFwkTag::APPKIT, "compressNativeLibs flag true for: %{public}s", item.moduleName.c_str());
1796             loadSoFromDir = true;
1797         }
1798     }
1799 
1800     if (loadSoFromDir) {
1801         if (nativeLibraryPath.empty()) {
1802             TAG_LOGW(AAFwkTag::APPKIT, "Native library path is empty");
1803             return;
1804         }
1805 
1806         if (nativeLibraryPath.back() == '/') {
1807             nativeLibraryPath.pop_back();
1808         }
1809         std::string libPath = LOCAL_CODE_PATH;
1810         libPath += (libPath.back() == '/') ? nativeLibraryPath : "/" + nativeLibraryPath;
1811         TAG_LOGD(AAFwkTag::APPKIT, "native library path = %{public}s", libPath.c_str());
1812 
1813         if (!ScanDir(libPath, nativeFileEntries_)) {
1814             TAG_LOGW(AAFwkTag::APPKIT, "scanDir %{public}s not exits", libPath.c_str());
1815         }
1816     }
1817 
1818     if (!nativeFileEntries.empty()) {
1819         nativeFileEntries_.insert(nativeFileEntries_.end(), nativeFileEntries.begin(), nativeFileEntries.end());
1820     }
1821 }
1822 
LoadNativeLibrary(const BundleInfo &bundleInfo, std::string &nativeLibraryPath)1823 void MainThread::LoadNativeLibrary(const BundleInfo &bundleInfo, std::string &nativeLibraryPath)
1824 {
1825     CalcNativeLiabraryEntries(bundleInfo, nativeLibraryPath);
1826     if (nativeFileEntries_.empty()) {
1827         TAG_LOGW(AAFwkTag::APPKIT, "No native library");
1828         return;
1829     }
1830 
1831     void *handleAbilityLib = nullptr;
1832     for (auto fileEntry : nativeFileEntries_) {
1833         if (fileEntry.empty()) {
1834             continue;
1835         }
1836         handleAbilityLib = dlopen(fileEntry.c_str(), RTLD_NOW | RTLD_GLOBAL);
1837         if (handleAbilityLib == nullptr) {
1838             if (fileEntry.find("libformrender.z.so") == std::string::npos) {
1839                 TAG_LOGE(AAFwkTag::APPKIT, "fail to dlopen %{public}s, [%{public}s]",
1840                     fileEntry.c_str(), dlerror());
1841                 exit(-1);
1842             } else {
1843                 TAG_LOGD(AAFwkTag::APPKIT, "Load libformrender.z.so from native lib path.");
1844                 handleAbilityLib = dlopen(FORM_RENDER_LIB_PATH, RTLD_NOW | RTLD_GLOBAL);
1845                 if (handleAbilityLib == nullptr) {
1846                     TAG_LOGE(AAFwkTag::APPKIT, "fail to dlopen %{public}s, [%{public}s]",
1847                         FORM_RENDER_LIB_PATH, dlerror());
1848                     exit(-1);
1849                 }
1850                 fileEntry = FORM_RENDER_LIB_PATH;
1851             }
1852         }
1853         TAG_LOGD(AAFwkTag::APPKIT, "success to dlopen %{public}s", fileEntry.c_str());
1854         handleAbilityLib_.emplace_back(handleAbilityLib);
1855     }
1856 }
1857 #endif
1858 
ChangeToLocalPath(const std::string &bundleName, const std::vector<std::string> &sourceDirs, std::vector<std::string> &localPath)1859 void MainThread::ChangeToLocalPath(const std::string &bundleName,
1860     const std::vector<std::string> &sourceDirs, std::vector<std::string> &localPath)
1861 {
1862     std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + bundleName
1863         + std::string(FILE_SEPARATOR));
1864     for (auto item : sourceDirs) {
1865         if (item.empty()) {
1866             continue;
1867         }
1868         localPath.emplace_back(
1869             std::regex_replace(item, pattern, std::string(LOCAL_CODE_PATH) + std::string(FILE_SEPARATOR)));
1870     }
1871 }
1872 
ChangeToLocalPath(const std::string &bundleName, const std::string &sourceDir, std::string &localPath)1873 void MainThread::ChangeToLocalPath(const std::string &bundleName,
1874     const std::string &sourceDir, std::string &localPath)
1875 {
1876     std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + bundleName);
1877     if (sourceDir.empty()) {
1878         return;
1879     }
1880     bool isExist = false;
1881     try {
1882         isExist = std::regex_search(localPath, std::regex(bundleName));
1883     } catch (...) {
1884         TAG_LOGE(AAFwkTag::APPKIT, "ChangeToLocalPath error localPath:%{public}s bundleName:%{public}s",
1885             localPath.c_str(), bundleName.c_str());
1886     }
1887     if (isExist) {
1888         localPath = std::regex_replace(localPath, pattern, std::string(LOCAL_CODE_PATH));
1889     } else {
1890         localPath = std::regex_replace(localPath, std::regex(ABS_CODE_PATH), LOCAL_BUNDLES);
1891     }
1892 }
1893 
HandleUpdateApplicationInfoInstalled(const ApplicationInfo &appInfo)1894 void MainThread::HandleUpdateApplicationInfoInstalled(const ApplicationInfo &appInfo)
1895 {
1896     TAG_LOGD(AAFwkTag::APPKIT, "called");
1897     if (!application_) {
1898         TAG_LOGE(AAFwkTag::APPKIT, "application_ is nullptr");
1899         return;
1900     }
1901     application_->UpdateApplicationInfoInstalled(appInfo);
1902 }
1903 
HandleAbilityStage(const HapModuleInfo &abilityStage)1904 void MainThread::HandleAbilityStage(const HapModuleInfo &abilityStage)
1905 {
1906     TAG_LOGD(AAFwkTag::APPKIT, "called");
1907     if (!application_) {
1908         TAG_LOGE(AAFwkTag::APPKIT, "application_ is nullptr");
1909         return;
1910     }
1911 
1912     wptr<MainThread> weak = this;
1913     auto callback = [weak]() {
1914         auto appThread = weak.promote();
1915         if (appThread == nullptr) {
1916             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
1917             return;
1918         }
1919         if (!appThread->appMgr_ || !appThread->applicationImpl_) {
1920             TAG_LOGE(AAFwkTag::APPKIT, "appMgr_ is nullptr");
1921             return;
1922         }
1923         appThread->appMgr_->AddAbilityStageDone(appThread->applicationImpl_->GetRecordId());
1924     };
1925     bool isAsyncCallback = false;
1926     application_->AddAbilityStage(abilityStage, callback, isAsyncCallback);
1927     if (isAsyncCallback) {
1928         return;
1929     }
1930 
1931     if (!appMgr_ || !applicationImpl_) {
1932         TAG_LOGE(AAFwkTag::APPKIT, "appMgr_ is nullptr");
1933         return;
1934     }
1935 
1936     appMgr_->AddAbilityStageDone(applicationImpl_->GetRecordId());
1937 }
1938 
LoadAllExtensions(NativeEngine &nativeEngine)1939 void MainThread::LoadAllExtensions(NativeEngine &nativeEngine)
1940 {
1941     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1942     TAG_LOGD(AAFwkTag::APPKIT, "LoadAllExtensions");
1943     auto extensionPlugins = AbilityRuntime::ExtensionPluginInfo::GetInstance().GetExtensionPlugins();
1944     if (extensionPlugins.empty()) {
1945         TAG_LOGE(AAFwkTag::APPKIT, "no extension type map");
1946         return;
1947     }
1948 
1949     std::map<int32_t, std::string> extensionTypeMap;
1950     for (auto& item : extensionPlugins) {
1951         extensionTypeMap.insert(std::pair<int32_t, std::string>(item.extensionType, item.extensionName));
1952         AddExtensionBlockItem(item.extensionName, item.extensionType);
1953 
1954         std::string file = item.extensionLibFile;
1955         std::weak_ptr<OHOSApplication> wApp = application_;
1956         AbilityLoader::GetInstance().RegisterExtension(item.extensionName,
1957             [wApp, file]() -> AbilityRuntime::Extension* {
1958             auto app = wApp.lock();
1959             if (app != nullptr) {
1960                 return AbilityRuntime::ExtensionModuleLoader::GetLoader(file.c_str()).Create(app->GetRuntime());
1961             }
1962             TAG_LOGE(AAFwkTag::APPKIT, "failed.");
1963             return nullptr;
1964         });
1965     }
1966     application_->SetExtensionTypeMap(extensionTypeMap);
1967 }
1968 
PrepareAbilityDelegator(const std::shared_ptr<UserTestRecord> &record, bool isStageBased, const AppExecFwk::HapModuleInfo &entryHapModuleInfo)1969 bool MainThread::PrepareAbilityDelegator(const std::shared_ptr<UserTestRecord> &record, bool isStageBased,
1970     const AppExecFwk::HapModuleInfo &entryHapModuleInfo)
1971 {
1972     TAG_LOGD(AAFwkTag::APPKIT, "enter, isStageBased = %{public}d", isStageBased);
1973     if (!record) {
1974         TAG_LOGE(AAFwkTag::APPKIT, "Invalid UserTestRecord");
1975         return false;
1976     }
1977     auto args = std::make_shared<AbilityDelegatorArgs>(record->want);
1978     if (isStageBased) { // Stage model
1979         TAG_LOGD(AAFwkTag::APPKIT, "Stage model");
1980         auto testRunner = TestRunner::Create(application_->GetRuntime(), args, false);
1981         auto delegator = std::make_shared<AbilityDelegator>(
1982             application_->GetAppContext(), std::move(testRunner), record->observer);
1983         AbilityDelegatorRegistry::RegisterInstance(delegator, args);
1984         delegator->Prepare();
1985     } else { // FA model
1986         TAG_LOGD(AAFwkTag::APPKIT, "FA model");
1987         AbilityRuntime::Runtime::Options options;
1988         options.codePath = LOCAL_CODE_PATH;
1989         options.eventRunner = mainHandler_->GetEventRunner();
1990         options.hapPath = entryHapModuleInfo.hapPath;
1991         options.loadAce = false;
1992         options.isStageModel = false;
1993         options.isTestFramework = true;
1994         if (applicationInfo_) {
1995             options.apiTargetVersion = applicationInfo_->apiTargetVersion;
1996         }
1997         if (entryHapModuleInfo.abilityInfos.empty()) {
1998             TAG_LOGE(AAFwkTag::APPKIT, "Failed to abilityInfos");
1999             return false;
2000         }
2001         bool isFaJsModel = entryHapModuleInfo.abilityInfos.front().srcLanguage == "js" ? true : false;
2002         static auto runtime = AbilityRuntime::Runtime::Create(options);
2003         auto testRunner = TestRunner::Create(runtime, args, isFaJsModel);
2004         if (testRunner == nullptr) {
2005             TAG_LOGE(AAFwkTag::APPKIT, "Failed to Create testRunner");
2006             return false;
2007         }
2008         if (!testRunner->Initialize()) {
2009             TAG_LOGE(AAFwkTag::APPKIT, "Failed to Initialize testRunner");
2010             return false;
2011         }
2012         auto delegator = std::make_shared<AbilityDelegator>(
2013             application_->GetAppContext(), std::move(testRunner), record->observer);
2014         AbilityDelegatorRegistry::RegisterInstance(delegator, args);
2015         delegator->Prepare();
2016     }
2017     return true;
2018 }
2019 
2020 /**
2021  *
2022  * @brief launch the ability.
2023  *
2024  * @param abilityRecord The abilityRecord which belongs to the ability launched.
2025  *
2026  */
HandleLaunchAbility(const std::shared_ptr<AbilityLocalRecord> &abilityRecord)2027 void MainThread::HandleLaunchAbility(const std::shared_ptr<AbilityLocalRecord> &abilityRecord)
2028 {
2029     TAG_LOGD(AAFwkTag::APPKIT, "called");
2030     CHECK_POINTER_LOG(abilityRecord, "parameter(abilityRecord) is null");
2031     std::string connector = "##";
2032     std::string traceName = __PRETTY_FUNCTION__ + connector;
2033     if (abilityRecord->GetWant() != nullptr) {
2034         traceName += abilityRecord->GetWant()->GetElement().GetBundleName();
2035     } else {
2036         TAG_LOGE(AAFwkTag::APPKIT, "Want is nullptr, cant not get abilityName");
2037     }
2038     HITRACE_METER_NAME(HITRACE_TAG_APP, traceName);
2039     CHECK_POINTER_LOG(applicationImpl_, "applicationImpl_ is null");
2040     CHECK_POINTER_LOG(abilityRecordMgr_, "abilityRecordMgr_ is null");
2041 
2042     auto abilityToken = abilityRecord->GetToken();
2043     CHECK_POINTER_LOG(abilityToken, "abilityRecord->GetToken failed");
2044     FreezeUtil::LifecycleFlow flow = { abilityToken, FreezeUtil::TimeoutState::LOAD };
2045     std::string entry = "MainThread::HandleLaunchAbility; the load lifecycle.";
2046     FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
2047 
2048     abilityRecordMgr_->SetToken(abilityToken);
2049     abilityRecordMgr_->AddAbilityRecord(abilityToken, abilityRecord);
2050 
2051     if (!IsApplicationReady()) {
2052         TAG_LOGE(AAFwkTag::APPKIT, "should launch application first");
2053         return;
2054     }
2055 
2056     if (!CheckAbilityItem(abilityRecord)) {
2057         TAG_LOGE(AAFwkTag::APPKIT, "record is invalid");
2058         return;
2059     }
2060 
2061     mainThreadState_ = MainThreadState::RUNNING;
2062     wptr<MainThread> weak = this;
2063     auto callback = [weak, abilityRecord](const std::shared_ptr<AbilityRuntime::Context> &stageContext) {
2064         auto appThread = weak.promote();
2065         if (appThread == nullptr) {
2066             TAG_LOGE(AAFwkTag::APPKIT, "abilityThread is nullptr");
2067             return;
2068         }
2069         appThread->SetProcessExtensionType(abilityRecord);
2070         auto application = appThread->GetApplication();
2071         if (application == nullptr) {
2072             TAG_LOGE(AAFwkTag::APPKIT, "application is nullptr");
2073             return;
2074         }
2075         auto& runtime = application->GetRuntime();
2076         appThread->UpdateRuntimeModuleChecker(runtime);
2077 #ifdef APP_ABILITY_USE_TWO_RUNNER
2078         AbilityThread::AbilityThreadMain(application, abilityRecord, stageContext);
2079 #else
2080         AbilityThread::AbilityThreadMain(application, abilityRecord, mainHandler_->GetEventRunner(), stageContext);
2081 #endif
2082     };
2083 #ifdef SUPPORT_SCREEN
2084     Rosen::DisplayId defaultDisplayId = Rosen::DisplayManager::GetInstance().GetDefaultDisplayId();
2085     Rosen::DisplayId displayId = defaultDisplayId;
2086     if (abilityRecord->GetWant() != nullptr) {
2087         displayId = static_cast<uint64_t>(abilityRecord->GetWant()->GetIntParam(
2088             AAFwk::Want::PARAM_RESV_DISPLAY_ID, defaultDisplayId));
2089     }
2090     Rosen::DisplayManager::GetInstance().AddDisplayIdFromAms(displayId, abilityRecord->GetToken());
2091     TAG_LOGD(AAFwkTag::APPKIT, "add displayId: %{public}" PRIu64, displayId);
2092 #endif
2093     bool isAsyncCallback = false;
2094     std::shared_ptr<AbilityRuntime::Context> stageContext = application_->AddAbilityStage(
2095         abilityRecord, callback, isAsyncCallback);
2096     if (isAsyncCallback) {
2097         return;
2098     }
2099     SetProcessExtensionType(abilityRecord);
2100     auto& runtime = application_->GetRuntime();
2101     UpdateRuntimeModuleChecker(runtime);
2102 #ifdef APP_ABILITY_USE_TWO_RUNNER
2103     AbilityThread::AbilityThreadMain(application_, abilityRecord, stageContext);
2104 #else
2105     AbilityThread::AbilityThreadMain(application_, abilityRecord, mainHandler_->GetEventRunner(), stageContext);
2106 #endif
2107 }
2108 
2109 /**
2110  *
2111  * @brief Clean the ability but don't notify ams.
2112  *
2113  * @param token The token which belongs to the ability launched.
2114  *
2115  */
HandleCleanAbilityLocal(const sptr<IRemoteObject> &token)2116 void MainThread::HandleCleanAbilityLocal(const sptr<IRemoteObject> &token)
2117 {
2118     TAG_LOGD(AAFwkTag::APPKIT, "start");
2119     if (!IsApplicationReady()) {
2120         TAG_LOGE(AAFwkTag::APPKIT, "should launch application first");
2121         return;
2122     }
2123 
2124     if (token == nullptr) {
2125         TAG_LOGE(AAFwkTag::APPKIT, "token is null");
2126         return;
2127     }
2128 
2129     std::shared_ptr<AbilityLocalRecord> record = abilityRecordMgr_->GetAbilityItem(token);
2130     CHECK_POINTER_TAG_LOG(record, AAFwkTag::APPKIT, "abilityRecord not found");
2131     std::shared_ptr<AbilityInfo> abilityInfo = record->GetAbilityInfo();
2132     CHECK_POINTER_TAG_LOG(abilityInfo, AAFwkTag::APPKIT, "record->GetAbilityInfo() failed");
2133     TAG_LOGD(AAFwkTag::APPKIT, "ability name: %{public}s", abilityInfo->name.c_str());
2134     abilityRecordMgr_->RemoveAbilityRecord(token);
2135     application_->CleanAbilityStage(token, abilityInfo, false);
2136 #ifdef APP_ABILITY_USE_TWO_RUNNER
2137     std::shared_ptr<EventRunner> runner = record->GetEventRunner();
2138     if (runner != nullptr) {
2139         int ret = runner->Stop();
2140         if (ret != ERR_OK) {
2141             TAG_LOGE(AAFwkTag::APPKIT, "MainThread::main failed. ability runner->Run failed ret = %{public}d", ret);
2142         }
2143         abilityRecordMgr_->RemoveAbilityRecord(token);
2144         application_->CleanAbilityStage(token, abilityInfo, false);
2145     } else {
2146         TAG_LOGW(AAFwkTag::APPKIT, "runner not found");
2147     }
2148 #endif
2149 }
2150 
2151 /**
2152  *
2153  * @brief Clean the ability.
2154  *
2155  * @param token The token which belongs to the ability launched.
2156  *
2157  */
HandleCleanAbility(const sptr<IRemoteObject> &token, bool isCacheProcess)2158 void MainThread::HandleCleanAbility(const sptr<IRemoteObject> &token, bool isCacheProcess)
2159 {
2160     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2161     if (applicationInfo_ == nullptr) {
2162         TAG_LOGE(AAFwkTag::APPKIT, "applicationInfo is null");
2163         return;
2164     }
2165     TAG_LOGD(AAFwkTag::APPKIT, "Handle clean ability start, app is %{public}s.", applicationInfo_->name.c_str());
2166 
2167     if (!IsApplicationReady()) {
2168         TAG_LOGE(AAFwkTag::APPKIT, "should launch application first");
2169         return;
2170     }
2171     CHECK_POINTER_TAG_LOG(token, AAFwkTag::APPKIT, "token is null");
2172     std::shared_ptr<AbilityLocalRecord> record = abilityRecordMgr_->GetAbilityItem(token);
2173     CHECK_POINTER_TAG_LOG(record, AAFwkTag::APPKIT, "abilityRecord not found");
2174     std::shared_ptr<AbilityInfo> abilityInfo = record->GetAbilityInfo();
2175     CHECK_POINTER_TAG_LOG(abilityInfo, AAFwkTag::APPKIT, "record->GetAbilityInfo() failed");
2176 #ifdef SUPPORT_GRAPHICS
2177     if (abilityInfo->type == AbilityType::PAGE && abilityInfo->isStageBasedModel) {
2178         AppRecovery::GetInstance().RemoveAbility(token);
2179     }
2180 #endif
2181     abilityRecordMgr_->RemoveAbilityRecord(token);
2182     application_->CleanAbilityStage(token, abilityInfo, isCacheProcess);
2183 #ifdef APP_ABILITY_USE_TWO_RUNNER
2184     std::shared_ptr<EventRunner> runner = record->GetEventRunner();
2185     if (runner != nullptr) {
2186         int ret = runner->Stop();
2187         if (ret != ERR_OK) {
2188             TAG_LOGE(AAFwkTag::APPKIT, "MainThread::main failed. ability runner->Run failed ret = %{public}d", ret);
2189         }
2190         abilityRecordMgr_->RemoveAbilityRecord(token);
2191         application_->CleanAbilityStage(token, abilityInfo, isCacheProcess);
2192     } else {
2193         TAG_LOGW(AAFwkTag::APPKIT, "runner not found");
2194     }
2195 #endif
2196     appMgr_->AbilityCleaned(token);
2197     TAG_LOGD(AAFwkTag::APPKIT, "end. app: %{public}s, ability: %{public}s.",
2198         applicationInfo_->name.c_str(), abilityInfo->name.c_str());
2199 }
2200 
2201 /**
2202  *
2203  * @brief Foreground the application.
2204  *
2205  */
HandleForegroundApplication()2206 void MainThread::HandleForegroundApplication()
2207 {
2208     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2209     FreezeUtil::GetInstance().AddAppLifecycleEvent(0, "HandleForegroundApplication");
2210     TAG_LOGI(AAFwkTag::APPKIT, "called");
2211     if ((application_ == nullptr) || (appMgr_ == nullptr)) {
2212         TAG_LOGE(AAFwkTag::APPKIT, "handleForegroundApplication error!");
2213         return;
2214     }
2215 
2216     if (!applicationImpl_->PerformForeground()) {
2217         FreezeUtil::GetInstance().AddAppLifecycleEvent(0, "HandleForegroundApplication fail");
2218         TAG_LOGE(AAFwkTag::APPKIT, "applicationImpl_->PerformForeground() failed");
2219     }
2220 
2221     // Start accessing PurgeableMem if the event of foreground is successful.
2222 #ifdef IMAGE_PURGEABLE_PIXELMAP
2223     PurgeableMem::PurgeableResourceManager::GetInstance().BeginAccessPurgeableMem();
2224 #endif
2225 
2226     TAG_LOGD(AAFwkTag::APPKIT, "to foreground success, recordId is %{public}d", applicationImpl_->GetRecordId());
2227     appMgr_->ApplicationForegrounded(applicationImpl_->GetRecordId());
2228 }
2229 
2230 /**
2231  *
2232  * @brief Background the application.
2233  *
2234  */
HandleBackgroundApplication()2235 void MainThread::HandleBackgroundApplication()
2236 {
2237     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2238     TAG_LOGI(AAFwkTag::APPKIT, "start");
2239     FreezeUtil::GetInstance().AddAppLifecycleEvent(0, "HandleBackgroundApplication");
2240     if ((application_ == nullptr) || (appMgr_ == nullptr)) {
2241         TAG_LOGE(AAFwkTag::APPKIT, "error");
2242         return;
2243     }
2244 
2245     if (!applicationImpl_->PerformBackground()) {
2246         TAG_LOGE(AAFwkTag::APPKIT, "applicationImpl_->PerformBackground() failed");
2247     }
2248 
2249     // End accessing PurgeableMem if the event of background is successful.
2250 #ifdef IMAGE_PURGEABLE_PIXELMAP
2251     PurgeableMem::PurgeableResourceManager::GetInstance().EndAccessPurgeableMem();
2252 #endif
2253 
2254     appMgr_->ApplicationBackgrounded(applicationImpl_->GetRecordId());
2255 }
2256 
2257 /**
2258  *
2259  * @brief Terminate the application.
2260  *
2261  * @param isLastProcess When it is the last application process, pass in true.
2262  */
HandleTerminateApplication(bool isLastProcess)2263 void MainThread::HandleTerminateApplication(bool isLastProcess)
2264 {
2265     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2266     TAG_LOGD(AAFwkTag::APPKIT, "start");
2267     if ((applicationImpl_ == nullptr) || (appMgr_ == nullptr)) {
2268         TAG_LOGE(AAFwkTag::APPKIT, "error");
2269         return;
2270     }
2271 
2272     if (!applicationImpl_->PerformTerminate(isLastProcess)) {
2273         TAG_LOGD(AAFwkTag::APPKIT, "PerformTerminate() failed");
2274     }
2275 
2276     std::shared_ptr<EventRunner> runner = mainHandler_->GetEventRunner();
2277     if (runner == nullptr) {
2278         TAG_LOGE(AAFwkTag::APPKIT, "get manHandler error");
2279         return;
2280     }
2281 
2282     if (watchdog_ != nullptr && !watchdog_->IsStopWatchdog()) {
2283         watchdog_->Stop();
2284         watchdog_ = nullptr;
2285     }
2286 
2287     int ret = runner->Stop();
2288     if (ret != ERR_OK) {
2289         TAG_LOGE(AAFwkTag::APPKIT, "runner->Run failed ret = %{public}d", ret);
2290     }
2291     SetRunnerStarted(false);
2292     appMgr_->ApplicationTerminated(applicationImpl_->GetRecordId());
2293 }
2294 
2295 /**
2296  *
2297  * @brief Shrink the memory which used by application.
2298  *
2299  * @param level Indicates the memory trim level, which shows the current memory usage status.
2300  *
2301  */
HandleShrinkMemory(const int level)2302 void MainThread::HandleShrinkMemory(const int level)
2303 {
2304     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2305 
2306     if (applicationImpl_ == nullptr) {
2307         TAG_LOGE(AAFwkTag::APPKIT, "applicationImpl_ is null");
2308         return;
2309     }
2310 
2311     applicationImpl_->PerformMemoryLevel(level);
2312 }
2313 
2314 /**
2315  *
2316  * @brief Handle NotifyMemoryLevel.
2317  *
2318  * @param level Indicates the memory trim level, which shows the current memory usage status.
2319  *
2320  */
HandleMemoryLevel(int level)2321 void MainThread::HandleMemoryLevel(int level)
2322 {
2323     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2324     TAG_LOGD(AAFwkTag::APPKIT, "start");
2325 
2326     if (application_ == nullptr) {
2327         TAG_LOGE(AAFwkTag::APPKIT, "application_ is null");
2328         return;
2329     }
2330 
2331     application_->OnMemoryLevel(level);
2332 }
2333 
2334 /**
2335  *
2336  * @brief send the new config to the application.
2337  *
2338  * @param config The updated config.
2339  *
2340  */
HandleConfigurationUpdated(const Configuration &config)2341 void MainThread::HandleConfigurationUpdated(const Configuration &config)
2342 {
2343     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2344     if (applicationImpl_ == nullptr) {
2345         TAG_LOGE(AAFwkTag::APPKIT, "applicationImpl_ is null");
2346         return;
2347     }
2348 
2349     applicationImpl_->PerformConfigurationUpdated(config);
2350 }
2351 
TaskTimeoutDetected(const std::shared_ptr<EventRunner> &runner)2352 void MainThread::TaskTimeoutDetected(const std::shared_ptr<EventRunner> &runner)
2353 {
2354     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2355     TAG_LOGD(AAFwkTag::APPKIT, "start");
2356 
2357     auto deliveryTimeoutCallback = []() {
2358         TAG_LOGD(AAFwkTag::APPKIT, "delivery timeout");
2359     };
2360     auto distributeTimeoutCallback = []() {
2361         TAG_LOGD(AAFwkTag::APPKIT, "distribute timeout");
2362     };
2363 
2364     if (runner !=nullptr && mainHandler_ != nullptr) {
2365         runner->SetDeliveryTimeout(DELIVERY_TIME);
2366         mainHandler_->SetDeliveryTimeoutCallback(deliveryTimeoutCallback);
2367 
2368         runner->SetDistributeTimeout(DISTRIBUTE_TIME);
2369         mainHandler_->SetDistributeTimeoutCallback(distributeTimeoutCallback);
2370     }
2371 }
2372 
Init(const std::shared_ptr<EventRunner> &runner)2373 void MainThread::Init(const std::shared_ptr<EventRunner> &runner)
2374 {
2375     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2376     TAG_LOGD(AAFwkTag::APPKIT, "Start");
2377     mainHandler_ = std::make_shared<MainHandler>(runner, this);
2378     watchdog_ = std::make_shared<Watchdog>();
2379     extensionConfigMgr_ = std::make_unique<AbilityRuntime::ExtensionConfigMgr>();
2380     wptr<MainThread> weak = this;
2381     auto task = [weak]() {
2382         auto appThread = weak.promote();
2383         if (appThread == nullptr) {
2384             TAG_LOGE(AAFwkTag::APPKIT, "abilityThread is nullptr");
2385             return;
2386         }
2387         appThread->SetRunnerStarted(true);
2388     };
2389     if (!mainHandler_->PostTask(task, "MainThread:SetRunnerStarted")) {
2390         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
2391     }
2392     TaskTimeoutDetected(runner);
2393 
2394     watchdog_->Init(mainHandler_);
2395     AppExecFwk::AppfreezeInner::GetInstance()->SetMainHandler(mainHandler_);
2396     extensionConfigMgr_->Init();
2397 }
2398 
HandleSignal(int signal, [[maybe_unused]] siginfo_t *siginfo, void *context)2399 void MainThread::HandleSignal(int signal, [[maybe_unused]] siginfo_t *siginfo, void *context)
2400 {
2401     if (signal != MUSL_SIGNAL_JSHEAP) {
2402         TAG_LOGE(AAFwkTag::APPKIT, "signal is %{public}d", signal);
2403         return;
2404     }
2405     TAG_LOGI(AAFwkTag::APPKIT, "sival_int is %{public}d", siginfo->si_value.sival_int);
2406     if (static_cast<SignalType>(siginfo->si_value.sival_int) != SignalType::SIGNAL_FORCE_FULLGC) {
2407         HandleDumpHeapPrepare();
2408     }
2409     switch (static_cast<SignalType>(siginfo->si_value.sival_int)) {
2410         case SignalType::SIGNAL_JSHEAP_OLD: {
2411             auto heapFunc = []() { return MainThread::HandleDumpHeap(false); };
2412             mainHandler_->PostTask(heapFunc, "MainThread::SIGNAL_JSHEAP_OLD");
2413             break;
2414         }
2415         case SignalType::SIGNAL_JSHEAP: {
2416             auto heapFunc = []() { return MainThread::HandleDumpHeap(false); };
2417             mainHandler_->PostTask(heapFunc, "MainThread::SIGNAL_JSHEAP");
2418             break;
2419         }
2420         case SignalType::SIGNAL_JSHEAP_PRIV: {
2421             auto privateHeapFunc = []() { return MainThread::HandleDumpHeap(true); };
2422             mainHandler_->PostTask(privateHeapFunc, "MainThread:SIGNAL_JSHEAP_PRIV");
2423             break;
2424         }
2425         case SignalType::SIGNAL_NO_TRIGGERID: {
2426             auto heapFunc = []() { return MainThread::HandleDumpHeap(false); };
2427             mainHandler_->PostTask(heapFunc, "MainThread::SIGNAL_JSHEAP");
2428 
2429             auto noTriggerIdFunc = []() { MainThread::DestroyHeapProfiler(); };
2430             mainHandler_->PostTask(noTriggerIdFunc, "MainThread::SIGNAL_NO_TRIGGERID");
2431             break;
2432         }
2433         case SignalType::SIGNAL_NO_TRIGGERID_PRIV: {
2434             auto privateHeapFunc = []() { return MainThread::HandleDumpHeap(true); };
2435             mainHandler_->PostTask(privateHeapFunc, "MainThread:SIGNAL_JSHEAP_PRIV");
2436 
2437             auto noTriggerIdFunc = []() { MainThread::DestroyHeapProfiler(); };
2438             mainHandler_->PostTask(noTriggerIdFunc, "MainThread::SIGNAL_NO_TRIGGERID_PRIV");
2439             break;
2440         }
2441         case SignalType::SIGNAL_FORCE_FULLGC: {
2442             auto forceFullGCFunc = []() { MainThread::ForceFullGC(); };
2443             ffrt::submit(forceFullGCFunc);
2444             break;
2445         }
2446         default:
2447             break;
2448     }
2449 }
2450 
HandleDumpHeapPrepare()2451 void MainThread::HandleDumpHeapPrepare()
2452 {
2453     TAG_LOGD(AAFwkTag::APPKIT, "start");
2454     if (mainHandler_ == nullptr) {
2455         TAG_LOGE(AAFwkTag::APPKIT, "mainHandler is nullptr");
2456         return;
2457     }
2458     auto app = applicationForDump_.lock();
2459     if (app == nullptr) {
2460         TAG_LOGE(AAFwkTag::APPKIT, "app is nullptr");
2461         return;
2462     }
2463     auto &runtime = app->GetRuntime();
2464     if (runtime == nullptr) {
2465         TAG_LOGE(AAFwkTag::APPKIT, "runtime is nullptr");
2466         return;
2467     }
2468     runtime->GetHeapPrepare();
2469 }
2470 
HandleDumpHeap(bool isPrivate)2471 void MainThread::HandleDumpHeap(bool isPrivate)
2472 {
2473     TAG_LOGD(AAFwkTag::APPKIT, "start");
2474     if (mainHandler_ == nullptr) {
2475         TAG_LOGE(AAFwkTag::APPKIT, "mainHandler is nullptr");
2476         return;
2477     }
2478     auto app = applicationForDump_.lock();
2479     if (app == nullptr) {
2480         TAG_LOGE(AAFwkTag::APPKIT, "app is nullptr");
2481         return;
2482     }
2483     auto &runtime = app->GetRuntime();
2484     if (runtime == nullptr) {
2485         TAG_LOGE(AAFwkTag::APPKIT, "runtime is nullptr");
2486         return;
2487     }
2488     auto taskFork = [&runtime, &isPrivate] {
2489         TAG_LOGD(AAFwkTag::APPKIT, "HandleDump Heap taskFork start");
2490         time_t startTime = time(nullptr);
2491         int pid = -1;
2492         if ((pid = fork()) < 0) {
2493             TAG_LOGE(AAFwkTag::APPKIT, "HandleDumpHeap Fork error, err:%{public}d", errno);
2494             return;
2495         }
2496         if (pid == 0) {
2497             runtime->AllowCrossThreadExecution();
2498             runtime->DumpHeapSnapshot(isPrivate);
2499             TAG_LOGI(AAFwkTag::APPKIT, "HandleDumpHeap successful, now you can check some file");
2500             _exit(0);
2501         }
2502         while (true) {
2503             int status = 0;
2504             pid_t p = waitpid(pid, &status, 0);
2505             if (p < 0) {
2506                 TAG_LOGE(AAFwkTag::APPKIT, "HandleDumpHeap waitpid return p=%{public}d, err:%{public}d", p, errno);
2507                 break;
2508             }
2509             if (p == pid) {
2510                 TAG_LOGE(AAFwkTag::APPKIT, "HandleDumpHeap dump process exited status is %{public}d", status);
2511                 break;
2512             }
2513             if (time(nullptr) > startTime + TIME_OUT) {
2514                 TAG_LOGE(AAFwkTag::APPKIT, "time out to wait childprocess, killing forkpid %{public}d", pid);
2515                 kill(pid, SIGKILL);
2516                 break;
2517             }
2518             usleep(DEFAULT_SLEEP_TIME);
2519         }
2520     };
2521 
2522     ffrt::submit(taskFork, {}, {}, ffrt::task_attr().qos(ffrt::qos_user_initiated));
2523     runtime->DumpCpuProfile();
2524 }
2525 
DestroyHeapProfiler()2526 void MainThread::DestroyHeapProfiler()
2527 {
2528     TAG_LOGD(AAFwkTag::APPKIT, "called");
2529     if (mainHandler_ == nullptr) {
2530         TAG_LOGE(AAFwkTag::APPKIT, "mainHandler is nullptr");
2531         return;
2532     }
2533 
2534     auto task = [] {
2535         auto app = applicationForDump_.lock();
2536         if (app == nullptr || app->GetRuntime() == nullptr) {
2537             TAG_LOGE(AAFwkTag::APPKIT, "runtime is nullptr");
2538             return;
2539         }
2540         app->GetRuntime()->DestroyHeapProfiler();
2541     };
2542     mainHandler_->PostTask(task, "MainThread:DestroyHeapProfiler");
2543 }
2544 
ForceFullGC()2545 void MainThread::ForceFullGC()
2546 {
2547     TAG_LOGD(AAFwkTag::APPKIT, "Force fullGC");
2548     if (mainHandler_ == nullptr) {
2549         TAG_LOGE(AAFwkTag::APPKIT, "mainHandler is nullptr");
2550         return;
2551     }
2552 
2553     auto task = [] {
2554         auto app = applicationForDump_.lock();
2555         if (app == nullptr || app->GetRuntime() == nullptr) {
2556             TAG_LOGE(AAFwkTag::APPKIT, "runtime is nullptr");
2557             return;
2558         }
2559         app->GetRuntime()->ForceFullGC();
2560     };
2561     mainHandler_->PostTask(task, "MainThread:ForceFullGC");
2562 }
2563 
Start()2564 void MainThread::Start()
2565 {
2566     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2567     TAG_LOGI(AAFwkTag::APPKIT, "App main thread create, pid:%{public}d", getprocpid());
2568 
2569     std::shared_ptr<EventRunner> runner = EventRunner::GetMainEventRunner();
2570     if (runner == nullptr) {
2571         TAG_LOGE(AAFwkTag::APPKIT, "runner is nullptr");
2572         return;
2573     }
2574     sptr<MainThread> thread = sptr<MainThread>(new (std::nothrow) MainThread());
2575     if (thread == nullptr) {
2576         TAG_LOGE(AAFwkTag::APPKIT, "new MainThread failed");
2577         return;
2578     }
2579 
2580     struct sigaction sigAct;
2581     sigemptyset(&sigAct.sa_mask);
2582     sigAct.sa_flags = SA_SIGINFO;
2583     sigAct.sa_sigaction = &MainThread::HandleSignal;
2584     sigaction(MUSL_SIGNAL_JSHEAP, &sigAct, NULL);
2585 
2586     thread->Init(runner);
2587 
2588     thread->Attach();
2589 
2590     int ret = runner->Run();
2591     if (ret != ERR_OK) {
2592         TAG_LOGE(AAFwkTag::APPKIT, "runner->Run failed ret = %{public}d", ret);
2593     }
2594 
2595     thread->RemoveAppMgrDeathRecipient();
2596 }
2597 
StartChild(const std::map<std::string, int32_t> &fds)2598 void MainThread::StartChild(const std::map<std::string, int32_t> &fds)
2599 {
2600     TAG_LOGI(AAFwkTag::APPKIT, "MainThread StartChild, fds size:%{public}zu", fds.size());
2601     ChildMainThread::Start(fds);
2602 }
2603 
PreloadExtensionPlugin()2604 void MainThread::PreloadExtensionPlugin()
2605 {
2606     AbilityRuntime::ExtensionPluginInfo::GetInstance().Preload();
2607 }
2608 
MainHandler(const std::shared_ptr<EventRunner> &runner, const sptr<MainThread> &thread)2609 MainThread::MainHandler::MainHandler(const std::shared_ptr<EventRunner> &runner, const sptr<MainThread> &thread)
2610     : AppExecFwk::EventHandler(runner), mainThreadObj_(thread)
2611 {}
2612 
2613 /**
2614  *
2615  * @brief Process the event.
2616  *
2617  * @param event the event want to be processed.
2618  *
2619  */
ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer &event)2620 void MainThread::MainHandler::ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer &event)
2621 {
2622     auto eventId = event->GetInnerEventId();
2623     if (eventId == CHECK_MAIN_THREAD_IS_ALIVE) {
2624         auto mt = mainThreadObj_.promote();
2625         if (mt != nullptr) {
2626             mt->CheckMainThreadIsAlive();
2627         }
2628     }
2629 }
2630 
2631 /**
2632  *
2633  * @brief Check whether the OHOSApplication is ready.
2634  *
2635  * @return if the record is legal, return true. else return false.
2636  *
2637  */
IsApplicationReady() const2638 bool MainThread::IsApplicationReady() const
2639 {
2640     TAG_LOGD(AAFwkTag::APPKIT, "start");
2641     if (application_ == nullptr || applicationImpl_ == nullptr) {
2642         TAG_LOGW(AAFwkTag::APPKIT, "application_=null or applicationImpl_=null");
2643         return false;
2644     }
2645 
2646     return true;
2647 }
2648 
2649 #ifdef ABILITY_LIBRARY_LOADER
2650 /**
2651  *
2652  * @brief Load the ability library.
2653  *
2654  * @param libraryPaths the library paths.
2655  *
2656  */
LoadAbilityLibrary(const std::vector<std::string> &libraryPaths)2657 void MainThread::LoadAbilityLibrary(const std::vector<std::string> &libraryPaths)
2658 {
2659     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2660 #ifdef ABILITY_LIBRARY_LOADER
2661     TAG_LOGD(AAFwkTag::APPKIT, "start");
2662 #ifdef SUPPORT_SCREEN
2663     LoadAceAbilityLibrary();
2664 #endif
2665     size_t size = libraryPaths.size();
2666     for (size_t index = 0; index < size; index++) {
2667         std::string libraryPath = libraryPaths[index];
2668         TAG_LOGD(AAFwkTag::APPKIT, "Try to scanDir %{public}s", libraryPath.c_str());
2669         if (!ScanDir(libraryPath, fileEntries_)) {
2670             TAG_LOGW(AAFwkTag::APPKIT, "scanDir %{public}s not exits", libraryPath.c_str());
2671         }
2672         libraryPath = libraryPath + "/libs";
2673         if (!ScanDir(libraryPath, fileEntries_)) {
2674             TAG_LOGW(AAFwkTag::APPKIT, "scanDir %{public}s not exits", libraryPath.c_str());
2675         }
2676     }
2677 
2678     if (fileEntries_.empty()) {
2679         TAG_LOGD(AAFwkTag::APPKIT, "No ability library");
2680         return;
2681     }
2682 
2683     char resolvedPath[PATH_MAX] = {0};
2684     void *handleAbilityLib = nullptr;
2685     for (const auto& fileEntry : fileEntries_) {
2686         if (fileEntry.empty() || fileEntry.size() >= PATH_MAX) {
2687             continue;
2688         }
2689         if (realpath(fileEntry.c_str(), resolvedPath) == nullptr) {
2690             TAG_LOGE(AAFwkTag::APPKIT, "Failed to get realpath, errno = %{public}d", errno);
2691             continue;
2692         }
2693 
2694         handleAbilityLib = dlopen(resolvedPath, RTLD_NOW | RTLD_GLOBAL);
2695         if (handleAbilityLib == nullptr) {
2696             TAG_LOGE(AAFwkTag::APPKIT, "Fail to dlopen %{public}s, [%{public}s]",
2697                 resolvedPath, dlerror());
2698             exit(-1);
2699         }
2700         TAG_LOGI(AAFwkTag::APPKIT, "Success to dlopen %{public}s", fileEntry.c_str());
2701         handleAbilityLib_.emplace_back(handleAbilityLib);
2702     }
2703 #endif  // ABILITY_LIBRARY_LOADER
2704 }
2705 
LoadAceAbilityLibrary()2706 void MainThread::LoadAceAbilityLibrary()
2707 {
2708     void *AceAbilityLib = nullptr;
2709     const char *path = Ace::AceForwardCompatibility::GetAceLibName();
2710     AceAbilityLib = dlopen(path, RTLD_NOW | RTLD_LOCAL);
2711     if (AceAbilityLib == nullptr) {
2712         TAG_LOGE(AAFwkTag::APPKIT, "Fail to dlopen %{public}s, [%{public}s]", path, dlerror());
2713     } else {
2714         TAG_LOGD(AAFwkTag::APPKIT, "Success to dlopen %{public}s", path);
2715         handleAbilityLib_.emplace_back(AceAbilityLib);
2716     }
2717 }
2718 
LoadAppLibrary()2719 void MainThread::LoadAppLibrary()
2720 {
2721     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2722 #ifdef APPLICATION_LIBRARY_LOADER
2723     std::string appPath = applicationLibraryPath;
2724     TAG_LOGI(AAFwkTag::APPKIT, "calling dlopen. appPath=%{public}s", appPath.c_str());
2725     handleAppLib_ = dlopen(appPath.c_str(), RTLD_NOW | RTLD_GLOBAL);
2726     if (handleAppLib_ == nullptr) {
2727         TAG_LOGE(AAFwkTag::APPKIT, "Fail to dlopen %{public}s, [%{public}s]", appPath.c_str(), dlerror());
2728         exit(-1);
2729     }
2730 #endif  // APPLICATION_LIBRARY_LOADER
2731 }
2732 
LoadAppDetailAbilityLibrary(std::string &nativeLibraryPath)2733 void MainThread::LoadAppDetailAbilityLibrary(std::string &nativeLibraryPath)
2734 {
2735     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2736 #ifdef ABILITY_LIBRARY_LOADER
2737     TAG_LOGD(AAFwkTag::APPKIT, "try to scanDir %{public}s", nativeLibraryPath.c_str());
2738     std::vector<std::string> fileEntries;
2739     if (!ScanDir(nativeLibraryPath, fileEntries)) {
2740         TAG_LOGW(AAFwkTag::APPKIT, "scanDir %{public}s not exits", nativeLibraryPath.c_str());
2741     }
2742     if (fileEntries.empty()) {
2743         TAG_LOGW(AAFwkTag::APPKIT, "No ability library");
2744         return;
2745     }
2746     char resolvedPath[PATH_MAX] = {0};
2747     void *handleAbilityLib = nullptr;
2748     for (const auto& fileEntry : fileEntries) {
2749         if (fileEntry.empty() || fileEntry.size() >= PATH_MAX) {
2750             continue;
2751         }
2752         if (realpath(fileEntry.c_str(), resolvedPath) == nullptr) {
2753             TAG_LOGE(AAFwkTag::APPKIT, "Failed to get realpath, errno = %{public}d", errno);
2754             continue;
2755         }
2756 
2757         handleAbilityLib = dlopen(resolvedPath, RTLD_NOW | RTLD_GLOBAL);
2758         if (handleAbilityLib == nullptr) {
2759             TAG_LOGE(AAFwkTag::APPKIT, "Fail to dlopen %{public}s, [%{public}s]",
2760                 resolvedPath, dlerror());
2761             exit(-1);
2762         }
2763         TAG_LOGI(AAFwkTag::APPKIT, "Success to dlopen %{public}s", fileEntry.c_str());
2764         handleAbilityLib_.emplace_back(handleAbilityLib);
2765     }
2766 #endif // ABILITY_LIBRARY_LOADER
2767 }
2768 
ScanDir(const std::string &dirPath, std::vector<std::string> &files)2769 bool MainThread::ScanDir(const std::string &dirPath, std::vector<std::string> &files)
2770 {
2771     DIR *dirp = opendir(dirPath.c_str());
2772     if (dirp == nullptr) {
2773         TAG_LOGE(AAFwkTag::APPKIT, "MainThread::ScanDir open dir:%{public}s fail", dirPath.c_str());
2774         return false;
2775     }
2776     struct dirent *df = nullptr;
2777     for (;;) {
2778         df = readdir(dirp);
2779         if (df == nullptr) {
2780             break;
2781         }
2782 
2783         std::string currentName(df->d_name);
2784         if (currentName.compare(".") == 0 || currentName.compare("..") == 0) {
2785             continue;
2786         }
2787 
2788         if (CheckFileType(currentName, abilityLibraryType_)) {
2789             files.emplace_back(dirPath + pathSeparator_ + currentName);
2790         }
2791     }
2792 
2793     if (closedir(dirp) == -1) {
2794         TAG_LOGW(AAFwkTag::APPKIT, "close dir fail");
2795     }
2796     return true;
2797 }
2798 
2799 /**
2800  *
2801  * @brief Check the fileType.
2802  *
2803  * @param fileName The fileName of the lib.
2804  * @param extensionName The extensionName of the lib.
2805  *
2806  * @return if the FileType is legal, return true. else return false.
2807  *
2808  */
CheckFileType(const std::string &fileName, const std::string &extensionName)2809 bool MainThread::CheckFileType(const std::string &fileName, const std::string &extensionName)
2810 {
2811     TAG_LOGD(AAFwkTag::APPKIT, "path is %{public}s, support suffix is %{public}s",
2812         fileName.c_str(),
2813         extensionName.c_str());
2814 
2815     if (fileName.empty()) {
2816         TAG_LOGE(AAFwkTag::APPKIT, "the file name is empty");
2817         return false;
2818     }
2819 
2820     auto position = fileName.rfind('.');
2821     if (position == std::string::npos) {
2822         TAG_LOGW(AAFwkTag::APPKIT, "filename no extension name");
2823         return false;
2824     }
2825 
2826     std::string suffixStr = fileName.substr(position);
2827     return LowerStr(suffixStr) == extensionName;
2828 }
2829 
HandleScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName)2830 void MainThread::HandleScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName)
2831 {
2832     TAG_LOGD(AAFwkTag::APPKIT, "called");
2833     if (!application_) {
2834         TAG_LOGE(AAFwkTag::APPKIT, "application_ is nullptr");
2835         return;
2836     }
2837 
2838     std::string specifiedFlag;
2839     application_->ScheduleAcceptWant(want, moduleName, specifiedFlag);
2840 
2841     if (!appMgr_ || !applicationImpl_) {
2842         TAG_LOGE(AAFwkTag::APPKIT, "appMgr_ is nullptr");
2843         return;
2844     }
2845 
2846     appMgr_->ScheduleAcceptWantDone(applicationImpl_->GetRecordId(), want, specifiedFlag);
2847 }
2848 
ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName)2849 void MainThread::ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName)
2850 {
2851     TAG_LOGD(AAFwkTag::APPKIT, "start");
2852     wptr<MainThread> weak = this;
2853     auto task = [weak, want, moduleName]() {
2854         auto appThread = weak.promote();
2855         if (appThread == nullptr) {
2856             TAG_LOGE(AAFwkTag::APPKIT, "abilityThread is nullptr");
2857             return;
2858         }
2859         appThread->HandleScheduleAcceptWant(want, moduleName);
2860     };
2861     if (!mainHandler_->PostTask(task, "MainThread:AcceptWant")) {
2862         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
2863     }
2864 }
2865 
HandleScheduleNewProcessRequest(const AAFwk::Want &want, const std::string &moduleName)2866 void MainThread::HandleScheduleNewProcessRequest(const AAFwk::Want &want, const std::string &moduleName)
2867 {
2868     TAG_LOGD(AAFwkTag::APPKIT, "called");
2869     if (!application_) {
2870         TAG_LOGE(AAFwkTag::APPKIT, "application_ is nullptr");
2871         return;
2872     }
2873 
2874     std::string specifiedProcessFlag;
2875     application_->ScheduleNewProcessRequest(want, moduleName, specifiedProcessFlag);
2876 
2877     if (!appMgr_ || !applicationImpl_) {
2878         TAG_LOGE(AAFwkTag::APPKIT, "appMgr_ is nullptr");
2879         return;
2880     }
2881 
2882     appMgr_->ScheduleNewProcessRequestDone(applicationImpl_->GetRecordId(), want, specifiedProcessFlag);
2883 }
2884 
ScheduleNewProcessRequest(const AAFwk::Want &want, const std::string &moduleName)2885 void MainThread::ScheduleNewProcessRequest(const AAFwk::Want &want, const std::string &moduleName)
2886 {
2887     TAG_LOGD(AAFwkTag::APPKIT, "start");
2888     wptr<MainThread> weak = this;
2889     auto task = [weak, want, moduleName]() {
2890         auto appThread = weak.promote();
2891         if (appThread == nullptr) {
2892             TAG_LOGE(AAFwkTag::APPKIT, "abilityThread is nullptr");
2893             return;
2894         }
2895         appThread->HandleScheduleNewProcessRequest(want, moduleName);
2896     };
2897     if (!mainHandler_->PostTask(task, "MainThread:ScheduleNewProcessRequest")) {
2898         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
2899     }
2900 }
2901 
CheckMainThreadIsAlive()2902 void MainThread::CheckMainThreadIsAlive()
2903 {
2904     auto tmpWatchdog = watchdog_;
2905     if (tmpWatchdog == nullptr) {
2906         TAG_LOGE(AAFwkTag::APPKIT, "Watch dog is nullptr.");
2907         return;
2908     }
2909 
2910     tmpWatchdog->SetAppMainThreadState(true);
2911     tmpWatchdog->AllowReportEvent();
2912     tmpWatchdog = nullptr;
2913 }
2914 #endif  // ABILITY_LIBRARY_LOADER
2915 
ScheduleNotifyLoadRepairPatch(const std::string &bundleName, const sptr<IQuickFixCallback> &callback, const int32_t recordId)2916 int32_t MainThread::ScheduleNotifyLoadRepairPatch(const std::string &bundleName,
2917     const sptr<IQuickFixCallback> &callback, const int32_t recordId)
2918 {
2919     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2920     TAG_LOGD(AAFwkTag::APPKIT, "called");
2921     wptr<MainThread> weak = this;
2922     auto task = [weak, bundleName, callback, recordId]() {
2923         auto appThread = weak.promote();
2924         if (appThread == nullptr || appThread->application_ == nullptr || callback == nullptr) {
2925             TAG_LOGE(AAFwkTag::APPKIT, "ScheduleNotifyLoadRepairPatch, parameter is nullptr.");
2926             return;
2927         }
2928 
2929         bool ret = true;
2930         std::vector<std::pair<std::string, std::string>> hqfFilePair;
2931         if (appThread->GetHqfFileAndHapPath(bundleName, hqfFilePair)) {
2932             for (auto it = hqfFilePair.begin(); it != hqfFilePair.end(); it++) {
2933                 TAG_LOGI(AAFwkTag::APPKIT, "hqfFile: %{private}s, hapPath: %{private}s",
2934                     it->first.c_str(), it->second.c_str());
2935                 ret = appThread->application_->NotifyLoadRepairPatch(it->first, it->second);
2936             }
2937         } else {
2938             TAG_LOGD(AAFwkTag::APPKIT, "ScheduleNotifyLoadRepairPatch, There's no hqfFile need to load");
2939         }
2940 
2941         callback->OnLoadPatchDone(ret ? NO_ERROR : ERR_INVALID_OPERATION, recordId);
2942     };
2943     if (mainHandler_ == nullptr || !mainHandler_->PostTask(task, "MainThread:NotifyLoadRepairPatch")) {
2944         TAG_LOGE(AAFwkTag::APPKIT, "ScheduleNotifyLoadRepairPatch, Post task failed");
2945         return ERR_INVALID_VALUE;
2946     }
2947 
2948     return NO_ERROR;
2949 }
2950 
ScheduleNotifyHotReloadPage(const sptr<IQuickFixCallback> &callback, const int32_t recordId)2951 int32_t MainThread::ScheduleNotifyHotReloadPage(const sptr<IQuickFixCallback> &callback, const int32_t recordId)
2952 {
2953     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2954     TAG_LOGD(AAFwkTag::APPKIT, "called");
2955     wptr<MainThread> weak = this;
2956     auto task = [weak, callback, recordId]() {
2957         auto appThread = weak.promote();
2958         if (appThread == nullptr || appThread->application_ == nullptr || callback == nullptr) {
2959             TAG_LOGE(AAFwkTag::APPKIT, "parameter is nullptr");
2960             return;
2961         }
2962         auto ret = appThread->application_->NotifyHotReloadPage();
2963         callback->OnReloadPageDone(ret ? NO_ERROR : ERR_INVALID_OPERATION, recordId);
2964     };
2965     if (mainHandler_ == nullptr || !mainHandler_->PostTask(task, "MainThread:NotifyHotReloadPage")) {
2966         TAG_LOGE(AAFwkTag::APPKIT, "Post task failed");
2967         return ERR_INVALID_VALUE;
2968     }
2969 
2970     return NO_ERROR;
2971 }
2972 
GetHqfFileAndHapPath(const std::string &bundleName, std::vector<std::pair<std::string, std::string>> &fileMap)2973 bool MainThread::GetHqfFileAndHapPath(const std::string &bundleName,
2974     std::vector<std::pair<std::string, std::string>> &fileMap)
2975 {
2976     TAG_LOGD(AAFwkTag::APPKIT, "called");
2977     auto bundleMgrHelper = DelayedSingleton<BundleMgrHelper>::GetInstance();
2978     if (bundleMgrHelper == nullptr) {
2979         TAG_LOGE(AAFwkTag::APPKIT, "The bundleMgrHelper is nullptr");
2980         return false;
2981     }
2982 
2983     BundleInfo bundleInfo;
2984     if (bundleMgrHelper->GetBundleInfoForSelf(
2985         (static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) +
2986         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY) +
2987         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) +
2988         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE) +
2989         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) +
2990         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) +
2991         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_METADATA)), bundleInfo) != ERR_OK) {
2992         TAG_LOGE(AAFwkTag::APPKIT, "Get bundle info of %{public}s failed", bundleName.c_str());
2993         return false;
2994     }
2995 
2996     for (auto hapInfo : bundleInfo.hapModuleInfos) {
2997         if ((processInfo_ != nullptr) && (processInfo_->GetProcessName() == hapInfo.process) &&
2998             (!hapInfo.hqfInfo.hqfFilePath.empty())) {
2999             std::string resolvedHapPath(AbilityBase::GetLoadPath(hapInfo.hapPath));
3000             std::string resolvedHqfFile(AbilityBase::GetLoadPath(hapInfo.hqfInfo.hqfFilePath));
3001             TAG_LOGD(AAFwkTag::APPKIT, "bundleName: %{public}s, moduleName: %{public}s, processName: %{private}s, "
3002                 "hqf file: %{private}s, hap path: %{private}s", bundleName.c_str(), hapInfo.moduleName.c_str(),
3003                 hapInfo.process.c_str(), resolvedHqfFile.c_str(), resolvedHapPath.c_str());
3004             fileMap.push_back(std::pair<std::string, std::string>(resolvedHqfFile, resolvedHapPath));
3005         }
3006     }
3007 
3008     return true;
3009 }
3010 
ScheduleNotifyUnLoadRepairPatch(const std::string &bundleName, const sptr<IQuickFixCallback> &callback, const int32_t recordId)3011 int32_t MainThread::ScheduleNotifyUnLoadRepairPatch(const std::string &bundleName,
3012     const sptr<IQuickFixCallback> &callback, const int32_t recordId)
3013 {
3014     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3015     TAG_LOGD(AAFwkTag::APPKIT, "called");
3016     wptr<MainThread> weak = this;
3017     auto task = [weak, bundleName, callback, recordId]() {
3018         auto appThread = weak.promote();
3019         if (appThread == nullptr || appThread->application_ == nullptr || callback == nullptr) {
3020             TAG_LOGE(AAFwkTag::APPKIT, " parameter is nullptr");
3021             return;
3022         }
3023 
3024         bool ret = true;
3025         std::vector<std::pair<std::string, std::string>> hqfFilePair;
3026         if (appThread->GetHqfFileAndHapPath(bundleName, hqfFilePair)) {
3027             for (auto it = hqfFilePair.begin(); it != hqfFilePair.end(); it++) {
3028                 TAG_LOGI(AAFwkTag::APPKIT, "hqfFile: %{private}s", it->first.c_str());
3029                 ret = appThread->application_->NotifyUnLoadRepairPatch(it->first);
3030             }
3031         } else {
3032             TAG_LOGD(AAFwkTag::APPKIT, "ScheduleNotifyUnLoadRepairPatch, There's no hqfFile need to unload");
3033         }
3034 
3035         callback->OnUnloadPatchDone(ret ? NO_ERROR : ERR_INVALID_OPERATION, recordId);
3036     };
3037     if (mainHandler_ == nullptr || !mainHandler_->PostTask(task, "MainThread:NotifyUnLoadRepairPatch")) {
3038         TAG_LOGE(AAFwkTag::APPKIT, "ScheduleNotifyUnLoadRepairPatch, Post task failed");
3039         return ERR_INVALID_VALUE;
3040     }
3041 
3042     return NO_ERROR;
3043 }
3044 
ScheduleNotifyAppFault(const FaultData &faultData)3045 int32_t MainThread::ScheduleNotifyAppFault(const FaultData &faultData)
3046 {
3047     if (mainHandler_ == nullptr) {
3048         TAG_LOGE(AAFwkTag::APPKIT, "mainHandler is nullptr");
3049         return ERR_INVALID_VALUE;
3050     }
3051 
3052     if (faultData.faultType == FaultDataType::APP_FREEZE) {
3053         return AppExecFwk::AppfreezeInner::GetInstance()->AppfreezeHandle(faultData, false);
3054     }
3055 
3056     wptr<MainThread> weak = this;
3057     auto task = [weak, faultData] {
3058         auto appThread = weak.promote();
3059         if (appThread == nullptr) {
3060             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr, NotifyAppFault failed");
3061             return;
3062         }
3063         appThread->NotifyAppFault(faultData);
3064     };
3065     mainHandler_->PostTask(task, "MainThread:NotifyAppFault");
3066     return NO_ERROR;
3067 }
3068 
NotifyAppFault(const FaultData &faultData)3069 void MainThread::NotifyAppFault(const FaultData &faultData)
3070 {
3071     if (faultData.notifyApp) {
3072         ErrorObject faultErrorObj = {
3073             .name = faultData.errorObject.name,
3074             .message = faultData.errorObject.message,
3075             .stack = faultData.errorObject.stack
3076         };
3077         ApplicationDataManager::GetInstance().NotifyExceptionObject(faultErrorObj);
3078     }
3079 }
3080 
SetProcessExtensionType(const std::shared_ptr<AbilityLocalRecord> &abilityRecord)3081 void MainThread::SetProcessExtensionType(const std::shared_ptr<AbilityLocalRecord> &abilityRecord)
3082 {
3083     if (!extensionConfigMgr_) {
3084         TAG_LOGE(AAFwkTag::APPKIT, "extensionConfigMgr_ is null");
3085         return;
3086     }
3087     if (!abilityRecord) {
3088         TAG_LOGE(AAFwkTag::APPKIT, "abilityRecord is null");
3089         return;
3090     }
3091     if (!abilityRecord->GetAbilityInfo()) {
3092         TAG_LOGE(AAFwkTag::APPKIT, "abilityInfo is null");
3093         return;
3094     }
3095     TAG_LOGD(AAFwkTag::APPKIT, "type = %{public}d",
3096         static_cast<int32_t>(abilityRecord->GetAbilityInfo()->extensionAbilityType));
3097     extensionConfigMgr_->SetProcessExtensionType(
3098         static_cast<int32_t>(abilityRecord->GetAbilityInfo()->extensionAbilityType));
3099 }
3100 
AddExtensionBlockItem(const std::string &extensionName, int32_t type)3101 void MainThread::AddExtensionBlockItem(const std::string &extensionName, int32_t type)
3102 {
3103     if (!extensionConfigMgr_) {
3104         TAG_LOGE(AAFwkTag::APPKIT, "extensionConfigMgr_ is null");
3105         return;
3106     }
3107     extensionConfigMgr_->AddBlockListItem(extensionName, type);
3108 }
3109 
UpdateRuntimeModuleChecker(const std::unique_ptr<AbilityRuntime::Runtime> &runtime)3110 void MainThread::UpdateRuntimeModuleChecker(const std::unique_ptr<AbilityRuntime::Runtime> &runtime)
3111 {
3112     if (!extensionConfigMgr_) {
3113         TAG_LOGE(AAFwkTag::APPKIT, "extensionConfigMgr_ is null");
3114         return;
3115     }
3116     extensionConfigMgr_->UpdateRuntimeModuleChecker(runtime);
3117 }
3118 
GetOverlayModuleInfos(const std::string &bundleName, const std::string &moduleName, std::vector<OverlayModuleInfo> &overlayModuleInfos) const3119 int MainThread::GetOverlayModuleInfos(const std::string &bundleName, const std::string &moduleName,
3120     std::vector<OverlayModuleInfo> &overlayModuleInfos) const
3121 {
3122     auto bundleMgrHelper = DelayedSingleton<BundleMgrHelper>::GetInstance();
3123     if (bundleMgrHelper == nullptr) {
3124         TAG_LOGE(AAFwkTag::APPKIT, "The bundleMgrHelper is nullptr");
3125         return ERR_INVALID_VALUE;
3126     }
3127 
3128     auto overlayMgrProxy = bundleMgrHelper->GetOverlayManagerProxy();
3129     if (overlayMgrProxy == nullptr) {
3130         TAG_LOGE(AAFwkTag::APPKIT, "The overlayMgrProxy is nullptr");
3131         return ERR_INVALID_VALUE;
3132     }
3133 
3134     auto ret = overlayMgrProxy->GetTargetOverlayModuleInfo(moduleName, overlayModuleInfos);
3135     if (ret != ERR_OK) {
3136         TAG_LOGE(AAFwkTag::APPKIT, "failed");
3137         return ret;
3138     }
3139     std::sort(overlayModuleInfos.begin(), overlayModuleInfos.end(),
3140         [](const OverlayModuleInfo& lhs, const OverlayModuleInfo& rhs) -> bool {
3141         return lhs.priority > rhs.priority;
3142     });
3143     TAG_LOGD(AAFwkTag::APPKIT, "the size of overlay is: %{public}zu", overlayModuleInfos.size());
3144     return ERR_OK;
3145 }
3146 
GetAddOverlayPaths(const std::vector<OverlayModuleInfo> &overlayModuleInfos)3147 std::vector<std::string> MainThread::GetAddOverlayPaths(const std::vector<OverlayModuleInfo> &overlayModuleInfos)
3148 {
3149     std::vector<std::string> addPaths;
3150     for (auto &it : overlayModuleInfos) {
3151         auto iter = std::find_if(
3152             overlayModuleInfos_.begin(), overlayModuleInfos_.end(), [it](OverlayModuleInfo item) {
3153                 return it.moduleName == item.moduleName;
3154             });
3155         if ((iter != overlayModuleInfos_.end()) && (it.state == AppExecFwk::OverlayState::OVERLAY_ENABLE)) {
3156             iter->state = it.state;
3157             ChangeToLocalPath(iter->bundleName, iter->hapPath, iter->hapPath);
3158             TAG_LOGD(AAFwkTag::APPKIT, "add path:%{public}s", iter->hapPath.c_str());
3159             addPaths.emplace_back(iter->hapPath);
3160         }
3161     }
3162     return addPaths;
3163 }
3164 
GetRemoveOverlayPaths(const std::vector<OverlayModuleInfo> &overlayModuleInfos)3165 std::vector<std::string> MainThread::GetRemoveOverlayPaths(const std::vector<OverlayModuleInfo> &overlayModuleInfos)
3166 {
3167     std::vector<std::string> removePaths;
3168     for (auto &it : overlayModuleInfos) {
3169         auto iter = std::find_if(
3170             overlayModuleInfos_.begin(), overlayModuleInfos_.end(), [it](OverlayModuleInfo item) {
3171                 return it.moduleName == item.moduleName;
3172             });
3173         if ((iter != overlayModuleInfos_.end()) && (it.state != AppExecFwk::OverlayState::OVERLAY_ENABLE)) {
3174             iter->state = it.state;
3175             ChangeToLocalPath(iter->bundleName, iter->hapPath, iter->hapPath);
3176             TAG_LOGD(AAFwkTag::APPKIT, "remove path:%{public}s", iter->hapPath.c_str());
3177             removePaths.emplace_back(iter->hapPath);
3178         }
3179     }
3180 
3181     return removePaths;
3182 }
3183 
ScheduleChangeAppGcState(int32_t state)3184 int32_t MainThread::ScheduleChangeAppGcState(int32_t state)
3185 {
3186     TAG_LOGD(AAFwkTag::APPKIT, "called, state is %{public}d", state);
3187     if (mainHandler_ == nullptr) {
3188         TAG_LOGE(AAFwkTag::APPKIT, "mainHandler is nullptr");
3189         return ERR_INVALID_VALUE;
3190     }
3191 
3192     wptr<MainThread> weak = this;
3193     auto task = [weak, state] {
3194         auto appThread = weak.promote();
3195         if (appThread == nullptr) {
3196             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr, ChangeAppGcState failed.");
3197             return;
3198         }
3199         appThread->ChangeAppGcState(state);
3200     };
3201 
3202     if (state == START_HIGH_SENSITIVE || state == EXIT_HIGH_SENSITIVE) {
3203         ChangeAppGcState(state);
3204     } else {
3205         mainHandler_->PostTask(task, "MainThread:ChangeAppGcState");
3206     }
3207     return NO_ERROR;
3208 }
3209 
ChangeAppGcState(int32_t state)3210 int32_t MainThread::ChangeAppGcState(int32_t state)
3211 {
3212     TAG_LOGD(AAFwkTag::APPKIT, "called");
3213     if (application_ == nullptr) {
3214         TAG_LOGE(AAFwkTag::APPKIT, "application_ is nullptr");
3215         return ERR_INVALID_VALUE;
3216     }
3217     auto &runtime = application_->GetRuntime();
3218     if (runtime == nullptr) {
3219         TAG_LOGE(AAFwkTag::APPKIT, "runtime is nullptr");
3220         return ERR_INVALID_VALUE;
3221     }
3222     if (runtime->GetLanguage() == AbilityRuntime::Runtime::Language::CJ) {
3223         return NO_ERROR;
3224     }
3225     auto& nativeEngine = (static_cast<AbilityRuntime::JsRuntime&>(*runtime)).GetNativeEngine();
3226     nativeEngine.NotifyForceExpandState(state);
3227     return NO_ERROR;
3228 }
3229 
AttachAppDebug()3230 void MainThread::AttachAppDebug()
3231 {
3232     TAG_LOGD(AAFwkTag::APPKIT, "called");
3233     SetAppDebug(AbilityRuntime::AppFreezeState::AppFreezeFlag::ATTACH_DEBUG_MODE, true);
3234 }
3235 
DetachAppDebug()3236 void MainThread::DetachAppDebug()
3237 {
3238     TAG_LOGD(AAFwkTag::APPKIT, "called");
3239     SetAppDebug(AbilityRuntime::AppFreezeState::AppFreezeFlag::ATTACH_DEBUG_MODE, false);
3240 }
3241 
NotifyDeviceDisConnect()3242 bool MainThread::NotifyDeviceDisConnect()
3243 {
3244     TAG_LOGD(AAFwkTag::APPKIT, "called");
3245     if (appMgr_ == nullptr) {
3246         TAG_LOGE(AAFwkTag::APPKIT, "appMgr is nullptr");
3247         return false;
3248     }
3249     bool isLastProcess = appMgr_->IsFinalAppProcess();
3250     ScheduleTerminateApplication(isLastProcess);
3251     return true;
3252 }
3253 
AssertFaultPauseMainThreadDetection()3254 void MainThread::AssertFaultPauseMainThreadDetection()
3255 {
3256     TAG_LOGD(AAFwkTag::APPKIT, "called");
3257     SetAppDebug(AbilityRuntime::AppFreezeState::AppFreezeFlag::ASSERT_DEBUG_MODE, true);
3258     if (appMgr_ == nullptr) {
3259         TAG_LOGE(AAFwkTag::APPKIT, "appMgr is nullptr");
3260         return;
3261     }
3262     appMgr_->SetAppAssertionPauseState(true);
3263 }
3264 
AssertFaultResumeMainThreadDetection()3265 void MainThread::AssertFaultResumeMainThreadDetection()
3266 {
3267     TAG_LOGD(AAFwkTag::APPKIT, "called");
3268     SetAppDebug(AbilityRuntime::AppFreezeState::AppFreezeFlag::ASSERT_DEBUG_MODE, false);
3269     if (appMgr_ == nullptr) {
3270         TAG_LOGE(AAFwkTag::APPKIT, "appMgr is nullptr");
3271         return;
3272     }
3273     appMgr_->SetAppAssertionPauseState(false);
3274 }
3275 
HandleInitAssertFaultTask(bool isDebugModule, bool isDebugApp)3276 void MainThread::HandleInitAssertFaultTask(bool isDebugModule, bool isDebugApp)
3277 {
3278     if (!isDeveloperMode_) {
3279         TAG_LOGE(AAFwkTag::APPKIT, "Developer Mode is false");
3280         return;
3281     }
3282     if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
3283         TAG_LOGD(AAFwkTag::APPKIT, "Unsupport assert fault dialog");
3284         return;
3285     }
3286     if (!isDebugApp) {
3287         TAG_LOGE(AAFwkTag::APPKIT, "Non-debug version application");
3288         return;
3289     }
3290     auto assertThread = DelayedSingleton<AbilityRuntime::AssertFaultTaskThread>::GetInstance();
3291     if (assertThread == nullptr) {
3292         TAG_LOGE(AAFwkTag::APPKIT, "Get assert thread instance is nullptr");
3293         return;
3294     }
3295     assertThread->InitAssertFaultTask(this, isDebugModule);
3296     assertThread_ = assertThread;
3297 }
3298 
SetAppDebug(uint32_t modeFlag, bool isDebug)3299 void MainThread::SetAppDebug(uint32_t modeFlag, bool isDebug)
3300 {
3301     TAG_LOGD(AAFwkTag::APPKIT, "called");
3302     auto state = DelayedSingleton<AbilityRuntime::AppFreezeState>::GetInstance();
3303     if (state == nullptr) {
3304         TAG_LOGE(AAFwkTag::APPKIT, "Get app freeze state instance is nullptr");
3305         return;
3306     }
3307 
3308     if (!isDebug) {
3309         TAG_LOGD(AAFwkTag::APPKIT, "Call Cancel modeFlag is %{public}u", modeFlag);
3310         state->CancelAppFreezeState(modeFlag);
3311         return;
3312     }
3313 
3314     TAG_LOGD(AAFwkTag::APPKIT, "Call Set modeFlag is %{public}u", modeFlag);
3315     state->SetAppFreezeState(modeFlag);
3316 }
3317 
HandleCancelAssertFaultTask()3318 void MainThread::HandleCancelAssertFaultTask()
3319 {
3320     auto assertThread = assertThread_.lock();
3321     if (assertThread == nullptr) {
3322         TAG_LOGE(AAFwkTag::APPKIT, "Get assert thread instance is nullptr");
3323         return;
3324     }
3325     assertThread->Stop();
3326 }
3327 
ScheduleDumpIpcStart(std::string& result)3328 int32_t MainThread::ScheduleDumpIpcStart(std::string& result)
3329 {
3330     TAG_LOGD(AAFwkTag::APPKIT, "MainThread::ScheduleDumpIpcStart::pid:%{public}d", getprocpid());
3331     DumpIpcHelper::DumpIpcStart(result);
3332     return ERR_OK;
3333 }
3334 
ScheduleDumpIpcStop(std::string& result)3335 int32_t MainThread::ScheduleDumpIpcStop(std::string& result)
3336 {
3337     TAG_LOGD(AAFwkTag::APPKIT, "pid:%{public}d", getprocpid());
3338     DumpIpcHelper::DumpIpcStop(result);
3339     return ERR_OK;
3340 }
3341 
ScheduleDumpIpcStat(std::string& result)3342 int32_t MainThread::ScheduleDumpIpcStat(std::string& result)
3343 {
3344     TAG_LOGD(AAFwkTag::APPKIT, "pid:%{public}d", getprocpid());
3345     DumpIpcHelper::DumpIpcStat(result);
3346     return ERR_OK;
3347 }
3348 
ScheduleDumpFfrt(std::string& result)3349 int32_t MainThread::ScheduleDumpFfrt(std::string& result)
3350 {
3351     TAG_LOGD(AAFwkTag::APPKIT, "pid:%{public}d", getprocpid());
3352     return DumpFfrtHelper::DumpFfrt(result);
3353 }
3354 
3355 /**
3356  *
3357  * @brief Notify application to prepare for process caching.
3358  *
3359  */
ScheduleCacheProcess()3360 void MainThread::ScheduleCacheProcess()
3361 {
3362     TAG_LOGD(AAFwkTag::APPKIT, "ScheduleCacheProcess");
3363     wptr<MainThread> weak = this;
3364     auto task = [weak]() {
3365         auto appThread = weak.promote();
3366         if (appThread == nullptr) {
3367             TAG_LOGE(AAFwkTag::APPKIT, "appThread is nullptr");
3368             return;
3369         }
3370         appThread->HandleCacheProcess();
3371     };
3372     if (mainHandler_ == nullptr) {
3373         TAG_LOGE(AAFwkTag::APPKIT, "handler nullptr");
3374         return;
3375     }
3376     if (!mainHandler_->PostTask(task, "MainThread:ScheduleCacheProcess")) {
3377         TAG_LOGE(AAFwkTag::APPKIT, "PostTask task failed");
3378     }
3379 }
3380 
ParseAppConfigurationParams(const std::string configuration, Configuration &appConfig)3381 void MainThread::ParseAppConfigurationParams(const std::string configuration, Configuration &appConfig)
3382 {
3383     TAG_LOGD(AAFwkTag::APPKIT, "start");
3384     appConfig.AddItem(AAFwk::GlobalConfigurationKey::APP_FONT_SIZE_SCALE, DEFAULT_APP_FONT_SIZE_SCALE);
3385     if (configuration.empty()) {
3386         TAG_LOGE(AAFwkTag::ABILITYMGR, "empty config");
3387         return;
3388     }
3389     nlohmann::json configurationJson = nlohmann::json::parse(configuration, nullptr, false);
3390     if (configurationJson.is_discarded()) {
3391         TAG_LOGE(AAFwkTag::ABILITYMGR, "discarded error");
3392         return;
3393     }
3394     if (!configurationJson.contains(JSON_KEY_APP_CONFIGURATION)) {
3395         TAG_LOGE(AAFwkTag::ABILITYMGR, "app config not exist");
3396         return;
3397     }
3398     nlohmann::json jsonObject = configurationJson.at(JSON_KEY_APP_CONFIGURATION).get<nlohmann::json>();
3399     if (jsonObject.empty()) {
3400         TAG_LOGE(AAFwkTag::ABILITYMGR, "null app config");
3401         return;
3402     }
3403     if (jsonObject.contains(JSON_KEY_APP_FONT_SIZE_SCALE)
3404         && jsonObject[JSON_KEY_APP_FONT_SIZE_SCALE].is_string()) {
3405         std::string configFontSizeScal = jsonObject.at(JSON_KEY_APP_FONT_SIZE_SCALE).get<std::string>();
3406         appConfig.AddItem(AAFwk::GlobalConfigurationKey::APP_FONT_SIZE_SCALE,
3407             jsonObject.at(JSON_KEY_APP_FONT_SIZE_SCALE).get<std::string>());
3408     }
3409     if (jsonObject.contains(JSON_KEY_APP_FONT_MAX_SCALE)
3410         && jsonObject[JSON_KEY_APP_FONT_MAX_SCALE].is_string()) {
3411         std::string appFontMaxScale = jsonObject.at(JSON_KEY_APP_FONT_MAX_SCALE).get<std::string>();
3412         const std::regex INTEGER_REGEX("^[-+]?([0-9]+)([.]([0-9]+))?$");
3413         if (std::regex_match(appFontMaxScale, INTEGER_REGEX)) {
3414             appConfig.AddItem(AAFwk::GlobalConfigurationKey::APP_FONT_MAX_SCALE, appFontMaxScale);
3415         }
3416     }
3417     TAG_LOGD(AAFwkTag::APPKIT, "configuration_: %{public}s", appConfig.GetName().c_str());
3418 }
3419 
3420 /**
3421  *
3422  * @brief Notify application to prepare for process caching.
3423  *
3424  */
HandleCacheProcess()3425 void MainThread::HandleCacheProcess()
3426 {
3427     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3428     TAG_LOGD(AAFwkTag::APPKIT, "start");
3429 
3430     // force gc
3431     if (application_ != nullptr) {
3432         auto &runtime = application_->GetRuntime();
3433         if (runtime == nullptr) {
3434             TAG_LOGE(AAFwkTag::APPKIT, "null runtime");
3435             return;
3436         }
3437         runtime->ForceFullGC();
3438     }
3439 }
3440 }  // namespace AppExecFwk
3441 }  // namespace OHOS
3442