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