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