• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023-2025 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 "aot/aot_handler.h"
17 
18 #include <dlfcn.h>
19 #include <filesystem>
20 #include <fstream>
21 #include <iostream>
22 #include <sys/stat.h>
23 #include <tuple>
24 
25 #include "account_helper.h"
26 #ifdef CODE_SIGNATURE_ENABLE
27 #include "aot/aot_sign_data_cache_mgr.h"
28 #endif
29 #include "app_log_tag_wrapper.h"
30 #include "bundle_mgr_service_event_handler.h"
31 #include "scope_guard.h"
32 #include "installd_client.h"
33 #include "parameter.h"
34 #include "parameters.h"
35 #ifdef BUNDLE_FRAMEWORK_POWER_MGR_ENABLE
36 #include "display_power_mgr_client.h"
37 #endif
38 
39 namespace OHOS {
40 namespace AppExecFwk {
41 namespace {
42 using UserStatusFunc = ErrCode (*)(int32_t, std::vector<std::string>&, std::vector<std::string>&);
43 using AOTVersionFunc = ErrCode (*)(std::string&);
44 // ark compile option parameter key
45 constexpr const char* INSTALL_COMPILE_MODE = "persist.bm.install.arkopt";
46 constexpr const char* IDLE_COMPILE_MODE = "persist.bm.idle.arkopt";
47 constexpr const char* OTA_COMPILE_MODE = "persist.bm.ota.arkopt";
48 
49 constexpr const char* COMPILE_OPTCODE_RANGE_KEY = "ark.optcode.range";
50 constexpr const char* DEBUG_APP_IDENTIFIER = "DEBUG_LIB_ID";
51 
52 constexpr const char* UPDATE_TYPE = "persist.dupdate_engine.update_type";
53 constexpr const char* UPDATE_TYPE_MANUAL = "manual";
54 constexpr const char* UPDATE_TYPE_NIGHT = "night";
55 
56 constexpr const char* OTA_COMPILE_SWITCH = "const.bms.optimizing_apps.switch";
57 constexpr const char* OTA_COMPILE_SWITCH_DEFAULT = "off";
58 constexpr const char* OTA_COMPILE_SWITCH_ON = "on";
59 
60 constexpr const char* OTA_COMPILE_TIME = "persist.bms.optimizing_apps.timing";
61 constexpr int16_t OTA_COMPILE_TIME_DEFAULT = 4 * 60; // 4min
62 constexpr int8_t GAP_SECONDS = 10;
63 
64 constexpr const char* OTA_COMPILE_COUNT_MANUAL = "persist.bms.optimizing_apps.counts.manual";
65 constexpr int8_t OTA_COMPILE_COUNT_MANUAL_DEFAULT = 20;
66 constexpr const char* OTA_COMPILE_COUNT_NIGHT = "persist.bms.optimizing_apps.counts.night";
67 constexpr int8_t OTA_COMPILE_COUNT_NIGHT_DEFAULT = 30;
68 
69 constexpr const char* OTA_COMPILE_STATUS = "bms.optimizing_apps.status";
70 constexpr const char* OTA_COMPILE_STATUS_BEGIN = "0";
71 constexpr const char* OTA_COMPILE_STATUS_END = "1";
72 
73 constexpr const char* QUEUE_NAME = "OTAQueue";
74 constexpr const char* TASK_NAME = "OTACompileTimer";
75 
76 constexpr uint16_t CONVERSION_FACTOR = 1000; // s to ms
77 
78 constexpr const char* FAILURE_REASON_TIME_OUT = "timeout";
79 constexpr const char* FAILURE_REASON_BUNDLE_NOT_EXIST = "bundle not exist";
80 constexpr const char* FAILURE_REASON_NOT_STAGE_MODEL = "not stage model";
81 constexpr const char* FAILURE_REASON_COMPILE_FAILED = "compile failed";
82 
83 constexpr const char* PGO_MERGED_AP_PREFIX = "merged_";
84 constexpr const char* PGO_RT_AP_PREFIX = "rt_";
85 constexpr const char* COPY_AP_DEST_PATH  = "/data/local/pgo/";
86 constexpr const char* COMPILE_NONE = "none";
87 
88 constexpr const char* USER_STATUS_SO_NAME = "libuser_status_client.z.so";
89 constexpr const char* USER_STATUS_FUNC_NAME = "GetUserPreferenceApp";
90 constexpr const char* BM_AOT_TEST = "bm.aot.test";
91 
92 constexpr const char* SYS_COMP_AN_DIR = "/data/service/el1/public/for-all-app/framework_ark_cache/";
93 constexpr const char* SYS_COMP_CONFIG_PATH = "/system/etc/ark/system_framework_aot_enable_list.conf";
94 
95 constexpr const char* DEPRECATED_ARK_CACHE_PATH = "/data/local/ark-cache";
96 constexpr const char* DEPRECATED_ARK_PROFILE_PATH = "/data/local/ark-profile";
97 }
98 
AOTHandler()99 AOTHandler::AOTHandler()
100 {
101     serialQueue_ = std::make_shared<SerialQueue>(QUEUE_NAME);
102 }
103 
GetInstance()104 AOTHandler& AOTHandler::GetInstance()
105 {
106     static AOTHandler handler;
107     return handler;
108 }
109 
BuildArkProfilePath(const int32_t userId,const std::string & bundleName,const std::string & moduleName)110 std::string AOTHandler::BuildArkProfilePath(
111     const int32_t userId, const std::string &bundleName, const std::string &moduleName)
112 {
113     std::filesystem::path path("/data/app/el1");
114     path /= std::to_string(userId);
115     path /= "aot_compiler/ark_profile";
116 
117     if (bundleName.empty()) {
118         return path.string();
119     }
120     path /= bundleName;
121     if (moduleName.empty()) {
122         return path.string();
123     }
124     path /= moduleName;
125     return path.string();
126 }
127 
IsSupportARM64() const128 bool AOTHandler::IsSupportARM64() const
129 {
130     std::string abis = GetAbiList();
131     APP_LOGD("abi list : %{public}s", abis.c_str());
132     std::vector<std::string> abiList;
133     SplitStr(abis, ServiceConstants::ABI_SEPARATOR, abiList, false, false);
134     if (abiList.empty()) {
135         APP_LOGD("abiList empty");
136         return false;
137     }
138     return std::find(abiList.begin(), abiList.end(), ServiceConstants::ARM64_V8A) != abiList.end();
139 }
140 
FindArkProfilePath(const std::string & bundleName,const std::string & moduleName) const141 std::string AOTHandler::FindArkProfilePath(const std::string &bundleName, const std::string &moduleName) const
142 {
143     APP_LOGD("FindArkProfilePath begin");
144     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
145     if (!dataMgr) {
146         APP_LOGE("dataMgr is null");
147         return Constants::EMPTY_STRING;
148     }
149     int32_t userId = AccountHelper::GetCurrentActiveUserId();
150     if (userId <= 0) {
151         userId = Constants::START_USERID;
152     }
153     std::string path = BuildArkProfilePath(userId, bundleName, moduleName + ServiceConstants::AP_SUFFIX);
154     APP_LOGD("path : %{public}s", path.c_str());
155     bool isExistFile = false;
156     (void)InstalldClient::GetInstance()->IsExistApFile(path, isExistFile);
157     if (isExistFile) {
158         return path;
159     }
160     APP_LOGD("FindArkProfilePath failed");
161     return Constants::EMPTY_STRING;
162 }
163 
BuildAOTArgs(const InnerBundleInfo & info,const std::string & moduleName,const std::string & compileMode,bool isEnableBaselinePgo) const164 std::optional<AOTArgs> AOTHandler::BuildAOTArgs(const InnerBundleInfo &info, const std::string &moduleName,
165     const std::string &compileMode, bool isEnableBaselinePgo) const
166 {
167     AOTArgs aotArgs;
168     aotArgs.bundleName = info.GetBundleName();
169     aotArgs.moduleName = moduleName;
170     if (compileMode == ServiceConstants::COMPILE_PARTIAL) {
171         aotArgs.arkProfilePath = FindArkProfilePath(aotArgs.bundleName, aotArgs.moduleName);
172         if (aotArgs.arkProfilePath.empty()) {
173             APP_LOGD("compile mode is partial, but ap not exist, no need to AOT");
174             return std::nullopt;
175         }
176     }
177     aotArgs.compileMode = compileMode;
178     aotArgs.hapPath = info.GetModuleHapPath(aotArgs.moduleName);
179     aotArgs.coreLibPath = Constants::EMPTY_STRING;
180     aotArgs.outputPath = ServiceConstants::ARK_CACHE_PATH + aotArgs.bundleName + ServiceConstants::PATH_SEPARATOR
181         + ServiceConstants::ARM64;
182     // handle internal hsp
183     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
184     if (!dataMgr) {
185         APP_LOGE("dataMgr is null");
186         return std::nullopt;
187     }
188     InnerBundleInfo installedInfo;
189     if (!dataMgr->QueryInnerBundleInfo(info.GetBundleName(), installedInfo)) {
190         APP_LOGE("QueryInnerBundleInfo failed");
191         return std::nullopt;
192     }
193     installedInfo.GetInternalDependentHspInfo(moduleName, aotArgs.hspVector);
194 
195     InnerBundleUserInfo newInnerBundleUserInfo;
196     int32_t curActiveUserId = AccountHelper::GetCurrentActiveUserId();
197     int32_t activeUserId = curActiveUserId <= 0 ? Constants::START_USERID : curActiveUserId;
198     if (!installedInfo.GetInnerBundleUserInfo(activeUserId, newInnerBundleUserInfo)) {
199         APP_LOGE("bundle(%{public}s) get user (%{public}d) failed",
200             installedInfo.GetBundleName().c_str(), activeUserId);
201         return std::nullopt;
202     }
203     aotArgs.bundleUid = newInnerBundleUserInfo.uid;
204     aotArgs.bundleGid = installedInfo.GetGid(activeUserId);
205     aotArgs.isEncryptedBundle = installedInfo.IsEncryptedMoudle(moduleName) ? 1 : 0;
206     aotArgs.appIdentifier = (info.GetAppProvisionType() == Constants::APP_PROVISION_TYPE_DEBUG) ?
207         DEBUG_APP_IDENTIFIER : info.GetAppIdentifier();
208     aotArgs.anFileName = aotArgs.outputPath + ServiceConstants::PATH_SEPARATOR + aotArgs.moduleName
209         + ServiceConstants::AN_SUFFIX;
210 
211     std::string optBCRange = system::GetParameter(COMPILE_OPTCODE_RANGE_KEY, "");
212     aotArgs.optBCRangeList = optBCRange;
213 
214     bool deviceIsScreenOff = CheckDeviceState();
215     aotArgs.isScreenOff = static_cast<uint32_t>(deviceIsScreenOff);
216 
217     aotArgs.isEnableBaselinePgo = static_cast<uint32_t>(isEnableBaselinePgo);
218     aotArgs.moduleArkTSMode = installedInfo.GetModuleArkTSMode(moduleName);
219     if (aotArgs.moduleArkTSMode.empty()) {
220         APP_LOGE("moduleArkTSMode empty");
221         return std::nullopt;
222     }
223     APP_LOGD("args : %{public}s", aotArgs.ToString().c_str());
224     return aotArgs;
225 }
226 
AOTInternal(const std::optional<AOTArgs> & aotArgs,uint32_t versionCode) const227 ErrCode AOTHandler::AOTInternal(const std::optional<AOTArgs> &aotArgs, uint32_t versionCode) const
228 {
229     if (!aotArgs) {
230         APP_LOGD("aotArgs empty");
231         return ERR_APPEXECFWK_AOT_ARGS_EMPTY;
232     }
233     ErrCode ret = ERR_OK;
234     std::vector<uint8_t> pendSignData;
235     {
236         std::lock_guard<std::mutex> lock(executeMutex_);
237         ret = InstalldClient::GetInstance()->ExecuteAOT(*aotArgs, pendSignData);
238     }
239     LOG_I(BMS_TAG_AOT, "ExecuteAOT ret : %{public}d", ret);
240 #ifdef CODE_SIGNATURE_ENABLE
241     AOTSignDataCacheMgr::GetInstance().AddSignDataForHap(*aotArgs, versionCode, pendSignData, ret);
242 #endif
243     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
244     if (!dataMgr) {
245         APP_LOGE("dataMgr is null");
246         return ERR_APPEXECFWK_SERVICE_INTERNAL_ERROR;
247     }
248     AOTCompileStatus status = ConvertToAOTCompileStatus(ret);
249     dataMgr->SetAOTCompileStatus(aotArgs->bundleName, aotArgs->moduleName, status, versionCode);
250     return ret;
251 }
252 
ConvertToAOTCompileStatus(const ErrCode ret) const253 AOTCompileStatus AOTHandler::ConvertToAOTCompileStatus(const ErrCode ret) const
254 {
255     switch (ret) {
256         case ERR_OK:
257             return AOTCompileStatus::COMPILE_SUCCESS;
258         case ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_CRASH:
259             return AOTCompileStatus::COMPILE_CRASH;
260         case ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_CANCELLED:
261             return AOTCompileStatus::COMPILE_CANCELLED;
262         default:
263             return AOTCompileStatus::COMPILE_FAILED;
264     }
265 }
266 
HandleInstallWithSingleHap(const InnerBundleInfo & info,const std::string & compileMode) const267 void AOTHandler::HandleInstallWithSingleHap(const InnerBundleInfo &info, const std::string &compileMode) const
268 {
269     std::optional<AOTArgs> aotArgs = BuildAOTArgs(info, info.GetCurrentModulePackage(), compileMode, true);
270     (void)AOTInternal(aotArgs, info.GetVersionCode());
271 }
272 
HandleInstall(const std::unordered_map<std::string,InnerBundleInfo> & infos) const273 void AOTHandler::HandleInstall(const std::unordered_map<std::string, InnerBundleInfo> &infos) const
274 {
275     auto task = [this, infos]() {
276         APP_LOGD("HandleInstall begin");
277         if (infos.empty() || !(infos.cbegin()->second.GetIsNewVersion())) {
278             APP_LOGD("not stage model, no need to AOT");
279             return;
280         }
281         if (!IsSupportARM64()) {
282             APP_LOGD("current device doesn't support arm64, no need to AOT");
283             return;
284         }
285         std::string compileMode = system::GetParameter(INSTALL_COMPILE_MODE, COMPILE_NONE);
286         APP_LOGD("%{public}s = %{public}s", INSTALL_COMPILE_MODE, compileMode.c_str());
287         if (compileMode == COMPILE_NONE) {
288             APP_LOGD("%{public}s = none, no need to AOT", INSTALL_COMPILE_MODE);
289             return;
290         }
291         std::for_each(infos.cbegin(), infos.cend(), [this, compileMode](const auto &item) {
292             HandleInstallWithSingleHap(item.second, compileMode);
293         });
294         APP_LOGD("HandleInstall end");
295     };
296     std::thread t(task);
297     t.detach();
298 }
299 
ClearArkCacheDir() const300 void AOTHandler::ClearArkCacheDir() const
301 {
302     (void)InstalldClient::GetInstance()->ClearDir(SYS_COMP_AN_DIR);
303 
304     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
305     if (!dataMgr) {
306         APP_LOGE("dataMgr is null");
307         return;
308     }
309     std::vector<std::string> bundleNames = dataMgr->GetAllBundleName();
310     std::for_each(bundleNames.cbegin(), bundleNames.cend(), [dataMgr](const auto &bundleName) {
311         std::string removeDir = ServiceConstants::ARK_CACHE_PATH + bundleName;
312         ErrCode ret = InstalldClient::GetInstance()->RemoveDir(removeDir);
313         APP_LOGD("removeDir %{public}s, ret : %{public}d", removeDir.c_str(), ret);
314     });
315 }
316 
ClearArkAp() const317 void AOTHandler::ClearArkAp() const
318 {
319     APP_LOGI("ClearArkAp start");
320     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
321     if (dataMgr == nullptr) {
322         APP_LOGE("is nullptr");
323         return;
324     }
325     std::set<int32_t> userIds = dataMgr->GetAllUser();
326     for (const auto &userId : userIds) {
327         std::vector<BundleInfo> bundleInfos;
328         if (dataMgr->GetBundleInfosV9(static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE),
329             bundleInfos, userId) != ERR_OK) {
330             APP_LOGE("GetAllBundleInfos failed");
331             continue;
332         }
333         for (const auto &bundleInfo : bundleInfos) {
334             DeleteArkAp(bundleInfo, userId);
335         }
336     }
337     APP_LOGI("ClearArkAp end");
338 }
339 
DeleteArkAp(const BundleInfo & bundleInfo,const int32_t userId) const340 void AOTHandler::DeleteArkAp(const BundleInfo &bundleInfo, const int32_t userId) const
341 {
342     std::string arkProfilePath = BuildArkProfilePath(userId, bundleInfo.name) + ServiceConstants::PATH_SEPARATOR;
343     for (const auto &moduleName : bundleInfo.moduleNames) {
344         std::string runtimeAp = arkProfilePath;
345         std::string mergedAp = arkProfilePath;
346         runtimeAp.append(PGO_RT_AP_PREFIX).append(moduleName)
347             .append(ServiceConstants::PGO_FILE_SUFFIX);
348         APP_LOGD("begin rm runtimeAp: %{public}s", runtimeAp.c_str());
349         (void)InstalldClient::GetInstance()->RemoveDir(runtimeAp);
350         mergedAp.append(PGO_MERGED_AP_PREFIX).append(moduleName).append(ServiceConstants::PGO_FILE_SUFFIX);
351         APP_LOGD("begin rm mergedAp: %{public}s", mergedAp.c_str());
352         (void)InstalldClient::GetInstance()->RemoveDir(mergedAp);
353     }
354 }
355 
HandleResetAOT(const std::string & bundleName,bool isAllBundle) const356 void AOTHandler::HandleResetAOT(const std::string &bundleName, bool isAllBundle) const
357 {
358     if (isAllBundle && system::GetParameter(BM_AOT_TEST, "").empty()) {
359         APP_LOGD("isAllBundle true, param bm.aot.test empty, so ignore");
360         return;
361     }
362     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
363     if (!dataMgr) {
364         APP_LOGE("dataMgr is null");
365         return;
366     }
367     std::vector<std::string> bundleNames;
368     if (isAllBundle) {
369         bundleNames = dataMgr->GetAllBundleName();
370     } else {
371         bundleNames = {bundleName};
372     }
373     std::for_each(bundleNames.cbegin(), bundleNames.cend(), [dataMgr](const auto &bundleToReset) {
374         std::string removeDir = ServiceConstants::ARK_CACHE_PATH + bundleToReset;
375         ErrCode ret = InstalldClient::GetInstance()->RemoveDir(removeDir);
376         APP_LOGD("removeDir %{public}s, ret : %{public}d", removeDir.c_str(), ret);
377         dataMgr->ResetAOTFlagsCommand(bundleToReset);
378     });
379 }
380 
HandleResetAllAOT() const381 void AOTHandler::HandleResetAllAOT() const
382 {
383     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
384     if (!dataMgr) {
385         APP_LOGE("dataMgr is null");
386         return;
387     }
388     std::vector<std::string> bundleNames = dataMgr->GetAllBundleName();
389     std::for_each(bundleNames.cbegin(), bundleNames.cend(), [dataMgr](const auto &bundleToReset) {
390         std::string removeDir = ServiceConstants::ARK_CACHE_PATH + bundleToReset;
391         ErrCode ret = InstalldClient::GetInstance()->RemoveDir(removeDir);
392         APP_LOGI("reset all aot removeDir %{public}s, ret : %{public}d", removeDir.c_str(), ret);
393         dataMgr->ResetAOTFlagsCommand(bundleToReset);
394     });
395 }
396 
MkApDestDirIfNotExist() const397 ErrCode AOTHandler::MkApDestDirIfNotExist() const
398 {
399     ErrCode errCode;
400     bool isDirExist = false;
401     errCode = InstalldClient::GetInstance()->IsExistDir(COPY_AP_DEST_PATH, isDirExist);
402     if (errCode != ERR_OK) {
403         APP_LOGE("check if dir exist failed, err %{public}d", errCode);
404     }
405     if (isDirExist) {
406         APP_LOGI("Copy ap path is exist");
407         return ERR_OK;
408     }
409     mode_t mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP;
410     errCode = InstalldClient::GetInstance()->Mkdir(
411         COPY_AP_DEST_PATH, mode, Constants::FOUNDATION_UID, ServiceConstants::SHELL_UID);
412     if (errCode != ERR_OK) {
413         APP_LOGE("fail create dir err %{public}d", errCode);
414         return errCode;
415     }
416     APP_LOGI("MkApDestDir path success");
417     return ERR_OK;
418 }
419 
HandleCopyAp(const std::string & bundleName,bool isAllBundle,std::vector<std::string> & results) const420 ErrCode AOTHandler::HandleCopyAp(const std::string &bundleName, bool isAllBundle,
421     std::vector<std::string> &results) const
422 {
423     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
424     if (!dataMgr) {
425         APP_LOGE("dataMgr is null");
426         return ERR_APPEXECFWK_SERVICE_INTERNAL_ERROR;
427     }
428     std::vector<std::string> bundleNames;
429     if (isAllBundle) {
430         bundleNames = dataMgr->GetAllBundleName();
431     } else {
432         bundleNames = {bundleName};
433     }
434     ErrCode errCode = MkApDestDirIfNotExist();
435     if (errCode != ERR_OK) {
436         return errCode;
437     }
438     int32_t userId = AccountHelper::GetCurrentActiveUserId();
439     if (userId <= 0) {
440         userId = Constants::START_USERID;
441     }
442     for (const auto &bundleName : bundleNames) {
443         BundleInfo bundleInfo;
444         if (!dataMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId)) {
445             std::string errInfo = bundleName + " GetBundleInfo failed";
446             APP_LOGW("%{public}s", errInfo.c_str());
447             results.emplace_back(errInfo);
448             continue;
449         }
450         CopyApWithBundle(bundleName, bundleInfo, userId, results);
451     };
452     return ERR_OK;
453 }
454 
GetSouceAp(const std::string & mergedAp,const std::string & rtAp) const455 std::string AOTHandler::GetSouceAp(const std::string &mergedAp, const std::string &rtAp) const
456 {
457     ErrCode errCode;
458     bool isMergedApExist = false;
459     bool isRtApExist = false;
460     errCode = InstalldClient::GetInstance()->IsExistFile(mergedAp, isMergedApExist);
461     if (errCode != ERR_OK) {
462         APP_LOGE("CopyAp mergedAp %{public}s failed due to call IsExistFile failed %{public}d",
463             mergedAp.c_str(), errCode);
464         return Constants::EMPTY_STRING;
465     }
466     if (isMergedApExist) {
467         return mergedAp;
468     }
469     errCode = InstalldClient::GetInstance()->IsExistFile(rtAp, isRtApExist);
470     if (errCode != ERR_OK) {
471         APP_LOGE("CopyAp rtAp %{public}s failed due to call IsExistFile failed %{public}d",
472             rtAp.c_str(), errCode);
473         return Constants::EMPTY_STRING;
474     }
475     if (isRtApExist) {
476         return rtAp;
477     }
478     APP_LOGE("Source ap is not exist");
479     return Constants::EMPTY_STRING;
480 }
481 
CopyApWithBundle(const std::string & bundleName,const BundleInfo & bundleInfo,const int32_t userId,std::vector<std::string> & results) const482 void AOTHandler::CopyApWithBundle(const std::string &bundleName, const BundleInfo &bundleInfo,
483     const int32_t userId, std::vector<std::string> &results) const
484 {
485     std::string arkProfilePath = BuildArkProfilePath(userId, bundleName) + ServiceConstants::PATH_SEPARATOR;
486     ErrCode errCode;
487     for (const auto &moduleName : bundleInfo.moduleNames) {
488         std::string mergedAp = arkProfilePath + PGO_MERGED_AP_PREFIX + moduleName + ServiceConstants::AP_SUFFIX;
489         std::string rtAp = arkProfilePath + PGO_RT_AP_PREFIX + moduleName + ServiceConstants::AP_SUFFIX;
490         std::string sourceAp = GetSouceAp(mergedAp, rtAp);
491         std::string result;
492         if (sourceAp.empty()) {
493             result.append(bundleName).append(" ").append(moduleName).append(" get source ap failed");
494             results.emplace_back(result);
495             continue;
496         }
497         if (sourceAp.find(ServiceConstants::RELATIVE_PATH) != std::string::npos) {
498             return;
499         }
500         std::string destAp = COPY_AP_DEST_PATH  + bundleName + "_" + moduleName + ServiceConstants::AP_SUFFIX;
501         result.append(sourceAp);
502         errCode = InstalldClient::GetInstance()->CopyFile(sourceAp, destAp);
503         if (errCode != ERR_OK) {
504             APP_LOGE("Copy ap dir %{public}s failed err %{public}d", sourceAp.c_str(), errCode);
505             result.append(" copy ap failed");
506             continue;
507         }
508         result.append(" copy ap success");
509         results.emplace_back(result);
510     }
511 }
512 
ResetAOTFlags() const513 void AOTHandler::ResetAOTFlags() const
514 {
515     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
516     if (!dataMgr) {
517         APP_LOGE("dataMgr is null");
518         return;
519     }
520     dataMgr->ResetAOTFlags();
521 }
522 
HandleOTA()523 void AOTHandler::HandleOTA()
524 {
525     APP_LOGI("AOTHandler OTA begin");
526     ResetAOTFlags();
527     HandleArkPathsChange();
528     ClearArkCacheDir();
529     ClearArkAp();
530     HandleOTACompile();
531 }
532 
HandleOTACompile()533 void AOTHandler::HandleOTACompile()
534 {
535     if (!IsOTACompileSwitchOn()) {
536         APP_LOGI("OTACompileSwitch off, no need to compile");
537         return;
538     }
539     BeforeOTACompile();
540     OTACompile();
541 }
542 
IsOTACompileSwitchOn() const543 bool AOTHandler::IsOTACompileSwitchOn() const
544 {
545     std::string OTACompileSwitch = system::GetParameter(OTA_COMPILE_SWITCH, OTA_COMPILE_SWITCH_DEFAULT);
546     APP_LOGI("OTACompileSwitch %{public}s", OTACompileSwitch.c_str());
547     return OTACompileSwitch == OTA_COMPILE_SWITCH_ON;
548 }
549 
BeforeOTACompile()550 void AOTHandler::BeforeOTACompile()
551 {
552     OTACompileDeadline_ = false;
553     int32_t limitSeconds = system::GetIntParameter<int32_t>(OTA_COMPILE_TIME, OTA_COMPILE_TIME_DEFAULT);
554     APP_LOGI("OTA compile time limit seconds %{public}d", limitSeconds);
555     auto task = [this]() {
556         APP_LOGI("compile timer end");
557         OTACompileDeadline_ = true;
558         ErrCode ret = InstalldClient::GetInstance()->StopAOT();
559         APP_LOGI("StopAOT ret %{public}d", ret);
560     };
561     int32_t delayTimeSeconds = limitSeconds - GAP_SECONDS;
562     if (delayTimeSeconds < 0) {
563         delayTimeSeconds = 0;
564     }
565     serialQueue_->ScheduleDelayTask(TASK_NAME, delayTimeSeconds * CONVERSION_FACTOR, task);
566 }
567 
OTACompile() const568 void AOTHandler::OTACompile() const
569 {
570     auto OTACompileTask = [this]() {
571         OTACompileInternal();
572     };
573     std::thread(OTACompileTask).detach();
574 }
575 
OTACompileInternal() const576 void AOTHandler::OTACompileInternal() const
577 {
578     APP_LOGI("OTACompileInternal begin");
579     system::SetParameter(OTA_COMPILE_STATUS, OTA_COMPILE_STATUS_BEGIN);
580     ScopeGuard guard([this] {
581         APP_LOGI("set OTA compile status to end");
582         system::SetParameter(OTA_COMPILE_STATUS, OTA_COMPILE_STATUS_END);
583         serialQueue_->CancelDelayTask(TASK_NAME);
584     });
585 
586     if (!IsSupportARM64()) {
587         APP_LOGI("current device doesn't support arm64, no need to AOT");
588         return;
589     }
590 
591     std::string compileMode = system::GetParameter(OTA_COMPILE_MODE, COMPILE_NONE);
592     APP_LOGI("%{public}s = %{public}s", OTA_COMPILE_MODE, compileMode.c_str());
593     if (compileMode == COMPILE_NONE) {
594         APP_LOGI("%{public}s none, no need to AOT", OTA_COMPILE_MODE);
595         return;
596     }
597 
598     std::vector<std::string> bundleNames;
599     if (!GetOTACompileList(bundleNames)) {
600         APP_LOGE("get OTA compile list failed");
601         return;
602     }
603 
604     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
605     if (!dataMgr) {
606         APP_LOGE("dataMgr is null");
607         return;
608     }
609 
610     std::map<std::string, EventInfo> sysEventMap;
611     for (const std::string &bundleName : bundleNames) {
612         EventInfo eventInfo = HandleCompileWithBundle(bundleName, compileMode, dataMgr);
613         sysEventMap.emplace(bundleName, eventInfo);
614     }
615     ReportSysEvent(sysEventMap);
616     APP_LOGI("OTACompileInternal end");
617 }
618 
GetOTACompileList(std::vector<std::string> & bundleNames) const619 bool AOTHandler::GetOTACompileList(std::vector<std::string> &bundleNames) const
620 {
621     std::string updateType = system::GetParameter(UPDATE_TYPE, "");
622     APP_LOGI("updateType %{public}s", updateType.c_str());
623     int32_t size = 0;
624     if (updateType == UPDATE_TYPE_MANUAL) {
625         size = system::GetIntParameter<int32_t>(OTA_COMPILE_COUNT_MANUAL, OTA_COMPILE_COUNT_MANUAL_DEFAULT);
626     } else if (updateType == UPDATE_TYPE_NIGHT) {
627         size = system::GetIntParameter<int32_t>(OTA_COMPILE_COUNT_NIGHT, OTA_COMPILE_COUNT_NIGHT_DEFAULT);
628     } else {
629         APP_LOGE("invalid updateType");
630         return false;
631     }
632     return GetUserBehaviourAppList(bundleNames, size);
633 }
634 
GetUserBehaviourAppList(std::vector<std::string> & bundleNames,int32_t size) const635 bool AOTHandler::GetUserBehaviourAppList(std::vector<std::string> &bundleNames, int32_t size) const
636 {
637     APP_LOGI("GetUserBehaviourAppList begin, size %{public}d", size);
638     void* handle = dlopen(USER_STATUS_SO_NAME, RTLD_NOW);
639     if (handle == nullptr) {
640         APP_LOGE("user status dlopen failed : %{public}s", dlerror());
641         return false;
642     }
643     UserStatusFunc userStatusFunc = reinterpret_cast<UserStatusFunc>(dlsym(handle, USER_STATUS_FUNC_NAME));
644     if (userStatusFunc == nullptr) {
645         APP_LOGE("user status dlsym failed : %{public}s", dlerror());
646         dlclose(handle);
647         return false;
648     }
649     std::vector<std::string> interestedApps;
650     ErrCode ret = userStatusFunc(size, interestedApps, bundleNames);
651     APP_LOGI("GetUserPreferenceApp ret : %{public}d, bundleNames size : %{public}zu", ret, bundleNames.size());
652     dlclose(handle);
653     return ret == ERR_OK;
654 }
655 
HandleCompileWithBundle(const std::string & bundleName,const std::string & compileMode,std::shared_ptr<BundleDataMgr> dataMgr) const656 EventInfo AOTHandler::HandleCompileWithBundle(const std::string &bundleName, const std::string &compileMode,
657     std::shared_ptr<BundleDataMgr> dataMgr) const
658 {
659     APP_LOGI("handle compile bundle %{public}s", bundleName.c_str());
660     EventInfo eventInfo;
661     eventInfo.timeStamp = BundleUtil::GetCurrentTime();
662     eventInfo.bundleName = bundleName;
663     eventInfo.compileMode = compileMode;
664     eventInfo.compileResult = false;
665 
666     if (OTACompileDeadline_) {
667         APP_LOGI("reach OTA deadline, stop compile bundle");
668         eventInfo.failureReason = FAILURE_REASON_TIME_OUT;
669         return eventInfo;
670     }
671 
672     InnerBundleInfo info;
673     if (!dataMgr->QueryInnerBundleInfo(bundleName, info)) {
674         APP_LOGE("QueryInnerBundleInfo failed");
675         eventInfo.failureReason = FAILURE_REASON_BUNDLE_NOT_EXIST;
676         return eventInfo;
677     }
678     if (!info.GetIsNewVersion()) {
679         APP_LOGI("not stage model, no need to AOT");
680         eventInfo.failureReason = FAILURE_REASON_NOT_STAGE_MODEL;
681         return eventInfo;
682     }
683 
684     int64_t beginTimeSeconds = BundleUtil::GetCurrentTime();
685     bool compileRet = true;
686 
687     std::vector<std::string> moduleNames;
688     info.GetModuleNames(moduleNames);
689     for (const std::string &moduleName : moduleNames) {
690         if (OTACompileDeadline_) {
691             APP_LOGI("reach OTA deadline, stop compile module");
692             eventInfo.failureReason = FAILURE_REASON_TIME_OUT;
693             eventInfo.costTimeSeconds = BundleUtil::GetCurrentTime() - beginTimeSeconds;
694             return eventInfo;
695         }
696         ErrCode ret = HandleCompileWithSingleHap(info, moduleName, compileMode, true);
697         APP_LOGI("moduleName : %{public}s, ret : %{public}d", moduleName.c_str(), ret);
698         if (ret != ERR_OK) {
699             compileRet = false;
700         }
701     }
702 
703     if (compileRet) {
704         eventInfo.compileResult = true;
705         eventInfo.failureReason.clear();
706     } else {
707         eventInfo.compileResult = false;
708         eventInfo.failureReason = FAILURE_REASON_COMPILE_FAILED;
709     }
710     eventInfo.costTimeSeconds = BundleUtil::GetCurrentTime() - beginTimeSeconds;
711     return eventInfo;
712 }
713 
ReportSysEvent(const std::map<std::string,EventInfo> & sysEventMap) const714 void AOTHandler::ReportSysEvent(const std::map<std::string, EventInfo> &sysEventMap) const
715 {
716     auto task = [sysEventMap]() {
717         APP_LOGI("begin to report AOT sysEvent");
718         EventInfo summaryInfo;
719         summaryInfo.timeStamp = BundleUtil::GetCurrentTime();
720         for (const auto &item : sysEventMap) {
721             summaryInfo.totalBundleNames.emplace_back(item.first);
722             if (item.second.compileResult) {
723                 summaryInfo.successCnt++;
724             }
725             summaryInfo.costTimeSeconds += item.second.costTimeSeconds;
726             EventReport::SendSystemEvent(BMSEventType::AOT_COMPILE_RECORD, item.second);
727         }
728         EventReport::SendSystemEvent(BMSEventType::AOT_COMPILE_SUMMARY, summaryInfo);
729         APP_LOGI("report AOT sysEvent done");
730     };
731     std::thread(task).detach();
732 }
733 
HandleIdleWithSingleSysComp(const std::string & abcPath) const734 void AOTHandler::HandleIdleWithSingleSysComp(const std::string &abcPath) const
735 {
736     AOTArgs aotArgs;
737     aotArgs.isSysComp = true;
738     aotArgs.sysCompPath = abcPath;
739     std::string abcNameNoSuffix = std::filesystem::path(abcPath).stem().string();
740     std::filesystem::path tmpAnFileName =
741         std::filesystem::path(SYS_COMP_AN_DIR) / (abcNameNoSuffix + ServiceConstants::AN_SUFFIX);
742     aotArgs.anFileName = tmpAnFileName.string();
743     aotArgs.outputPath = aotArgs.anFileName;
744 
745     ErrCode ret = ERR_OK;
746     std::vector<uint8_t> signData;
747     {
748         std::lock_guard<std::mutex> lock(executeMutex_);
749         ret = InstalldClient::GetInstance()->ExecuteAOT(aotArgs, signData);
750     }
751     APP_LOGI_NOFUNC("ExecuteAOT ret : %{public}d", ret);
752 #ifdef CODE_SIGNATURE_ENABLE
753     AOTSignDataCacheMgr::GetInstance().AddSignDataForSysComp(aotArgs.anFileName, signData, ret);
754 #endif
755 }
756 
HandleIdleWithSingleHap(const InnerBundleInfo & info,const std::string & moduleName,const std::string & compileMode) const757 void AOTHandler::HandleIdleWithSingleHap(
758     const InnerBundleInfo &info, const std::string &moduleName, const std::string &compileMode) const
759 {
760     APP_LOGD("HandleIdleWithSingleHap, moduleName : %{public}s", moduleName.c_str());
761     if (!NeedCompile(info, moduleName)) {
762         return;
763     }
764     std::optional<AOTArgs> aotArgs = BuildAOTArgs(info, moduleName, compileMode);
765     (void)AOTInternal(aotArgs, info.GetVersionCode());
766 }
767 
NeedCompile(const InnerBundleInfo & info,const std::string & moduleName) const768 bool AOTHandler::NeedCompile(const InnerBundleInfo &info, const std::string &moduleName) const
769 {
770     AOTCompileStatus status = info.GetAOTCompileStatus(moduleName);
771     if (status == AOTCompileStatus::NOT_COMPILED || status == AOTCompileStatus::COMPILE_CANCELLED) {
772         return true;
773     }
774     APP_LOGI("%{public}s:%{public}d, skip compile", moduleName.c_str(), static_cast<int32_t>(status));
775     return false;
776 }
777 
HandleCompileWithSingleHap(const InnerBundleInfo & info,const std::string & moduleName,const std::string & compileMode,bool isEnableBaselinePgo) const778 ErrCode AOTHandler::HandleCompileWithSingleHap(const InnerBundleInfo &info, const std::string &moduleName,
779     const std::string &compileMode, bool isEnableBaselinePgo) const
780 {
781     APP_LOGI("HandleCompileWithSingleHap, moduleName : %{public}s", moduleName.c_str());
782     std::optional<AOTArgs> aotArgs = BuildAOTArgs(info, moduleName, compileMode, isEnableBaselinePgo);
783     return AOTInternal(aotArgs, info.GetVersionCode());
784 }
785 
CheckDeviceState() const786 bool AOTHandler::CheckDeviceState() const
787 {
788 #ifdef BUNDLE_FRAMEWORK_POWER_MGR_ENABLE
789     DisplayPowerMgr::DisplayState displayState =
790         DisplayPowerMgr::DisplayPowerMgrClient::GetInstance().GetDisplayState();
791     if (displayState != DisplayPowerMgr::DisplayState::DISPLAY_OFF) {
792         LOG_I(BMS_TAG_AOT, "displayState is not DISPLAY_OFF");
793         return false;
794     }
795     return true;
796 #else
797     APP_LOGI("device not support power system");
798     return false;
799 #endif
800 }
801 
HandleIdle() const802 void AOTHandler::HandleIdle() const
803 {
804     APP_LOGI("HandleIdle begin");
805     std::unique_lock<std::mutex> lock(idleMutex_, std::defer_lock);
806     if (!lock.try_lock()) {
807         APP_LOGI("idle task is running, skip");
808         return;
809     }
810     if (!IsSupportARM64()) {
811         APP_LOGI("current device doesn't support arm64, no need to AOT");
812         return;
813     }
814     std::string compileMode = system::GetParameter(IDLE_COMPILE_MODE, ServiceConstants::COMPILE_PARTIAL);
815     APP_LOGI("%{public}s = %{public}s", IDLE_COMPILE_MODE, compileMode.c_str());
816     if (compileMode == COMPILE_NONE) {
817         APP_LOGI("%{public}s none, no need to AOT", IDLE_COMPILE_MODE);
818         return;
819     }
820     if (!CheckDeviceState()) {
821         APP_LOGI("device state is not suitable");
822         return;
823     }
824     IdleForSysComp();
825     IdleForHap(compileMode);
826     APP_LOGI("HandleIdle end");
827 }
828 
HandleCompile(const std::string & bundleName,const std::string & compileMode,bool isAllBundle,std::vector<std::string> & compileResults) const829 ErrCode AOTHandler::HandleCompile(const std::string &bundleName, const std::string &compileMode, bool isAllBundle,
830     std::vector<std::string> &compileResults) const
831 {
832     APP_LOGI("HandleCompile begin");
833     if (isAllBundle && system::GetParameter("BM_AOT_TEST", "").empty()) {
834         APP_LOGD("isAllBundle true, param bm.aot.test empty, so ignore");
835         return ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_FAILED;
836     }
837     std::unique_lock<std::mutex> lock(compileMutex_, std::defer_lock);
838     if (!lock.try_lock()) {
839         APP_LOGI("compile task running, skip %{public}s", bundleName.c_str());
840         std::string compileResult = "info: compile task is running, skip.";
841         compileResults.emplace_back(compileResult);
842         return ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_FAILED;
843     }
844     if (!IsSupportARM64()) {
845         APP_LOGI("current device doesn't support arm64, no need to AOT");
846         std::string compileResult = "info: current device doesn't support arm64, no need to AOT.";
847         compileResults.emplace_back(compileResult);
848         return ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_FAILED;
849     }
850     if (compileMode == COMPILE_NONE) {
851         APP_LOGI("%{public}s none, no need to AOT", IDLE_COMPILE_MODE);
852         std::string compileResult = "info: persist.bm.idle.arkopt = none, no need to AOT.";
853         compileResults.emplace_back(compileResult);
854         return ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_FAILED;
855     }
856     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
857     if (!dataMgr) {
858         APP_LOGE("dataMgr is null");
859         std::string compileResult = "error: dataMgr is null, compile fail.";
860         compileResults.emplace_back(compileResult);
861         return ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_FAILED;
862     }
863     std::vector<std::string> bundleNames;
864     if (isAllBundle) {
865         bundleNames = dataMgr->GetAllBundleName();
866     } else {
867         bundleNames = {bundleName};
868     }
869     ErrCode ret = HandleCompileBundles(bundleNames, compileMode, dataMgr, compileResults);
870     if (ret == ERR_OK) {
871         compileResults.clear();
872     }
873     APP_LOGI("HandleCompile end");
874     return ret;
875 }
876 
HandleCompileBundles(const std::vector<std::string> & bundleNames,const std::string & compileMode,std::shared_ptr<BundleDataMgr> & dataMgr,std::vector<std::string> & compileResults) const877 ErrCode AOTHandler::HandleCompileBundles(const std::vector<std::string> &bundleNames, const std::string &compileMode,
878     std::shared_ptr<BundleDataMgr> &dataMgr, std::vector<std::string> &compileResults) const
879 {
880     ErrCode ret = ERR_OK;
881     std::for_each(bundleNames.cbegin(), bundleNames.cend(),
882         [this, dataMgr, &compileMode, &ret, &compileResults](const auto &bundleToCompile) {
883         APP_LOGD("HandleCompile bundleToCompile : %{public}s", bundleToCompile.c_str());
884         InnerBundleInfo info;
885         if (!dataMgr->QueryInnerBundleInfo(bundleToCompile, info)) {
886             APP_LOGE("QueryInnerBundleInfo failed. bundleToCompile %{public}s", bundleToCompile.c_str());
887             std::string compileResult = bundleToCompile + ": QueryInnerBundleInfo failed.";
888             compileResults.emplace_back(compileResult);
889             ret = ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_FAILED;
890             return;
891         }
892         if (!info.GetIsNewVersion()) {
893             APP_LOGD("not stage model, no need to AOT");
894             std::string compileResult = bundleToCompile + ": not stage model, no need to AOT.";
895             compileResults.emplace_back(compileResult);
896             ret = ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_FAILED;
897             return;
898         }
899         std::vector<std::string> moduleNames;
900         info.GetModuleNames(moduleNames);
901         std::string compileResult = "";
902         if (HandleCompileModules(moduleNames, compileMode, info, compileResult) == ERR_OK) {
903             compileResult = bundleToCompile + ": compile success.";
904         } else {
905             compileResult = bundleToCompile + ":" + compileResult;
906             ret = ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_FAILED;
907         }
908         compileResults.emplace_back(compileResult);
909     });
910     return ret;
911 }
912 
HandleCompileModules(const std::vector<std::string> & moduleNames,const std::string & compileMode,InnerBundleInfo & info,std::string & compileResult) const913 ErrCode AOTHandler::HandleCompileModules(const std::vector<std::string> &moduleNames, const std::string &compileMode,
914     InnerBundleInfo &info, std::string &compileResult) const
915 {
916     ErrCode ret = ERR_OK;
917     std::for_each(moduleNames.cbegin(), moduleNames.cend(),
918         [this, &info, &compileMode, &ret, &compileResult](const auto &moduleName) {
919         ErrCode errCode = HandleCompileWithSingleHap(info, moduleName, compileMode);
920         switch (errCode) {
921             case ERR_OK:
922                 break;
923             case ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_FAILED:
924                 compileResult += "  " + moduleName + ":compile-fail";
925                 break;
926             case ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_CRASH:
927                 compileResult += "  " + moduleName + ":compile-crash";
928                 break;
929             case ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_CANCELLED:
930                 compileResult += "  " + moduleName + ":compile-cancelled";
931                 break;
932             case ERR_APPEXECFWK_INSTALLD_SIGN_AOT_FAILED:
933                 compileResult += "  " + moduleName + ":signature-fail";
934                 break;
935             case ERR_APPEXECFWK_INSTALLD_SIGN_AOT_DISABLE:
936                 compileResult += "  " + moduleName + ":signature-disable";
937                 break;
938             case ERR_APPEXECFWK_AOT_ARGS_EMPTY:
939                 compileResult += "  " + moduleName + ":args-empty";
940                 break;
941             default:
942                 compileResult += "  " + moduleName + ":other-fail";
943                 break;
944         }
945         if (errCode != ERR_OK) {
946             ret = ERR_APPEXECFWK_INSTALLD_AOT_EXECUTE_FAILED;
947         }
948     });
949     return ret;
950 }
951 
HandleArkPathsChange() const952 void AOTHandler::HandleArkPathsChange() const
953 {
954     bool isHandled = false;
955     (void)BMSEventHandler::CheckOtaFlag(OTAFlag::DELETE_DEPRECATED_ARK_PATHS, isHandled);
956     if (isHandled) {
957         return;
958     }
959     APP_LOGI("HandleArkPathsChange begin");
960     DelDeprecatedArkPaths();
961     CreateArkProfilePaths();
962     APP_LOGI("HandleArkPathsChange end");
963     (void)BMSEventHandler::UpdateOtaFlag(OTAFlag::DELETE_DEPRECATED_ARK_PATHS);
964 }
965 
DelDeprecatedArkPaths() const966 void AOTHandler::DelDeprecatedArkPaths() const
967 {
968     (void)InstalldClient::GetInstance()->RemoveDir(DEPRECATED_ARK_CACHE_PATH);
969     (void)InstalldClient::GetInstance()->RemoveDir(DEPRECATED_ARK_PROFILE_PATH);
970 }
971 
CreateArkProfilePaths() const972 void AOTHandler::CreateArkProfilePaths() const
973 {
974     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
975     if (dataMgr == nullptr) {
976         APP_LOGE("dataMgr null");
977         return;
978     }
979     std::set<int32_t> userIds = dataMgr->GetAllUser();
980     for (const int32_t &userId : userIds) {
981         std::string userIdPath = BuildArkProfilePath(userId);
982         bool isExist = false;
983         (void)InstalldClient::GetInstance()->IsExistDir(userIdPath, isExist);
984         if (!isExist) {
985             APP_LOGE("userIdPath %{public}s not exist", userIdPath.c_str());
986             continue;
987         }
988         auto bundles = dataMgr->GetAllLiteBundleInfo(userId);
989         for (const auto &[bundleName, uid, gid] : bundles) {
990             std::string arkProfilePath = BuildArkProfilePath(userId, bundleName);
991             (void)InstalldClient::GetInstance()->Mkdir(arkProfilePath, S_IRWXU, uid, gid);
992         }
993     }
994 }
995 
GetSysCompList() const996 std::vector<std::string> AOTHandler::GetSysCompList() const
997 {
998     std::ifstream configFile(SYS_COMP_CONFIG_PATH);
999     if (!configFile.is_open()) {
1000         APP_LOGE_NOFUNC("open %{public}s failed", SYS_COMP_CONFIG_PATH);
1001         return {};
1002     }
1003     std::vector<std::string> sysCompList;
1004     std::string line;
1005     while (std::getline(configFile, line)) {
1006         if (!line.empty()) {
1007             sysCompList.emplace_back(line);
1008         }
1009     }
1010     return sysCompList;
1011 }
1012 
IdleForSysComp() const1013 void AOTHandler::IdleForSysComp() const
1014 {
1015     APP_LOGI_NOFUNC("IdleForSysComp begin");
1016     std::vector<std::string> sysCompList = GetSysCompList();
1017     if (sysCompList.empty()) {
1018         APP_LOGI_NOFUNC("sysCompList empty");
1019         return;
1020     }
1021     APP_LOGI_NOFUNC("sysCompList size : %{public}zu", sysCompList.size());
1022     for (const std::string &abcPath : sysCompList) {
1023         HandleIdleWithSingleSysComp(abcPath);
1024     }
1025     APP_LOGI_NOFUNC("IdleForSysComp end");
1026 }
1027 
IdleForHap(const std::string & compileMode) const1028 void AOTHandler::IdleForHap(const std::string &compileMode) const
1029 {
1030     APP_LOGI_NOFUNC("IdleForHap begin");
1031     auto dataMgr = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1032     if (!dataMgr) {
1033         APP_LOGE_NOFUNC("dataMgr is null");
1034         return;
1035     }
1036     std::vector<std::string> bundleNames = dataMgr->GetAllBundleName();
1037     std::for_each(bundleNames.cbegin(), bundleNames.cend(), [this, dataMgr, &compileMode](const auto &bundleName) {
1038         APP_LOGD("HandleIdle bundleName : %{public}s", bundleName.c_str());
1039         InnerBundleInfo info;
1040         if (!dataMgr->QueryInnerBundleInfo(bundleName, info)) {
1041             APP_LOGE_NOFUNC("QueryInnerBundleInfo failed");
1042             return;
1043         }
1044         if (!info.GetIsNewVersion()) {
1045             APP_LOGD("not stage model, no need to AOT");
1046             return;
1047         }
1048         std::vector<std::string> moduleNames;
1049         info.GetModuleNames(moduleNames);
1050         std::for_each(moduleNames.cbegin(), moduleNames.cend(), [this, &info, &compileMode](const auto &moduleName) {
1051             HandleIdleWithSingleHap(info, moduleName, compileMode);
1052         });
1053     });
1054     APP_LOGI_NOFUNC("IdleForHap end");
1055 }
1056 }  // namespace AppExecFwk
1057 }  // namespace OHOS
1058