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