• 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     application_->CleanAbilityStage(token, abilityInfo);
1499 #ifdef APP_ABILITY_USE_TWO_RUNNER
1500     std::shared_ptr<EventRunner> runner = record->GetEventRunner();
1501     if (runner != nullptr) {
1502         int ret = runner->Stop();
1503         if (ret != ERR_OK) {
1504             HILOG_ERROR("MainThread::main failed. ability runner->Run failed ret = %{public}d", ret);
1505         }
1506         abilityRecordMgr_->RemoveAbilityRecord(token);
1507         application_->CleanAbilityStage(token, abilityInfo);
1508     } else {
1509         HILOG_WARN("runner not found");
1510     }
1511 #endif
1512     HILOG_DEBUG("end.");
1513 }
1514 
1515 /**
1516  *
1517  * @brief Clean the ability.
1518  *
1519  * @param token The token which belongs to the ability launched.
1520  *
1521  */
HandleCleanAbility(const sptr<IRemoteObject> & token)1522 void MainThread::HandleCleanAbility(const sptr<IRemoteObject> &token)
1523 {
1524     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1525     HILOG_DEBUG("Handle clean ability start, app is %{public}s.", applicationInfo_->name.c_str());
1526     if (!IsApplicationReady()) {
1527         HILOG_ERROR("not init OHOSApplication, should launch application first");
1528         return;
1529     }
1530 
1531     if (token == nullptr) {
1532         HILOG_ERROR("token is null");
1533         return;
1534     }
1535 
1536     std::shared_ptr<AbilityLocalRecord> record = abilityRecordMgr_->GetAbilityItem(token);
1537     if (record == nullptr) {
1538         HILOG_ERROR("abilityRecord not found");
1539         return;
1540     }
1541     std::shared_ptr<AbilityInfo> abilityInfo = record->GetAbilityInfo();
1542     if (abilityInfo == nullptr) {
1543         HILOG_ERROR("record->GetAbilityInfo() failed");
1544         return;
1545     }
1546 
1547     abilityRecordMgr_->RemoveAbilityRecord(token);
1548     application_->CleanAbilityStage(token, abilityInfo);
1549 #ifdef APP_ABILITY_USE_TWO_RUNNER
1550     std::shared_ptr<EventRunner> runner = record->GetEventRunner();
1551     if (runner != nullptr) {
1552         int ret = runner->Stop();
1553         if (ret != ERR_OK) {
1554             HILOG_ERROR("MainThread::main failed. ability runner->Run failed ret = %{public}d", ret);
1555         }
1556         abilityRecordMgr_->RemoveAbilityRecord(token);
1557         application_->CleanAbilityStage(token, abilityInfo);
1558     } else {
1559         HILOG_WARN("runner not found");
1560     }
1561 #endif
1562     appMgr_->AbilityCleaned(token);
1563     HILOG_INFO("Handle clean ability end, app: %{public}s, ability: %{public}s.",
1564         applicationInfo_->name.c_str(), abilityInfo->name.c_str());
1565 }
1566 
1567 /**
1568  *
1569  * @brief Foreground the application.
1570  *
1571  */
HandleForegroundApplication()1572 void MainThread::HandleForegroundApplication()
1573 {
1574     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1575     HILOG_DEBUG("MainThread handle application to foreground called.");
1576     if ((application_ == nullptr) || (appMgr_ == nullptr)) {
1577         HILOG_ERROR("MainThread::handleForegroundApplication error!");
1578         return;
1579     }
1580 
1581     if (!applicationImpl_->PerformForeground()) {
1582         HILOG_ERROR("MainThread::handleForegroundApplication error!, applicationImpl_->PerformForeground() failed");
1583         return;
1584     }
1585 
1586     HILOG_DEBUG("to foreground success, recordId is %{public}d", applicationImpl_->GetRecordId());
1587     appMgr_->ApplicationForegrounded(applicationImpl_->GetRecordId());
1588 }
1589 
1590 /**
1591  *
1592  * @brief Background the application.
1593  *
1594  */
HandleBackgroundApplication()1595 void MainThread::HandleBackgroundApplication()
1596 {
1597     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1598     HILOG_DEBUG("MainThread::handleBackgroundApplication called start.");
1599 
1600     if ((application_ == nullptr) || (appMgr_ == nullptr)) {
1601         HILOG_ERROR("MainThread::handleBackgroundApplication error!");
1602         return;
1603     }
1604 
1605     if (!applicationImpl_->PerformBackground()) {
1606         HILOG_ERROR("MainThread::handleForegroundApplication error!, applicationImpl_->PerformBackground() failed");
1607         return;
1608     }
1609     appMgr_->ApplicationBackgrounded(applicationImpl_->GetRecordId());
1610 
1611     HILOG_DEBUG("MainThread::handleBackgroundApplication called end");
1612 }
1613 
1614 /**
1615  *
1616  * @brief Terminate the application.
1617  *
1618  */
HandleTerminateApplication()1619 void MainThread::HandleTerminateApplication()
1620 {
1621     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1622     HILOG_DEBUG("MainThread::handleTerminateApplication called start.");
1623     if ((application_ == nullptr) || (appMgr_ == nullptr)) {
1624         HILOG_ERROR("MainThread::handleTerminateApplication error!");
1625         return;
1626     }
1627 
1628     if (!applicationImpl_->PerformTerminate()) {
1629         HILOG_WARN("%{public}s: applicationImpl_->PerformTerminate() failed.", __func__);
1630     }
1631 
1632     std::shared_ptr<EventRunner> signalRunner = signalHandler_->GetEventRunner();
1633     if (signalRunner) {
1634         signalRunner->Stop();
1635     }
1636 
1637     std::shared_ptr<EventRunner> runner = mainHandler_->GetEventRunner();
1638     if (runner == nullptr) {
1639         HILOG_ERROR("MainThread::handleTerminateApplication get manHandler error");
1640         return;
1641     }
1642 
1643     if (watchdog_ != nullptr && !watchdog_->IsStopWatchdog()) {
1644         watchdog_->Stop();
1645         watchdog_ = nullptr;
1646     }
1647 
1648     int ret = runner->Stop();
1649     if (ret != ERR_OK) {
1650         HILOG_ERROR("MainThread::handleTerminateApplication failed. runner->Run failed ret = %{public}d", ret);
1651     }
1652     SetRunnerStarted(false);
1653     appMgr_->ApplicationTerminated(applicationImpl_->GetRecordId());
1654     HILOG_DEBUG("MainThread::handleTerminateApplication called end.");
1655 }
1656 
1657 /**
1658  *
1659  * @brief Shrink the memory which used by application.
1660  *
1661  * @param level Indicates the memory trim level, which shows the current memory usage status.
1662  *
1663  */
HandleShrinkMemory(const int level)1664 void MainThread::HandleShrinkMemory(const int level)
1665 {
1666     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1667     HILOG_DEBUG("MainThread::HandleShrinkMemory called start.");
1668 
1669     if (applicationImpl_ == nullptr) {
1670         HILOG_ERROR("MainThread::HandleShrinkMemory error! applicationImpl_ is null");
1671         return;
1672     }
1673 
1674     applicationImpl_->PerformMemoryLevel(level);
1675     HILOG_DEBUG("MainThread::HandleShrinkMemory called end.");
1676 }
1677 
1678 /**
1679  *
1680  * @brief Handle NotifyMemoryLevel.
1681  *
1682  * @param level Indicates the memory trim level, which shows the current memory usage status.
1683  *
1684  */
HandleMemoryLevel(int level)1685 void MainThread::HandleMemoryLevel(int level)
1686 {
1687     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1688     HILOG_DEBUG("MainThread::HandleMemoryLevel called start.");
1689 
1690     if (application_ == nullptr) {
1691         HILOG_ERROR("MainThread::HandleMemoryLevel error! application_ is null");
1692         return;
1693     }
1694 
1695     application_->OnMemoryLevel(level);
1696     HILOG_DEBUG("MainThread::HandleMemoryLevel called end.");
1697 }
1698 
1699 /**
1700  *
1701  * @brief send the new config to the application.
1702  *
1703  * @param config The updated config.
1704  *
1705  */
HandleConfigurationUpdated(const Configuration & config)1706 void MainThread::HandleConfigurationUpdated(const Configuration &config)
1707 {
1708     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1709     HILOG_DEBUG("MainThread::HandleConfigurationUpdated called start.");
1710 
1711     if (applicationImpl_ == nullptr) {
1712         HILOG_ERROR("MainThread::HandleConfigurationUpdated error! applicationImpl_ is null");
1713         return;
1714     }
1715 
1716     applicationImpl_->PerformConfigurationUpdated(config);
1717     HILOG_DEBUG("MainThread::HandleConfigurationUpdated called end.");
1718 }
1719 
TaskTimeoutDetected(const std::shared_ptr<EventRunner> & runner)1720 void MainThread::TaskTimeoutDetected(const std::shared_ptr<EventRunner> &runner)
1721 {
1722     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1723     HILOG_DEBUG("MainThread::TaskTimeoutDetected called start.");
1724 
1725     auto deliveryTimeoutCallback = []() {
1726         HILOG_DEBUG("MainThread::TaskTimeoutDetected delivery timeout");
1727     };
1728     auto distributeTimeoutCallback = []() {
1729         HILOG_DEBUG("MainThread::TaskTimeoutDetected distribute timeout");
1730     };
1731 
1732     if (runner !=nullptr && mainHandler_ != nullptr) {
1733         runner->SetDeliveryTimeout(DELIVERY_TIME);
1734         mainHandler_->SetDeliveryTimeoutCallback(deliveryTimeoutCallback);
1735 
1736         runner->SetDistributeTimeout(DISTRIBUTE_TIME);
1737         mainHandler_->SetDistributeTimeoutCallback(distributeTimeoutCallback);
1738     }
1739     HILOG_DEBUG("MainThread::TaskTimeoutDetected called end.");
1740 }
1741 
Init(const std::shared_ptr<EventRunner> & runner)1742 void MainThread::Init(const std::shared_ptr<EventRunner> &runner)
1743 {
1744     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1745     HILOG_DEBUG("MainThread:Init Start");
1746     mainHandler_ = std::make_shared<MainHandler>(runner, this);
1747     watchdog_ = std::make_shared<Watchdog>();
1748     signalHandler_ = std::make_shared<EventHandler>(EventRunner::Create(SIGNAL_HANDLER));
1749     extensionConfigMgr_ = std::make_unique<AbilityRuntime::ExtensionConfigMgr>();
1750     wptr<MainThread> weak = this;
1751     auto task = [weak]() {
1752         auto appThread = weak.promote();
1753         if (appThread == nullptr) {
1754             HILOG_ERROR("abilityThread is nullptr, SetRunnerStarted failed.");
1755             return;
1756         }
1757         appThread->SetRunnerStarted(true);
1758     };
1759     if (!mainHandler_->PostTask(task)) {
1760         HILOG_ERROR("MainThread::Init PostTask task failed");
1761     }
1762     TaskTimeoutDetected(runner);
1763 
1764     watchdog_->Init(mainHandler_);
1765     extensionConfigMgr_->Init();
1766     HILOG_DEBUG("MainThread:Init end.");
1767 }
1768 
HandleSignal(int signal)1769 void MainThread::HandleSignal(int signal)
1770 {
1771     switch (signal) {
1772         case SIGNAL_JS_HEAP: {
1773             auto heapFunc = std::bind(&MainThread::HandleDumpHeap, false);
1774             signalHandler_->PostTask(heapFunc);
1775             break;
1776         }
1777         case SIGNAL_JS_HEAP_PRIV: {
1778             auto privateHeapFunc = std::bind(&MainThread::HandleDumpHeap, true);
1779             signalHandler_->PostTask(privateHeapFunc);
1780             break;
1781         }
1782         default:
1783             break;
1784     }
1785 }
1786 
HandleDumpHeap(bool isPrivate)1787 void MainThread::HandleDumpHeap(bool isPrivate)
1788 {
1789     HILOG_DEBUG("Dump heap start.");
1790     if (mainHandler_ == nullptr) {
1791         HILOG_ERROR("HandleDumpHeap failed, mainHandler is nullptr");
1792         return;
1793     }
1794 
1795     auto task = [isPrivate] {
1796         if (applicationForDump_ == nullptr || applicationForDump_->GetRuntime() == nullptr) {
1797             HILOG_ERROR("runtime is nullptr.");
1798             return;
1799         }
1800         applicationForDump_->GetRuntime()->DumpHeapSnapshot(isPrivate);
1801     };
1802     mainHandler_->PostTask(task);
1803 }
1804 
Start()1805 void MainThread::Start()
1806 {
1807     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1808     HILOG_DEBUG("MainThread start come.");
1809     std::shared_ptr<EventRunner> runner = EventRunner::GetMainEventRunner();
1810     if (runner == nullptr) {
1811         HILOG_ERROR("MainThread::main failed, runner is nullptr");
1812         return;
1813     }
1814     sptr<MainThread> thread = sptr<MainThread>(new (std::nothrow) MainThread());
1815     if (thread == nullptr) {
1816         HILOG_ERROR("MainThread::static failed. new MainThread failed");
1817         return;
1818     }
1819 
1820     struct sigaction sigAct;
1821     sigemptyset(&sigAct.sa_mask);
1822     sigAct.sa_flags = 0;
1823     sigAct.sa_handler = &MainThread::HandleSignal;
1824     sigaction(SIGUSR1, &sigAct, NULL);
1825     sigaction(SIGNAL_JS_HEAP, &sigAct, NULL);
1826     sigaction(SIGNAL_JS_HEAP_PRIV, &sigAct, NULL);
1827 
1828     thread->Init(runner);
1829 
1830     thread->Attach();
1831 
1832     int ret = runner->Run();
1833     if (ret != ERR_OK) {
1834         HILOG_ERROR("MainThread::main failed. runner->Run failed ret = %{public}d", ret);
1835     }
1836 
1837     thread->RemoveAppMgrDeathRecipient();
1838     HILOG_DEBUG("MainThread::main runner stopped");
1839 }
1840 
MainHandler(const std::shared_ptr<EventRunner> & runner,const sptr<MainThread> & thread)1841 MainThread::MainHandler::MainHandler(const std::shared_ptr<EventRunner> &runner, const sptr<MainThread> &thread)
1842     : AppExecFwk::EventHandler(runner), mainThreadObj_(thread)
1843 {}
1844 
1845 /**
1846  *
1847  * @brief Process the event.
1848  *
1849  * @param event the event want to be processed.
1850  *
1851  */
ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer & event)1852 void MainThread::MainHandler::ProcessEvent(const OHOS::AppExecFwk::InnerEvent::Pointer &event)
1853 {
1854     auto eventId = event->GetInnerEventId();
1855     if (eventId == CHECK_MAIN_THREAD_IS_ALIVE) {
1856         if (mainThreadObj_ != nullptr) {
1857             mainThreadObj_->CheckMainThreadIsAlive();
1858         }
1859     }
1860 }
1861 
1862 /**
1863  *
1864  * @brief Check whether the OHOSApplication is ready.
1865  *
1866  * @return if the record is legal, return true. else return false.
1867  *
1868  */
IsApplicationReady() const1869 bool MainThread::IsApplicationReady() const
1870 {
1871     HILOG_DEBUG("MainThread::IsApplicationReady called start");
1872     if (application_ == nullptr || applicationImpl_ == nullptr) {
1873         HILOG_WARN("MainThread::IsApplicationReady called. application_=null or applicationImpl_=null");
1874         return false;
1875     }
1876 
1877     return true;
1878 }
1879 
1880 #ifdef ABILITY_LIBRARY_LOADER
1881 /**
1882  *
1883  * @brief Load the ability library.
1884  *
1885  * @param libraryPaths the library paths.
1886  *
1887  */
LoadAbilityLibrary(const std::vector<std::string> & libraryPaths)1888 void MainThread::LoadAbilityLibrary(const std::vector<std::string> &libraryPaths)
1889 {
1890     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1891 #ifdef ABILITY_LIBRARY_LOADER
1892     HILOG_DEBUG("MainThread load ability library start.");
1893 #ifdef ACEABILITY_LIBRARY_LOADER
1894     void *AceAbilityLib = nullptr;
1895     AceAbilityLib = dlopen(acelibdir.c_str(), RTLD_NOW | RTLD_GLOBAL);
1896     if (AceAbilityLib == nullptr) {
1897         HILOG_ERROR("Fail to dlopen %{public}s, [%{public}s]", acelibdir.c_str(), dlerror());
1898     } else {
1899         HILOG_DEBUG("Success to dlopen %{public}s", acelibdir.c_str());
1900         handleAbilityLib_.emplace_back(AceAbilityLib);
1901     }
1902 #endif  // ACEABILITY_LIBRARY_LOADER
1903     size_t size = libraryPaths.size();
1904     for (size_t index = 0; index < size; index++) {
1905         std::string libraryPath = libraryPaths[index];
1906         HILOG_DEBUG("Try to scanDir %{public}s", libraryPath.c_str());
1907         if (!ScanDir(libraryPath, fileEntries_)) {
1908             HILOG_WARN("scanDir %{public}s not exits", libraryPath.c_str());
1909         }
1910         libraryPath = libraryPath + "/libs";
1911         if (!ScanDir(libraryPath, fileEntries_)) {
1912             HILOG_WARN("scanDir %{public}s not exits", libraryPath.c_str());
1913         }
1914     }
1915 
1916     if (fileEntries_.empty()) {
1917         HILOG_WARN("No ability library");
1918         return;
1919     }
1920 
1921     char resolvedPath[PATH_MAX] = {0};
1922     void *handleAbilityLib = nullptr;
1923     for (const auto& fileEntry : fileEntries_) {
1924         if (fileEntry.empty() || fileEntry.size() >= PATH_MAX) {
1925             continue;
1926         }
1927         if (realpath(fileEntry.c_str(), resolvedPath) == nullptr) {
1928             HILOG_ERROR("Failed to get realpath, errno = %{public}d", errno);
1929             continue;
1930         }
1931 
1932         handleAbilityLib = dlopen(resolvedPath, RTLD_NOW | RTLD_GLOBAL);
1933         if (handleAbilityLib == nullptr) {
1934             HILOG_ERROR("Fail to dlopen %{public}s, [%{public}s]",
1935                 resolvedPath, dlerror());
1936             exit(-1);
1937         }
1938         HILOG_INFO("Success to dlopen %{public}s", fileEntry.c_str());
1939         handleAbilityLib_.emplace_back(handleAbilityLib);
1940     }
1941     HILOG_DEBUG("end.");
1942 #endif  // ABILITY_LIBRARY_LOADER
1943 }
1944 
LoadAppLibrary()1945 void MainThread::LoadAppLibrary()
1946 {
1947     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1948 #ifdef APPLICATION_LIBRARY_LOADER
1949     std::string appPath = applicationLibraryPath;
1950     HILOG_INFO("calling dlopen. appPath=%{public}s", appPath.c_str());
1951     handleAppLib_ = dlopen(appPath.c_str(), RTLD_NOW | RTLD_GLOBAL);
1952     if (handleAppLib_ == nullptr) {
1953         HILOG_ERROR("Fail to dlopen %{public}s, [%{public}s]", appPath.c_str(), dlerror());
1954         exit(-1);
1955     }
1956     HILOG_DEBUG("end.");
1957 #endif  // APPLICATION_LIBRARY_LOADER
1958 }
1959 
LoadAppDetailAbilityLibrary(std::string & nativeLibraryPath)1960 void MainThread::LoadAppDetailAbilityLibrary(std::string &nativeLibraryPath)
1961 {
1962     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1963 #ifdef ABILITY_LIBRARY_LOADER
1964     HILOG_DEBUG("LoadAppDetailAbilityLibrary try to scanDir %{public}s", nativeLibraryPath.c_str());
1965     std::vector<std::string> fileEntries;
1966     if (!ScanDir(nativeLibraryPath, fileEntries)) {
1967         HILOG_WARN("scanDir %{public}s not exits", nativeLibraryPath.c_str());
1968     }
1969     if (fileEntries.empty()) {
1970         HILOG_WARN("No ability library");
1971         return;
1972     }
1973     char resolvedPath[PATH_MAX] = {0};
1974     void *handleAbilityLib = nullptr;
1975     for (const auto& fileEntry : fileEntries) {
1976         if (fileEntry.empty() || fileEntry.size() >= PATH_MAX) {
1977             continue;
1978         }
1979         if (realpath(fileEntry.c_str(), resolvedPath) == nullptr) {
1980             HILOG_ERROR("Failed to get realpath, errno = %{public}d", errno);
1981             continue;
1982         }
1983 
1984         handleAbilityLib = dlopen(resolvedPath, RTLD_NOW | RTLD_GLOBAL);
1985         if (handleAbilityLib == nullptr) {
1986             HILOG_ERROR("Fail to dlopen %{public}s, [%{public}s]",
1987                 resolvedPath, dlerror());
1988             exit(-1);
1989         }
1990         HILOG_INFO("Success to dlopen %{public}s", fileEntry.c_str());
1991         handleAbilityLib_.emplace_back(handleAbilityLib);
1992     }
1993     HILOG_DEBUG("LoadAppDetailAbilityLibrary end.");
1994 #endif // ABILITY_LIBRARY_LOADER
1995 }
1996 
1997 /**
1998  *
1999  * @brief Close the ability library loaded.
2000  *
2001  */
CloseAbilityLibrary()2002 void MainThread::CloseAbilityLibrary()
2003 {
2004     HILOG_DEBUG("start");
2005     for (auto iter : handleAbilityLib_) {
2006         if (iter != nullptr) {
2007             dlclose(iter);
2008             iter = nullptr;
2009         }
2010     }
2011     handleAbilityLib_.clear();
2012     fileEntries_.clear();
2013     nativeFileEntries_.clear();
2014 }
2015 
ScanDir(const std::string & dirPath,std::vector<std::string> & files)2016 bool MainThread::ScanDir(const std::string &dirPath, std::vector<std::string> &files)
2017 {
2018     DIR *dirp = opendir(dirPath.c_str());
2019     if (dirp == nullptr) {
2020         HILOG_ERROR("MainThread::ScanDir open dir:%{public}s fail", dirPath.c_str());
2021         return false;
2022     }
2023     struct dirent *df = nullptr;
2024     for (;;) {
2025         df = readdir(dirp);
2026         if (df == nullptr) {
2027             break;
2028         }
2029 
2030         std::string currentName(df->d_name);
2031         if (currentName.compare(".") == 0 || currentName.compare("..") == 0) {
2032             continue;
2033         }
2034 
2035         if (CheckFileType(currentName, abilityLibraryType_)) {
2036             files.emplace_back(dirPath + pathSeparator_ + currentName);
2037         }
2038     }
2039 
2040     if (closedir(dirp) == -1) {
2041         HILOG_WARN("close dir fail");
2042     }
2043     return true;
2044 }
2045 
2046 /**
2047  *
2048  * @brief Check the fileType.
2049  *
2050  * @param fileName The fileName of the lib.
2051  * @param extensionName The extensionName of the lib.
2052  *
2053  * @return if the FileType is legal, return true. else return false.
2054  *
2055  */
CheckFileType(const std::string & fileName,const std::string & extensionName)2056 bool MainThread::CheckFileType(const std::string &fileName, const std::string &extensionName)
2057 {
2058     HILOG_DEBUG("MainThread::CheckFileType path is %{public}s, support suffix is %{public}s",
2059         fileName.c_str(),
2060         extensionName.c_str());
2061 
2062     if (fileName.empty()) {
2063         HILOG_ERROR("the file name is empty");
2064         return false;
2065     }
2066 
2067     auto position = fileName.rfind('.');
2068     if (position == std::string::npos) {
2069         HILOG_WARN("filename no extension name");
2070         return false;
2071     }
2072 
2073     std::string suffixStr = fileName.substr(position);
2074     return LowerStr(suffixStr) == extensionName;
2075 }
2076 
HandleScheduleAcceptWant(const AAFwk::Want & want,const std::string & moduleName)2077 void MainThread::HandleScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName)
2078 {
2079     HILOG_DEBUG("MainThread::HandleScheduleAcceptWant");
2080     if (!application_) {
2081         HILOG_ERROR("application_ is nullptr");
2082         return;
2083     }
2084 
2085     std::string specifiedFlag;
2086     application_->ScheduleAcceptWant(want, moduleName, specifiedFlag);
2087 
2088     if (!appMgr_ || !applicationImpl_) {
2089         HILOG_ERROR("appMgr_ is nullptr");
2090         return;
2091     }
2092 
2093     appMgr_->ScheduleAcceptWantDone(applicationImpl_->GetRecordId(), want, specifiedFlag);
2094 }
2095 
ScheduleAcceptWant(const AAFwk::Want & want,const std::string & moduleName)2096 void MainThread::ScheduleAcceptWant(const AAFwk::Want &want, const std::string &moduleName)
2097 {
2098     HILOG_DEBUG("start");
2099     wptr<MainThread> weak = this;
2100     auto task = [weak, want, moduleName]() {
2101         auto appThread = weak.promote();
2102         if (appThread == nullptr) {
2103             HILOG_ERROR("abilityThread is nullptr, HandleScheduleAcceptWant failed.");
2104             return;
2105         }
2106         appThread->HandleScheduleAcceptWant(want, moduleName);
2107     };
2108     if (!mainHandler_->PostTask(task)) {
2109         HILOG_ERROR("PostTask task failed");
2110     }
2111     HILOG_DEBUG("end.");
2112 }
2113 
CheckMainThreadIsAlive()2114 void MainThread::CheckMainThreadIsAlive()
2115 {
2116     watchdog_->SetAppMainThreadState(true);
2117     watchdog_->AllowReportEvent();
2118 }
2119 #endif  // ABILITY_LIBRARY_LOADER
2120 
ScheduleNotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback,const int32_t recordId)2121 int32_t MainThread::ScheduleNotifyLoadRepairPatch(const std::string &bundleName,
2122     const sptr<IQuickFixCallback> &callback, const int32_t recordId)
2123 {
2124     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2125     HILOG_DEBUG("ScheduleNotifyLoadRepairPatch function called.");
2126     wptr<MainThread> weak = this;
2127     auto task = [weak, bundleName, callback, recordId]() {
2128         auto appThread = weak.promote();
2129         if (appThread == nullptr || appThread->application_ == nullptr || callback == nullptr) {
2130             HILOG_ERROR("ScheduleNotifyLoadRepairPatch, parameter is nullptr.");
2131             return;
2132         }
2133 
2134         bool ret = true;
2135         std::vector<std::pair<std::string, std::string>> hqfFilePair;
2136         if (appThread->GetHqfFileAndHapPath(bundleName, hqfFilePair)) {
2137             for (auto it = hqfFilePair.begin(); it != hqfFilePair.end(); it++) {
2138                 HILOG_INFO("ScheduleNotifyLoadRepairPatch, LoadPatch, hqfFile: %{private}s, hapPath: %{private}s.",
2139                     it->first.c_str(), it->second.c_str());
2140                 ret = appThread->application_->NotifyLoadRepairPatch(it->first, it->second);
2141             }
2142         } else {
2143             HILOG_DEBUG("ScheduleNotifyLoadRepairPatch, There's no hqfFile need to load.");
2144         }
2145 
2146         callback->OnLoadPatchDone(ret ? NO_ERROR : ERR_INVALID_OPERATION, recordId);
2147     };
2148     if (mainHandler_ == nullptr || !mainHandler_->PostTask(task)) {
2149         HILOG_ERROR("ScheduleNotifyLoadRepairPatch, Post task failed.");
2150         return ERR_INVALID_VALUE;
2151     }
2152 
2153     return NO_ERROR;
2154 }
2155 
ScheduleNotifyHotReloadPage(const sptr<IQuickFixCallback> & callback,const int32_t recordId)2156 int32_t MainThread::ScheduleNotifyHotReloadPage(const sptr<IQuickFixCallback> &callback, const int32_t recordId)
2157 {
2158     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2159     HILOG_DEBUG("function called.");
2160     wptr<MainThread> weak = this;
2161     auto task = [weak, callback, recordId]() {
2162         auto appThread = weak.promote();
2163         if (appThread == nullptr || appThread->application_ == nullptr || callback == nullptr) {
2164             HILOG_ERROR("parameter is nullptr.");
2165             return;
2166         }
2167         auto ret = appThread->application_->NotifyHotReloadPage();
2168         callback->OnReloadPageDone(ret ? NO_ERROR : ERR_INVALID_OPERATION, recordId);
2169     };
2170     if (mainHandler_ == nullptr || !mainHandler_->PostTask(task)) {
2171         HILOG_ERROR("Post task failed.");
2172         return ERR_INVALID_VALUE;
2173     }
2174 
2175     return NO_ERROR;
2176 }
2177 
GetHqfFileAndHapPath(const std::string & bundleName,std::vector<std::pair<std::string,std::string>> & fileMap)2178 bool MainThread::GetHqfFileAndHapPath(const std::string &bundleName,
2179     std::vector<std::pair<std::string, std::string>> &fileMap)
2180 {
2181     HILOG_DEBUG("function called.");
2182     auto bundleObj = DelayedSingleton<SysMrgClient>::GetInstance()->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
2183     if (bundleObj == nullptr) {
2184         HILOG_ERROR("Failed to get bundle manager service.");
2185         return false;
2186     }
2187 
2188     sptr<IBundleMgr> bundleMgr = iface_cast<IBundleMgr>(bundleObj);
2189     if (bundleMgr == nullptr) {
2190         HILOG_ERROR("Bundle manager is nullptr.");
2191         return false;
2192     }
2193 
2194     BundleInfo bundleInfo;
2195     if (bundleMgr->GetBundleInfoForSelf(
2196         (static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) +
2197         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY) +
2198         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) +
2199         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_DISABLE) +
2200         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) +
2201         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) +
2202         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_METADATA)), bundleInfo) != ERR_OK) {
2203         HILOG_ERROR("Get bundle info of %{public}s failed.", bundleName.c_str());
2204         return false;
2205     }
2206 
2207     for (auto hapInfo : bundleInfo.hapModuleInfos) {
2208         if ((processInfo_ != nullptr) && (processInfo_->GetProcessName() == hapInfo.process) &&
2209             (!hapInfo.hqfInfo.hqfFilePath.empty())) {
2210             std::string resolvedHapPath;
2211             std::string hapPath = AbilityRuntime::GetLoadPath(hapInfo.hapPath);
2212             auto position = hapPath.rfind('/');
2213             if (position != std::string::npos) {
2214                 resolvedHapPath = hapPath.erase(position) + FILE_SEPARATOR + hapInfo.moduleName;
2215             }
2216             std::string resolvedHqfFile(AbilityRuntime::GetLoadPath(hapInfo.hqfInfo.hqfFilePath));
2217             HILOG_INFO("bundleName: %{public}s, moduleName: %{public}s, processName: %{private}s, "
2218                 "hqf file: %{private}s, hap path: %{private}s.", bundleName.c_str(), hapInfo.moduleName.c_str(),
2219                 hapInfo.process.c_str(), resolvedHqfFile.c_str(), resolvedHapPath.c_str());
2220             fileMap.push_back(std::pair<std::string, std::string>(resolvedHqfFile, resolvedHapPath));
2221         }
2222     }
2223 
2224     return true;
2225 }
2226 
ScheduleNotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback,const int32_t recordId)2227 int32_t MainThread::ScheduleNotifyUnLoadRepairPatch(const std::string &bundleName,
2228     const sptr<IQuickFixCallback> &callback, const int32_t recordId)
2229 {
2230     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2231     HILOG_DEBUG("ScheduleNotifyUnLoadRepairPatch function called.");
2232     wptr<MainThread> weak = this;
2233     auto task = [weak, bundleName, callback, recordId]() {
2234         auto appThread = weak.promote();
2235         if (appThread == nullptr || appThread->application_ == nullptr || callback == nullptr) {
2236             HILOG_ERROR("ScheduleNotifyUnLoadRepairPatch, parameter is nullptr.");
2237             return;
2238         }
2239 
2240         bool ret = true;
2241         std::vector<std::pair<std::string, std::string>> hqfFilePair;
2242         if (appThread->GetHqfFileAndHapPath(bundleName, hqfFilePair)) {
2243             for (auto it = hqfFilePair.begin(); it != hqfFilePair.end(); it++) {
2244                 HILOG_INFO("ScheduleNotifyUnLoadRepairPatch, UnloadPatch, hqfFile: %{private}s.", it->first.c_str());
2245                 ret = appThread->application_->NotifyUnLoadRepairPatch(it->first);
2246             }
2247         } else {
2248             HILOG_DEBUG("ScheduleNotifyUnLoadRepairPatch, There's no hqfFile need to unload.");
2249         }
2250 
2251         callback->OnUnloadPatchDone(ret ? NO_ERROR : ERR_INVALID_OPERATION, recordId);
2252     };
2253     if (mainHandler_ == nullptr || !mainHandler_->PostTask(task)) {
2254         HILOG_ERROR("ScheduleNotifyUnLoadRepairPatch, Post task failed.");
2255         return ERR_INVALID_VALUE;
2256     }
2257 
2258     return NO_ERROR;
2259 }
2260 
UpdateProcessExtensionType(const std::shared_ptr<AbilityLocalRecord> & abilityRecord)2261 void MainThread::UpdateProcessExtensionType(const std::shared_ptr<AbilityLocalRecord> &abilityRecord)
2262 {
2263     auto &runtime = application_->GetRuntime();
2264     if (!runtime) {
2265         HILOG_ERROR("Get runtime failed");
2266         return;
2267     }
2268     if (!abilityRecord) {
2269         HILOG_ERROR("abilityRecord is nullptr");
2270         return;
2271     }
2272     auto &abilityInfo = abilityRecord->GetAbilityInfo();
2273     if (!abilityInfo) {
2274         HILOG_ERROR("Get abilityInfo failed");
2275         return;
2276     }
2277     runtime->UpdateExtensionType(static_cast<int32_t>(abilityInfo->extensionAbilityType));
2278     HILOG_INFO("UpdateExtensionType, type = %{public}d", static_cast<int32_t>(abilityInfo->extensionAbilityType));
2279 }
2280 
AddExtensionBlockItem(const std::string & extensionName,int32_t type)2281 void MainThread::AddExtensionBlockItem(const std::string &extensionName, int32_t type)
2282 {
2283     if (!extensionConfigMgr_) {
2284         return;
2285     }
2286     extensionConfigMgr_->AddBlockListItem(extensionName, type);
2287 }
2288 
UpdateEngineExtensionBlockList(NativeEngine & nativeEngine)2289 void MainThread::UpdateEngineExtensionBlockList(NativeEngine &nativeEngine)
2290 {
2291     if (!extensionConfigMgr_) {
2292         return;
2293     }
2294     extensionConfigMgr_->UpdateBlockListToEngine(nativeEngine);
2295 }
2296 }  // namespace AppExecFwk
2297 }  // namespace OHOS
2298