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