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