• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 <new>
19 #include <regex>
20 #include <unistd.h>
21 
22 #include "ability_constants.h"
23 #include "ability_delegator.h"
24 #include "ability_delegator_registry.h"
25 #include "ability_loader.h"
26 #include "ability_thread.h"
27 #include "ability_util.h"
28 #include "app_loader.h"
29 #include "app_recovery.h"
30 #include "application_data_manager.h"
31 #include "application_env_impl.h"
32 #include "hitrace_meter.h"
33 #include "configuration_convertor.h"
34 #include "context_deal.h"
35 #include "context_impl.h"
36 #include "extension_module_loader.h"
37 #include "file_path_utils.h"
38 #include "hilog_wrapper.h"
39 #ifdef SUPPORT_GRAPHICS
40 #include "form_extension.h"
41 #include "locale_config.h"
42 #endif
43 #include "if_system_ability_manager.h"
44 #include "iservice_registry.h"
45 #include "js_runtime.h"
46 #include "mix_stack_dumper.h"
47 #include "ohos_application.h"
48 #include "parameters.h"
49 #include "resource_manager.h"
50 #include "runtime.h"
51 #include "service_extension.h"
52 #include "static_subscriber_extension.h"
53 #include "sys_mgr_client.h"
54 #include "system_ability_definition.h"
55 #include "task_handler_client.h"
56 #include "hisysevent.h"
57 #include "js_runtime_utils.h"
58 #include "context/application_context.h"
59 
60 #if defined(NWEB)
61 #include <thread>
62 #include "app_mgr_client.h"
63 #include "nweb_pre_dns_adapter.h"
64 #include "nweb_helper.h"
65 #endif
66 
67 #if defined(ABILITY_LIBRARY_LOADER) || defined(APPLICATION_LIBRARY_LOADER)
68 #include <dirent.h>
69 #include <dlfcn.h>
70 #endif
71 
72 namespace OHOS {
73 namespace AppExecFwk {
74 using namespace OHOS::AbilityRuntime::Constants;
75 std::shared_ptr<OHOSApplication> MainThread::applicationForDump_ = nullptr;
76 std::shared_ptr<EventHandler> MainThread::signalHandler_ = nullptr;
77 std::shared_ptr<MainThread::MainHandler> MainThread::mainHandler_ = nullptr;
78 static std::shared_ptr<MixStackDumper> mixStackDumper_ = nullptr;
79 namespace {
80 #ifdef APP_USE_ARM64
81 constexpr char FORM_RENDER_LIB_PATH[] = "/system/lib64/libformrender.z.so";
82 #else
83 constexpr char FORM_RENDER_LIB_PATH[] = "/system/lib/libformrender.z.so";
84 #endif
85 
86 constexpr int32_t DELIVERY_TIME = 200;
87 constexpr int32_t DISTRIBUTE_TIME = 100;
88 constexpr int32_t UNSPECIFIED_USERID = -2;
89 constexpr int SIGNAL_JS_HEAP = 39;
90 constexpr int SIGNAL_JS_HEAP_PRIV = 40;
91 
92 constexpr char EVENT_KEY_PACKAGE_NAME[] = "PACKAGE_NAME";
93 constexpr char EVENT_KEY_VERSION[] = "VERSION";
94 constexpr char EVENT_KEY_TYPE[] = "TYPE";
95 constexpr char EVENT_KEY_HAPPEN_TIME[] = "HAPPEN_TIME";
96 constexpr char EVENT_KEY_REASON[] = "REASON";
97 constexpr char EVENT_KEY_JSVM[] = "JSVM";
98 constexpr char EVENT_KEY_SUMMARY[] = "SUMMARY";
99 
100 const int32_t JSCRASH_TYPE = 3;
101 const std::string JSVM_TYPE = "ARK";
102 const std::string SIGNAL_HANDLER = "SignalHandler";
103 constexpr char EXTENSION_PARAMS_TYPE[] = "type";
104 constexpr char EXTENSION_PARAMS_NAME[] = "name";
105 
106 constexpr uint32_t CHECK_MAIN_THREAD_IS_ALIVE = 1;
107 
SetNativeLibPath(const BundleInfo & bundleInfo,AbilityRuntime::Runtime::Options & options)108 void SetNativeLibPath(const BundleInfo &bundleInfo, AbilityRuntime::Runtime::Options &options)
109 {
110     std::string patchNativeLibraryPath = bundleInfo.applicationInfo.appQuickFix.deployedAppqfInfo.nativeLibraryPath;
111     if (!patchNativeLibraryPath.empty()) {
112         // libraries in patch lib path has a higher priority when loading.
113         std::string patchLibPath = LOCAL_CODE_PATH;
114         patchLibPath += (patchLibPath.back() == '/') ? patchNativeLibraryPath : "/" + patchNativeLibraryPath;
115         HILOG_INFO("napi patch lib path = %{private}s", patchLibPath.c_str());
116         options.appLibPaths["default"].emplace_back(patchLibPath);
117     }
118 
119     std::string nativeLibraryPath = bundleInfo.applicationInfo.nativeLibraryPath;
120     if (!nativeLibraryPath.empty()) {
121         if (nativeLibraryPath.back() == '/') {
122             nativeLibraryPath.pop_back();
123         }
124         std::string libPath = LOCAL_CODE_PATH;
125         libPath += (libPath.back() == '/') ? nativeLibraryPath : "/" + nativeLibraryPath;
126         HILOG_INFO("napi lib path = %{private}s", libPath.c_str());
127         options.appLibPaths["default"].emplace_back(libPath);
128     }
129 
130     for (auto &hapInfo : bundleInfo.hapModuleInfos) {
131         HILOG_DEBUG("name: %{public}s, isLibIsolated: %{public}d, nativeLibraryPath: %{public}s",
132             hapInfo.name.c_str(), hapInfo.isLibIsolated, hapInfo.nativeLibraryPath.c_str());
133         if (!hapInfo.isLibIsolated) {
134             continue;
135         }
136         std::string appLibPathKey = hapInfo.bundleName + "/" + hapInfo.moduleName;
137 
138         // libraries in patch lib path has a higher priority when loading.
139         std::string patchNativeLibraryPath = hapInfo.hqfInfo.nativeLibraryPath;
140         if (!patchNativeLibraryPath.empty()) {
141             std::string patchLibPath = LOCAL_CODE_PATH;
142             patchLibPath += (patchLibPath.back() == '/') ? patchNativeLibraryPath : "/" + patchNativeLibraryPath;
143             HILOG_INFO("name: %{public}s, patch lib path = %{private}s", hapInfo.name.c_str(), patchLibPath.c_str());
144             options.appLibPaths[appLibPathKey].emplace_back(patchLibPath);
145         }
146 
147         std::string libPath = LOCAL_CODE_PATH;
148         libPath += (libPath.back() == '/') ? hapInfo.nativeLibraryPath : "/" + hapInfo.nativeLibraryPath;
149         options.appLibPaths[appLibPathKey].emplace_back(libPath);
150     }
151 }
152 } // namespace
153 
154 #define ACEABILITY_LIBRARY_LOADER
155 #ifdef ABILITY_LIBRARY_LOADER
156     const std::string acelibdir("libace.z.so");
157 #endif
158 
159 /**
160  *
161  * @brief Notify the AppMgrDeathRecipient that the remote is dead.
162  *
163  * @param remote The remote which is dead.
164  */
OnRemoteDied(const wptr<IRemoteObject> & remote)165 void AppMgrDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
166 {
167     HILOG_ERROR("MainThread::AppMgrDeathRecipient remote died receive");
168 }
169 
MainThread()170 MainThread::MainThread()
171 {
172 #ifdef ABILITY_LIBRARY_LOADER
173     fileEntries_.clear();
174     nativeFileEntries_.clear();
175     handleAbilityLib_.clear();
176 #endif  // ABILITY_LIBRARY_LOADER
177 }
178 
~MainThread()179 MainThread::~MainThread()
180 {
181     if (watchdog_ != nullptr && !watchdog_->IsStopWatchdog()) {
182         watchdog_->Stop();
183         watchdog_ = nullptr;
184     }
185 #ifdef ABILITY_LIBRARY_LOADER
186     CloseAbilityLibrary();
187 #endif  // ABILITY_LIBRARY_LOADER
188 }
189 
190 /**
191  *
192  * @brief Get the current MainThreadState.
193  *
194  * @return Returns the current MainThreadState.
195  */
GetMainThreadState() const196 MainThreadState MainThread::GetMainThreadState() const
197 {
198     return mainThreadState_;
199 }
200 
201 /**
202  *
203  * @brief Set the runner state of mainthread.
204  *
205  * @param runnerStart whether the runner is started.
206  */
SetRunnerStarted(bool runnerStart)207 void MainThread::SetRunnerStarted(bool runnerStart)
208 {
209     isRunnerStarted_ = runnerStart;
210 }
211 
212 /**
213  *
214  * @brief Get the runner state of mainthread.
215  *
216  * @return Returns the runner state of mainthread.
217  */
GetRunnerStarted() const218 bool MainThread::GetRunnerStarted() const
219 {
220     return isRunnerStarted_;
221 }
222 
223 /**
224  *
225  * @brief Get the newThreadId.
226  *
227  * @return Returns the newThreadId.
228  */
GetNewThreadId()229 int MainThread::GetNewThreadId()
230 {
231     return newThreadId_++;
232 }
233 
234 /**
235  *
236  * @brief Get the application.
237  *
238  * @return Returns the application.
239  */
GetApplication() const240 std::shared_ptr<OHOSApplication> MainThread::GetApplication() const
241 {
242     return application_;
243 }
244 
245 /**
246  *
247  * @brief Get the applicationInfo.
248  *
249  * @return Returns the applicationInfo.
250  */
GetApplicationInfo() const251 std::shared_ptr<ApplicationInfo> MainThread::GetApplicationInfo() const
252 {
253     return applicationInfo_;
254 }
255 
256 /**
257  *
258  * @brief Get the applicationImpl.
259  *
260  * @return Returns the applicationImpl.
261  */
GetApplicationImpl()262 std::shared_ptr<ApplicationImpl> MainThread::GetApplicationImpl()
263 {
264     return applicationImpl_;
265 }
266 
267 /**
268  *
269  * @brief Connect the mainthread to the AppMgr.
270  *
271  */
ConnectToAppMgr()272 bool MainThread::ConnectToAppMgr()
273 {
274     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
275     HILOG_DEBUG("MainThread ConnectToAppMgr start.");
276     auto object = OHOS::DelayedSingleton<SysMrgClient>::GetInstance()->GetSystemAbility(APP_MGR_SERVICE_ID);
277     if (object == nullptr) {
278         HILOG_ERROR("failed to get app manager service");
279         return false;
280     }
281     deathRecipient_ = new (std::nothrow) AppMgrDeathRecipient();
282     if (deathRecipient_ == nullptr) {
283         HILOG_ERROR("failed to new AppMgrDeathRecipient");
284         return false;
285     }
286 
287     if (!object->AddDeathRecipient(deathRecipient_)) {
288         HILOG_ERROR("failed to AddDeathRecipient");
289         return false;
290     }
291 
292     appMgr_ = iface_cast<IAppMgr>(object);
293     if (appMgr_ == nullptr) {
294         HILOG_ERROR("failed to iface_cast object to appMgr_");
295         return false;
296     }
297     appMgr_->AttachApplication(this);
298     HILOG_DEBUG("MainThread::connectToAppMgr end");
299     return true;
300 }
301 
302 /**
303  *
304  * @brief Attach the mainthread to the AppMgr.
305  *
306  */
Attach()307 void MainThread::Attach()
308 {
309     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
310     HILOG_DEBUG("MainThread attach called.");
311     if (!ConnectToAppMgr()) {
312         HILOG_ERROR("attachApplication failed");
313         return;
314     }
315     mainThreadState_ = MainThreadState::ATTACH;
316     HILOG_DEBUG("MainThread::attach end");
317 }
318 
319 /**
320  *
321  * @brief remove the deathRecipient from appMgr.
322  *
323  */
RemoveAppMgrDeathRecipient()324 void MainThread::RemoveAppMgrDeathRecipient()
325 {
326     HILOG_DEBUG("MainThread::RemoveAppMgrDeathRecipient called begin");
327     if (appMgr_ == nullptr) {
328         HILOG_ERROR("MainThread::RemoveAppMgrDeathRecipient failed");
329         return;
330     }
331 
332     sptr<IRemoteObject> object = appMgr_->AsObject();
333     if (object != nullptr) {
334         object->RemoveDeathRecipient(deathRecipient_);
335     } else {
336         HILOG_ERROR("appMgr_->AsObject() failed");
337     }
338     HILOG_DEBUG("end");
339 }
340 
341 /**
342  *
343  * @brief Get the eventHandler of mainthread.
344  *
345  * @return Returns the eventHandler of mainthread.
346  */
GetMainHandler() const347 std::shared_ptr<EventHandler> MainThread::GetMainHandler() const
348 {
349     return mainHandler_;
350 }
351 
352 /**
353  *
354  * @brief Schedule the foreground lifecycle of application.
355  *
356  */
ScheduleForegroundApplication()357 void MainThread::ScheduleForegroundApplication()
358 {
359     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
360     HILOG_DEBUG("Schedule the application to foreground begin.");
361     wptr<MainThread> weak = this;
362     auto task = [weak]() {
363         auto appThread = weak.promote();
364         if (appThread == nullptr) {
365             HILOG_ERROR("appThread is nullptr, HandleForegroundApplication failed.");
366             return;
367         }
368         appThread->HandleForegroundApplication();
369     };
370     if (!mainHandler_->PostTask(task)) {
371         HILOG_ERROR("PostTask task failed");
372     }
373     watchdog_->SetBackgroundStatus(false);
374     HILOG_DEBUG("Schedule the application to foreground end.");
375 }
376 
377 /**
378  *
379  * @brief Schedule the background lifecycle of application.
380  *
381  */
ScheduleBackgroundApplication()382 void MainThread::ScheduleBackgroundApplication()
383 {
384     HILOG_DEBUG("MainThread::scheduleBackgroundApplication called begin");
385     wptr<MainThread> weak = this;
386     auto task = [weak]() {
387         auto appThread = weak.promote();
388         if (appThread == nullptr) {
389             HILOG_ERROR("appThread is nullptr, HandleBackgroundApplication failed.");
390             return;
391         }
392         appThread->HandleBackgroundApplication();
393     };
394     if (!mainHandler_->PostTask(task)) {
395         HILOG_ERROR("MainThread::ScheduleBackgroundApplication PostTask task failed");
396     }
397     watchdog_->SetBackgroundStatus(true);
398     HILOG_DEBUG("MainThread::scheduleBackgroundApplication called end.");
399 }
400 
401 /**
402  *
403  * @brief Schedule the terminate lifecycle of application.
404  *
405  */
ScheduleTerminateApplication()406 void MainThread::ScheduleTerminateApplication()
407 {
408     HILOG_DEBUG("MainThread::scheduleTerminateApplication called begin");
409     wptr<MainThread> weak = this;
410     auto task = [weak]() {
411         auto appThread = weak.promote();
412         if (appThread == nullptr) {
413             HILOG_ERROR("appThread is nullptr, HandleTerminateApplication failed.");
414             return;
415         }
416         appThread->HandleTerminateApplication();
417     };
418     if (!mainHandler_->PostTask(task)) {
419         HILOG_ERROR("MainThread::ScheduleTerminateApplication PostTask task failed");
420     }
421     HILOG_DEBUG("MainThread::scheduleTerminateApplication called.");
422 }
423 
424 /**
425  *
426  * @brief Shrink the memory which used by application.
427  *
428  * @param level Indicates the memory trim level, which shows the current memory usage status.
429  */
ScheduleShrinkMemory(const int level)430 void MainThread::ScheduleShrinkMemory(const int level)
431 {
432     HILOG_DEBUG("scheduleShrinkMemory level: %{public}d", level);
433     wptr<MainThread> weak = this;
434     auto task = [weak, level]() {
435         auto appThread = weak.promote();
436         if (appThread == nullptr) {
437             HILOG_ERROR("appThread is nullptr, HandleShrinkMemory failed.");
438             return;
439         }
440         appThread->HandleShrinkMemory(level);
441     };
442     if (!mainHandler_->PostTask(task)) {
443         HILOG_ERROR("MainThread::ScheduleShrinkMemory PostTask task failed");
444     }
445     HILOG_DEBUG("scheduleShrinkMemory level: %{public}d end.", level);
446 }
447 
448 /**
449  *
450  * @brief Notify the memory level.
451  *
452  * @param level Indicates the memory trim level, which shows the current memory usage status.
453  */
ScheduleMemoryLevel(const int level)454 void MainThread::ScheduleMemoryLevel(const int level)
455 {
456     HILOG_DEBUG("ScheduleMemoryLevel level: %{public}d", level);
457     wptr<MainThread> weak = this;
458     auto task = [weak, level]() {
459         auto appThread = weak.promote();
460         if (appThread == nullptr) {
461             HILOG_ERROR("appThread is nullptr, HandleMemoryLevel failed.");
462             return;
463         }
464         appThread->HandleMemoryLevel(level);
465     };
466     if (!mainHandler_->PostTask(task)) {
467         HILOG_ERROR("MainThread::ScheduleMemoryLevel PostTask task failed");
468     }
469     HILOG_DEBUG("MainThread::ScheduleMemoryLevel level: %{public}d end.", level);
470 }
471 
472 /**
473  *
474  * @brief Schedule the application process exit safely.
475  *
476  */
ScheduleProcessSecurityExit()477 void MainThread::ScheduleProcessSecurityExit()
478 {
479     HILOG_DEBUG("ScheduleProcessSecurityExit called");
480     wptr<MainThread> weak = this;
481     auto task = [weak]() {
482         auto appThread = weak.promote();
483         if (appThread == nullptr) {
484             HILOG_ERROR("appThread is nullptr, ScheduleProcessSecurityExit failed.");
485             return;
486         }
487         appThread->HandleProcessSecurityExit();
488     };
489     bool result = mainHandler_->PostTask(task);
490     if (!result) {
491         HILOG_ERROR("ScheduleProcessSecurityExit post task failed");
492     }
493 }
494 
495 /**
496  *
497  * @brief Low the memory which used by application.
498  *
499  */
ScheduleLowMemory()500 void MainThread::ScheduleLowMemory()
501 {
502     HILOG_DEBUG("MainThread::scheduleLowMemory called");
503 }
504 
505 /**
506  *
507  * @brief Launch the application.
508  *
509  * @param data The launchdata of the application witch launced.
510  *
511  */
ScheduleLaunchApplication(const AppLaunchData & data,const Configuration & config)512 void MainThread::ScheduleLaunchApplication(const AppLaunchData &data, const Configuration &config)
513 {
514     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
515     HILOG_DEBUG("MainThread schedule launch application start.");
516     wptr<MainThread> weak = this;
517     auto task = [weak, data, config]() {
518         auto appThread = weak.promote();
519         if (appThread == nullptr) {
520             HILOG_ERROR("appThread is nullptr, HandleLaunchApplication failed.");
521             return;
522         }
523         appThread->HandleLaunchApplication(data, config);
524     };
525     if (!mainHandler_->PostTask(task)) {
526         HILOG_ERROR("MainThread::ScheduleLaunchApplication PostTask task failed");
527     }
528 }
529 
530 /**
531  *
532  * @brief update the application info after new module installed.
533  *
534  * @param appInfo The latest application info obtained from bms for update abilityRuntimeContext.
535  *
536  */
ScheduleUpdateApplicationInfoInstalled(const ApplicationInfo & appInfo)537 void MainThread::ScheduleUpdateApplicationInfoInstalled(const ApplicationInfo &appInfo)
538 {
539     HILOG_DEBUG("MainThread::ScheduleUpdateApplicationInfoInstalled start");
540     wptr<MainThread> weak = this;
541     auto task = [weak, appInfo]() {
542         auto appThread = weak.promote();
543         if (appThread == nullptr) {
544             HILOG_ERROR("appThread is nullptr, HandleUpdateApplicationInfoInstalled failed.");
545             return;
546         }
547         appThread->HandleUpdateApplicationInfoInstalled(appInfo);
548     };
549     if (!mainHandler_->PostTask(task)) {
550         HILOG_ERROR("MainThread::ScheduleUpdateApplicationInfoInstalled PostTask task failed");
551     }
552     HILOG_DEBUG("MainThread::ScheduleUpdateApplicationInfoInstalled end.");
553 }
554 
ScheduleAbilityStage(const HapModuleInfo & abilityStage)555 void MainThread::ScheduleAbilityStage(const HapModuleInfo &abilityStage)
556 {
557     HILOG_DEBUG("MainThread::ScheduleAbilityStageInfo start");
558     wptr<MainThread> weak = this;
559     auto task = [weak, abilityStage]() {
560         auto appThread = weak.promote();
561         if (appThread == nullptr) {
562             HILOG_ERROR("appThread is nullptr, HandleShrinkMemory failed.");
563             return;
564         }
565         appThread->HandleAbilityStage(abilityStage);
566     };
567     if (!mainHandler_->PostTask(task)) {
568         HILOG_ERROR("MainThread::ScheduleAbilityStageInfo PostTask task failed");
569     }
570     HILOG_DEBUG("MainThread::ScheduleAbilityStageInfo end.");
571 }
572 
ScheduleLaunchAbility(const AbilityInfo & info,const sptr<IRemoteObject> & token,const std::shared_ptr<AAFwk::Want> & want)573 void MainThread::ScheduleLaunchAbility(const AbilityInfo &info, const sptr<IRemoteObject> &token,
574     const std::shared_ptr<AAFwk::Want> &want)
575 {
576     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
577     HILOG_DEBUG("schedule launch ability %{public}s, type is %{public}d.", info.name.c_str(), info.type);
578 
579     std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>(info);
580     std::shared_ptr<AbilityLocalRecord> abilityRecord = std::make_shared<AbilityLocalRecord>(abilityInfo, token);
581     abilityRecord->SetWant(want);
582 
583     wptr<MainThread> weak = this;
584     auto task = [weak, abilityRecord]() {
585         auto appThread = weak.promote();
586         if (appThread == nullptr) {
587             HILOG_ERROR("appThread is nullptr, HandleLaunchAbility failed.");
588             return;
589         }
590         appThread->HandleLaunchAbility(abilityRecord);
591     };
592     if (!mainHandler_->PostTask(task)) {
593         HILOG_ERROR("MainThread::ScheduleLaunchAbility PostTask task failed");
594     }
595 }
596 
597 /**
598  *
599  * @brief clean the ability by token.
600  *
601  * @param token The token belong to the ability which want to be cleaned.
602  *
603  */
ScheduleCleanAbility(const sptr<IRemoteObject> & token)604 void MainThread::ScheduleCleanAbility(const sptr<IRemoteObject> &token)
605 {
606     HILOG_DEBUG("Schedule clean ability called.");
607     wptr<MainThread> weak = this;
608     auto task = [weak, token]() {
609         auto appThread = weak.promote();
610         if (appThread == nullptr) {
611             HILOG_ERROR("appThread is nullptr, HandleCleanAbility failed.");
612             return;
613         }
614         appThread->HandleCleanAbility(token);
615     };
616     if (!mainHandler_->PostTask(task)) {
617         HILOG_ERROR("MainThread::ScheduleCleanAbility PostTask task failed");
618     }
619 }
620 
621 /**
622  *
623  * @brief send the new profile.
624  *
625  * @param profile The updated profile.
626  *
627  */
ScheduleProfileChanged(const Profile & profile)628 void MainThread::ScheduleProfileChanged(const Profile &profile)
629 {
630     HILOG_DEBUG("MainThread::scheduleProfileChanged profile name: %{public}s", profile.GetName().c_str());
631 }
632 
633 /**
634  *
635  * @brief send the new config to the application.
636  *
637  * @param config The updated config.
638  *
639  */
ScheduleConfigurationUpdated(const Configuration & config)640 void MainThread::ScheduleConfigurationUpdated(const Configuration &config)
641 {
642     HILOG_DEBUG("MainThread::ScheduleConfigurationUpdated called start.");
643     wptr<MainThread> weak = this;
644     auto task = [weak, config]() {
645         auto appThread = weak.promote();
646         if (appThread == nullptr) {
647             HILOG_ERROR("appThread is nullptr, HandleConfigurationUpdated failed.");
648             return;
649         }
650         appThread->HandleConfigurationUpdated(config);
651     };
652     if (!mainHandler_->PostTask(task)) {
653         HILOG_ERROR("MainThread::ScheduleConfigurationUpdated PostTask task failed");
654     }
655     HILOG_DEBUG("MainThread::ScheduleConfigurationUpdated called end.");
656 }
657 
CheckLaunchApplicationParam(const AppLaunchData & appLaunchData) const658 bool MainThread::CheckLaunchApplicationParam(const AppLaunchData &appLaunchData) const
659 {
660     ApplicationInfo appInfo = appLaunchData.GetApplicationInfo();
661     ProcessInfo processInfo = appLaunchData.GetProcessInfo();
662 
663     if (appInfo.name.empty()) {
664         HILOG_ERROR("MainThread::checkLaunchApplicationParam applicationName is empty");
665         return false;
666     }
667 
668     if (processInfo.GetProcessName().empty()) {
669         HILOG_ERROR("MainThread::checkLaunchApplicationParam processName is empty");
670         return false;
671     }
672     return true;
673 }
674 
675 /**
676  *
677  * @brief Check whether the record is legal.
678  *
679  * @param record The record should be checked.
680  *
681  * @return if the record is legal, return true. else return false.
682  */
CheckAbilityItem(const std::shared_ptr<AbilityLocalRecord> & record) const683 bool MainThread::CheckAbilityItem(const std::shared_ptr<AbilityLocalRecord> &record) const
684 {
685     if (record == nullptr) {
686         HILOG_ERROR("MainThread::checkAbilityItem record is null");
687         return false;
688     }
689 
690     std::shared_ptr<AbilityInfo> abilityInfo = record->GetAbilityInfo();
691     sptr<IRemoteObject> token = record->GetToken();
692 
693     if (abilityInfo == nullptr) {
694         HILOG_ERROR("MainThread::checkAbilityItem abilityInfo is null");
695         return false;
696     }
697 
698     if (token == nullptr) {
699         HILOG_ERROR("MainThread::checkAbilityItem token is null");
700         return false;
701     }
702     return true;
703 }
704 
705 /**
706  *
707  * @brief Terminate the application but don't notify ams.
708  *
709  */
HandleTerminateApplicationLocal()710 void MainThread::HandleTerminateApplicationLocal()
711 {
712     HILOG_DEBUG("MainThread::HandleTerminateApplicationLocal called start.");
713     if (application_ == nullptr) {
714         HILOG_ERROR("MainThread::HandleTerminateApplicationLocal error!");
715         return;
716     }
717     applicationImpl_->PerformTerminateStrong();
718 
719     std::shared_ptr<EventRunner> signalRunner = signalHandler_->GetEventRunner();
720     if (signalRunner) {
721         signalRunner->Stop();
722     }
723 
724     std::shared_ptr<EventRunner> runner = mainHandler_->GetEventRunner();
725     if (runner == nullptr) {
726         HILOG_ERROR("MainThread::HandleTerminateApplicationLocal get manHandler error");
727         return;
728     }
729 
730     if (watchdog_ != nullptr && !watchdog_->IsStopWatchdog()) {
731         watchdog_->Stop();
732         watchdog_ = nullptr;
733     }
734 
735     int ret = runner->Stop();
736     if (ret != ERR_OK) {
737         HILOG_ERROR("MainThread::HandleTerminateApplicationLocal failed. runner->Run failed ret = %{public}d", ret);
738     }
739     HILOG_DEBUG("runner is stopped");
740     SetRunnerStarted(false);
741 
742 #ifdef ABILITY_LIBRARY_LOADER
743     CloseAbilityLibrary();
744 #endif  // ABILITY_LIBRARY_LOADER
745 #ifdef APPLICATION_LIBRARY_LOADER
746     if (handleAppLib_ != nullptr) {
747         dlclose(handleAppLib_);
748         handleAppLib_ = nullptr;
749     }
750 #endif  // APPLICATION_LIBRARY_LOADER
751     HILOG_DEBUG("MainThread::HandleTerminateApplicationLocal called end.");
752 }
753 
754 /**
755  *
756  * @brief Schedule the application process exit safely.
757  *
758  */
HandleProcessSecurityExit()759 void MainThread::HandleProcessSecurityExit()
760 {
761     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
762     HILOG_DEBUG("MainThread::HandleProcessSecurityExit called start.");
763     if (abilityRecordMgr_ == nullptr) {
764         HILOG_ERROR("MainThread::HandleProcessSecurityExit abilityRecordMgr_ is null");
765         return;
766     }
767 
768     std::vector<sptr<IRemoteObject>> tokens = (abilityRecordMgr_->GetAllTokens());
769 
770     for (auto iter = tokens.begin(); iter != tokens.end(); ++iter) {
771         HandleCleanAbilityLocal(*iter);
772     }
773 
774     HandleTerminateApplicationLocal();
775     HILOG_DEBUG("MainThread::HandleProcessSecurityExit called end.");
776 }
777 
InitCreate(std::shared_ptr<ContextDeal> & contextDeal,ApplicationInfo & appInfo,ProcessInfo & processInfo,Profile & appProfile)778 bool MainThread::InitCreate(
779     std::shared_ptr<ContextDeal> &contextDeal, ApplicationInfo &appInfo, ProcessInfo &processInfo, Profile &appProfile)
780 {
781     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
782     applicationInfo_ = std::make_shared<ApplicationInfo>(appInfo);
783     if (applicationInfo_ == nullptr) {
784         HILOG_ERROR("MainThread::InitCreate create applicationInfo_ failed");
785         return false;
786     }
787 
788     processInfo_ = std::make_shared<ProcessInfo>(processInfo);
789     if (processInfo_ == nullptr) {
790         HILOG_ERROR("MainThread::InitCreate create processInfo_ failed");
791         return false;
792     }
793 
794     appProfile_ = std::make_shared<Profile>(appProfile);
795     if (appProfile_ == nullptr) {
796         HILOG_ERROR("MainThread::InitCreate create appProfile_ failed");
797         return false;
798     }
799 
800     applicationImpl_ = std::make_shared<ApplicationImpl>();
801     if (applicationImpl_ == nullptr) {
802         HILOG_ERROR("MainThread::InitCreate create applicationImpl_ failed");
803         return false;
804     }
805 
806     abilityRecordMgr_ = std::make_shared<AbilityRecordMgr>();
807     if (abilityRecordMgr_ == nullptr) {
808         HILOG_ERROR("MainThread::InitCreate create AbilityRecordMgr failed");
809         return false;
810     }
811 
812     contextDeal = std::make_shared<ContextDeal>();
813     if (contextDeal == nullptr) {
814         HILOG_ERROR("MainThread::InitCreate create contextDeal failed");
815         return false;
816     }
817 
818     if (watchdog_ != nullptr) {
819         watchdog_->SetApplicationInfo(applicationInfo_);
820     }
821 
822     contextDeal->SetProcessInfo(processInfo_);
823     contextDeal->SetApplicationInfo(applicationInfo_);
824     contextDeal->SetProfile(appProfile_);
825     contextDeal->SetBundleCodePath(applicationInfo_->codePath);  // BMS need to add cpath
826 
827     return true;
828 }
829 
CheckForHandleLaunchApplication(const AppLaunchData & appLaunchData)830 bool MainThread::CheckForHandleLaunchApplication(const AppLaunchData &appLaunchData)
831 {
832     if (application_ != nullptr) {
833         HILOG_ERROR("MainThread::handleLaunchApplication already create application");
834         return false;
835     }
836 
837     if (!CheckLaunchApplicationParam(appLaunchData)) {
838         HILOG_ERROR("MainThread::handleLaunchApplication appLaunchData invalid");
839         return false;
840     }
841     return true;
842 }
843 
InitResourceManager(std::shared_ptr<Global::Resource::ResourceManager> & resourceManager,BundleInfo & bundleInfo,const Configuration & config)844 bool MainThread::InitResourceManager(std::shared_ptr<Global::Resource::ResourceManager> &resourceManager,
845     BundleInfo& bundleInfo, const Configuration &config)
846 {
847     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
848     bool isStageBased = bundleInfo.hapModuleInfos.empty() ? false : bundleInfo.hapModuleInfos.back().isStageBasedModel;
849     if (isStageBased && bundleInfo.applicationInfo.multiProjects) {
850         HILOG_INFO("MainThread::InitResourceManager for multiProjects.");
851     } else {
852         std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + bundleInfo.name);
853         for (auto hapModuleInfo : bundleInfo.hapModuleInfos) {
854             std::string loadPath =  (system::GetBoolParameter(AbilityRuntime::Constants::COMPRESS_PROPERTY, false) &&
855                 !hapModuleInfo.hapPath.empty()) ? hapModuleInfo.hapPath : hapModuleInfo.resourcePath;
856             if (loadPath.empty()) {
857                 continue;
858             }
859             loadPath = std::regex_replace(loadPath, pattern, std::string(LOCAL_CODE_PATH));
860             HILOG_DEBUG("ModuleResPath: %{public}s", loadPath.c_str());
861             if (!resourceManager->AddResource(loadPath.c_str())) {
862                 HILOG_ERROR("AddResource failed");
863             }
864         }
865     }
866 
867     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
868 #ifdef SUPPORT_GRAPHICS
869     UErrorCode status = U_ZERO_ERROR;
870     icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status);
871     resConfig->SetLocaleInfo(locale);
872     const icu::Locale *localeInfo = resConfig->GetLocaleInfo();
873     if (localeInfo != nullptr) {
874         HILOG_INFO("Language: %{public}s, script: %{public}s, region: %{public}s",
875             localeInfo->getLanguage(), localeInfo->getScript(), localeInfo->getCountry());
876     } else {
877         HILOG_INFO("LocaleInfo is nullptr.");
878     }
879 #endif
880     std::string colormode = config.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
881     HILOG_DEBUG("Colormode is %{public}s.", colormode.c_str());
882     resConfig->SetColorMode(ConvertColorMode(colormode));
883 
884     std::string hasPointerDevice = config.GetItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE);
885     HILOG_DEBUG("HasPointerDevice is %{public}s.", hasPointerDevice.c_str());
886     resConfig->SetInputDevice(ConvertHasPointerDevice(hasPointerDevice));
887 
888     std::string deviceType = config.GetItem(AAFwk::GlobalConfigurationKey::DEVICE_TYPE);
889     HILOG_DEBUG("deviceType is %{public}s <---->  %{public}d.", deviceType.c_str(), ConvertDeviceType(deviceType));
890     resConfig->SetDeviceType(ConvertDeviceType(deviceType));
891     resourceManager->UpdateResConfig(*resConfig);
892     return true;
893 }
894 
GetNativeStrFromJsTaggedObj(NativeObject * obj,const char * key)895 static std::string GetNativeStrFromJsTaggedObj(NativeObject* obj, const char* key)
896 {
897     if (obj == nullptr) {
898         HILOG_ERROR("Failed to get value from key:%{public}s, Null NativeObject", key);
899         return "";
900     }
901 
902     NativeValue* value = obj->GetProperty(key);
903     NativeString* valueStr = AbilityRuntime::ConvertNativeValueTo<NativeString>(value);
904     if (valueStr == nullptr) {
905         HILOG_ERROR("Failed to convert value from key:%{public}s", key);
906         return "";
907     }
908     size_t valueStrBufLength = valueStr->GetLength();
909     size_t valueStrLength = 0;
910     char* valueCStr = new (std::nothrow) char[valueStrBufLength + 1];
911     if (valueCStr == nullptr) {
912         HILOG_ERROR("Failed to new valueCStr");
913         return "";
914     }
915     valueStr->GetCString(valueCStr, valueStrBufLength + 1, &valueStrLength);
916     std::string ret(valueCStr, valueStrLength);
917     delete []valueCStr;
918     HILOG_DEBUG("GetNativeStrFromJsTaggedObj Success %{public}s:%{public}s", key, ret.c_str());
919     return ret;
920 }
921 
922 /**
923  *
924  * @brief Launch the application.
925  *
926  * @param appLaunchData The launchdata of the application witch launced.
927  *
928  */
HandleLaunchApplication(const AppLaunchData & appLaunchData,const Configuration & config)929 void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, const Configuration &config)
930 {
931     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
932     HILOG_DEBUG("MainThread handle launch application start.");
933     if (!CheckForHandleLaunchApplication(appLaunchData)) {
934         HILOG_ERROR("MainThread::handleLaunchApplication CheckForHandleLaunchApplication failed");
935         return;
936     }
937 
938     std::string contactsDataAbility("com.ohos.contactsdataability");
939     std::string mediaDataAbility("com.ohos.medialibrary.medialibrarydata");
940     std::string telephonyDataAbility("com.ohos.telephonydataability");
941     std::string fusionSearchAbility("com.ohos.FusionSearch");
942     std::string formRenderExtensionAbility("com.ohos.formrenderservice");
943     auto appInfo = appLaunchData.GetApplicationInfo();
944     auto bundleName = appInfo.bundleName;
945     if (bundleName == contactsDataAbility || bundleName == mediaDataAbility || bundleName == telephonyDataAbility
946         || bundleName == fusionSearchAbility || bundleName == formRenderExtensionAbility) {
947         std::vector<std::string> localPaths;
948         ChangeToLocalPath(bundleName, appInfo.moduleSourceDirs, localPaths);
949         LoadAbilityLibrary(localPaths);
950         LoadNativeLiabrary(appInfo.nativeLibraryPath);
951     }
952     if (appInfo.needAppDetail) {
953         HILOG_DEBUG("MainThread::handleLaunchApplication %{public}s need add app detail ability library path",
954             bundleName.c_str());
955         LoadAppDetailAbilityLibrary(appInfo.appDetailAbilityLibraryPath);
956     }
957     LoadAppLibrary();
958 
959     ProcessInfo processInfo = appLaunchData.GetProcessInfo();
960     Profile appProfile = appLaunchData.GetProfile();
961 
962     HILOG_DEBUG("MainThread handle launch application, InitCreate Start.");
963     std::shared_ptr<ContextDeal> contextDeal = nullptr;
964     if (!InitCreate(contextDeal, appInfo, processInfo, appProfile)) {
965         HILOG_ERROR("MainThread::handleLaunchApplication InitCreate failed");
966         return;
967     }
968     HILOG_DEBUG("MainThread handle launch application, InitCreate End.");
969 
970     // get application shared point
971     application_ = std::shared_ptr<OHOSApplication>(ApplicationLoader::GetInstance().GetApplicationByName());
972     if (application_ == nullptr) {
973         HILOG_ERROR("HandleLaunchApplication::application launch failed");
974         return;
975     }
976     applicationForDump_ = application_;
977     mixStackDumper_ = std::make_shared<MixStackDumper>();
978     mixStackDumper_->InstallDumpHandler(applicationForDump_, signalHandler_);
979 
980     // init resourceManager.
981     HILOG_DEBUG("MainThread handle launch application, CreateResourceManager Start.");
982     std::shared_ptr<Global::Resource::ResourceManager> resourceManager(Global::Resource::CreateResourceManager());
983     if (resourceManager == nullptr) {
984         HILOG_ERROR("MainThread::handleLaunchApplication create resourceManager failed");
985         return;
986     }
987     HILOG_DEBUG("MainThread handle launch application, CreateResourceManager End.");
988 
989     sptr<IBundleMgr> bundleMgr = contextDeal->GetBundleManager();
990     if (bundleMgr == nullptr) {
991         HILOG_ERROR("MainThread::handleLaunchApplication GetBundleManager is nullptr");
992         return;
993     }
994 
995     BundleInfo bundleInfo;
996     bool queryResult;
997     if (appLaunchData.GetAppIndex() != 0) {
998         queryResult = (bundleMgr->GetSandboxBundleInfo(appInfo.bundleName,
999             appLaunchData.GetAppIndex(), UNSPECIFIED_USERID, bundleInfo) == 0);
1000     } else {
1001         HILOG_INFO("GetBundleInfo, bundleName = %{public}s", appInfo.bundleName.c_str());
1002         queryResult = (bundleMgr->GetBundleInfoForSelf(
1003             (static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) +
1004             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) +
1005             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE) +
1006             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) +
1007             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) +
1008             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY) +
1009             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_METADATA)), bundleInfo) == ERR_OK);
1010     }
1011 
1012     if (!queryResult) {
1013         HILOG_ERROR("HandleLaunchApplication GetBundleInfo failed!");
1014         return;
1015     }
1016 
1017     bool moduelJson = false;
1018     bool isStageBased = false;
1019     if (!bundleInfo.hapModuleInfos.empty()) {
1020         moduelJson = bundleInfo.hapModuleInfos.back().isModuleJson;
1021         isStageBased = bundleInfo.hapModuleInfos.back().isStageBasedModel;
1022     }
1023 
1024     if (isStageBased) {
1025         AppRecovery::GetInstance().InitApplicationInfo(GetMainHandler(), GetApplicationInfo());
1026     }
1027     HILOG_INFO("stageBased:%{public}d moduleJson:%{public}d size:%{public}zu",
1028         isStageBased, moduelJson, bundleInfo.hapModuleInfos.size());
1029 
1030     HILOG_DEBUG("MainThread handle launch application, InitResourceManager Start.");
1031     if (!InitResourceManager(resourceManager, bundleInfo, config)) {
1032         HILOG_ERROR("MainThread::handleLaunchApplication InitResourceManager failed");
1033         return;
1034     }
1035     HILOG_DEBUG("MainThread handle launch application, InitResourceManager End.");
1036 
1037     // create contextImpl
1038     std::shared_ptr<AbilityRuntime::ContextImpl> contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
1039     contextImpl->SetResourceManager(resourceManager);
1040     contextImpl->SetApplicationInfo(std::make_shared<ApplicationInfo>(appInfo));
1041     std::shared_ptr<AbilityRuntime::ApplicationContext> applicationContext =
1042         AbilityRuntime::ApplicationContext::GetInstance();
1043     applicationContext->AttachContextImpl(contextImpl);
1044     application_->SetApplicationContext(applicationContext);
1045     std::string BundleCodeDir = applicationContext->GetBundleCodeDir();
1046     if (isStageBased) {
1047         // Create runtime
1048         AbilityRuntime::Runtime::Options options;
1049         options.bundleName = appInfo.bundleName;
1050         options.codePath = LOCAL_CODE_PATH;
1051         options.hapPath = bundleInfo.hapModuleInfos.back().hapPath;
1052         options.eventRunner = mainHandler_->GetEventRunner();
1053         options.loadAce = true;
1054         options.isBundle = (bundleInfo.hapModuleInfos.back().compileMode != AppExecFwk::CompileMode::ES_MODULE);
1055         options.isDebugVersion = bundleInfo.applicationInfo.debug;
1056         options.arkNativeFilePath = bundleInfo.applicationInfo.arkNativeFilePath;
1057         SetNativeLibPath(bundleInfo, options);
1058         auto runtime = AbilityRuntime::Runtime::Create(options);
1059         if (!runtime) {
1060             HILOG_ERROR("Failed to create runtime");
1061             return;
1062         }
1063         auto& jsEngine = (static_cast<AbilityRuntime::JsRuntime&>(*runtime)).GetNativeEngine();
1064         auto bundleName = appInfo.bundleName;
1065         auto versionCode = appInfo.versionCode;
1066         wptr<MainThread> weak = this;
1067         auto uncaughtTask = [weak, bundleName, versionCode, BundleCodeDir](NativeValue* v) {
1068             HILOG_INFO("Js uncaught exception callback come.");
1069             auto appThread = weak.promote();
1070             if (appThread == nullptr) {
1071                 HILOG_ERROR("appThread is nullptr, HandleLaunchApplication failed.");
1072                 return;
1073             }
1074             NativeObject* obj = AbilityRuntime::ConvertNativeValueTo<NativeObject>(v);
1075             std::string errorMsg = GetNativeStrFromJsTaggedObj(obj, "message");
1076             std::string errorName = GetNativeStrFromJsTaggedObj(obj, "name");
1077             std::string errorStack = GetNativeStrFromJsTaggedObj(obj, "stack");
1078             std::string summary = "Error message:" + errorMsg + "\n";
1079             if (appThread->application_ == nullptr) {
1080                 HILOG_ERROR("appThread is nullptr, HandleLaunchApplication failde.");
1081                 return;
1082             }
1083             auto& bindSourceMaps = (static_cast<AbilityRuntime::JsRuntime&>(*
1084                 (weak->application_->GetRuntime()))).GetSourceMap();
1085             // bindRuntime.bindSourceMaps lazy loading
1086             if (errorStack.empty()) {
1087                 HILOG_ERROR("errorStack is empty");
1088                 return;
1089             }
1090             HILOG_INFO("JS Stack:\n%{public}s", errorStack.c_str());
1091             auto errorPos = ModSourceMap::GetErrorPos(errorStack);
1092             std::string error;
1093             if (obj != nullptr) {
1094                 NativeValue* value = obj->GetProperty("errorfunc");
1095                 NativeFunction* fuc = AbilityRuntime::ConvertNativeValueTo<NativeFunction>(value);
1096                 if (fuc != nullptr) {
1097                     error = fuc->GetSourceCodeInfo(errorPos);
1098                 }
1099             }
1100             summary += error + "Stacktrace:\n" + OHOS::AbilityRuntime::ModSourceMap::TranslateBySourceMap
1101                 (errorStack, bindSourceMaps, BundleCodeDir);
1102             ApplicationDataManager::GetInstance().NotifyUnhandledException(summary);
1103             time_t timet;
1104             time(&timet);
1105             OHOS::HiviewDFX::HiSysEvent::Write(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, "JS_ERROR",
1106                 OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
1107                 EVENT_KEY_PACKAGE_NAME, bundleName,
1108                 EVENT_KEY_VERSION, std::to_string(versionCode),
1109                 EVENT_KEY_TYPE, JSCRASH_TYPE,
1110                 EVENT_KEY_HAPPEN_TIME, timet,
1111                 EVENT_KEY_REASON, errorName,
1112                 EVENT_KEY_JSVM, JSVM_TYPE,
1113                 EVENT_KEY_SUMMARY, summary);
1114             if (ApplicationDataManager::GetInstance().NotifyUnhandledException(summary)) {
1115                 return;
1116             }
1117             // if app's callback has been registered, let app decide whether exit or not.
1118             HILOG_ERROR("\n%{public}s is about to exit due to RuntimeError\nError type:%{public}s\n%{public}s",
1119                 bundleName.c_str(), errorName.c_str(), summary.c_str());
1120             appThread->ScheduleProcessSecurityExit();
1121         };
1122         jsEngine.RegisterUncaughtExceptionHandler(uncaughtTask);
1123         application_->SetRuntime(std::move(runtime));
1124 
1125         AbilityLoader::GetInstance().RegisterAbility("Ability", [application = application_]() {
1126             return Ability::Create(application->GetRuntime());
1127         });
1128 #ifdef SUPPORT_GRAPHICS
1129         AbilityLoader::GetInstance().RegisterExtension("FormExtension", [application = application_]() {
1130             return AbilityRuntime::FormExtension::Create(application->GetRuntime());
1131         });
1132         AddExtensionBlockItem("FormExtension", static_cast<int32_t>(ExtensionAbilityType::FORM));
1133 #endif
1134         AbilityLoader::GetInstance().RegisterExtension("StaticSubscriberExtension", [application = application_]() {
1135             return AbilityRuntime::StaticSubscriberExtension::Create(application->GetRuntime());
1136         });
1137         AddExtensionBlockItem("StaticSubscriberExtension",
1138             static_cast<int32_t>(ExtensionAbilityType::STATICSUBSCRIBER));
1139 
1140 #ifdef APP_USE_ARM
1141         LoadAllExtensions(jsEngine, "system/lib/extensionability");
1142 #else
1143         LoadAllExtensions(jsEngine, "system/lib64/extensionability");
1144 #endif
1145         std::shared_ptr<NativeEngine> nativeEngine(&jsEngine);
1146         idleTime_ = std::make_shared<IdleTime>(mainHandler_, nativeEngine);
1147         idleTime_->Start();
1148     }
1149 
1150     auto usertestInfo = appLaunchData.GetUserTestInfo();
1151     if (usertestInfo) {
1152         if (!PrepareAbilityDelegator(usertestInfo, isStageBased, bundleInfo)) {
1153             HILOG_ERROR("Failed to prepare ability delegator");
1154             return;
1155         }
1156     }
1157 
1158     contextDeal->initResourceManager(resourceManager);
1159     contextDeal->SetApplicationContext(application_);
1160     application_->AttachBaseContext(contextDeal);
1161     application_->SetAbilityRecordMgr(abilityRecordMgr_);
1162     application_->SetConfiguration(config);
1163     contextImpl->SetConfiguration(application_->GetConfiguration());
1164 
1165     applicationImpl_->SetRecordId(appLaunchData.GetRecordId());
1166     applicationImpl_->SetApplication(application_);
1167     mainThreadState_ = MainThreadState::READY;
1168     if (!applicationImpl_->PerformAppReady()) {
1169         HILOG_ERROR("HandleLaunchApplication::application applicationImpl_->PerformAppReady failed");
1170         return;
1171     }
1172     // L1 needs to add corresponding interface
1173     ApplicationEnvImpl *pAppEvnIml = ApplicationEnvImpl::GetInstance();
1174 
1175     if (pAppEvnIml) {
1176         pAppEvnIml->SetAppInfo(*applicationInfo_.get());
1177     } else {
1178         HILOG_ERROR("HandleLaunchApplication::application pAppEvnIml is null");
1179     }
1180 
1181 #if defined(NWEB)
1182     // pre dns for nweb
1183     std::thread(&OHOS::NWeb::PreDnsInThread).detach();
1184 
1185     // start nwebspawn process
1186     std::thread([nwebApp = application_, nwebMgr = appMgr_] {
1187         if (nwebApp == nullptr || nwebMgr == nullptr) {
1188             HILOG_ERROR("HandleLaunchApplication nwebApp or nwebMgr is null");
1189             return;
1190         }
1191         std::string nwebPath = nwebApp->GetAppContext()->GetCacheDir() + "/web";
1192         bool isFirstStartUpWeb = (access(nwebPath.c_str(), F_OK) != 0);
1193         if (!isFirstStartUpWeb) {
1194             nwebMgr->PreStartNWebSpawnProcess();
1195         }
1196         OHOS::NWeb::NWebHelper::TryPreReadLib(isFirstStartUpWeb, nwebApp->GetAppContext()->GetBundleCodeDir());
1197     }).detach();
1198 #endif
1199 
1200     HILOG_DEBUG("MainThread::handleLaunchApplication called end.");
1201 }
1202 
LoadNativeLiabrary(std::string & nativeLibraryPath)1203 void MainThread::LoadNativeLiabrary(std::string &nativeLibraryPath)
1204 {
1205 #ifdef ABILITY_LIBRARY_LOADER
1206     if (nativeLibraryPath.empty()) {
1207         HILOG_WARN("Native library path is empty.");
1208         return;
1209     }
1210 
1211     if (nativeLibraryPath.back() == '/') {
1212         nativeLibraryPath.pop_back();
1213     }
1214     std::string libPath = LOCAL_CODE_PATH;
1215     libPath += (libPath.back() == '/') ? nativeLibraryPath : "/" + nativeLibraryPath;
1216     HILOG_DEBUG("native library path = %{public}s", libPath.c_str());
1217 
1218     if (!ScanDir(libPath, nativeFileEntries_)) {
1219         HILOG_WARN("%{public}s scanDir %{public}s not exits", __func__, libPath.c_str());
1220     }
1221 
1222     if (nativeFileEntries_.empty()) {
1223         HILOG_WARN("No native library");
1224         return;
1225     }
1226 
1227     void *handleAbilityLib = nullptr;
1228     for (auto fileEntry : nativeFileEntries_) {
1229         if (fileEntry.empty()) {
1230             continue;
1231         }
1232         handleAbilityLib = dlopen(fileEntry.c_str(), RTLD_NOW | RTLD_GLOBAL);
1233         if (handleAbilityLib == nullptr) {
1234             if (fileEntry.find("libformrender.z.so") == std::string::npos) {
1235                 HILOG_ERROR("%{public}s Fail to dlopen %{public}s, [%{public}s]",
1236                     __func__, fileEntry.c_str(), dlerror());
1237                 exit(-1);
1238             } else {
1239                 HILOG_DEBUG("Load libformrender.z.so from native lib path.");
1240                 handleAbilityLib = dlopen(FORM_RENDER_LIB_PATH, RTLD_NOW | RTLD_GLOBAL);
1241                 if (handleAbilityLib == nullptr) {
1242                     HILOG_ERROR("%{public}s Fail to dlopen %{public}s, [%{public}s]",
1243                         __func__, FORM_RENDER_LIB_PATH, dlerror());
1244                     exit(-1);
1245                 }
1246                 fileEntry = FORM_RENDER_LIB_PATH;
1247             }
1248         }
1249         HILOG_DEBUG("%{public}s Success to dlopen %{public}s", __func__, fileEntry.c_str());
1250         handleAbilityLib_.emplace_back(handleAbilityLib);
1251     }
1252 #endif
1253 }
1254 
ChangeToLocalPath(const std::string & bundleName,const std::vector<std::string> & sourceDirs,std::vector<std::string> & localPath)1255 void MainThread::ChangeToLocalPath(const std::string &bundleName,
1256     const std::vector<std::string> &sourceDirs, std::vector<std::string> &localPath)
1257 {
1258     std::regex pattern(std::string(ABS_CODE_PATH) + std::string(FILE_SEPARATOR) + bundleName
1259         + std::string(FILE_SEPARATOR));
1260     for (auto item : sourceDirs) {
1261         if (item.empty()) {
1262             continue;
1263         }
1264         localPath.emplace_back(
1265             std::regex_replace(item, pattern, std::string(LOCAL_CODE_PATH) + std::string(FILE_SEPARATOR)));
1266     }
1267 }
1268 
HandleUpdateApplicationInfoInstalled(const ApplicationInfo & appInfo)1269 void MainThread::HandleUpdateApplicationInfoInstalled(const ApplicationInfo &appInfo)
1270 {
1271     HILOG_DEBUG("MainThread::HandleUpdateApplicationInfoInstalled");
1272     if (!application_) {
1273         HILOG_ERROR("application_ is nullptr");
1274         return;
1275     }
1276     application_->UpdateApplicationInfoInstalled(appInfo);
1277 }
1278 
HandleAbilityStage(const HapModuleInfo & abilityStage)1279 void MainThread::HandleAbilityStage(const HapModuleInfo &abilityStage)
1280 {
1281     HILOG_DEBUG("MainThread::HandleAbilityStageInfo");
1282     if (!application_) {
1283         HILOG_ERROR("application_ is nullptr");
1284         return;
1285     }
1286 
1287     application_->AddAbilityStage(abilityStage);
1288 
1289     if (!appMgr_ || !applicationImpl_) {
1290         HILOG_ERROR("appMgr_ is nullptr");
1291         return;
1292     }
1293 
1294     appMgr_->AddAbilityStageDone(applicationImpl_->GetRecordId());
1295 }
1296 
LoadAllExtensions(NativeEngine & nativeEngine,const std::string & filePath)1297 void MainThread::LoadAllExtensions(NativeEngine &nativeEngine, const std::string &filePath)
1298 {
1299     HILOG_DEBUG("LoadAllExtensions.filePath:%{public}s", filePath.c_str());
1300     if (application_ == nullptr) {
1301         HILOG_ERROR("application launch failed");
1302         return;
1303     }
1304     if (!extensionConfigMgr_) {
1305         return;
1306     }
1307 
1308     // scan all extensions in path
1309     std::vector<std::string> extensionFiles;
1310     ScanDir(filePath, extensionFiles);
1311     if (extensionFiles.empty()) {
1312         HILOG_ERROR("no extension files.");
1313         return;
1314     }
1315 
1316     std::map<OHOS::AppExecFwk::ExtensionAbilityType, std::set<std::string>> extensionBlacklist;
1317     std::map<int32_t, std::string> extensionTypeMap;
1318     for (auto file : extensionFiles) {
1319         HILOG_DEBUG("Begin load extension file:%{public}s", file.c_str());
1320         std::map<std::string, std::string> params =
1321             AbilityRuntime::ExtensionModuleLoader::GetLoader(file.c_str()).GetParams();
1322         if (params.empty()) {
1323             HILOG_ERROR("no extension params.");
1324             continue;
1325         }
1326         // get extension name and type
1327         std::map<std::string, std::string>::iterator it = params.find(EXTENSION_PARAMS_TYPE);
1328         if (it == params.end()) {
1329             HILOG_ERROR("no extension type.");
1330             continue;
1331         }
1332         int32_t type = -1;
1333         try {
1334             type = static_cast<int32_t>(std::stoi(it->second));
1335         } catch (...) {
1336             HILOG_WARN("stoi(%{public}s) failed", it->second.c_str());
1337             continue;
1338         }
1339 
1340         it = params.find(EXTENSION_PARAMS_NAME);
1341         if (it == params.end()) {
1342             HILOG_ERROR("no extension name.");
1343             continue;
1344         }
1345         std::string extensionName = it->second;
1346 
1347         extensionTypeMap.insert(std::pair<int32_t, std::string>(type, extensionName));
1348         AddExtensionBlockItem(extensionName, type);
1349 
1350         HILOG_DEBUG("Success load extension type: %{public}d, name:%{public}s", type, extensionName.c_str());
1351         AbilityLoader::GetInstance().RegisterExtension(extensionName, [application = application_, file]() {
1352             return AbilityRuntime::ExtensionModuleLoader::GetLoader(file.c_str()).Create(application->GetRuntime());
1353         });
1354     }
1355     application_->SetExtensionTypeMap(extensionTypeMap);
1356     UpdateEngineExtensionBlockList(nativeEngine);
1357 }
1358 
PrepareAbilityDelegator(const std::shared_ptr<UserTestRecord> & record,bool isStageBased,BundleInfo & bundleInfo)1359 bool MainThread::PrepareAbilityDelegator(const std::shared_ptr<UserTestRecord> &record, bool isStageBased,
1360     BundleInfo& bundleInfo)
1361 {
1362     HILOG_DEBUG("enter, isStageBased = %{public}d", isStageBased);
1363     if (!record) {
1364         HILOG_ERROR("Invalid UserTestRecord");
1365         return false;
1366     }
1367     auto args = std::make_shared<AbilityDelegatorArgs>(record->want);
1368     if (isStageBased) { // Stage model
1369         HILOG_DEBUG("PrepareAbilityDelegator for Stage model.");
1370         auto testRunner = TestRunner::Create(application_->GetRuntime(), args, false);
1371         auto delegator = std::make_shared<AbilityDelegator>(
1372             application_->GetAppContext(), std::move(testRunner), record->observer);
1373         AbilityDelegatorRegistry::RegisterInstance(delegator, args);
1374         delegator->Prepare();
1375     } else { // FA model
1376         HILOG_DEBUG("PrepareAbilityDelegator for FA model.");
1377         AbilityRuntime::Runtime::Options options;
1378         options.codePath = LOCAL_CODE_PATH;
1379         options.eventRunner = mainHandler_->GetEventRunner();
1380         options.hapPath = bundleInfo.hapModuleInfos.back().hapPath;
1381         options.loadAce = false;
1382         options.isStageModel = false;
1383         if (bundleInfo.hapModuleInfos.empty() || bundleInfo.hapModuleInfos.front().abilityInfos.empty()) {
1384             HILOG_ERROR("Failed to abilityInfos");
1385             return false;
1386         }
1387         bool isFaJsModel = bundleInfo.hapModuleInfos.front().abilityInfos.front().srcLanguage == "js" ? true : false;
1388         static auto runtime = AbilityRuntime::Runtime::Create(options);
1389         auto testRunner = TestRunner::Create(runtime, args, isFaJsModel);
1390         if (testRunner == nullptr) {
1391             HILOG_ERROR("Failed to Create testRunner");
1392             return false;
1393         }
1394         if (!testRunner->Initialize()) {
1395             HILOG_ERROR("Failed to Initialize testRunner");
1396             return false;
1397         }
1398         auto delegator = std::make_shared<AbilityDelegator>(
1399             application_->GetAppContext(), std::move(testRunner), record->observer);
1400         AbilityDelegatorRegistry::RegisterInstance(delegator, args);
1401         delegator->Prepare();
1402     }
1403     return true;
1404 }
1405 
1406 /**
1407  *
1408  * @brief launch the ability.
1409  *
1410  * @param abilityRecord The abilityRecord which belongs to the ability launched.
1411  *
1412  */
HandleLaunchAbility(const std::shared_ptr<AbilityLocalRecord> & abilityRecord)1413 void MainThread::HandleLaunchAbility(const std::shared_ptr<AbilityLocalRecord> &abilityRecord)
1414 {
1415     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1416     HILOG_DEBUG("MainThread::handleLaunchAbility called start.");
1417     CHECK_POINTER_LOG(applicationImpl_, "MainThread::HandleLaunchAbility applicationImpl_ is null");
1418     CHECK_POINTER_LOG(abilityRecordMgr_, "MainThread::HandleLaunchAbility abilityRecordMgr_ is null");
1419     CHECK_POINTER_LOG(abilityRecord, "MainThread::HandleLaunchAbility parameter(abilityRecord) is null");
1420 
1421     auto abilityToken = abilityRecord->GetToken();
1422     CHECK_POINTER_LOG(abilityToken, "MainThread::HandleLaunchAbility failed. abilityRecord->GetToken failed");
1423 
1424     abilityRecordMgr_->SetToken(abilityToken);
1425     abilityRecordMgr_->AddAbilityRecord(abilityToken, abilityRecord);
1426 
1427     if (!IsApplicationReady()) {
1428         HILOG_ERROR("MainThread::handleLaunchAbility not init OHOSApplication, should launch application first");
1429         return;
1430     }
1431 
1432     if (!CheckAbilityItem(abilityRecord)) {
1433         HILOG_ERROR("MainThread::handleLaunchAbility record is invalid");
1434         return;
1435     }
1436 
1437     auto& runtime = application_->GetRuntime();
1438     auto appInfo = application_->GetApplicationInfo();
1439     auto want = abilityRecord->GetWant();
1440 
1441     if (runtime && appInfo && want && appInfo->debug) {
1442         runtime->StartDebugMode(want->GetBoolParam("debugApp", false));
1443     }
1444 
1445     mainThreadState_ = MainThreadState::RUNNING;
1446     std::shared_ptr<AbilityRuntime::Context> stageContext = application_->AddAbilityStage(abilityRecord);
1447     UpdateProcessExtensionType(abilityRecord);
1448 #ifdef APP_ABILITY_USE_TWO_RUNNER
1449     AbilityThread::AbilityThreadMain(application_, abilityRecord, stageContext);
1450 #else
1451     AbilityThread::AbilityThreadMain(application_, abilityRecord, mainHandler_->GetEventRunner(), stageContext);
1452 #endif
1453 
1454     if (runtime) {
1455         std::vector<std::pair<std::string, std::string>> hqfFilePair;
1456         if (GetHqfFileAndHapPath(appInfo->bundleName, hqfFilePair)) {
1457             for (auto it = hqfFilePair.begin(); it != hqfFilePair.end(); it++) {
1458                 HILOG_INFO("hqfFile: %{private}s, hapPath: %{private}s.", it->first.c_str(), it->second.c_str());
1459                 runtime->LoadRepairPatch(it->first, it->second);
1460             }
1461         }
1462     }
1463 }
1464 
1465 /**
1466  *
1467  * @brief Clean the ability but don't notify ams.
1468  *
1469  * @param token The token which belongs to the ability launched.
1470  *
1471  */
HandleCleanAbilityLocal(const sptr<IRemoteObject> & token)1472 void MainThread::HandleCleanAbilityLocal(const sptr<IRemoteObject> &token)
1473 {
1474     HILOG_DEBUG("start.");
1475     if (!IsApplicationReady()) {
1476         HILOG_ERROR("not init OHOSApplication, should launch application first");
1477         return;
1478     }
1479 
1480     if (token == nullptr) {
1481         HILOG_ERROR("token is null");
1482         return;
1483     }
1484 
1485     std::shared_ptr<AbilityLocalRecord> record = abilityRecordMgr_->GetAbilityItem(token);
1486     if (record == nullptr) {
1487         HILOG_ERROR("abilityRecord not found");
1488         return;
1489     }
1490     std::shared_ptr<AbilityInfo> abilityInfo = record->GetAbilityInfo();
1491     if (abilityInfo == nullptr) {
1492         HILOG_ERROR("record->GetAbilityInfo() failed");
1493         return;
1494     }
1495     HILOG_INFO("ability name: %{public}s", abilityInfo->name.c_str());
1496 
1497     abilityRecordMgr_->RemoveAbilityRecord(token);
1498 #ifdef APP_ABILITY_USE_TWO_RUNNER
1499     std::shared_ptr<EventRunner> runner = record->GetEventRunner();
1500     if (runner != nullptr) {
1501         int ret = runner->Stop();
1502         if (ret != ERR_OK) {
1503             HILOG_ERROR("MainThread::main failed. ability runner->Run failed ret = %{public}d", ret);
1504         }
1505         abilityRecordMgr_->RemoveAbilityRecord(token);
1506     } else {
1507         HILOG_WARN("runner not found");
1508     }
1509 #endif
1510     HILOG_DEBUG("end.");
1511 }
1512 
1513 /**
1514  *
1515  * @brief Clean the ability.
1516  *
1517  * @param token The token which belongs to the ability launched.
1518  *
1519  */
HandleCleanAbility(const sptr<IRemoteObject> & token)1520 void MainThread::HandleCleanAbility(const sptr<IRemoteObject> &token)
1521 {
1522     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1523     HILOG_DEBUG("Handle clean ability start, app is %{public}s.", applicationInfo_->name.c_str());
1524     if (!IsApplicationReady()) {
1525         HILOG_ERROR("not init OHOSApplication, should launch application first");
1526         return;
1527     }
1528 
1529     if (token == nullptr) {
1530         HILOG_ERROR("token is null");
1531         return;
1532     }
1533 
1534     std::shared_ptr<AbilityLocalRecord> record = abilityRecordMgr_->GetAbilityItem(token);
1535     if (record == nullptr) {
1536         HILOG_ERROR("abilityRecord not found");
1537         return;
1538     }
1539     std::shared_ptr<AbilityInfo> abilityInfo = record->GetAbilityInfo();
1540     if (abilityInfo == nullptr) {
1541         HILOG_ERROR("record->GetAbilityInfo() failed");
1542         return;
1543     }
1544 
1545     abilityRecordMgr_->RemoveAbilityRecord(token);
1546 #ifdef APP_ABILITY_USE_TWO_RUNNER
1547     std::shared_ptr<EventRunner> runner = record->GetEventRunner();
1548     if (runner != nullptr) {
1549         int ret = runner->Stop();
1550         if (ret != ERR_OK) {
1551             HILOG_ERROR("MainThread::main failed. ability runner->Run failed ret = %{public}d", ret);
1552         }
1553         abilityRecordMgr_->RemoveAbilityRecord(token);
1554     } else {
1555         HILOG_WARN("runner not found");
1556     }
1557 #endif
1558     appMgr_->AbilityCleaned(token);
1559     HILOG_INFO("Handle clean ability end, app: %{public}s, ability: %{public}s.",
1560         applicationInfo_->name.c_str(), abilityInfo->name.c_str());
1561 }
1562 
1563 /**
1564  *
1565  * @brief Foreground the application.
1566  *
1567  */
HandleForegroundApplication()1568 void MainThread::HandleForegroundApplication()
1569 {
1570     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1571     HILOG_DEBUG("MainThread handle application to foreground called.");
1572     if ((application_ == nullptr) || (appMgr_ == nullptr)) {
1573         HILOG_ERROR("MainThread::handleForegroundApplication error!");
1574         return;
1575     }
1576 
1577     if (!applicationImpl_->PerformForeground()) {
1578         HILOG_ERROR("MainThread::handleForegroundApplication error!, applicationImpl_->PerformForeground() failed");
1579         return;
1580     }
1581 
1582     HILOG_DEBUG("to foreground success, recordId is %{public}d", applicationImpl_->GetRecordId());
1583     appMgr_->ApplicationForegrounded(applicationImpl_->GetRecordId());
1584 }
1585 
1586 /**
1587  *
1588  * @brief Background the application.
1589  *
1590  */
HandleBackgroundApplication()1591 void MainThread::HandleBackgroundApplication()
1592 {
1593     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1594     HILOG_DEBUG("MainThread::handleBackgroundApplication called start.");
1595 
1596     if ((application_ == nullptr) || (appMgr_ == nullptr)) {
1597         HILOG_ERROR("MainThread::handleBackgroundApplication error!");
1598         return;
1599     }
1600 
1601     if (!applicationImpl_->PerformBackground()) {
1602         HILOG_ERROR("MainThread::handleForegroundApplication error!, applicationImpl_->PerformBackground() failed");
1603         return;
1604     }
1605     appMgr_->ApplicationBackgrounded(applicationImpl_->GetRecordId());
1606 
1607     HILOG_DEBUG("MainThread::handleBackgroundApplication called end");
1608 }
1609 
1610 /**
1611  *
1612  * @brief Terminate the application.
1613  *
1614  */
HandleTerminateApplication()1615 void MainThread::HandleTerminateApplication()
1616 {
1617     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1618     HILOG_DEBUG("MainThread::handleTerminateApplication called start.");
1619     if ((application_ == nullptr) || (appMgr_ == nullptr)) {
1620         HILOG_ERROR("MainThread::handleTerminateApplication error!");
1621         return;
1622     }
1623 
1624     if (!applicationImpl_->PerformTerminate()) {
1625         HILOG_WARN("%{public}s: applicationImpl_->PerformTerminate() failed.", __func__);
1626     }
1627 
1628     std::shared_ptr<EventRunner> signalRunner = signalHandler_->GetEventRunner();
1629     if (signalRunner) {
1630         signalRunner->Stop();
1631     }
1632 
1633     std::shared_ptr<EventRunner> runner = mainHandler_->GetEventRunner();
1634     if (runner == nullptr) {
1635         HILOG_ERROR("MainThread::handleTerminateApplication get manHandler error");
1636         return;
1637     }
1638 
1639     if (watchdog_ != nullptr && !watchdog_->IsStopWatchdog()) {
1640         watchdog_->Stop();
1641         watchdog_ = nullptr;
1642     }
1643 
1644     int ret = runner->Stop();
1645     if (ret != ERR_OK) {
1646         HILOG_ERROR("MainThread::handleTerminateApplication failed. runner->Run failed ret = %{public}d", ret);
1647     }
1648     SetRunnerStarted(false);
1649     appMgr_->ApplicationTerminated(applicationImpl_->GetRecordId());
1650     HILOG_DEBUG("MainThread::handleTerminateApplication called end.");
1651 }
1652 
1653 /**
1654  *
1655  * @brief Shrink the memory which used by application.
1656  *
1657  * @param level Indicates the memory trim level, which shows the current memory usage status.
1658  *
1659  */
HandleShrinkMemory(const int level)1660 void MainThread::HandleShrinkMemory(const int level)
1661 {
1662     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1663     HILOG_DEBUG("MainThread::HandleShrinkMemory called start.");
1664 
1665     if (applicationImpl_ == nullptr) {
1666         HILOG_ERROR("MainThread::HandleShrinkMemory error! applicationImpl_ is null");
1667         return;
1668     }
1669 
1670     applicationImpl_->PerformMemoryLevel(level);
1671     HILOG_DEBUG("MainThread::HandleShrinkMemory called end.");
1672 }
1673 
1674 /**
1675  *
1676  * @brief Handle NotifyMemoryLevel.
1677  *
1678  * @param level Indicates the memory trim level, which shows the current memory usage status.
1679  *
1680  */
HandleMemoryLevel(int level)1681 void MainThread::HandleMemoryLevel(int level)
1682 {
1683     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1684     HILOG_DEBUG("MainThread::HandleMemoryLevel called start.");
1685 
1686     if (application_ == nullptr) {
1687         HILOG_ERROR("MainThread::HandleMemoryLevel error! application_ is null");
1688         return;
1689     }
1690 
1691     application_->OnMemoryLevel(level);
1692     HILOG_DEBUG("MainThread::HandleMemoryLevel called end.");
1693 }
1694 
1695 /**
1696  *
1697  * @brief send the new config to the application.
1698  *
1699  * @param config The updated config.
1700  *
1701  */
HandleConfigurationUpdated(const Configuration & config)1702 void MainThread::HandleConfigurationUpdated(const Configuration &config)
1703 {
1704     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1705     HILOG_DEBUG("MainThread::HandleConfigurationUpdated called start.");
1706 
1707     if (applicationImpl_ == nullptr) {
1708         HILOG_ERROR("MainThread::HandleConfigurationUpdated error! applicationImpl_ is null");
1709         return;
1710     }
1711 
1712     applicationImpl_->PerformConfigurationUpdated(config);
1713     HILOG_DEBUG("MainThread::HandleConfigurationUpdated called end.");
1714 }
1715 
TaskTimeoutDetected(const std::shared_ptr<EventRunner> & runner)1716 void MainThread::TaskTimeoutDetected(const std::shared_ptr<EventRunner> &runner)
1717 {
1718     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1719     HILOG_DEBUG("MainThread::TaskTimeoutDetected called start.");
1720 
1721     auto deliveryTimeoutCallback = []() {
1722         HILOG_DEBUG("MainThread::TaskTimeoutDetected delivery timeout");
1723     };
1724     auto distributeTimeoutCallback = []() {
1725         HILOG_DEBUG("MainThread::TaskTimeoutDetected distribute timeout");
1726     };
1727 
1728     if (runner !=nullptr && mainHandler_ != nullptr) {
1729         runner->SetDeliveryTimeout(DELIVERY_TIME);
1730         mainHandler_->SetDeliveryTimeoutCallback(deliveryTimeoutCallback);
1731 
1732         runner->SetDistributeTimeout(DISTRIBUTE_TIME);
1733         mainHandler_->SetDistributeTimeoutCallback(distributeTimeoutCallback);
1734     }
1735     HILOG_DEBUG("MainThread::TaskTimeoutDetected called end.");
1736 }
1737 
Init(const std::shared_ptr<EventRunner> & runner)1738 void MainThread::Init(const std::shared_ptr<EventRunner> &runner)
1739 {
1740     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1741     HILOG_DEBUG("MainThread:Init Start");
1742     mainHandler_ = std::make_shared<MainHandler>(runner, this);
1743     watchdog_ = std::make_shared<Watchdog>();
1744     signalHandler_ = std::make_shared<EventHandler>(EventRunner::Create(SIGNAL_HANDLER));
1745     extensionConfigMgr_ = std::make_unique<AbilityRuntime::ExtensionConfigMgr>();
1746     wptr<MainThread> weak = this;
1747     auto task = [weak]() {
1748         auto appThread = weak.promote();
1749         if (appThread == nullptr) {
1750             HILOG_ERROR("abilityThread is nullptr, SetRunnerStarted failed.");
1751             return;
1752         }
1753         appThread->SetRunnerStarted(true);
1754     };
1755     if (!mainHandler_->PostTask(task)) {
1756         HILOG_ERROR("MainThread::Init PostTask task failed");
1757     }
1758     TaskTimeoutDetected(runner);
1759 
1760     watchdog_->Init(mainHandler_);
1761     extensionConfigMgr_->Init();
1762     HILOG_DEBUG("MainThread:Init end.");
1763 }
1764 
HandleSignal(int signal)1765 void MainThread::HandleSignal(int signal)
1766 {
1767     switch (signal) {
1768         case SIGNAL_JS_HEAP: {
1769             auto heapFunc = std::bind(&MainThread::HandleDumpHeap, false);
1770             signalHandler_->PostTask(heapFunc);
1771             break;
1772         }
1773         case SIGNAL_JS_HEAP_PRIV: {
1774             auto privateHeapFunc = std::bind(&MainThread::HandleDumpHeap, true);
1775             signalHandler_->PostTask(privateHeapFunc);
1776             break;
1777         }
1778         default:
1779             break;
1780     }
1781 }
1782 
HandleDumpHeap(bool isPrivate)1783 void MainThread::HandleDumpHeap(bool isPrivate)
1784 {
1785     HILOG_DEBUG("Dump heap start.");
1786     if (mainHandler_ == nullptr) {
1787         HILOG_ERROR("HandleDumpHeap failed, mainHandler is nullptr");
1788         return;
1789     }
1790 
1791     auto task = [isPrivate] {
1792         if (applicationForDump_ == nullptr || applicationForDump_->GetRuntime() == nullptr) {
1793             HILOG_ERROR("runtime is nullptr.");
1794             return;
1795         }
1796         applicationForDump_->GetRuntime()->DumpHeapSnapshot(isPrivate);
1797     };
1798     mainHandler_->PostTask(task);
1799 }
1800 
Start()1801 void MainThread::Start()
1802 {
1803     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1804     HILOG_DEBUG("MainThread start come.");
1805     std::shared_ptr<EventRunner> runner = EventRunner::GetMainEventRunner();
1806     if (runner == nullptr) {
1807         HILOG_ERROR("MainThread::main failed, runner is nullptr");
1808         return;
1809     }
1810     sptr<MainThread> thread = sptr<MainThread>(new (std::nothrow) MainThread());
1811     if (thread == nullptr) {
1812         HILOG_ERROR("MainThread::static failed. new MainThread failed");
1813         return;
1814     }
1815 
1816     struct sigaction sigAct;
1817     sigemptyset(&sigAct.sa_mask);
1818     sigAct.sa_flags = 0;
1819     sigAct.sa_handler = &MainThread::HandleSignal;
1820     sigaction(SIGUSR1, &sigAct, NULL);
1821     sigaction(SIGNAL_JS_HEAP, &sigAct, NULL);
1822     sigaction(SIGNAL_JS_HEAP_PRIV, &sigAct, NULL);
1823 
1824     thread->Init(runner);
1825 
1826     thread->Attach();
1827 
1828     int ret = runner->Run();
1829     if (ret != ERR_OK) {
1830         HILOG_ERROR("MainThread::main failed. runner->Run failed ret = %{public}d", ret);
1831     }
1832 
1833     thread->RemoveAppMgrDeathRecipient();
1834     HILOG_DEBUG("MainThread::main runner stopped");
1835 }
1836 
MainHandler(const std::shared_ptr<EventRunner> & runner,const sptr<MainThread> & thread)1837 MainThread::MainHandler::MainHandler(const std::shared_ptr<EventRunner> &runner, const sptr<MainThread> &thread)
1838     : AppExecFwk::EventHandler(runner), mainThreadObj_(thread)
1839 {}
1840 
1841 /**
1842  *
1843  * @brief Process the event.
1844  *
1845  * @param event the event want to be processed.
1846  *
1847  */
ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer & event)1848 void MainThread::MainHandler::ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer &event)
1849 {
1850     auto eventId = event->GetInnerEventId();
1851     if (eventId == CHECK_MAIN_THREAD_IS_ALIVE) {
1852         if (mainThreadObj_ != nullptr) {
1853             mainThreadObj_->CheckMainThreadIsAlive();
1854         }
1855     }
1856 }
1857 
1858 /**
1859  *
1860  * @brief Check whether the OHOSApplication is ready.
1861  *
1862  * @return if the record is legal, return true. else return false.
1863  *
1864  */
IsApplicationReady() const1865 bool MainThread::IsApplicationReady() const
1866 {
1867     HILOG_DEBUG("MainThread::IsApplicationReady called start");
1868     if (application_ == nullptr || applicationImpl_ == nullptr) {
1869         HILOG_WARN("MainThread::IsApplicationReady called. application_=null or applicationImpl_=null");
1870         return false;
1871     }
1872 
1873     return true;
1874 }
1875 
1876 #ifdef ABILITY_LIBRARY_LOADER
1877 /**
1878  *
1879  * @brief Load the ability library.
1880  *
1881  * @param libraryPaths the library paths.
1882  *
1883  */
LoadAbilityLibrary(const std::vector<std::string> & libraryPaths)1884 void MainThread::LoadAbilityLibrary(const std::vector<std::string> &libraryPaths)
1885 {
1886     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1887 #ifdef ABILITY_LIBRARY_LOADER
1888     HILOG_DEBUG("MainThread load ability library start.");
1889 #ifdef ACEABILITY_LIBRARY_LOADER
1890     void *AceAbilityLib = nullptr;
1891     AceAbilityLib = dlopen(acelibdir.c_str(), RTLD_NOW | RTLD_GLOBAL);
1892     if (AceAbilityLib == nullptr) {
1893         HILOG_ERROR("Fail to dlopen %{public}s, [%{public}s]", acelibdir.c_str(), dlerror());
1894     } else {
1895         HILOG_DEBUG("Success to dlopen %{public}s", acelibdir.c_str());
1896         handleAbilityLib_.emplace_back(AceAbilityLib);
1897     }
1898 #endif  // ACEABILITY_LIBRARY_LOADER
1899     size_t size = libraryPaths.size();
1900     for (size_t index = 0; index < size; index++) {
1901         std::string libraryPath = libraryPaths[index];
1902         HILOG_DEBUG("Try to scanDir %{public}s", libraryPath.c_str());
1903         if (!ScanDir(libraryPath, fileEntries_)) {
1904             HILOG_WARN("scanDir %{public}s not exits", libraryPath.c_str());
1905         }
1906         libraryPath = libraryPath + "/libs";
1907         if (!ScanDir(libraryPath, fileEntries_)) {
1908             HILOG_WARN("scanDir %{public}s not exits", libraryPath.c_str());
1909         }
1910     }
1911 
1912     if (fileEntries_.empty()) {
1913         HILOG_WARN("No ability library");
1914         return;
1915     }
1916 
1917     char resolvedPath[PATH_MAX] = {0};
1918     void *handleAbilityLib = nullptr;
1919     for (const auto& fileEntry : fileEntries_) {
1920         if (fileEntry.empty() || fileEntry.size() >= PATH_MAX) {
1921             continue;
1922         }
1923         if (realpath(fileEntry.c_str(), resolvedPath) == nullptr) {
1924             HILOG_ERROR("Failed to get realpath, errno = %{public}d", errno);
1925             continue;
1926         }
1927 
1928         handleAbilityLib = dlopen(resolvedPath, RTLD_NOW | RTLD_GLOBAL);
1929         if (handleAbilityLib == nullptr) {
1930             HILOG_ERROR("Fail to dlopen %{public}s, [%{public}s]",
1931                 resolvedPath, dlerror());
1932             exit(-1);
1933         }
1934         HILOG_INFO("Success to dlopen %{public}s", fileEntry.c_str());
1935         handleAbilityLib_.emplace_back(handleAbilityLib);
1936     }
1937     HILOG_DEBUG("end.");
1938 #endif  // ABILITY_LIBRARY_LOADER
1939 }
1940 
LoadAppLibrary()1941 void MainThread::LoadAppLibrary()
1942 {
1943     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1944 #ifdef APPLICATION_LIBRARY_LOADER
1945     std::string appPath = applicationLibraryPath;
1946     HILOG_INFO("calling dlopen. appPath=%{public}s", appPath.c_str());
1947     handleAppLib_ = dlopen(appPath.c_str(), RTLD_NOW | RTLD_GLOBAL);
1948     if (handleAppLib_ == nullptr) {
1949         HILOG_ERROR("Fail to dlopen %{public}s, [%{public}s]", appPath.c_str(), dlerror());
1950         exit(-1);
1951     }
1952     HILOG_DEBUG("end.");
1953 #endif  // APPLICATION_LIBRARY_LOADER
1954 }
1955 
LoadAppDetailAbilityLibrary(std::string & nativeLibraryPath)1956 void MainThread::LoadAppDetailAbilityLibrary(std::string &nativeLibraryPath)
1957 {
1958     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1959 #ifdef ABILITY_LIBRARY_LOADER
1960     HILOG_DEBUG("LoadAppDetailAbilityLibrary try to scanDir %{public}s", nativeLibraryPath.c_str());
1961     std::vector<std::string> fileEntries;
1962     if (!ScanDir(nativeLibraryPath, fileEntries)) {
1963         HILOG_WARN("scanDir %{public}s not exits", nativeLibraryPath.c_str());
1964     }
1965     if (fileEntries.empty()) {
1966         HILOG_WARN("No ability library");
1967         return;
1968     }
1969     char resolvedPath[PATH_MAX] = {0};
1970     void *handleAbilityLib = nullptr;
1971     for (const auto& fileEntry : fileEntries) {
1972         if (fileEntry.empty() || fileEntry.size() >= PATH_MAX) {
1973             continue;
1974         }
1975         if (realpath(fileEntry.c_str(), resolvedPath) == nullptr) {
1976             HILOG_ERROR("Failed to get realpath, errno = %{public}d", errno);
1977             continue;
1978         }
1979 
1980         handleAbilityLib = dlopen(resolvedPath, RTLD_NOW | RTLD_GLOBAL);
1981         if (handleAbilityLib == nullptr) {
1982             HILOG_ERROR("Fail to dlopen %{public}s, [%{public}s]",
1983                 resolvedPath, dlerror());
1984             exit(-1);
1985         }
1986         HILOG_INFO("Success to dlopen %{public}s", fileEntry.c_str());
1987         handleAbilityLib_.emplace_back(handleAbilityLib);
1988     }
1989     HILOG_DEBUG("LoadAppDetailAbilityLibrary end.");
1990 #endif // ABILITY_LIBRARY_LOADER
1991 }
1992 
1993 /**
1994  *
1995  * @brief Close the ability library loaded.
1996  *
1997  */
CloseAbilityLibrary()1998 void MainThread::CloseAbilityLibrary()
1999 {
2000     HILOG_DEBUG("start");
2001     for (auto iter : handleAbilityLib_) {
2002         if (iter != nullptr) {
2003             dlclose(iter);
2004             iter = nullptr;
2005         }
2006     }
2007     handleAbilityLib_.clear();
2008     fileEntries_.clear();
2009     nativeFileEntries_.clear();
2010 }
2011 
ScanDir(const std::string & dirPath,std::vector<std::string> & files)2012 bool MainThread::ScanDir(const std::string &dirPath, std::vector<std::string> &files)
2013 {
2014     DIR *dirp = opendir(dirPath.c_str());
2015     if (dirp == nullptr) {
2016         HILOG_ERROR("MainThread::ScanDir open dir:%{public}s fail", dirPath.c_str());
2017         return false;
2018     }
2019     struct dirent *df = nullptr;
2020     for (;;) {
2021         df = readdir(dirp);
2022         if (df == nullptr) {
2023             break;
2024         }
2025 
2026         std::string currentName(df->d_name);
2027         if (currentName.compare(".") == 0 || currentName.compare("..") == 0) {
2028             continue;
2029         }
2030 
2031         if (CheckFileType(currentName, abilityLibraryType_)) {
2032             files.emplace_back(dirPath + pathSeparator_ + currentName);
2033         }
2034     }
2035 
2036     if (closedir(dirp) == -1) {
2037         HILOG_WARN("close dir fail");
2038     }
2039     return true;
2040 }
2041 
2042 /**
2043  *
2044  * @brief Check the fileType.
2045  *
2046  * @param fileName The fileName of the lib.
2047  * @param extensionName The extensionName of the lib.
2048  *
2049  * @return if the FileType is legal, return true. else return false.
2050  *
2051  */
CheckFileType(const std::string & fileName,const std::string & extensionName)2052 bool MainThread::CheckFileType(const std::string &fileName, const std::string &extensionName)
2053 {
2054     HILOG_DEBUG("MainThread::CheckFileType path is %{public}s, support suffix is %{public}s",
2055         fileName.c_str(),
2056         extensionName.c_str());
2057 
2058     if (fileName.empty()) {
2059         HILOG_ERROR("the file name is empty");
2060         return false;
2061     }
2062 
2063     auto position = fileName.rfind('.');
2064     if (position == std::string::npos) {
2065         HILOG_WARN("filename no extension name");
2066         return false;
2067     }
2068 
2069     std::string suffixStr = fileName.substr(position);
2070     return LowerStr(suffixStr) == extensionName;
2071 }
2072 
HandleScheduleAcceptWant(const AAFwk::Want & want,const std::string & moduleName)2073 void MainThread::HandleScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName)
2074 {
2075     HILOG_DEBUG("MainThread::HandleScheduleAcceptWant");
2076     if (!application_) {
2077         HILOG_ERROR("application_ is nullptr");
2078         return;
2079     }
2080 
2081     std::string specifiedFlag;
2082     application_->ScheduleAcceptWant(want, moduleName, specifiedFlag);
2083 
2084     if (!appMgr_ || !applicationImpl_) {
2085         HILOG_ERROR("appMgr_ is nullptr");
2086         return;
2087     }
2088 
2089     appMgr_->ScheduleAcceptWantDone(applicationImpl_->GetRecordId(), want, specifiedFlag);
2090 }
2091 
ScheduleAcceptWant(const AAFwk::Want & want,const std::string & moduleName)2092 void MainThread::ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName)
2093 {
2094     HILOG_DEBUG("start");
2095     wptr<MainThread> weak = this;
2096     auto task = [weak, want, moduleName]() {
2097         auto appThread = weak.promote();
2098         if (appThread == nullptr) {
2099             HILOG_ERROR("abilityThread is nullptr, HandleScheduleAcceptWant failed.");
2100             return;
2101         }
2102         appThread->HandleScheduleAcceptWant(want, moduleName);
2103     };
2104     if (!mainHandler_->PostTask(task)) {
2105         HILOG_ERROR("PostTask task failed");
2106     }
2107     HILOG_DEBUG("end.");
2108 }
2109 
CheckMainThreadIsAlive()2110 void MainThread::CheckMainThreadIsAlive()
2111 {
2112     watchdog_->SetAppMainThreadState(true);
2113     watchdog_->AllowReportEvent();
2114 }
2115 #endif  // ABILITY_LIBRARY_LOADER
2116 
ScheduleNotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback,const int32_t recordId)2117 int32_t MainThread::ScheduleNotifyLoadRepairPatch(const std::string &bundleName,
2118     const sptr<IQuickFixCallback> &callback, const int32_t recordId)
2119 {
2120     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2121     HILOG_DEBUG("ScheduleNotifyLoadRepairPatch function called.");
2122     wptr<MainThread> weak = this;
2123     auto task = [weak, bundleName, callback, recordId]() {
2124         auto appThread = weak.promote();
2125         if (appThread == nullptr || appThread->application_ == nullptr || callback == nullptr) {
2126             HILOG_ERROR("ScheduleNotifyLoadRepairPatch, parameter is nullptr.");
2127             return;
2128         }
2129 
2130         bool ret = true;
2131         std::vector<std::pair<std::string, std::string>> hqfFilePair;
2132         if (appThread->GetHqfFileAndHapPath(bundleName, hqfFilePair)) {
2133             for (auto it = hqfFilePair.begin(); it != hqfFilePair.end(); it++) {
2134                 HILOG_INFO("ScheduleNotifyLoadRepairPatch, LoadPatch, hqfFile: %{private}s, hapPath: %{private}s.",
2135                     it->first.c_str(), it->second.c_str());
2136                 ret = appThread->application_->NotifyLoadRepairPatch(it->first, it->second);
2137             }
2138         } else {
2139             HILOG_DEBUG("ScheduleNotifyLoadRepairPatch, There's no hqfFile need to load.");
2140         }
2141 
2142         callback->OnLoadPatchDone(ret ? NO_ERROR : ERR_INVALID_OPERATION, recordId);
2143     };
2144     if (mainHandler_ == nullptr || !mainHandler_->PostTask(task)) {
2145         HILOG_ERROR("ScheduleNotifyLoadRepairPatch, Post task failed.");
2146         return ERR_INVALID_VALUE;
2147     }
2148 
2149     return NO_ERROR;
2150 }
2151 
ScheduleNotifyHotReloadPage(const sptr<IQuickFixCallback> & callback,const int32_t recordId)2152 int32_t MainThread::ScheduleNotifyHotReloadPage(const sptr<IQuickFixCallback> &callback, const int32_t recordId)
2153 {
2154     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2155     HILOG_DEBUG("function called.");
2156     wptr<MainThread> weak = this;
2157     auto task = [weak, callback, recordId]() {
2158         auto appThread = weak.promote();
2159         if (appThread == nullptr || appThread->application_ == nullptr || callback == nullptr) {
2160             HILOG_ERROR("parameter is nullptr.");
2161             return;
2162         }
2163         auto ret = appThread->application_->NotifyHotReloadPage();
2164         callback->OnReloadPageDone(ret ? NO_ERROR : ERR_INVALID_OPERATION, recordId);
2165     };
2166     if (mainHandler_ == nullptr || !mainHandler_->PostTask(task)) {
2167         HILOG_ERROR("Post task failed.");
2168         return ERR_INVALID_VALUE;
2169     }
2170 
2171     return NO_ERROR;
2172 }
2173 
GetHqfFileAndHapPath(const std::string & bundleName,std::vector<std::pair<std::string,std::string>> & fileMap)2174 bool MainThread::GetHqfFileAndHapPath(const std::string &bundleName,
2175     std::vector<std::pair<std::string, std::string>> &fileMap)
2176 {
2177     HILOG_DEBUG("function called.");
2178     auto bundleObj = DelayedSingleton<SysMrgClient>::GetInstance()->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
2179     if (bundleObj == nullptr) {
2180         HILOG_ERROR("Failed to get bundle manager service.");
2181         return false;
2182     }
2183 
2184     sptr<IBundleMgr> bundleMgr = iface_cast<IBundleMgr>(bundleObj);
2185     if (bundleMgr == nullptr) {
2186         HILOG_ERROR("Bundle manager is nullptr.");
2187         return false;
2188     }
2189 
2190     BundleInfo bundleInfo;
2191     if (bundleMgr->GetBundleInfoForSelf(
2192         (static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) +
2193         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY) +
2194         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) +
2195         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE) +
2196         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) +
2197         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) +
2198         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_METADATA)), bundleInfo) != ERR_OK) {
2199         HILOG_ERROR("Get bundle info of %{public}s failed.", bundleName.c_str());
2200         return false;
2201     }
2202 
2203     for (auto hapInfo : bundleInfo.hapModuleInfos) {
2204         if ((processInfo_ != nullptr) && (processInfo_->GetProcessName() == hapInfo.process) &&
2205             (!hapInfo.hqfInfo.hqfFilePath.empty())) {
2206             std::string resolvedHapPath;
2207             std::string hapPath = AbilityRuntime::GetLoadPath(hapInfo.hapPath);
2208             auto position = hapPath.rfind('/');
2209             if (position != std::string::npos) {
2210                 resolvedHapPath = hapPath.erase(position) + FILE_SEPARATOR + hapInfo.moduleName;
2211             }
2212             std::string resolvedHqfFile(AbilityRuntime::GetLoadPath(hapInfo.hqfInfo.hqfFilePath));
2213             HILOG_INFO("bundleName: %{public}s, moduleName: %{public}s, processName: %{private}s, "
2214                 "hqf file: %{private}s, hap path: %{private}s.", bundleName.c_str(), hapInfo.moduleName.c_str(),
2215                 hapInfo.process.c_str(), resolvedHqfFile.c_str(), resolvedHapPath.c_str());
2216             fileMap.push_back(std::pair<std::string, std::string>(resolvedHqfFile, resolvedHapPath));
2217         }
2218     }
2219 
2220     return true;
2221 }
2222 
ScheduleNotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback,const int32_t recordId)2223 int32_t MainThread::ScheduleNotifyUnLoadRepairPatch(const std::string &bundleName,
2224     const sptr<IQuickFixCallback> &callback, const int32_t recordId)
2225 {
2226     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2227     HILOG_DEBUG("ScheduleNotifyUnLoadRepairPatch function called.");
2228     wptr<MainThread> weak = this;
2229     auto task = [weak, bundleName, callback, recordId]() {
2230         auto appThread = weak.promote();
2231         if (appThread == nullptr || appThread->application_ == nullptr || callback == nullptr) {
2232             HILOG_ERROR("ScheduleNotifyUnLoadRepairPatch, parameter is nullptr.");
2233             return;
2234         }
2235 
2236         bool ret = true;
2237         std::vector<std::pair<std::string, std::string>> hqfFilePair;
2238         if (appThread->GetHqfFileAndHapPath(bundleName, hqfFilePair)) {
2239             for (auto it = hqfFilePair.begin(); it != hqfFilePair.end(); it++) {
2240                 HILOG_INFO("ScheduleNotifyUnLoadRepairPatch, UnloadPatch, hqfFile: %{private}s.", it->first.c_str());
2241                 ret = appThread->application_->NotifyUnLoadRepairPatch(it->first);
2242             }
2243         } else {
2244             HILOG_DEBUG("ScheduleNotifyUnLoadRepairPatch, There's no hqfFile need to unload.");
2245         }
2246 
2247         callback->OnUnloadPatchDone(ret ? NO_ERROR : ERR_INVALID_OPERATION, recordId);
2248     };
2249     if (mainHandler_ == nullptr || !mainHandler_->PostTask(task)) {
2250         HILOG_ERROR("ScheduleNotifyUnLoadRepairPatch, Post task failed.");
2251         return ERR_INVALID_VALUE;
2252     }
2253 
2254     return NO_ERROR;
2255 }
2256 
UpdateProcessExtensionType(const std::shared_ptr<AbilityLocalRecord> & abilityRecord)2257 void MainThread::UpdateProcessExtensionType(const std::shared_ptr<AbilityLocalRecord> &abilityRecord)
2258 {
2259     auto &runtime = application_->GetRuntime();
2260     if (!runtime) {
2261         HILOG_ERROR("Get runtime failed");
2262         return;
2263     }
2264     if (!abilityRecord) {
2265         HILOG_ERROR("abilityRecord is nullptr");
2266         return;
2267     }
2268     auto &abilityInfo = abilityRecord->GetAbilityInfo();
2269     if (!abilityInfo) {
2270         HILOG_ERROR("Get abilityInfo failed");
2271         return;
2272     }
2273     runtime->UpdateExtensionType(static_cast<int32_t>(abilityInfo->extensionAbilityType));
2274     HILOG_INFO("UpdateExtensionType, type = %{public}d", static_cast<int32_t>(abilityInfo->extensionAbilityType));
2275 }
2276 
AddExtensionBlockItem(const std::string & extensionName,int32_t type)2277 void MainThread::AddExtensionBlockItem(const std::string &extensionName, int32_t type)
2278 {
2279     if (!extensionConfigMgr_) {
2280         return;
2281     }
2282     extensionConfigMgr_->AddBlockListItem(extensionName, type);
2283 }
2284 
UpdateEngineExtensionBlockList(NativeEngine & nativeEngine)2285 void MainThread::UpdateEngineExtensionBlockList(NativeEngine &nativeEngine)
2286 {
2287     if (!extensionConfigMgr_) {
2288         return;
2289     }
2290     extensionConfigMgr_->UpdateBlockListToEngine(nativeEngine);
2291 }
2292 }  // namespace AppExecFwk
2293 }  // namespace OHOS
2294