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