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