• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "base_bundle_installer.h"
17 
18 #include <sys/stat.h>
19 #include "nlohmann/json.hpp"
20 
21 #include <unistd.h>
22 
23 #include "account_helper.h"
24 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
25 #include "aging/bundle_aging_mgr.h"
26 #endif
27 #include "app_control_constants.h"
28 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
29 #include "default_app_mgr.h"
30 #endif
31 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
32 #include "quick_fix/app_quick_fix.h"
33 #include "quick_fix/inner_app_quick_fix.h"
34 #include "quick_fix/quick_fix_data_mgr.h"
35 #include "quick_fix/quick_fix_switcher.h"
36 #include "quick_fix/quick_fix_deleter.h"
37 #endif
38 #include "ability_manager_helper.h"
39 #include "app_log_wrapper.h"
40 #include "bundle_constants.h"
41 #include "bundle_extractor.h"
42 #include "bundle_mgr_service.h"
43 #include "bundle_sandbox_app_helper.h"
44 #include "bundle_permission_mgr.h"
45 #include "bundle_util.h"
46 #include "hitrace_meter.h"
47 #include "datetime_ex.h"
48 #include "installd_client.h"
49 #include "parameter.h"
50 #include "perf_profile.h"
51 #include "scope_guard.h"
52 #include "string_ex.h"
53 
54 namespace OHOS {
55 namespace AppExecFwk {
56 using namespace OHOS::Security;
57 namespace {
58 const std::string ARK_CACHE_PATH = "/data/local/ark-cache/";
59 const std::string ARK_PROFILE_PATH = "/data/local/ark-profile/";
60 const std::string LOG = "log";
61 const char* BMS_KEY_SHELL_UID = "const.product.shell.uid";
62 
GetHapPath(const InnerBundleInfo & info,const std::string & moduleName)63 std::string GetHapPath(const InnerBundleInfo &info, const std::string &moduleName)
64 {
65     std::string fileSuffix = Constants::INSTALL_FILE_SUFFIX;
66     auto moduleInfo = info.GetInnerModuleInfoByModuleName(moduleName);
67     if (moduleInfo && moduleInfo->distro.moduleType == Profile::MODULE_TYPE_SHARED) {
68         APP_LOGD("The module(%{public}s) is shared.", moduleName.c_str());
69         fileSuffix = Constants::INSTALL_SHARED_FILE_SUFFIX;
70     }
71 
72     return info.GetAppCodePath() + Constants::PATH_SEPARATOR + moduleName + fileSuffix;
73 }
74 
GetHapPath(const InnerBundleInfo & info)75 std::string GetHapPath(const InnerBundleInfo &info)
76 {
77     return GetHapPath(info, info.GetModuleName(info.GetCurrentModulePackage()));
78 }
79 
BuildTempNativeLibraryPath(const std::string & nativeLibraryPath)80 std::string BuildTempNativeLibraryPath(const std::string &nativeLibraryPath)
81 {
82     auto position = nativeLibraryPath.find(Constants::PATH_SEPARATOR);
83     if (position == std::string::npos) {
84         return nativeLibraryPath;
85     }
86 
87     auto prefixPath = nativeLibraryPath.substr(0, position);
88     auto suffixPath = nativeLibraryPath.substr(position);
89     return prefixPath + Constants::TMP_SUFFIX + suffixPath;
90 }
91 }
92 
BaseBundleInstaller()93 BaseBundleInstaller::BaseBundleInstaller()
94     : bundleInstallChecker_(std::make_unique<BundleInstallChecker>())
95 {
96     APP_LOGI("base bundle installer instance is created");
97 }
98 
~BaseBundleInstaller()99 BaseBundleInstaller::~BaseBundleInstaller()
100 {
101     APP_LOGI("base bundle installer instance is destroyed");
102 }
103 
InstallBundle(const std::string & bundlePath,const InstallParam & installParam,const Constants::AppType appType)104 ErrCode BaseBundleInstaller::InstallBundle(
105     const std::string &bundlePath, const InstallParam &installParam, const Constants::AppType appType)
106 {
107     std::vector<std::string> bundlePaths { bundlePath };
108     return InstallBundle(bundlePaths, installParam, appType);
109 }
110 
InstallBundle(const std::vector<std::string> & bundlePaths,const InstallParam & installParam,const Constants::AppType appType)111 ErrCode BaseBundleInstaller::InstallBundle(
112     const std::vector<std::string> &bundlePaths, const InstallParam &installParam, const Constants::AppType appType)
113 {
114     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
115     APP_LOGD("begin to process bundle install");
116 
117     PerfProfile::GetInstance().SetBundleInstallStartTime(GetTickCount());
118 
119     int32_t uid = Constants::INVALID_UID;
120     ErrCode result = ProcessBundleInstall(bundlePaths, installParam, appType, uid);
121     if (installParam.needSendEvent && dataMgr_ && !bundleName_.empty()) {
122         NotifyBundleEvents installRes = {
123             .bundleName = bundleName_,
124             .abilityName = mainAbility_,
125             .resultCode = result,
126             .type = (isAppExist_ && hasInstalledInUser_) ? NotifyType::UPDATE : NotifyType::INSTALL,
127             .uid = uid,
128             .accessTokenId = accessTokenId_
129         };
130         if (NotifyBundleStatus(installRes) != ERR_OK) {
131             APP_LOGW("notify status failed for installation");
132         }
133     }
134 
135     SendBundleSystemEvent(
136         bundleName_,
137         ((isAppExist_ && hasInstalledInUser_) ? BundleEventType::UPDATE : BundleEventType::INSTALL),
138         installParam,
139         sysEventInfo_.preBundleScene,
140         result);
141     PerfProfile::GetInstance().SetBundleInstallEndTime(GetTickCount());
142     APP_LOGD("finish to process bundle install");
143     return result;
144 }
145 
InstallBundleByBundleName(const std::string & bundleName,const InstallParam & installParam)146 ErrCode BaseBundleInstaller::InstallBundleByBundleName(
147     const std::string &bundleName, const InstallParam &installParam)
148 {
149     APP_LOGD("begin to process bundle install by bundleName, which is %{public}s.", bundleName.c_str());
150     PerfProfile::GetInstance().SetBundleInstallStartTime(GetTickCount());
151 
152     int32_t uid = Constants::INVALID_UID;
153     ErrCode result = ProcessInstallBundleByBundleName(bundleName, installParam, uid);
154     if (installParam.needSendEvent && dataMgr_ && !bundleName.empty()) {
155         NotifyBundleEvents installRes = {
156             .bundleName = bundleName,
157             .resultCode = result,
158             .type = NotifyType::INSTALL,
159             .uid = uid,
160             .accessTokenId = accessTokenId_
161         };
162         if (NotifyBundleStatus(installRes) != ERR_OK) {
163             APP_LOGW("notify status failed for installation");
164         }
165     }
166 
167     SendBundleSystemEvent(
168         bundleName,
169         BundleEventType::INSTALL,
170         installParam,
171         InstallScene::CREATE_USER,
172         result);
173     PerfProfile::GetInstance().SetBundleInstallEndTime(GetTickCount());
174     APP_LOGD("finish to process %{public}s bundle install", bundleName.c_str());
175     return result;
176 }
177 
Recover(const std::string & bundleName,const InstallParam & installParam)178 ErrCode BaseBundleInstaller::Recover(
179     const std::string &bundleName, const InstallParam &installParam)
180 {
181     APP_LOGD("begin to process bundle recover by bundleName, which is %{public}s.", bundleName.c_str());
182     PerfProfile::GetInstance().SetBundleInstallStartTime(GetTickCount());
183     if (!BundlePermissionMgr::Init()) {
184         APP_LOGW("BundlePermissionMgr::Init failed");
185     }
186     int32_t uid = Constants::INVALID_UID;
187     ErrCode result = ProcessRecover(bundleName, installParam, uid);
188     if (installParam.needSendEvent && dataMgr_ && !bundleName_.empty() && !modulePackage_.empty()) {
189         NotifyBundleEvents installRes = {
190             .bundleName = bundleName,
191             .resultCode = result,
192             .type = NotifyType::INSTALL,
193             .uid = uid,
194             .accessTokenId = accessTokenId_
195         };
196         if (NotifyBundleStatus(installRes) != ERR_OK) {
197             APP_LOGW("notify status failed for installation");
198         }
199     }
200 
201     auto recoverInstallParam = installParam;
202     recoverInstallParam.isPreInstallApp = true;
203     SendBundleSystemEvent(
204         bundleName,
205         BundleEventType::RECOVER,
206         recoverInstallParam,
207         sysEventInfo_.preBundleScene,
208         result);
209     PerfProfile::GetInstance().SetBundleInstallEndTime(GetTickCount());
210     BundlePermissionMgr::UnInit();
211     APP_LOGD("finish to process %{public}s bundle recover", bundleName.c_str());
212     return result;
213 }
214 
UninstallBundle(const std::string & bundleName,const InstallParam & installParam)215 ErrCode BaseBundleInstaller::UninstallBundle(const std::string &bundleName, const InstallParam &installParam)
216 {
217     APP_LOGD("begin to process %{public}s bundle uninstall", bundleName.c_str());
218     PerfProfile::GetInstance().SetBundleUninstallStartTime(GetTickCount());
219 
220     // uninstall all sandbox app before
221     UninstallAllSandboxApps(bundleName, installParam.userId);
222 
223     int32_t uid = Constants::INVALID_UID;
224     ErrCode result = ProcessBundleUninstall(bundleName, installParam, uid);
225     if (installParam.needSendEvent && dataMgr_) {
226         NotifyBundleEvents installRes = {
227             .bundleName = bundleName,
228             .resultCode = result,
229             .type = NotifyType::UNINSTALL_BUNDLE,
230             .uid = uid,
231             .accessTokenId = accessTokenId_,
232             .isAgingUninstall = installParam.isAgingUninstall
233         };
234         if (NotifyBundleStatus(installRes) != ERR_OK) {
235             APP_LOGW("notify status failed for installation");
236         }
237     }
238 
239     if (result == ERR_OK) {
240 #ifdef BUNDLE_FRAMEWORK_DEFAULT_APP
241         DefaultAppMgr::GetInstance().HandleUninstallBundle(userId_, bundleName);
242 #endif
243     }
244 
245     SendBundleSystemEvent(
246         bundleName,
247         BundleEventType::UNINSTALL,
248         installParam,
249         sysEventInfo_.preBundleScene,
250         result);
251     PerfProfile::GetInstance().SetBundleUninstallEndTime(GetTickCount());
252     APP_LOGD("finish to process %{public}s bundle uninstall", bundleName.c_str());
253     return result;
254 }
255 
UninstallBundle(const std::string & bundleName,const std::string & modulePackage,const InstallParam & installParam)256 ErrCode BaseBundleInstaller::UninstallBundle(
257     const std::string &bundleName, const std::string &modulePackage, const InstallParam &installParam)
258 {
259     APP_LOGD("begin to process %{public}s module in %{public}s uninstall", modulePackage.c_str(), bundleName.c_str());
260     PerfProfile::GetInstance().SetBundleUninstallStartTime(GetTickCount());
261 
262     // uninstall all sandbox app before
263     UninstallAllSandboxApps(bundleName, installParam.userId);
264 
265     int32_t uid = Constants::INVALID_UID;
266     ErrCode result = ProcessBundleUninstall(bundleName, modulePackage, installParam, uid);
267     if (installParam.needSendEvent && dataMgr_) {
268         NotifyBundleEvents installRes = {
269             .bundleName = bundleName,
270             .modulePackage = modulePackage,
271             .resultCode = result,
272             .type = NotifyType::UNINSTALL_MODULE,
273             .uid = uid,
274             .accessTokenId = accessTokenId_,
275             .isAgingUninstall = installParam.isAgingUninstall
276         };
277         if (NotifyBundleStatus(installRes) != ERR_OK) {
278             APP_LOGW("notify status failed for installation");
279         }
280     }
281 
282     SendBundleSystemEvent(
283         bundleName,
284         BundleEventType::UNINSTALL,
285         installParam,
286         sysEventInfo_.preBundleScene,
287         result);
288     PerfProfile::GetInstance().SetBundleUninstallEndTime(GetTickCount());
289     APP_LOGD("finish to process %{public}s module in %{public}s uninstall", modulePackage.c_str(), bundleName.c_str());
290     return result;
291 }
292 
UninstallAppControl(const std::string & appId,int32_t userId)293 bool BaseBundleInstaller::UninstallAppControl(const std::string &appId, int32_t userId)
294 {
295 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
296     std::vector<std::string> appIds;
297     ErrCode ret = DelayedSingleton<AppControlManager>::GetInstance()->GetAppInstallControlRule(
298         AppControlConstants::EDM_CALLING, AppControlConstants::APP_DISALLOWED_UNINSTALL, userId, appIds);
299     if (ret != ERR_OK) {
300         APP_LOGE("GetAppInstallControlRule failed code:%{public}d", ret);
301         return true;
302     }
303     if (std::find(appIds.begin(), appIds.end(), appId) == appIds.end()) {
304         return true;
305     }
306     APP_LOGW("appId is not removable");
307     return false;
308 #else
309     APP_LOGW("app control is disable");
310     return true;
311 #endif
312 }
313 
InstallAppControl(const std::vector<std::string> & installAppIds,int32_t userId)314 ErrCode BaseBundleInstaller::InstallAppControl(
315     const std::vector<std::string> &installAppIds, int32_t userId)
316 {
317 #ifdef BUNDLE_FRAMEWORK_APP_CONTROL
318     std::vector<std::string> appIds;
319     ErrCode ret = DelayedSingleton<AppControlManager>::GetInstance()->GetAppInstallControlRule(
320         AppControlConstants::EDM_CALLING, AppControlConstants::APP_ALLOWED_INSTALL, userId, appIds);
321     if (ret != ERR_OK) {
322         APP_LOGE("GetAppInstallControlRule failed code:%{public}d", ret);
323         return ret;
324     }
325     if (appIds.empty()) {
326         return ERR_OK;
327     }
328     for (const auto &installAppId : installAppIds) {
329         if (std::find(appIds.begin(), appIds.end(), installAppId) == appIds.end()) {
330             APP_LOGE("appId:%{public}s is dis allow install", installAppId.c_str());
331             return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_INSTALL;
332         }
333     }
334     return ERR_OK;
335 #else
336     APP_LOGW("app control is disable");
337     return ERR_OK;
338 #endif
339 }
340 
UpdateInstallerState(const InstallerState state)341 void BaseBundleInstaller::UpdateInstallerState(const InstallerState state)
342 {
343     APP_LOGD("UpdateInstallerState in BaseBundleInstaller state %{public}d", state);
344     SetInstallerState(state);
345 }
346 
SaveOldRemovableInfo(InnerModuleInfo & newModuleInfo,InnerBundleInfo & oldInfo,bool existModule)347 void BaseBundleInstaller::SaveOldRemovableInfo(
348     InnerModuleInfo &newModuleInfo, InnerBundleInfo &oldInfo, bool existModule)
349 {
350     if (existModule) {
351         // save old module useId isRemovable info to new module
352         auto oldModule = oldInfo.FetchInnerModuleInfos().find(newModuleInfo.modulePackage);
353         if (oldModule == oldInfo.FetchInnerModuleInfos().end()) {
354             APP_LOGE("can not find module %{public}s in oldInfo", newModuleInfo.modulePackage.c_str());
355             return;
356         }
357         for (const auto &remove : oldModule->second.isRemovable) {
358             auto result = newModuleInfo.isRemovable.try_emplace(remove.first, remove.second);
359             if (!result.second) {
360                 APP_LOGE("%{public}s removable add %{public}s from old:%{public}d failed",
361                     newModuleInfo.modulePackage.c_str(), remove.first.c_str(), remove.second);
362             }
363             APP_LOGD("%{public}s removable add %{public}s from old:%{public}d",
364                 newModuleInfo.modulePackage.c_str(), remove.first.c_str(), remove.second);
365         }
366     }
367 }
368 
CheckEnableRemovable(std::unordered_map<std::string,InnerBundleInfo> & newInfos,InnerBundleInfo & oldInfo,int32_t & userId,bool isFreeInstallFlag,bool isAppExist)369 void BaseBundleInstaller::CheckEnableRemovable(std::unordered_map<std::string, InnerBundleInfo> &newInfos,
370     InnerBundleInfo &oldInfo, int32_t &userId, bool isFreeInstallFlag, bool isAppExist)
371 {
372     for (auto &item : newInfos) {
373         std::map<std::string, InnerModuleInfo> &moduleInfo = item.second.FetchInnerModuleInfos();
374         bool hasInstalledInUser = oldInfo.HasInnerBundleUserInfo(userId);
375         // now there are three cases for set haps isRemovable true:
376         // 1. FREE_INSTALL flag
377         // 2. bundle not exist in current user
378         // 3. bundle exist, hap not exist
379         // 4. hap exist not in current userId
380         for (auto &iter : moduleInfo) {
381             APP_LOGD("modulePackage:(%{public}s), userId:%{public}d, flag:%{public}d, isAppExist:%{public}d",
382                 iter.second.modulePackage.c_str(), userId, isFreeInstallFlag, isAppExist);
383             bool existModule = oldInfo.FindModule(iter.second.modulePackage);
384             bool hasModuleInUser = item.second.IsUserExistModule(iter.second.moduleName, userId);
385             APP_LOGD("hasInstalledInUser:%{public}d, existModule:(%{public}d), hasModuleInUser:(%{public}d)",
386                 hasInstalledInUser, existModule, hasModuleInUser);
387             if (isFreeInstallFlag && (!isAppExist || !hasInstalledInUser || !existModule || !hasModuleInUser)) {
388                 APP_LOGD("hasInstalledInUser:%{public}d, isAppExist:%{public}d existModule:(%{public}d)",
389                     hasInstalledInUser, isAppExist, existModule);
390                 item.second.SetModuleRemovable(iter.second.moduleName, true, userId);
391                 SaveOldRemovableInfo(iter.second, oldInfo, existModule);
392             }
393         }
394     }
395 }
396 
InnerProcessBundleInstall(std::unordered_map<std::string,InnerBundleInfo> & newInfos,InnerBundleInfo & oldInfo,const InstallParam & installParam,int32_t & uid)397 ErrCode BaseBundleInstaller::InnerProcessBundleInstall(std::unordered_map<std::string, InnerBundleInfo> &newInfos,
398     InnerBundleInfo &oldInfo, const InstallParam &installParam, int32_t &uid)
399 {
400     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
401     APP_LOGI("InnerProcessBundleInstall with bundleName %{public}s, userId is %{public}d", bundleName_.c_str(),
402         userId_);
403     if (installParam.needSavePreInstallInfo) {
404         PreInstallBundleInfo preInstallBundleInfo;
405         dataMgr_->GetPreInstallBundleInfo(bundleName_, preInstallBundleInfo);
406         preInstallBundleInfo.SetAppType(newInfos.begin()->second.GetAppType());
407         preInstallBundleInfo.SetVersionCode(newInfos.begin()->second.GetVersionCode());
408         for (const auto &item : newInfos) {
409             preInstallBundleInfo.AddBundlePath(item.first);
410         }
411 #ifdef USE_PRE_BUNDLE_PROFILE
412     preInstallBundleInfo.SetRemovable(installParam.removable);
413 #else
414     preInstallBundleInfo.SetRemovable(newInfos.begin()->second.IsRemovable());
415 #endif
416         dataMgr_->SavePreInstallBundleInfo(bundleName_, preInstallBundleInfo);
417     }
418 
419     // singleton app can only be installed in U0 and U0 can only install singleton app.
420     bool isSingleton = newInfos.begin()->second.IsSingleton();
421     if ((isSingleton && (userId_ != Constants::DEFAULT_USERID)) ||
422         (!isSingleton && (userId_ == Constants::DEFAULT_USERID))) {
423         APP_LOGW("singleton(%{public}d) app(%{public}s) and user(%{public}d) are not matched.",
424             isSingleton, bundleName_.c_str(), userId_);
425         return ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON;
426     }
427 
428     // try to get the bundle info to decide use install or update. Always keep other exceptions below this line.
429     if (!GetInnerBundleInfo(oldInfo, isAppExist_)) {
430         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
431     }
432     APP_LOGI("flag:%{public}d, userId:%{public}d, isAppExist:%{public}d",
433         installParam.installFlag, userId_, isAppExist_);
434     bool isFreeInstallFlag = (installParam.installFlag == InstallFlag::FREE_INSTALL);
435     CheckEnableRemovable(newInfos, oldInfo, userId_, isFreeInstallFlag, isAppExist_);
436 
437     ErrCode result = ERR_OK;
438     if (isAppExist_) {
439         result = CheckInstallationFree(oldInfo, newInfos);
440         CHECK_RESULT(result, "CheckInstallationFree failed %{public}d");
441         // to guarantee that the hap version can be compatible.
442         result = CheckVersionCompatibility(oldInfo);
443         CHECK_RESULT(result, "The app has been installed and update lower version bundle %{public}d");
444         // to check native file between oldInfo and newInfos.
445         result = CheckNativeFileWithOldInfo(oldInfo, newInfos);
446         CHECK_RESULT(result, "Check native so between oldInfo and newInfos failed %{public}d");
447 
448         hasInstalledInUser_ = oldInfo.HasInnerBundleUserInfo(userId_);
449         if (!hasInstalledInUser_) {
450             APP_LOGD("new userInfo with bundleName %{public}s and userId %{public}d",
451                 bundleName_.c_str(), userId_);
452             InnerBundleUserInfo newInnerBundleUserInfo;
453             newInnerBundleUserInfo.bundleUserInfo.userId = userId_;
454             newInnerBundleUserInfo.bundleName = bundleName_;
455             oldInfo.AddInnerBundleUserInfo(newInnerBundleUserInfo);
456             ScopeGuard userGuard([&] { RemoveBundleUserData(oldInfo, false); });
457             accessTokenId_ = CreateAccessTokenId(oldInfo);
458             oldInfo.SetAccessTokenId(accessTokenId_, userId_);
459             result = GrantRequestPermissions(oldInfo, accessTokenId_);
460             CHECK_RESULT(result, "GrantRequestPermissions failed %{public}d");
461 
462             result = CreateBundleUserData(oldInfo);
463             CHECK_RESULT(result, "CreateBundleUserData failed %{public}d");
464             // extract ap file
465             result = ExtractAllArkProfileFile(oldInfo);
466             CHECK_RESULT(result, "ExtractAllArkProfileFile failed %{public}d");
467 
468             userGuard.Dismiss();
469         }
470 
471         for (auto &info : newInfos) {
472             std::string packageName = info.second.GetCurrentModulePackage();
473             if (oldInfo.FindModule(packageName)) {
474                 installedModules_[packageName] = true;
475             }
476         }
477     }
478 
479     auto it = newInfos.begin();
480     if (!isAppExist_) {
481         APP_LOGI("app is not exist");
482         InnerBundleInfo &newInfo = it->second;
483         modulePath_ = it->first;
484         InnerBundleUserInfo newInnerBundleUserInfo;
485         newInnerBundleUserInfo.bundleUserInfo.userId = userId_;
486         newInnerBundleUserInfo.bundleName = bundleName_;
487         newInfo.AddInnerBundleUserInfo(newInnerBundleUserInfo);
488         APP_LOGI("SetIsFreeInstallApp(%{public}d)", InstallFlag::FREE_INSTALL == installParam.installFlag);
489         newInfo.SetIsFreeInstallApp(InstallFlag::FREE_INSTALL == installParam.installFlag);
490         result = ProcessBundleInstallStatus(newInfo, uid);
491         CHECK_RESULT(result, "ProcessBundleInstallStatus failed %{public}d");
492 
493         it++;
494         hasInstalledInUser_ = true;
495     }
496 
497     InnerBundleInfo bundleInfo;
498     bool isBundleExist = false;
499     if (!GetInnerBundleInfo(bundleInfo, isBundleExist) || !isBundleExist) {
500         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
501     }
502 
503     InnerBundleUserInfo innerBundleUserInfo;
504     if (!bundleInfo.GetInnerBundleUserInfo(userId_, innerBundleUserInfo)) {
505         APP_LOGE("oldInfo do not have user");
506         return ERR_APPEXECFWK_USER_NOT_EXIST;
507     }
508 
509     ScopeGuard userGuard([&] {
510         if (!hasInstalledInUser_ || (!isAppExist_)) {
511             RemoveBundleUserData(oldInfo, false);
512         }
513     });
514 
515     // update haps
516     for (; it != newInfos.end(); ++it) {
517         modulePath_ = it->first;
518         InnerBundleInfo &newInfo = it->second;
519         newInfo.AddInnerBundleUserInfo(innerBundleUserInfo);
520         bool isReplace = (installParam.installFlag == InstallFlag::REPLACE_EXISTING ||
521             installParam.installFlag == InstallFlag::FREE_INSTALL);
522         // app exist, but module may not
523         if ((result = ProcessBundleUpdateStatus(
524             bundleInfo, newInfo, isReplace, installParam.noSkipsKill)) != ERR_OK) {
525             break;
526         }
527     }
528 
529     if (result == ERR_OK) {
530         userGuard.Dismiss();
531     }
532 
533     uid = bundleInfo.GetUid(userId_);
534     mainAbility_ = bundleInfo.GetMainAbility();
535     return result;
536 }
537 
CreateAccessTokenId(const InnerBundleInfo & info)538 uint32_t BaseBundleInstaller::CreateAccessTokenId(const InnerBundleInfo &info)
539 {
540     return BundlePermissionMgr::CreateAccessTokenId(info, info.GetBundleName(), userId_);
541 }
542 
GrantRequestPermissions(const InnerBundleInfo & info,const uint32_t tokenId)543 ErrCode BaseBundleInstaller::GrantRequestPermissions(const InnerBundleInfo &info, const uint32_t tokenId)
544 {
545     if (!BundlePermissionMgr::GrantRequestPermissions(info, tokenId)) {
546         APP_LOGE("GrantRequestPermissions failed, bundleName: %{public}s", info.GetBundleName().c_str());
547         return ERR_APPEXECFWK_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED;
548     }
549     return ERR_OK;
550 }
551 
ProcessBundleInstall(const std::vector<std::string> & inBundlePaths,const InstallParam & installParam,const Constants::AppType appType,int32_t & uid)552 ErrCode BaseBundleInstaller::ProcessBundleInstall(const std::vector<std::string> &inBundlePaths,
553     const InstallParam &installParam, const Constants::AppType appType, int32_t &uid)
554 {
555     APP_LOGD("ProcessBundleInstall bundlePath install");
556     if (dataMgr_ == nullptr) {
557         dataMgr_ = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
558         if (dataMgr_ == nullptr) {
559             APP_LOGE("Get dataMgr shared_ptr nullptr");
560             return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
561         }
562     }
563 
564     userId_ = GetUserId(installParam.userId);
565     ErrCode result = CheckUserId(userId_);
566     CHECK_RESULT(result, "userId check failed %{public}d");
567 
568     std::vector<std::string> bundlePaths;
569     // check hap paths
570     result = BundleUtil::CheckFilePath(inBundlePaths, bundlePaths);
571     CHECK_RESULT(result, "hap file check failed %{public}d");
572     UpdateInstallerState(InstallerState::INSTALL_BUNDLE_CHECKED);                  // ---- 5%
573 
574     // check syscap
575     result = CheckSysCap(bundlePaths);
576     CHECK_RESULT(result, "hap syscap check failed %{public}d");
577     UpdateInstallerState(InstallerState::INSTALL_SYSCAP_CHECKED);                  // ---- 10%
578 
579     // verify signature info for all haps
580     std::vector<Security::Verify::HapVerifyResult> hapVerifyResults;
581     result = CheckMultipleHapsSignInfo(bundlePaths, installParam, hapVerifyResults);
582     CHECK_RESULT(result, "hap files check signature info failed %{public}d");
583     UpdateInstallerState(InstallerState::INSTALL_SIGNATURE_CHECKED);               // ---- 15%
584 
585     // parse the bundle infos for all haps
586     // key is bundlePath , value is innerBundleInfo
587     std::unordered_map<std::string, InnerBundleInfo> newInfos;
588     result = ParseHapFiles(bundlePaths, installParam, appType, hapVerifyResults, newInfos);
589     CHECK_RESULT(result, "parse haps file failed %{public}d");
590     // check the dependencies whether or not exists
591     result = CheckDependency(newInfos);
592     CHECK_RESULT(result, "check dependency failed %{public}d");
593     UpdateInstallerState(InstallerState::INSTALL_PARSED);                          // ---- 20%
594 
595     userId_ = GetConfirmUserId(userId_, newInfos);
596     // check hap is allow install by app control
597     std::vector<std::string> installAppIds;
598     for (const auto &info : newInfos) {
599         installAppIds.emplace_back(info.second.GetAppId());
600     }
601     result = InstallAppControl(installAppIds, userId_);
602     CHECK_RESULT(result, "install app control failed %{public}d");
603 
604     // check hap hash param
605     result = CheckHapHashParams(newInfos, installParam.hashParams);
606     CHECK_RESULT(result, "check hap hash param failed %{public}d");
607     UpdateInstallerState(InstallerState::INSTALL_HAP_HASH_PARAM_CHECKED);          // ---- 25%
608 
609     // check versioncode and bundleName
610     result = CheckAppLabelInfo(newInfos);
611     CHECK_RESULT(result, "verisoncode or bundleName is different in all haps %{public}d");
612     UpdateInstallerState(InstallerState::INSTALL_VERSION_AND_BUNDLENAME_CHECKED);  // ---- 30%
613 
614     // check native file
615     result = CheckMultiNativeFile(newInfos);
616     CHECK_RESULT(result, "native so is incompatible in all haps %{public}d");
617     UpdateInstallerState(InstallerState::INSTALL_NATIVE_SO_CHECKED);               // ---- 35%
618 
619     auto &mtx = dataMgr_->GetBundleMutex(bundleName_);
620     std::lock_guard lock {mtx};
621 
622     // uninstall all sandbox app before
623     UninstallAllSandboxApps(bundleName_);
624     UpdateInstallerState(InstallerState::INSTALL_REMOVE_SANDBOX_APP);              // ---- 50%
625 
626     // this state should always be set when return
627     ScopeGuard stateGuard([&] { dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::INSTALL_SUCCESS); });
628 
629     // this state should always be set when return
630     ScopeGuard enableGuard([&] { dataMgr_->EnableBundle(bundleName_); });
631     InnerBundleInfo oldInfo;
632     result = InnerProcessBundleInstall(newInfos, oldInfo, installParam, uid);
633     CHECK_RESULT_WITH_ROLLBACK(result, "internal processing failed with result %{public}d", newInfos, oldInfo);
634     UpdateInstallerState(InstallerState::INSTALL_INFO_SAVED);                      // ---- 80%
635 
636     // rename for all temp dirs
637     for (const auto &info : newInfos) {
638         if (info.second.IsOnlyCreateBundleUser()) {
639             continue;
640         }
641         if ((result = RenameModuleDir(info.second)) != ERR_OK) {
642             break;
643         }
644     }
645     UpdateInstallerState(InstallerState::INSTALL_RENAMED);                         // ---- 90%
646 
647     CHECK_RESULT_WITH_ROLLBACK(result, "rename temp dirs failed with result %{public}d", newInfos, oldInfo);
648     if (!uninstallModuleVec_.empty()) {
649         UninstallLowerVersionFeature(uninstallModuleVec_);
650     }
651 
652     SaveHapPathToRecords(installParam.isPreInstallApp, newInfos);
653     RemoveEmptyDirs(newInfos);
654     if (installParam.copyHapToInstallPath) {
655         APP_LOGD("begin to copy hap to install path");
656         if (!SaveHapToInstallPath()) {
657             APP_LOGE("copy hap to install path failed.");
658             return ERR_APPEXECFWK_INSTALL_COPY_HAP_FAILED;
659         }
660         APP_LOGD("copy hap to install path success");
661     }
662     UpdateInstallerState(InstallerState::INSTALL_SUCCESS);                         // ---- 100%
663     APP_LOGD("finish ProcessBundleInstall bundlePath install touch off aging");
664 #ifdef BUNDLE_FRAMEWORK_FREE_INSTALL
665     if (installParam.installFlag == InstallFlag::FREE_INSTALL) {
666         DelayedSingleton<BundleMgrService>::GetInstance()->GetAgingMgr()->Start(
667             BundleAgingMgr::AgingTriggertype::FREE_INSTALL);
668     }
669 #endif
670 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
671     if (needDeleteQuickFixInfo_) {
672         APP_LOGD("module update, quick fix old patch need to delete, bundleName:%{public}s", bundleName_.c_str());
673         if (!oldInfo.GetAppQuickFix().deployedAppqfInfo.hqfInfos.empty()) {
674             APP_LOGD("InnerBundleInfo quickFixInfo need disable, bundleName:%{public}s", bundleName_.c_str());
675             auto quickFixSwitcher = std::make_unique<QuickFixSwitcher>(bundleName_, false);
676             quickFixSwitcher->Execute();
677         }
678         auto quickFixDeleter = std::make_unique<QuickFixDeleter>(bundleName_);
679         quickFixDeleter->Execute();
680     }
681 #endif
682     OnSingletonChange(installParam.noSkipsKill);
683     sync();
684     return result;
685 }
686 
RollBack(const std::unordered_map<std::string,InnerBundleInfo> & newInfos,InnerBundleInfo & oldInfo)687 void BaseBundleInstaller::RollBack(const std::unordered_map<std::string, InnerBundleInfo> &newInfos,
688     InnerBundleInfo &oldInfo)
689 {
690     APP_LOGD("start rollback due to install failed");
691     if (!isAppExist_) {
692         RemoveBundleAndDataDir(newInfos.begin()->second, false);
693         // delete accessTokenId
694         if (BundlePermissionMgr::DeleteAccessTokenId(newInfos.begin()->second.GetAccessTokenId(userId_)) !=
695             AccessToken::AccessTokenKitRet::RET_SUCCESS) {
696             APP_LOGE("delete accessToken failed");
697         }
698         // remove innerBundleInfo
699         RemoveInfo(bundleName_, "");
700         return;
701     }
702     InnerBundleInfo preInfo;
703     bool isExist = false;
704     if (!GetInnerBundleInfo(preInfo, isExist) || !isExist) {
705         APP_LOGI("finish rollback due to install failed");
706         return;
707     }
708     for (const auto &info : newInfos) {
709         RollBack(info.second, oldInfo);
710     }
711     // need delete definePermissions and requestPermissions
712     ErrCode ret = UpdateDefineAndRequestPermissions(preInfo, oldInfo);
713     if (ret != ERR_OK) {
714         return;
715     }
716     APP_LOGD("finish rollback due to install failed");
717 }
718 
UpdateDefineAndRequestPermissions(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo)719 ErrCode BaseBundleInstaller::UpdateDefineAndRequestPermissions(const InnerBundleInfo &oldInfo,
720     const InnerBundleInfo &newInfo)
721 {
722     APP_LOGD("UpdateDefineAndRequestPermissions %{public}s start", bundleName_.c_str());
723     auto bundleUserInfos = newInfo.GetInnerBundleUserInfos();
724     for (const auto &uerInfo : bundleUserInfos) {
725         if (uerInfo.second.accessTokenId == 0) {
726             continue;
727         }
728         std::vector<std::string> newRequestPermName;
729         if (!BundlePermissionMgr::UpdateDefineAndRequestPermissions(uerInfo.second.accessTokenId, oldInfo,
730             newInfo, newRequestPermName)) {
731             APP_LOGE("UpdateDefineAndRequestPermissions %{public}s failed", bundleName_.c_str());
732             return ERR_APPEXECFWK_INSTALL_UPDATE_HAP_TOKEN_FAILED;
733         }
734         if (!BundlePermissionMgr::GrantRequestPermissions(newInfo, newRequestPermName, uerInfo.second.accessTokenId)) {
735             APP_LOGE("BundlePermissionMgr::GrantRequestPermissions failed %{public}s", bundleName_.c_str());
736             return ERR_APPEXECFWK_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED;
737         }
738     }
739     APP_LOGD("UpdateDefineAndRequestPermissions %{public}s end", bundleName_.c_str());
740     return ERR_OK;
741 }
742 
RollBack(const InnerBundleInfo & info,InnerBundleInfo & oldInfo)743 void BaseBundleInstaller::RollBack(const InnerBundleInfo &info, InnerBundleInfo &oldInfo)
744 {
745     // rollback hap installed
746     if (installedModules_[info.GetCurrentModulePackage()]) {
747         std::string createModulePath = info.GetAppCodePath() + Constants::PATH_SEPARATOR +
748             info.GetCurrentModulePackage() + Constants::TMP_SUFFIX;
749         RemoveModuleDir(createModulePath);
750         oldInfo.SetCurrentModulePackage(info.GetCurrentModulePackage());
751         RollBackMoudleInfo(bundleName_, oldInfo);
752     } else {
753         auto modulePackage = info.GetCurrentModulePackage();
754         RemoveModuleDir(info.GetModuleDir(modulePackage));
755         // remove module info
756         RemoveInfo(bundleName_, modulePackage);
757     }
758 }
759 
RemoveInfo(const std::string & bundleName,const std::string & packageName)760 void BaseBundleInstaller::RemoveInfo(const std::string &bundleName, const std::string &packageName)
761 {
762     APP_LOGD("remove innerBundleInfo due to rollback");
763     if (packageName.empty()) {
764         dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UPDATING_FAIL);
765     } else {
766         InnerBundleInfo innerBundleInfo;
767         bool isExist = false;
768         if (!GetInnerBundleInfo(innerBundleInfo, isExist) || !isExist) {
769             APP_LOGI("finish rollback due to install failed");
770             return;
771         }
772         dataMgr_->UpdateBundleInstallState(bundleName, InstallState::ROLL_BACK);
773         dataMgr_->RemoveModuleInfo(bundleName, packageName, innerBundleInfo);
774     }
775     APP_LOGD("finish to remove innerBundleInfo due to rollback");
776 }
777 
RollBackMoudleInfo(const std::string & bundleName,InnerBundleInfo & oldInfo)778 void BaseBundleInstaller::RollBackMoudleInfo(const std::string &bundleName, InnerBundleInfo &oldInfo)
779 {
780     APP_LOGD("rollBackMoudleInfo due to rollback");
781     InnerBundleInfo innerBundleInfo;
782     bool isExist = false;
783     if (!GetInnerBundleInfo(innerBundleInfo, isExist) || !isExist) {
784         return;
785     }
786     dataMgr_->UpdateBundleInstallState(bundleName, InstallState::ROLL_BACK);
787     dataMgr_->UpdateInnerBundleInfo(bundleName, oldInfo, innerBundleInfo);
788     APP_LOGD("finsih rollBackMoudleInfo due to rollback");
789 }
790 
ProcessBundleUninstall(const std::string & bundleName,const InstallParam & installParam,int32_t & uid)791 ErrCode BaseBundleInstaller::ProcessBundleUninstall(
792     const std::string &bundleName, const InstallParam &installParam, int32_t &uid)
793 {
794     APP_LOGD("start to process %{public}s bundle uninstall", bundleName.c_str());
795     if (bundleName.empty()) {
796         APP_LOGE("uninstall bundle name empty");
797         return ERR_APPEXECFWK_UNINSTALL_INVALID_NAME;
798     }
799 
800     dataMgr_ = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
801     if (dataMgr_ == nullptr) {
802         APP_LOGE("Get dataMgr shared_ptr nullptr");
803         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
804     }
805 
806     userId_ = GetUserId(installParam.userId);
807     if (userId_ == Constants::INVALID_USERID) {
808         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
809     }
810 
811     if (!dataMgr_->HasUserId(userId_)) {
812         APP_LOGE("The user %{public}d does not exist when uninstall.", userId_);
813         return ERR_APPEXECFWK_USER_NOT_EXIST;
814     }
815 
816     auto &mtx = dataMgr_->GetBundleMutex(bundleName);
817     std::lock_guard lock {mtx};
818     InnerBundleInfo oldInfo;
819     if (!dataMgr_->GetInnerBundleInfo(bundleName, oldInfo)) {
820         APP_LOGE("uninstall bundle info missing");
821         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
822     }
823 
824     versionCode_ = oldInfo.GetVersionCode();
825     ScopeGuard enableGuard([&] { dataMgr_->EnableBundle(bundleName); });
826 
827     InnerBundleUserInfo curInnerBundleUserInfo;
828     if (!oldInfo.GetInnerBundleUserInfo(userId_, curInnerBundleUserInfo)) {
829         APP_LOGE("bundle(%{public}s) get user(%{public}d) failed when uninstall.",
830             oldInfo.GetBundleName().c_str(), userId_);
831         return ERR_APPEXECFWK_USER_NOT_INSTALL_HAP;
832     }
833 
834     uid = curInnerBundleUserInfo.uid;
835     if (!installParam.forceExecuted && oldInfo.GetBaseApplicationInfo().isSystemApp &&
836         !oldInfo.IsRemovable() && installParam.noSkipsKill) {
837         APP_LOGE("uninstall system app");
838         return ERR_APPEXECFWK_UNINSTALL_SYSTEM_APP_ERROR;
839     }
840 
841     if (!UninstallAppControl(oldInfo.GetAppId(), userId_)) {
842         APP_LOGE("bundleName: %{public}s is not allow uninstall", bundleName.c_str());
843         return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_UNINSTALL;
844     }
845 
846     // reboot scan case will not kill the bundle
847     if (installParam.noSkipsKill) {
848         // kill the bundle process during uninstall.
849         if (!AbilityManagerHelper::UninstallApplicationProcesses(oldInfo.GetApplicationName(), uid)) {
850             APP_LOGE("can not kill process");
851             return ERR_APPEXECFWK_UNINSTALL_KILLING_APP_ERROR;
852         }
853     }
854 
855     if (oldInfo.GetInnerBundleUserInfos().size() > 1) {
856         APP_LOGD("only delete userinfo %{public}d", userId_);
857         return RemoveBundleUserData(oldInfo, installParam.isKeepData);
858     }
859 
860     if (!dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UNINSTALL_START)) {
861         APP_LOGE("uninstall already start");
862         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
863     }
864 
865     std::string packageName;
866     oldInfo.SetInstallMark(bundleName, packageName, InstallExceptionStatus::UNINSTALL_BUNDLE_START);
867     if (!dataMgr_->SaveInnerBundleInfo(oldInfo)) {
868         APP_LOGE("save install mark failed");
869         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
870     }
871 
872     ErrCode result = RemoveBundle(oldInfo, installParam.isKeepData);
873     if (result != ERR_OK) {
874         APP_LOGE("remove whole bundle failed");
875         return result;
876     }
877 
878     result = DeleteOldArkNativeFile(oldInfo);
879     if (result != ERR_OK) {
880         APP_LOGE("delete old arkNativeFile failed");
881         return result;
882     }
883 
884     result = DeleteArkProfile(bundleName, userId_);
885     if (result != ERR_OK) {
886         APP_LOGE("fail to removeArkProfile, error is %{public}d", result);
887         return result;
888     }
889     if ((result = CleanAsanDirectory(oldInfo)) != ERR_OK) {
890         APP_LOGE("fail to remove asan log path, error is %{public}d", result);
891         return result;
892     }
893 
894     enableGuard.Dismiss();
895 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
896     std::shared_ptr<QuickFixDataMgr> quickFixDataMgr = DelayedSingleton<QuickFixDataMgr>::GetInstance();
897     if (quickFixDataMgr != nullptr) {
898         APP_LOGD("DeleteInnerAppQuickFix when bundleName :%{public}s uninstall", bundleName.c_str());
899         quickFixDataMgr->DeleteInnerAppQuickFix(bundleName);
900     }
901 #endif
902     APP_LOGD("finish to process %{public}s bundle uninstall", bundleName.c_str());
903     return ERR_OK;
904 }
905 
ProcessBundleUninstall(const std::string & bundleName,const std::string & modulePackage,const InstallParam & installParam,int32_t & uid)906 ErrCode BaseBundleInstaller::ProcessBundleUninstall(
907     const std::string &bundleName, const std::string &modulePackage, const InstallParam &installParam, int32_t &uid)
908 {
909     APP_LOGD("start to process %{public}s in %{public}s uninstall", bundleName.c_str(), modulePackage.c_str());
910     if (bundleName.empty() || modulePackage.empty()) {
911         APP_LOGE("uninstall bundle name or module name empty");
912         return ERR_APPEXECFWK_UNINSTALL_INVALID_NAME;
913     }
914 
915     dataMgr_ = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
916     if (!dataMgr_) {
917         APP_LOGE("Get dataMgr shared_ptr nullptr");
918         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
919     }
920 
921     userId_ = GetUserId(installParam.userId);
922     if (userId_ == Constants::INVALID_USERID) {
923         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
924     }
925 
926     if (!dataMgr_->HasUserId(userId_)) {
927         APP_LOGE("The user %{public}d does not exist when uninstall.", userId_);
928         return ERR_APPEXECFWK_USER_NOT_EXIST;
929     }
930 
931     auto &mtx = dataMgr_->GetBundleMutex(bundleName);
932     std::lock_guard lock {mtx};
933     InnerBundleInfo oldInfo;
934     if (!dataMgr_->GetInnerBundleInfo(bundleName, oldInfo)) {
935         APP_LOGE("uninstall bundle info missing");
936         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_BUNDLE;
937     }
938 
939     versionCode_ = oldInfo.GetVersionCode();
940     ScopeGuard enableGuard([&] { dataMgr_->EnableBundle(bundleName); });
941 
942     InnerBundleUserInfo curInnerBundleUserInfo;
943     if (!oldInfo.GetInnerBundleUserInfo(userId_, curInnerBundleUserInfo)) {
944         APP_LOGE("bundle(%{public}s) get user(%{public}d) failed when uninstall.",
945             oldInfo.GetBundleName().c_str(), userId_);
946         return ERR_APPEXECFWK_USER_NOT_INSTALL_HAP;
947     }
948 
949     uid = curInnerBundleUserInfo.uid;
950     if (!installParam.forceExecuted && oldInfo.GetBaseApplicationInfo().isSystemApp
951         && !oldInfo.IsRemovable() && installParam.noSkipsKill) {
952         APP_LOGE("uninstall system app");
953         return ERR_APPEXECFWK_UNINSTALL_SYSTEM_APP_ERROR;
954     }
955 
956     bool isModuleExist = oldInfo.FindModule(modulePackage);
957     if (!isModuleExist) {
958         APP_LOGE("uninstall bundle info missing");
959         return ERR_APPEXECFWK_UNINSTALL_MISSING_INSTALLED_MODULE;
960     }
961 
962     if (!UninstallAppControl(oldInfo.GetAppId(), userId_)) {
963         APP_LOGE("bundleName: %{public}s is not allow uninstall", bundleName.c_str());
964         return ERR_BUNDLE_MANAGER_APP_CONTROL_DISALLOWED_UNINSTALL;
965     }
966 
967     if (!dataMgr_->UpdateBundleInstallState(bundleName, InstallState::UNINSTALL_START)) {
968         APP_LOGE("uninstall already start");
969         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
970     }
971 
972     ScopeGuard stateGuard([&] { dataMgr_->UpdateBundleInstallState(bundleName, InstallState::INSTALL_SUCCESS); });
973 
974     // reboot scan case will not kill the bundle
975     if (installParam.noSkipsKill) {
976         // kill the bundle process during uninstall.
977         if (!AbilityManagerHelper::UninstallApplicationProcesses(oldInfo.GetApplicationName(), uid)) {
978             APP_LOGE("can not kill process");
979             return ERR_APPEXECFWK_UNINSTALL_KILLING_APP_ERROR;
980         }
981     }
982 
983     oldInfo.SetInstallMark(bundleName, modulePackage, InstallExceptionStatus::UNINSTALL_PACKAGE_START);
984     if (!dataMgr_->SaveInnerBundleInfo(oldInfo)) {
985         APP_LOGE("save install mark failed");
986         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
987     }
988 
989     bool onlyInstallInUser = oldInfo.GetInnerBundleUserInfos().size() == 1;
990     ErrCode result = ERR_OK;
991     // if it is the only module in the bundle
992     if (oldInfo.IsOnlyModule(modulePackage)) {
993         APP_LOGI("%{public}s is only module", modulePackage.c_str());
994         enableGuard.Dismiss();
995         stateGuard.Dismiss();
996         if (onlyInstallInUser) {
997             result = RemoveBundle(oldInfo, installParam.isKeepData);
998             if (result != ERR_OK) {
999                 APP_LOGE("remove bundle failed");
1000                 return result;
1001             }
1002 
1003             result = DeleteOldArkNativeFile(oldInfo);
1004             if (result != ERR_OK) {
1005                 APP_LOGE("delete old arkNativeFile failed");
1006                 return result;
1007             }
1008 
1009             result = DeleteArkProfile(bundleName, userId_);
1010             if (result != ERR_OK) {
1011                 APP_LOGE("fail to removeArkProfile, error is %{public}d", result);
1012                 return result;
1013             }
1014             if ((result = CleanAsanDirectory(oldInfo)) != ERR_OK) {
1015                 APP_LOGE("fail to remove asan log path, error is %{public}d", result);
1016                 return result;
1017             }
1018 
1019             return ERR_OK;
1020         }
1021         return RemoveBundleUserData(oldInfo, installParam.isKeepData);
1022     }
1023 
1024     if (onlyInstallInUser) {
1025         APP_LOGI("%{public}s is only install at the userId %{public}d", bundleName.c_str(), userId_);
1026         result = RemoveModuleAndDataDir(oldInfo, modulePackage, userId_, installParam.isKeepData);
1027     } else {
1028         if (!installParam.isKeepData) {
1029             result = RemoveModuleDataDir(oldInfo, modulePackage, userId_);
1030         }
1031     }
1032 
1033     if (result != ERR_OK) {
1034         APP_LOGE("remove module dir failed");
1035         return result;
1036     }
1037 
1038     oldInfo.SetInstallMark(bundleName, modulePackage, InstallExceptionStatus::INSTALL_FINISH);
1039     APP_LOGD("start to remove module info of %{public}s in %{public}s ", modulePackage.c_str(), bundleName.c_str());
1040     if (!dataMgr_->RemoveModuleInfo(bundleName, modulePackage, oldInfo)) {
1041         APP_LOGE("RemoveModuleInfo failed");
1042         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1043     }
1044 
1045     APP_LOGD("finish to process %{public}s in %{public}s uninstall", bundleName.c_str(), modulePackage.c_str());
1046     return ERR_OK;
1047 }
1048 
ProcessInstallBundleByBundleName(const std::string & bundleName,const InstallParam & installParam,int32_t & uid)1049 ErrCode BaseBundleInstaller::ProcessInstallBundleByBundleName(
1050     const std::string &bundleName, const InstallParam &installParam, int32_t &uid)
1051 {
1052     APP_LOGD("Process Install Bundle(%{public}s) start", bundleName.c_str());
1053     return InnerProcessInstallByPreInstallInfo(bundleName, installParam, uid, false);
1054 }
1055 
ProcessRecover(const std::string & bundleName,const InstallParam & installParam,int32_t & uid)1056 ErrCode BaseBundleInstaller::ProcessRecover(
1057     const std::string &bundleName, const InstallParam &installParam, int32_t &uid)
1058 {
1059     APP_LOGD("Process Recover Bundle(%{public}s) start", bundleName.c_str());
1060     ErrCode result = InnerProcessInstallByPreInstallInfo(bundleName, installParam, uid, true);
1061     return result;
1062 }
1063 
InnerProcessInstallByPreInstallInfo(const std::string & bundleName,const InstallParam & installParam,int32_t & uid,bool recoverMode)1064 ErrCode BaseBundleInstaller::InnerProcessInstallByPreInstallInfo(
1065     const std::string &bundleName, const InstallParam &installParam, int32_t &uid, bool recoverMode)
1066 {
1067     dataMgr_ = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
1068     if (dataMgr_ == nullptr) {
1069         APP_LOGE("Get dataMgr shared_ptr nullptr.");
1070         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
1071     }
1072 
1073     userId_ = GetUserId(installParam.userId);
1074     if (userId_ == Constants::INVALID_USERID) {
1075         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
1076     }
1077 
1078     if (!dataMgr_->HasUserId(userId_)) {
1079         APP_LOGE("The user %{public}d does not exist.", userId_);
1080         return ERR_APPEXECFWK_USER_NOT_EXIST;
1081     }
1082 
1083     {
1084         auto &mtx = dataMgr_->GetBundleMutex(bundleName);
1085         std::lock_guard lock {mtx};
1086         InnerBundleInfo oldInfo;
1087         bool isAppExist = dataMgr_->GetInnerBundleInfo(bundleName, oldInfo);
1088         if (isAppExist) {
1089             dataMgr_->EnableBundle(bundleName);
1090             versionCode_ = oldInfo.GetVersionCode();
1091             if (oldInfo.HasInnerBundleUserInfo(userId_)) {
1092                 APP_LOGE("App is exist in user(%{public}d).", userId_);
1093                 return ERR_APPEXECFWK_INSTALL_ALREADY_EXIST;
1094             }
1095 
1096             std::vector<std::string> installAppIds(1, oldInfo.GetAppId());
1097             ErrCode result = InstallAppControl(installAppIds, userId_);
1098             if (result != ERR_OK) {
1099                 APP_LOGE("appid:%{private}s check install app control failed", oldInfo.GetAppId().c_str());
1100                 return result;
1101             }
1102 
1103             bool isSingleton = oldInfo.IsSingleton();
1104             if ((isSingleton && (userId_ != Constants::DEFAULT_USERID)) ||
1105                 (!isSingleton && (userId_ == Constants::DEFAULT_USERID))) {
1106                 APP_LOGW("singleton(%{public}d) app(%{public}s) and user(%{public}d) are not matched.",
1107                     isSingleton, bundleName_.c_str(), userId_);
1108                 return ERR_APPEXECFWK_INSTALL_ZERO_USER_WITH_NO_SINGLETON;
1109             }
1110 
1111             InnerBundleUserInfo curInnerBundleUserInfo;
1112             curInnerBundleUserInfo.bundleUserInfo.userId = userId_;
1113             curInnerBundleUserInfo.bundleName = bundleName;
1114             oldInfo.AddInnerBundleUserInfo(curInnerBundleUserInfo);
1115             ScopeGuard userGuard([&] { RemoveBundleUserData(oldInfo, false); });
1116             accessTokenId_ = CreateAccessTokenId(oldInfo);
1117             oldInfo.SetAccessTokenId(accessTokenId_, userId_);
1118             result = GrantRequestPermissions(oldInfo, accessTokenId_);
1119             if (result != ERR_OK) {
1120                 return result;
1121             }
1122 
1123             result = CreateBundleUserData(oldInfo);
1124             if (result != ERR_OK) {
1125                 return result;
1126             }
1127 
1128             // extract ap file
1129             result = ExtractAllArkProfileFile(oldInfo);
1130             if (result != ERR_OK) {
1131                 return result;
1132             }
1133 
1134             userGuard.Dismiss();
1135             uid = oldInfo.GetUid(userId_);
1136             return ERR_OK;
1137         }
1138     }
1139 
1140     PreInstallBundleInfo preInstallBundleInfo;
1141     preInstallBundleInfo.SetBundleName(bundleName);
1142     if (!dataMgr_->GetPreInstallBundleInfo(bundleName, preInstallBundleInfo)
1143         || preInstallBundleInfo.GetBundlePaths().empty()) {
1144         APP_LOGE("Get PreInstallBundleInfo faile, bundleName: %{public}s.", bundleName.c_str());
1145         return ERR_APPEXECFWK_INSTALL_INVALID_BUNDLE_FILE;
1146     }
1147 
1148     if (recoverMode) {
1149         if (preInstallBundleInfo.GetAppType() != Constants::AppType::SYSTEM_APP) {
1150             APP_LOGE("recover failed due to not system app");
1151             return ERR_APPEXECFWK_RECOVER_GET_BUNDLEPATH_ERROR;
1152         }
1153     }
1154 
1155     APP_LOGD("Get preInstall bundlePath success.");
1156     std::vector<std::string> pathVec { preInstallBundleInfo.GetBundlePaths() };
1157     auto innerInstallParam = installParam;
1158     innerInstallParam.isPreInstallApp = true;
1159     innerInstallParam.removable = preInstallBundleInfo.IsRemovable();
1160     innerInstallParam.copyHapToInstallPath = false;
1161     return ProcessBundleInstall(pathVec, innerInstallParam, preInstallBundleInfo.GetAppType(), uid);
1162 }
1163 
RemoveBundle(InnerBundleInfo & info,bool isKeepData)1164 ErrCode BaseBundleInstaller::RemoveBundle(InnerBundleInfo &info, bool isKeepData)
1165 {
1166     ErrCode result = RemoveBundleAndDataDir(info, isKeepData);
1167     if (result != ERR_OK) {
1168         APP_LOGE("remove bundle dir failed");
1169         dataMgr_->UpdateBundleInstallState(info.GetBundleName(), InstallState::INSTALL_SUCCESS);
1170         return result;
1171     }
1172 
1173     if (!dataMgr_->UpdateBundleInstallState(info.GetBundleName(), InstallState::UNINSTALL_SUCCESS)) {
1174         APP_LOGE("delete inner info failed");
1175         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1176     }
1177     accessTokenId_ = info.GetAccessTokenId(userId_);
1178     if (BundlePermissionMgr::DeleteAccessTokenId(accessTokenId_) !=
1179         AccessToken::AccessTokenKitRet::RET_SUCCESS) {
1180         APP_LOGE("delete accessToken failed");
1181     }
1182     return ERR_OK;
1183 }
1184 
ProcessBundleInstallStatus(InnerBundleInfo & info,int32_t & uid)1185 ErrCode BaseBundleInstaller::ProcessBundleInstallStatus(InnerBundleInfo &info, int32_t &uid)
1186 {
1187     if (!VerifyUriPrefix(info, userId_)) {
1188         APP_LOGE("VerifyUriPrefix failed");
1189         return ERR_APPEXECFWK_INSTALL_URI_DUPLICATE;
1190     }
1191     modulePackage_ = info.GetCurrentModulePackage();
1192     APP_LOGD("ProcessBundleInstallStatus with bundleName %{public}s and packageName %{public}s",
1193         bundleName_.c_str(), modulePackage_.c_str());
1194     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::INSTALL_START)) {
1195         APP_LOGE("install already start");
1196         return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
1197     }
1198     info.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::INSTALL_START);
1199     if (!dataMgr_->SaveInnerBundleInfo(info)) {
1200         APP_LOGE("save install mark to storage failed");
1201         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
1202     }
1203     ScopeGuard stateGuard([&] { dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::INSTALL_FAIL); });
1204     ErrCode result = CreateBundleAndDataDir(info);
1205     if (result != ERR_OK) {
1206         APP_LOGE("create bundle and data dir failed");
1207         return result;
1208     }
1209 
1210     ScopeGuard bundleGuard([&] { RemoveBundleAndDataDir(info, false); });
1211     std::string modulePath = info.GetAppCodePath() + Constants::PATH_SEPARATOR + modulePackage_;
1212     result = ExtractModule(info, modulePath);
1213     if (result != ERR_OK) {
1214         APP_LOGE("extract module failed");
1215         return result;
1216     }
1217 
1218     info.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::INSTALL_FINISH);
1219     uid = info.GetUid(userId_);
1220     info.SetBundleInstallTime(BundleUtil::GetCurrentTime(), userId_);
1221     accessTokenId_ = CreateAccessTokenId(info);
1222     info.SetAccessTokenId(accessTokenId_, userId_);
1223     result = GrantRequestPermissions(info, accessTokenId_);
1224     if (result != ERR_OK) {
1225         return result;
1226     }
1227     if (!dataMgr_->AddInnerBundleInfo(bundleName_, info)) {
1228         APP_LOGE("add bundle %{public}s info failed", bundleName_.c_str());
1229         dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UNINSTALL_START);
1230         dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UNINSTALL_SUCCESS);
1231         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1232     }
1233 
1234     stateGuard.Dismiss();
1235     bundleGuard.Dismiss();
1236 
1237     APP_LOGD("finish to call processBundleInstallStatus");
1238     return ERR_OK;
1239 }
1240 
ProcessBundleUpdateStatus(InnerBundleInfo & oldInfo,InnerBundleInfo & newInfo,bool isReplace,bool noSkipsKill)1241 ErrCode BaseBundleInstaller::ProcessBundleUpdateStatus(
1242     InnerBundleInfo &oldInfo, InnerBundleInfo &newInfo, bool isReplace, bool noSkipsKill)
1243 {
1244     modulePackage_ = newInfo.GetCurrentModulePackage();
1245     if (modulePackage_.empty()) {
1246         APP_LOGE("get current package failed");
1247         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
1248     }
1249 
1250     if (isFeatureNeedUninstall_) {
1251         uninstallModuleVec_.emplace_back(modulePackage_);
1252     }
1253 
1254 #ifdef USE_PRE_BUNDLE_PROFILE
1255     if (oldInfo.IsSingleton() != newInfo.IsSingleton()) {
1256         APP_LOGE("Singleton not allow changed");
1257         return ERR_APPEXECFWK_INSTALL_SINGLETON_INCOMPATIBLE;
1258     }
1259 #else
1260     if (oldInfo.IsSingleton() && !newInfo.IsSingleton()) {
1261         singletonState_ = SingletonState::SINGLETON_TO_NON;
1262     } else if (!oldInfo.IsSingleton() && newInfo.IsSingleton()) {
1263         singletonState_ = SingletonState::NON_TO_SINGLETON;
1264     }
1265 #endif
1266 
1267     APP_LOGD("ProcessBundleUpdateStatus with bundleName %{public}s and packageName %{public}s",
1268         newInfo.GetBundleName().c_str(), modulePackage_.c_str());
1269     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UPDATING_START)) {
1270         APP_LOGE("update already start");
1271         return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
1272     }
1273 
1274     if (oldInfo.GetProvisionId() != newInfo.GetProvisionId()) {
1275         APP_LOGE("the signature of the new bundle is not the same as old one");
1276         return ERR_APPEXECFWK_INSTALL_FAILED_INCONSISTENT_SIGNATURE;
1277     }
1278     APP_LOGD("ProcessBundleUpdateStatus noSkipsKill = %{public}d", noSkipsKill);
1279     // now there are two cases for updating:
1280     // 1. bundle exist, hap exist, update hap
1281     // 2. bundle exist, install new hap
1282     bool isModuleExist = oldInfo.FindModule(modulePackage_);
1283     newInfo.RestoreFromOldInfo(oldInfo);
1284     auto result = isModuleExist ? ProcessModuleUpdate(newInfo, oldInfo,
1285         isReplace, noSkipsKill) : ProcessNewModuleInstall(newInfo, oldInfo);
1286     if (result != ERR_OK) {
1287         APP_LOGE("install module failed %{public}d", result);
1288         return result;
1289     }
1290 
1291     APP_LOGD("finish to call ProcessBundleUpdateStatus");
1292     return ERR_OK;
1293 }
1294 
ProcessNewModuleInstall(InnerBundleInfo & newInfo,InnerBundleInfo & oldInfo)1295 ErrCode BaseBundleInstaller::ProcessNewModuleInstall(InnerBundleInfo &newInfo, InnerBundleInfo &oldInfo)
1296 {
1297     APP_LOGD("ProcessNewModuleInstall %{public}s, userId: %{public}d.",
1298         newInfo.GetBundleName().c_str(), userId_);
1299     if (!VerifyUriPrefix(newInfo, userId_)) {
1300         APP_LOGE("VerifyUriPrefix failed");
1301         return ERR_APPEXECFWK_INSTALL_URI_DUPLICATE;
1302     }
1303 
1304     if (newInfo.HasEntry() && oldInfo.HasEntry()) {
1305         APP_LOGE("install more than one entry module");
1306         return ERR_APPEXECFWK_INSTALL_ENTRY_ALREADY_EXIST;
1307     }
1308 
1309     if (bundleInstallChecker_->IsContainModuleName(newInfo, oldInfo)) {
1310         APP_LOGE("moduleName is already existed");
1311         return ERR_APPEXECFWK_INSTALL_NOT_UNIQUE_DISTRO_MODULE_NAME;
1312     }
1313 
1314     // same version need to check app label
1315     ErrCode result = ERR_OK;
1316     if (oldInfo.GetVersionCode() == newInfo.GetVersionCode()) {
1317         result = CheckAppLabel(oldInfo, newInfo);
1318         if (result != ERR_OK) {
1319             APP_LOGE("CheckAppLabel failed %{public}d", result);
1320             return result;
1321         }
1322     }
1323 
1324     oldInfo.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::UPDATING_NEW_START);
1325     if (!dataMgr_->SaveInnerBundleInfo(oldInfo)) {
1326         APP_LOGE("save install mark failed");
1327         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
1328     }
1329     std::string modulePath = newInfo.GetAppCodePath() + Constants::PATH_SEPARATOR + modulePackage_;
1330     result = ExtractModule(newInfo, modulePath);
1331     if (result != ERR_OK) {
1332         APP_LOGE("extract module and rename failed");
1333         return result;
1334     }
1335     ScopeGuard moduleGuard([&] { RemoveModuleDir(modulePath); });
1336     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UPDATING_SUCCESS)) {
1337         APP_LOGE("new moduleupdate state failed");
1338         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1339     }
1340 
1341     oldInfo.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::INSTALL_FINISH);
1342 
1343     auto bundleUserInfos = oldInfo.GetInnerBundleUserInfos();
1344     for (const auto &info : bundleUserInfos) {
1345         if (info.second.accessTokenId == 0) {
1346             continue;
1347         }
1348         std::vector<std::string> newRequestPermName;
1349         if (!BundlePermissionMgr::AddDefineAndRequestPermissions(info.second.accessTokenId, newInfo,
1350             newRequestPermName)) {
1351             APP_LOGE("BundlePermissionMgr::AddDefineAndRequestPermissions failed %{public}s", bundleName_.c_str());
1352             return ERR_APPEXECFWK_INSTALL_UPDATE_HAP_TOKEN_FAILED;
1353         }
1354         if (!BundlePermissionMgr::GrantRequestPermissions(newInfo, newRequestPermName, info.second.accessTokenId)) {
1355             APP_LOGE("BundlePermissionMgr::GrantRequestPermissions failed %{public}s", bundleName_.c_str());
1356             return ERR_APPEXECFWK_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED;
1357         }
1358     }
1359 
1360     oldInfo.SetBundleUpdateTime(BundleUtil::GetCurrentTime(), userId_);
1361     if ((result = ProcessAsanDirectory(newInfo)) != ERR_OK) {
1362         APP_LOGE("process asan log directory failed!");
1363         return result;
1364     }
1365     if (!dataMgr_->AddNewModuleInfo(bundleName_, newInfo, oldInfo)) {
1366         APP_LOGE(
1367             "add module %{public}s to innerBundleInfo %{public}s failed", modulePackage_.c_str(), bundleName_.c_str());
1368         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1369     }
1370     moduleGuard.Dismiss();
1371 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
1372     // hqf extract diff file or apply diff patch failed does not affect the hap installation
1373     ProcessHqfInfo(oldInfo, newInfo);
1374 #endif
1375     return ERR_OK;
1376 }
1377 
ProcessModuleUpdate(InnerBundleInfo & newInfo,InnerBundleInfo & oldInfo,bool isReplace,bool noSkipsKill)1378 ErrCode BaseBundleInstaller::ProcessModuleUpdate(InnerBundleInfo &newInfo,
1379     InnerBundleInfo &oldInfo, bool isReplace, bool noSkipsKill)
1380 {
1381     APP_LOGD("ProcessModuleUpdate, bundleName : %{public}s, moduleName : %{public}s, userId: %{public}d.",
1382         newInfo.GetBundleName().c_str(), newInfo.GetCurrentModulePackage().c_str(), userId_);
1383     if (!VerifyUriPrefix(newInfo, userId_, true)) {
1384         APP_LOGE("VerifyUriPrefix failed");
1385         return ERR_APPEXECFWK_INSTALL_URI_DUPLICATE;
1386     }
1387     if (newInfo.HasEntry() && oldInfo.HasEntry()) {
1388         if (!oldInfo.IsEntryModule(modulePackage_)) {
1389             APP_LOGE("install more than one entry module");
1390             return ERR_APPEXECFWK_INSTALL_ENTRY_ALREADY_EXIST;
1391         }
1392     }
1393 
1394     if (!bundleInstallChecker_->IsExistedDistroModule(newInfo, oldInfo)) {
1395         APP_LOGE("moduleName is inconsistent in the updating hap");
1396         return ERR_APPEXECFWK_INSTALL_INCONSISTENT_MODULE_NAME;
1397     }
1398 
1399     ErrCode result = ERR_OK;
1400     if (versionCode_ == oldInfo.GetVersionCode()) {
1401         if ((result = CheckAppLabel(oldInfo, newInfo)) != ERR_OK) {
1402             APP_LOGE("CheckAppLabel failed %{public}d", result);
1403             return result;
1404         }
1405 
1406         if (!isReplace) {
1407             if (hasInstalledInUser_) {
1408                 APP_LOGE("fail to install already existing bundle using normal flag");
1409                 return ERR_APPEXECFWK_INSTALL_ALREADY_EXIST;
1410             }
1411 
1412             // app versionCode equals to the old and do not need to update module
1413             // and only need to update userInfo
1414             newInfo.SetOnlyCreateBundleUser(true);
1415             if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UPDATING_SUCCESS)) {
1416                 APP_LOGE("update state failed");
1417                 return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
1418             }
1419             return ERR_OK;
1420         }
1421     }
1422 
1423     APP_LOGE("ProcessModuleUpdate noSkipsKill = %{public}d", noSkipsKill);
1424     // reboot scan case will not kill the bundle
1425     if (noSkipsKill) {
1426         // kill the bundle process during updating
1427         if (!AbilityManagerHelper::UninstallApplicationProcesses(
1428             oldInfo.GetApplicationName(), oldInfo.GetUid(userId_))) {
1429             APP_LOGE("fail to kill running application");
1430             return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
1431         }
1432     }
1433 
1434     oldInfo.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::UPDATING_EXISTED_START);
1435     if (!dataMgr_->SaveInnerBundleInfo(oldInfo)) {
1436         APP_LOGE("save install mark failed");
1437         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
1438     }
1439 
1440     if ((result = ProcessAsanDirectory(newInfo)) != ERR_OK) {
1441         APP_LOGE("process asan log directory failed!");
1442         return result;
1443     }
1444     result = CheckArkProfileDir(newInfo, oldInfo);
1445     if (result != ERR_OK) {
1446         return result;
1447     }
1448 
1449     moduleTmpDir_ = newInfo.GetAppCodePath() + Constants::PATH_SEPARATOR + modulePackage_ + Constants::TMP_SUFFIX;
1450     result = ExtractModule(newInfo, moduleTmpDir_);
1451     if (result != ERR_OK) {
1452         APP_LOGE("extract module and rename failed");
1453         return result;
1454     }
1455 
1456     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UPDATING_SUCCESS)) {
1457         APP_LOGE("old module update state failed");
1458         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1459     }
1460 
1461     newInfo.RestoreModuleInfo(oldInfo);
1462     oldInfo.SetInstallMark(bundleName_, modulePackage_, InstallExceptionStatus::UPDATING_FINISH);
1463     oldInfo.SetBundleUpdateTime(BundleUtil::GetCurrentTime(), userId_);
1464     auto noUpdateInfo = oldInfo;
1465     if (!dataMgr_->UpdateInnerBundleInfo(bundleName_, newInfo, oldInfo)) {
1466         APP_LOGE("update innerBundleInfo %{public}s failed", bundleName_.c_str());
1467         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1468     }
1469 
1470     auto bundleUserInfos = oldInfo.GetInnerBundleUserInfos();
1471     for (const auto &info : bundleUserInfos) {
1472         if (info.second.accessTokenId == 0) {
1473             continue;
1474         }
1475 
1476         std::vector<std::string> newRequestPermName;
1477         if (!BundlePermissionMgr::UpdateDefineAndRequestPermissions(info.second.accessTokenId, noUpdateInfo,
1478             oldInfo, newRequestPermName)) {
1479             APP_LOGE("UpdateDefineAndRequestPermissions %{public}s failed", bundleName_.c_str());
1480             return ERR_APPEXECFWK_INSTALL_UPDATE_HAP_TOKEN_FAILED;
1481         }
1482 
1483         if (!BundlePermissionMgr::GrantRequestPermissions(oldInfo, newRequestPermName, info.second.accessTokenId)) {
1484             APP_LOGE("BundlePermissionMgr::GrantRequestPermissions failed %{public}s", bundleName_.c_str());
1485             return ERR_APPEXECFWK_INSTALL_GRANT_REQUEST_PERMISSIONS_FAILED;
1486         }
1487     }
1488 
1489     ErrCode ret = SetDirApl(newInfo);
1490     if (ret != ERR_OK) {
1491         APP_LOGE("SetDirApl failed");
1492         return ret;
1493     }
1494     needDeleteQuickFixInfo_ = true;
1495     return ERR_OK;
1496 }
1497 
CheckArkProfileDir(const InnerBundleInfo & newInfo,const InnerBundleInfo & oldInfo) const1498 ErrCode BaseBundleInstaller::CheckArkProfileDir(const InnerBundleInfo &newInfo, const InnerBundleInfo &oldInfo) const
1499 {
1500     if (newInfo.GetVersionCode() > oldInfo.GetVersionCode()) {
1501         const auto userInfos = oldInfo.GetInnerBundleUserInfos();
1502         for (auto iter = userInfos.begin(); iter != userInfos.end(); iter++) {
1503             int32_t userId = iter->second.bundleUserInfo.userId;
1504             int32_t gid = (newInfo.GetAppProvisionType() == Constants::APP_PROVISION_TYPE_DEBUG) ?
1505                 GetIntParameter(BMS_KEY_SHELL_UID, Constants::SHELL_UID) :
1506                 oldInfo.GetUid(userId);
1507             ErrCode result = newInfo.GetIsNewVersion() ?
1508                 CreateArkProfile(bundleName_, userId, oldInfo.GetUid(userId), gid) :
1509                 DeleteArkProfile(bundleName_, userId);
1510             if (result != ERR_OK) {
1511                 APP_LOGE("bundleName: %{public}s CheckArkProfileDir failed, result:%{public}d",
1512                     bundleName_.c_str(), result);
1513                 return result;
1514             }
1515         }
1516     }
1517     return ERR_OK;
1518 }
1519 
ProcessHqfInfo(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const1520 void BaseBundleInstaller::ProcessHqfInfo(
1521     const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
1522 {
1523 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
1524     APP_LOGI("ProcessHqfInfo start, bundleName: %{public}s, moduleName: %{public}s", bundleName_.c_str(),
1525         modulePackage_.c_str());
1526     std::string cpuAbi;
1527     std::string nativeLibraryPath;
1528     if (!newInfo.FetchNativeSoAttrs(modulePackage_, cpuAbi, nativeLibraryPath)) {
1529         APP_LOGI("No native so, bundleName: %{public}s, moduleName: %{public}s", bundleName_.c_str(),
1530             modulePackage_.c_str());
1531         return;
1532     }
1533 
1534     ErrCode ret = ProcessDeployedHqfInfo(
1535         nativeLibraryPath, cpuAbi, newInfo, oldInfo.GetAppQuickFix());
1536     if (ret != ERR_OK) {
1537         APP_LOGW("ProcessDeployedHqfInfo failed, errcode: %{public}d", ret);
1538         return;
1539     }
1540 
1541     ret = ProcessDeployingHqfInfo(nativeLibraryPath, cpuAbi, newInfo);
1542     if (ret != ERR_OK) {
1543         APP_LOGW("ProcessDeployingHqfInfo failed, errcode: %{public}d", ret);
1544         return;
1545     }
1546 
1547     APP_LOGI("ProcessHqfInfo end");
1548 #endif
1549 }
1550 
ProcessDeployedHqfInfo(const std::string & nativeLibraryPath,const std::string & cpuAbi,const InnerBundleInfo & newInfo,const AppQuickFix & oldAppQuickFix) const1551 ErrCode BaseBundleInstaller::ProcessDeployedHqfInfo(const std::string &nativeLibraryPath,
1552     const std::string &cpuAbi, const InnerBundleInfo &newInfo, const AppQuickFix &oldAppQuickFix) const
1553 {
1554 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
1555     APP_LOGI("ProcessDeployedHqfInfo");
1556     auto appQuickFix = oldAppQuickFix;
1557     AppqfInfo &appQfInfo = appQuickFix.deployedAppqfInfo;
1558     if (isFeatureNeedUninstall_ || appQfInfo.hqfInfos.empty()) {
1559         APP_LOGI("No need ProcessDeployedHqfInfo");
1560         return ERR_OK;
1561     }
1562 
1563     ErrCode ret = ProcessDiffFiles(appQfInfo, nativeLibraryPath);
1564     if (ret != ERR_OK) {
1565         APP_LOGE("ProcessDeployedHqfInfo failed, errcode: %{public}d", ret);
1566         return ret;
1567     }
1568 
1569     std::string newSoPath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName_ +
1570         Constants::PATH_SEPARATOR + Constants::PATCH_PATH +
1571         std::to_string(appQfInfo.versionCode) + Constants::PATH_SEPARATOR + nativeLibraryPath;
1572     bool isExist = false;
1573     if ((InstalldClient::GetInstance()->IsExistDir(newSoPath, isExist) != ERR_OK) || !isExist) {
1574         APP_LOGW("Patch no diff file");
1575         return ERR_OK;
1576     }
1577 
1578     ret = UpdateLibAttrs(newInfo, cpuAbi, nativeLibraryPath, appQfInfo);
1579     if (ret != ERR_OK) {
1580         APP_LOGE("UpdateModuleLib failed, errcode: %{public}d", ret);
1581         return ret;
1582     }
1583 
1584     InnerBundleInfo innerBundleInfo;
1585     if (!dataMgr_->FetchInnerBundleInfo(bundleName_, innerBundleInfo)) {
1586         APP_LOGE("Fetch bundleInfo(%{public}s) failed.", bundleName_.c_str());
1587         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
1588     }
1589 
1590     innerBundleInfo.SetAppQuickFix(appQuickFix);
1591     if (!dataMgr_->UpdateQuickFixInnerBundleInfo(bundleName_, innerBundleInfo)) {
1592         APP_LOGE("update quickfix innerbundleInfo failed");
1593         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
1594     }
1595 #endif
1596     return ERR_OK;
1597 }
1598 
ProcessDeployingHqfInfo(const std::string & nativeLibraryPath,const std::string & cpuAbi,const InnerBundleInfo & newInfo) const1599 ErrCode BaseBundleInstaller::ProcessDeployingHqfInfo(
1600     const std::string &nativeLibraryPath, const std::string &cpuAbi, const InnerBundleInfo &newInfo) const
1601 {
1602 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
1603     APP_LOGI("ProcessDeployingHqfInfo");
1604     std::shared_ptr<QuickFixDataMgr> quickFixDataMgr = DelayedSingleton<QuickFixDataMgr>::GetInstance();
1605     if (quickFixDataMgr == nullptr) {
1606         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
1607     }
1608 
1609     InnerAppQuickFix innerAppQuickFix;
1610     if (!quickFixDataMgr->QueryInnerAppQuickFix(bundleName_, innerAppQuickFix)) {
1611         return ERR_OK;
1612     }
1613 
1614     auto appQuickFix = innerAppQuickFix.GetAppQuickFix();
1615     AppqfInfo &appQfInfo = appQuickFix.deployingAppqfInfo;
1616     ErrCode ret = ProcessDiffFiles(appQfInfo, nativeLibraryPath);
1617     if (ret != ERR_OK) {
1618         APP_LOGE("ProcessDeployingHqfInfo failed, errcode: %{public}d", ret);
1619         return ret;
1620     }
1621 
1622     std::string newSoPath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName_ +
1623         Constants::PATH_SEPARATOR + Constants::PATCH_PATH +
1624         std::to_string(appQfInfo.versionCode) + Constants::PATH_SEPARATOR + nativeLibraryPath;
1625     bool isExist = false;
1626     if ((InstalldClient::GetInstance()->IsExistDir(newSoPath, isExist) != ERR_OK) || !isExist) {
1627         APP_LOGW("Patch no diff file");
1628         return ERR_OK;
1629     }
1630 
1631     ret = UpdateLibAttrs(newInfo, cpuAbi, nativeLibraryPath, appQfInfo);
1632     if (ret != ERR_OK) {
1633         APP_LOGE("UpdateModuleLib failed, errcode: %{public}d", ret);
1634         return ret;
1635     }
1636 
1637     innerAppQuickFix.SetAppQuickFix(appQuickFix);
1638     if (!quickFixDataMgr->SaveInnerAppQuickFix(innerAppQuickFix)) {
1639         APP_LOGE("bundleName: %{public}s, inner app quick fix save failed", bundleName_.c_str());
1640         return ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED;
1641     }
1642 #endif
1643     return ERR_OK;
1644 }
1645 
UpdateLibAttrs(const InnerBundleInfo & newInfo,const std::string & cpuAbi,const std::string & nativeLibraryPath,AppqfInfo & appQfInfo) const1646 ErrCode BaseBundleInstaller::UpdateLibAttrs(const InnerBundleInfo &newInfo,
1647     const std::string &cpuAbi, const std::string &nativeLibraryPath, AppqfInfo &appQfInfo) const
1648 {
1649 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
1650     auto newNativeLibraryPath = Constants::PATCH_PATH +
1651         std::to_string(appQfInfo.versionCode) + Constants::PATH_SEPARATOR + nativeLibraryPath;
1652     auto moduleName = newInfo.GetCurModuleName();
1653     bool isLibIsolated = newInfo.IsLibIsolated(moduleName);
1654     if (!isLibIsolated) {
1655         appQfInfo.nativeLibraryPath = newNativeLibraryPath;
1656         appQfInfo.cpuAbi = cpuAbi;
1657         return ERR_OK;
1658     }
1659 
1660     for (auto &hqfInfo : appQfInfo.hqfInfos) {
1661         if (hqfInfo.moduleName != moduleName) {
1662             continue;
1663         }
1664 
1665         hqfInfo.nativeLibraryPath = newNativeLibraryPath;
1666         hqfInfo.cpuAbi = cpuAbi;
1667         if (!BundleUtil::StartWith(appQfInfo.nativeLibraryPath, Constants::PATCH_PATH)) {
1668             appQfInfo.nativeLibraryPath.clear();
1669         }
1670 
1671         return ERR_OK;
1672     }
1673 
1674     return ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST;
1675 #else
1676     return ERR_OK;
1677 #endif
1678 }
1679 
CheckHapLibsWithPatchLibs(const std::string & nativeLibraryPath,const std::string & hqfLibraryPath) const1680 bool BaseBundleInstaller::CheckHapLibsWithPatchLibs(
1681     const std::string &nativeLibraryPath, const std::string &hqfLibraryPath) const
1682 {
1683 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
1684     if (!hqfLibraryPath.empty()) {
1685         auto position = hqfLibraryPath.find(Constants::PATH_SEPARATOR);
1686         if (position == std::string::npos) {
1687             return false;
1688         }
1689 
1690         auto newHqfLibraryPath = hqfLibraryPath.substr(position);
1691         if (!BundleUtil::EndWith(nativeLibraryPath, newHqfLibraryPath)) {
1692             APP_LOGE("error: nativeLibraryPath not same, newInfo: %{public}s, hqf: %{public}s",
1693                 nativeLibraryPath.c_str(), newHqfLibraryPath.c_str());
1694             return false;
1695         }
1696     }
1697 #endif
1698     return true;
1699 }
1700 
ProcessDiffFiles(const AppqfInfo & appQfInfo,const std::string & nativeLibraryPath) const1701 ErrCode BaseBundleInstaller::ProcessDiffFiles(const AppqfInfo &appQfInfo, const std::string &nativeLibraryPath) const
1702 {
1703 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
1704     const std::string moduleName = modulePackage_;
1705     auto iter = find_if(appQfInfo.hqfInfos.begin(), appQfInfo.hqfInfos.end(),
1706         [&moduleName](const auto &hqfInfo) {
1707         return hqfInfo.moduleName == moduleName;
1708     });
1709     if (iter != appQfInfo.hqfInfos.end()) {
1710         // appQfInfo.nativeLibraryPath may be start with patch_versionCode
1711         if (!CheckHapLibsWithPatchLibs(nativeLibraryPath, appQfInfo.nativeLibraryPath)) {
1712             APP_LOGE("CheckHapLibsWithPatchLibs failed newInfo: %{public}s, hqf: %{public}s",
1713                      nativeLibraryPath.c_str(), appQfInfo.nativeLibraryPath.c_str());
1714             return ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE;
1715         }
1716         const std::string tempDiffPath = Constants::HAP_COPY_PATH + Constants::PATH_SEPARATOR +
1717             bundleName_ + Constants::TMP_SUFFIX;
1718         ScopeGuard removeDiffPath([tempDiffPath] { InstalldClient::GetInstance()->RemoveDir(tempDiffPath); });
1719         ErrCode ret = InstalldClient::GetInstance()->ExtractDiffFiles(iter->hqfFilePath,
1720             tempDiffPath, appQfInfo.cpuAbi);
1721         if (ret != ERR_OK) {
1722             APP_LOGE("error: ExtractDiffFiles failed errcode :%{public}d", ret);
1723             return ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED;
1724         }
1725         std::string oldSoPath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName_ +
1726             Constants::PATH_SEPARATOR + nativeLibraryPath;
1727         std::string newSoPath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName_ +
1728             Constants::PATH_SEPARATOR + Constants::PATCH_PATH +
1729             std::to_string(appQfInfo.versionCode) + Constants::PATH_SEPARATOR + nativeLibraryPath;
1730         ret = InstalldClient::GetInstance()->ApplyDiffPatch(oldSoPath, tempDiffPath, newSoPath);
1731         if (ret != ERR_OK) {
1732             APP_LOGE("error: ApplyDiffPatch failed errcode :%{public}d", ret);
1733             return ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED;
1734         }
1735     }
1736 #endif
1737     return ERR_OK;
1738 }
1739 
SetDirApl(const InnerBundleInfo & info)1740 ErrCode BaseBundleInstaller::SetDirApl(const InnerBundleInfo &info)
1741 {
1742     for (const auto &el : Constants::BUNDLE_EL) {
1743         std::string baseBundleDataDir = Constants::BUNDLE_APP_DATA_BASE_DIR +
1744                                         el +
1745                                         Constants::PATH_SEPARATOR +
1746                                         std::to_string(userId_);
1747         std::string baseDataDir = baseBundleDataDir + Constants::BASE + info.GetBundleName();
1748         bool isExist = true;
1749         ErrCode result = InstalldClient::GetInstance()->IsExistDir(baseDataDir, isExist);
1750         if (result != ERR_OK) {
1751             APP_LOGE("IsExistDir failed, error is %{public}d", result);
1752             return result;
1753         }
1754         if (!isExist) {
1755             APP_LOGD("baseDir: %{public}s is not exist", baseDataDir.c_str());
1756             continue;
1757         }
1758         result = InstalldClient::GetInstance()->SetDirApl(
1759             baseDataDir, info.GetBundleName(), info.GetAppPrivilegeLevel());
1760         if (result != ERR_OK) {
1761             APP_LOGE("fail to SetDirApl baseDir dir, error is %{public}d", result);
1762             return result;
1763         }
1764         std::string databaseDataDir = baseBundleDataDir + Constants::DATABASE + info.GetBundleName();
1765         result = InstalldClient::GetInstance()->SetDirApl(
1766             databaseDataDir, info.GetBundleName(), info.GetAppPrivilegeLevel());
1767         if (result != ERR_OK) {
1768             APP_LOGE("fail to SetDirApl databaseDir dir, error is %{public}d", result);
1769             return result;
1770         }
1771     }
1772 
1773     return ERR_OK;
1774 }
1775 
CreateBundleAndDataDir(InnerBundleInfo & info) const1776 ErrCode BaseBundleInstaller::CreateBundleAndDataDir(InnerBundleInfo &info) const
1777 {
1778     ErrCode result = CreateBundleCodeDir(info);
1779     if (result != ERR_OK) {
1780         APP_LOGE("fail to create bundle code dir, error is %{public}d", result);
1781         return result;
1782     }
1783     ScopeGuard codePathGuard([&] { InstalldClient::GetInstance()->RemoveDir(info.GetAppCodePath()); });
1784     result = CreateBundleDataDir(info);
1785     if (result != ERR_OK) {
1786         APP_LOGE("fail to create bundle data dir, error is %{public}d", result);
1787         return result;
1788     }
1789     codePathGuard.Dismiss();
1790     return ERR_OK;
1791 }
1792 
CreateBundleCodeDir(InnerBundleInfo & info) const1793 ErrCode BaseBundleInstaller::CreateBundleCodeDir(InnerBundleInfo &info) const
1794 {
1795     auto appCodePath = Constants::BUNDLE_CODE_DIR + Constants::PATH_SEPARATOR + bundleName_;
1796     APP_LOGD("create bundle dir %{private}s", appCodePath.c_str());
1797     ErrCode result = InstalldClient::GetInstance()->CreateBundleDir(appCodePath);
1798     if (result != ERR_OK) {
1799         APP_LOGE("fail to create bundle dir, error is %{public}d", result);
1800         return result;
1801     }
1802 
1803     info.SetAppCodePath(appCodePath);
1804     return ERR_OK;
1805 }
1806 
CreateBundleDataDir(InnerBundleInfo & info) const1807 ErrCode BaseBundleInstaller::CreateBundleDataDir(InnerBundleInfo &info) const
1808 {
1809     InnerBundleUserInfo newInnerBundleUserInfo;
1810     if (!info.GetInnerBundleUserInfo(userId_, newInnerBundleUserInfo)) {
1811         APP_LOGE("bundle(%{public}s) get user(%{public}d) failed.",
1812             info.GetBundleName().c_str(), userId_);
1813         return ERR_APPEXECFWK_USER_NOT_EXIST;
1814     }
1815 
1816     if (!dataMgr_->GenerateUidAndGid(newInnerBundleUserInfo)) {
1817         APP_LOGE("fail to generate uid and gid");
1818         return ERR_APPEXECFWK_INSTALL_GENERATE_UID_ERROR;
1819     }
1820 
1821     auto result = InstalldClient::GetInstance()->CreateBundleDataDir(info.GetBundleName(), userId_,
1822         newInnerBundleUserInfo.uid, newInnerBundleUserInfo.uid, info.GetAppPrivilegeLevel());
1823     if (result != ERR_OK) {
1824         APP_LOGE("fail to create bundle data dir, error is %{public}d", result);
1825         return result;
1826     }
1827 
1828     if (info.GetIsNewVersion()) {
1829         int32_t gid = (info.GetAppProvisionType() == Constants::APP_PROVISION_TYPE_DEBUG) ?
1830             GetIntParameter(BMS_KEY_SHELL_UID, Constants::SHELL_UID) :
1831             newInnerBundleUserInfo.uid;
1832         result = CreateArkProfile(
1833             info.GetBundleName(), userId_, newInnerBundleUserInfo.uid, gid);
1834         if (result != ERR_OK) {
1835             APP_LOGE("fail to create ark profile, error is %{public}d", result);
1836             return result;
1837         }
1838     }
1839 
1840     // create asan log directory when asanEnabled is true
1841     // In update condition, delete asan log directory when asanEnabled is false if directory is exist
1842     if ((result = ProcessAsanDirectory(info)) != ERR_OK) {
1843         APP_LOGE("process asan log directory failed!");
1844         return result;
1845     }
1846 
1847     std::string dataBaseDir = Constants::BUNDLE_APP_DATA_BASE_DIR + Constants::BUNDLE_EL[1] +
1848         Constants::DATABASE + info.GetBundleName();
1849     info.SetAppDataBaseDir(dataBaseDir);
1850     info.AddInnerBundleUserInfo(newInnerBundleUserInfo);
1851     return ERR_OK;
1852 }
1853 
CreateArkProfile(const std::string & bundleName,int32_t userId,int32_t uid,int32_t gid) const1854 ErrCode BaseBundleInstaller::CreateArkProfile(
1855     const std::string &bundleName, int32_t userId, int32_t uid, int32_t gid) const
1856 {
1857     ErrCode result = DeleteArkProfile(bundleName, userId);
1858     if (result != ERR_OK) {
1859         APP_LOGE("fail to removeArkProfile, error is %{public}d", result);
1860         return result;
1861     }
1862 
1863     std::string arkProfilePath;
1864     arkProfilePath.append(ARK_PROFILE_PATH).append(std::to_string(userId))
1865         .append(Constants::PATH_SEPARATOR).append(bundleName);
1866     APP_LOGI("CreateArkProfile %{public}s", arkProfilePath.c_str());
1867     int32_t mode = (uid == gid) ? S_IRWXU : (S_IRWXU | S_IRGRP | S_IXGRP);
1868     return InstalldClient::GetInstance()->Mkdir(arkProfilePath, mode, uid, gid);
1869 }
1870 
DeleteArkProfile(const std::string & bundleName,int32_t userId) const1871 ErrCode BaseBundleInstaller::DeleteArkProfile(const std::string &bundleName, int32_t userId) const
1872 {
1873     std::string arkProfilePath;
1874     arkProfilePath.append(ARK_PROFILE_PATH).append(std::to_string(userId))
1875         .append(Constants::PATH_SEPARATOR).append(bundleName);
1876     APP_LOGI("DeleteArkProfile %{public}s", arkProfilePath.c_str());
1877     return InstalldClient::GetInstance()->RemoveDir(arkProfilePath);
1878 }
1879 
ExtractModule(InnerBundleInfo & info,const std::string & modulePath)1880 ErrCode BaseBundleInstaller::ExtractModule(InnerBundleInfo &info, const std::string &modulePath)
1881 {
1882     std::string targetSoPath;
1883     std::string cpuAbi;
1884     std::string nativeLibraryPath;
1885     if (info.FetchNativeSoAttrs(modulePackage_, cpuAbi, nativeLibraryPath)) {
1886         bool isLibIsolated = info.IsLibIsolated(info.GetCurModuleName());
1887         if (isLibIsolated && BundleUtil::EndWith(modulePath, Constants::TMP_SUFFIX)) {
1888             nativeLibraryPath = BuildTempNativeLibraryPath(nativeLibraryPath);
1889             APP_LOGD("Need extract to temp dir: %{public}s", nativeLibraryPath.c_str());
1890         }
1891         targetSoPath.append(Constants::BUNDLE_CODE_DIR).append(Constants::PATH_SEPARATOR)
1892             .append(info.GetBundleName()).append(Constants::PATH_SEPARATOR)
1893             .append(nativeLibraryPath).append(Constants::PATH_SEPARATOR);
1894     }
1895 
1896     APP_LOGD("begin to extract module files, modulePath : %{private}s, targetSoPath : %{private}s, cpuAbi : %{public}s",
1897         modulePath.c_str(), targetSoPath.c_str(), cpuAbi.c_str());
1898     auto result = ExtractModuleFiles(info, modulePath, targetSoPath, cpuAbi);
1899     if (result != ERR_OK) {
1900         APP_LOGE("fail to extrace module dir, error is %{public}d", result);
1901         return result;
1902     }
1903 
1904     result = ExtractArkNativeFile(info, modulePath);
1905     if (result != ERR_OK) {
1906         APP_LOGE("fail to extractArkNativeFile, error is %{public}d", result);
1907         return result;
1908     }
1909 
1910     if (info.GetIsNewVersion()) {
1911         result = ExtractArkProfileFile(modulePath_, info.GetBundleName(), userId_);
1912         if (result != ERR_OK) {
1913             APP_LOGE("fail to ExtractArkProfileFile, error is %{public}d", result);
1914             return result;
1915         }
1916     }
1917 
1918     if (info.IsPreInstallApp()) {
1919         info.SetModuleHapPath(modulePath_);
1920     } else {
1921         info.SetModuleHapPath(GetHapPath(info));
1922     }
1923 
1924     auto moduleDir = info.GetAppCodePath() + Constants::PATH_SEPARATOR + info.GetCurrentModulePackage();
1925     info.AddModuleSrcDir(moduleDir);
1926     info.AddModuleResPath(moduleDir);
1927     return ERR_OK;
1928 }
1929 
ExtractArkNativeFile(InnerBundleInfo & info,const std::string & modulePath)1930 ErrCode BaseBundleInstaller::ExtractArkNativeFile(InnerBundleInfo &info, const std::string &modulePath)
1931 {
1932     if (!info.GetArkNativeFilePath().empty()) {
1933         APP_LOGD("Module %{public}s no need to extract an", modulePackage_.c_str());
1934         return ERR_OK;
1935     }
1936 
1937     std::string cpuAbi = info.GetArkNativeFileAbi();
1938     if (cpuAbi.empty()) {
1939         APP_LOGD("Module %{public}s no native file", modulePackage_.c_str());
1940         return ERR_OK;
1941     }
1942 
1943     if (Constants::ABI_MAP.find(cpuAbi) == Constants::ABI_MAP.end()) {
1944         APP_LOGE("No support %{public}s abi", cpuAbi.c_str());
1945         return ERR_APPEXECFWK_PARSE_AN_FAILED;
1946     }
1947 
1948     std::string arkNativeFilePath;
1949     arkNativeFilePath.append(Constants::ABI_MAP.at(cpuAbi)).append(Constants::PATH_SEPARATOR);
1950     std::string targetPath;
1951     targetPath.append(ARK_CACHE_PATH).append(info.GetBundleName())
1952         .append(Constants::PATH_SEPARATOR).append(arkNativeFilePath);
1953     APP_LOGD("Begin to extract an file, modulePath : %{private}s, targetPath : %{private}s, cpuAbi : %{public}s",
1954         modulePath.c_str(), targetPath.c_str(), cpuAbi.c_str());
1955     ExtractParam extractParam;
1956     extractParam.srcPath = modulePath_;
1957     extractParam.targetPath = targetPath;
1958     extractParam.cpuAbi = cpuAbi;
1959     extractParam.extractFileType = ExtractFileType::AN;
1960     auto result = InstalldClient::GetInstance()->ExtractFiles(extractParam);
1961     if (result != ERR_OK) {
1962         APP_LOGE("extract files failed, error is %{public}d", result);
1963         return result;
1964     }
1965 
1966     info.SetArkNativeFilePath(arkNativeFilePath);
1967     return ERR_OK;
1968 }
1969 
ExtractAllArkProfileFile(const InnerBundleInfo & oldInfo) const1970 ErrCode BaseBundleInstaller::ExtractAllArkProfileFile(const InnerBundleInfo &oldInfo) const
1971 {
1972     if (!oldInfo.GetIsNewVersion()) {
1973         return ERR_OK;
1974     }
1975     std::string bundleName = oldInfo.GetBundleName();
1976     APP_LOGD("Begin to ExtractAllArkProfileFile, bundleName : %{public}s", bundleName.c_str());
1977     const auto &innerModuleInfos = oldInfo.GetInnerModuleInfos();
1978     for (auto iter = innerModuleInfos.cbegin(); iter != innerModuleInfos.cend(); ++iter) {
1979         ErrCode ret = ExtractArkProfileFile(iter->second.hapPath, bundleName, userId_);
1980         if (ret != ERR_OK) {
1981             return ret;
1982         }
1983     }
1984     APP_LOGD("ExtractAllArkProfileFile succeed, bundleName : %{public}s", bundleName.c_str());
1985     return ERR_OK;
1986 }
1987 
ExtractArkProfileFile(const std::string & modulePath,const std::string & bundleName,int32_t userId) const1988 ErrCode BaseBundleInstaller::ExtractArkProfileFile(
1989     const std::string &modulePath,
1990     const std::string &bundleName,
1991     int32_t userId) const
1992 {
1993     std::string targetPath;
1994     targetPath.append(ARK_PROFILE_PATH).append(std::to_string(userId))
1995         .append(Constants::PATH_SEPARATOR).append(bundleName);
1996     APP_LOGD("Begin to extract ap file, modulePath : %{private}s, targetPath : %{private}s",
1997         modulePath.c_str(), targetPath.c_str());
1998     ExtractParam extractParam;
1999     extractParam.srcPath = modulePath;
2000     extractParam.targetPath = targetPath;
2001     extractParam.cpuAbi = Constants::EMPTY_STRING;
2002     extractParam.extractFileType = ExtractFileType::AP;
2003     auto result = InstalldClient::GetInstance()->ExtractFiles(extractParam);
2004     if (result != ERR_OK) {
2005         APP_LOGE("extract ap files failed, error is %{public}d", result);
2006         return result;
2007     }
2008     return ERR_OK;
2009 }
2010 
DeleteOldArkNativeFile(const InnerBundleInfo & oldInfo)2011 ErrCode BaseBundleInstaller::DeleteOldArkNativeFile(const InnerBundleInfo &oldInfo)
2012 {
2013     std::string arkNativeFilePath = oldInfo.GetArkNativeFilePath();
2014     if (arkNativeFilePath.empty()) {
2015         APP_LOGD("OldInfo(%{public}s) no arkNativeFilePath", oldInfo.GetBundleName().c_str());
2016         return ERR_OK;
2017     }
2018 
2019     std::string targetPath;
2020     targetPath.append(ARK_CACHE_PATH).append(oldInfo.GetBundleName());
2021     auto result = InstalldClient::GetInstance()->RemoveDir(targetPath);
2022     if (result != ERR_OK) {
2023         APP_LOGE("fail to remove arkNativeFilePath %{public}s, error is %{public}d",
2024             arkNativeFilePath.c_str(), result);
2025     }
2026 
2027     return result;
2028 }
2029 
RemoveBundleAndDataDir(const InnerBundleInfo & info,bool isKeepData) const2030 ErrCode BaseBundleInstaller::RemoveBundleAndDataDir(const InnerBundleInfo &info, bool isKeepData) const
2031 {
2032     // remove bundle dir
2033     auto result = RemoveBundleCodeDir(info);
2034     if (result != ERR_OK) {
2035         APP_LOGE("fail to remove bundle dir %{private}s, error is %{public}d", info.GetAppCodePath().c_str(), result);
2036         return result;
2037     }
2038     if (!isKeepData) {
2039         result = RemoveBundleDataDir(info);
2040         if (result != ERR_OK) {
2041             APP_LOGE("fail to remove bundleData dir %{private}s, error is %{public}d",
2042                 info.GetBundleName().c_str(), result);
2043         }
2044     }
2045     return result;
2046 }
2047 
RemoveBundleCodeDir(const InnerBundleInfo & info) const2048 ErrCode BaseBundleInstaller::RemoveBundleCodeDir(const InnerBundleInfo &info) const
2049 {
2050     auto result = InstalldClient::GetInstance()->RemoveDir(info.GetAppCodePath());
2051     if (result != ERR_OK) {
2052         APP_LOGE("fail to remove bundle code dir %{public}s, error is %{public}d",
2053             info.GetAppCodePath().c_str(), result);
2054     }
2055     return result;
2056 }
2057 
RemoveBundleDataDir(const InnerBundleInfo & info) const2058 ErrCode BaseBundleInstaller::RemoveBundleDataDir(const InnerBundleInfo &info) const
2059 {
2060     ErrCode result =
2061         InstalldClient::GetInstance()->RemoveBundleDataDir(info.GetBundleName(), userId_);
2062     if (result != ERR_OK) {
2063         APP_LOGE("fail to remove bundleName: %{public}s, error is %{public}d",
2064             info.GetBundleName().c_str(), result);
2065     }
2066     return result;
2067 }
2068 
RemoveEmptyDirs(const std::unordered_map<std::string,InnerBundleInfo> & infos) const2069 void BaseBundleInstaller::RemoveEmptyDirs(const std::unordered_map<std::string, InnerBundleInfo> &infos) const
2070 {
2071     for (const auto &item : infos) {
2072         const InnerBundleInfo &info = item.second;
2073         std::string moduleDir = info.GetAppCodePath() + Constants::PATH_SEPARATOR + info.GetCurrentModulePackage();
2074         bool isDirEmpty = false;
2075         InstalldClient::GetInstance()->IsDirEmpty(moduleDir, isDirEmpty);
2076         if (isDirEmpty) {
2077             APP_LOGD("remove empty dir : %{public}s", moduleDir.c_str());
2078             InstalldClient::GetInstance()->RemoveDir(moduleDir);
2079         }
2080     }
2081 }
2082 
RemoveModuleAndDataDir(const InnerBundleInfo & info,const std::string & modulePackage,int32_t userId,bool isKeepData) const2083 ErrCode BaseBundleInstaller::RemoveModuleAndDataDir(
2084     const InnerBundleInfo &info, const std::string &modulePackage, int32_t userId, bool isKeepData) const
2085 {
2086     APP_LOGD("RemoveModuleAndDataDir with package name %{public}s", modulePackage.c_str());
2087     auto moduleDir = info.GetModuleDir(modulePackage);
2088     auto result = RemoveModuleDir(moduleDir);
2089     if (result != ERR_OK) {
2090         APP_LOGE("fail to remove module dir, error is %{public}d", result);
2091         return result;
2092     }
2093 
2094     // remove hap
2095     result = RemoveModuleDir(GetHapPath(info, info.GetModuleName(modulePackage)));
2096     if (result != ERR_OK) {
2097         APP_LOGE("fail to remove module hap, error is %{public}d", result);
2098         return result;
2099     }
2100 
2101     if (!isKeepData) {
2102         // uninstall hap remove current userId data dir
2103         if (userId != Constants::UNSPECIFIED_USERID) {
2104             RemoveModuleDataDir(info, modulePackage, userId);
2105             return ERR_OK;
2106         }
2107 
2108         // update hap remove all lower version data dir
2109         for (auto infoItem : info.GetInnerBundleUserInfos()) {
2110             int32_t installedUserId = infoItem.second.bundleUserInfo.userId;
2111             RemoveModuleDataDir(info, modulePackage, installedUserId);
2112         }
2113     }
2114     APP_LOGD("RemoveModuleAndDataDir successfully");
2115     return ERR_OK;
2116 }
2117 
RemoveModuleDir(const std::string & modulePath) const2118 ErrCode BaseBundleInstaller::RemoveModuleDir(const std::string &modulePath) const
2119 {
2120     APP_LOGD("module dir %{private}s to be removed", modulePath.c_str());
2121     return InstalldClient::GetInstance()->RemoveDir(modulePath);
2122 }
2123 
RemoveModuleDataDir(const InnerBundleInfo & info,const std::string & modulePackage,int32_t userId) const2124 ErrCode BaseBundleInstaller::RemoveModuleDataDir(
2125     const InnerBundleInfo &info, const std::string &modulePackage, int32_t userId) const
2126 {
2127     APP_LOGD("RemoveModuleDataDir bundleName: %{public}s  modulePackage: %{public}s",
2128              info.GetBundleName().c_str(),
2129              modulePackage.c_str());
2130     auto hapModuleInfo = info.FindHapModuleInfo(modulePackage);
2131     if (!hapModuleInfo) {
2132         APP_LOGE("fail to findHapModule info modulePackage: %{public}s", modulePackage.c_str());
2133         return ERR_NO_INIT;
2134     }
2135     std::string moduleDataDir = info.GetBundleName() + Constants::HAPS + (*hapModuleInfo).moduleName;
2136     APP_LOGD("RemoveModuleDataDir moduleDataDir: %{public}s", moduleDataDir.c_str());
2137     auto result = InstalldClient::GetInstance()->RemoveModuleDataDir(moduleDataDir, userId);
2138     if (result != ERR_OK) {
2139         APP_LOGE("fail to remove HapModuleData dir, error is %{public}d", result);
2140     }
2141     return result;
2142 }
2143 
ExtractModuleFiles(const InnerBundleInfo & info,const std::string & modulePath,const std::string & targetSoPath,const std::string & cpuAbi)2144 ErrCode BaseBundleInstaller::ExtractModuleFiles(const InnerBundleInfo &info, const std::string &modulePath,
2145     const std::string &targetSoPath, const std::string &cpuAbi)
2146 {
2147     APP_LOGD("extract module to %{private}s", modulePath.c_str());
2148     auto result = InstalldClient::GetInstance()->ExtractModuleFiles(modulePath_, modulePath, targetSoPath, cpuAbi);
2149     if (result != ERR_OK) {
2150         APP_LOGE("extract module files failed, error is %{public}d", result);
2151         return result;
2152     }
2153 
2154     return ERR_OK;
2155 }
2156 
RenameModuleDir(const InnerBundleInfo & info) const2157 ErrCode BaseBundleInstaller::RenameModuleDir(const InnerBundleInfo &info) const
2158 {
2159     auto moduleDir = info.GetAppCodePath() + Constants::PATH_SEPARATOR + info.GetCurrentModulePackage();
2160     APP_LOGD("rename module to %{public}s", moduleDir.c_str());
2161     auto result = InstalldClient::GetInstance()->RenameModuleDir(moduleDir + Constants::TMP_SUFFIX, moduleDir);
2162     if (result != ERR_OK) {
2163         APP_LOGE("rename module dir failed, error is %{public}d", result);
2164         return result;
2165     }
2166     return ERR_OK;
2167 }
2168 
CheckSysCap(const std::vector<std::string> & bundlePaths)2169 ErrCode BaseBundleInstaller::CheckSysCap(const std::vector<std::string> &bundlePaths)
2170 {
2171     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2172     return bundleInstallChecker_->CheckSysCap(bundlePaths);
2173 }
2174 
CheckMultipleHapsSignInfo(const std::vector<std::string> & bundlePaths,const InstallParam & installParam,std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes)2175 ErrCode BaseBundleInstaller::CheckMultipleHapsSignInfo(
2176     const std::vector<std::string> &bundlePaths,
2177     const InstallParam &installParam,
2178     std::vector<Security::Verify::HapVerifyResult>& hapVerifyRes)
2179 {
2180     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2181     return bundleInstallChecker_->CheckMultipleHapsSignInfo(bundlePaths, hapVerifyRes);
2182 }
2183 
ParseHapFiles(const std::vector<std::string> & bundlePaths,const InstallParam & installParam,const Constants::AppType appType,std::vector<Security::Verify::HapVerifyResult> & hapVerifyRes,std::unordered_map<std::string,InnerBundleInfo> & infos)2184 ErrCode BaseBundleInstaller::ParseHapFiles(
2185     const std::vector<std::string> &bundlePaths,
2186     const InstallParam &installParam,
2187     const Constants::AppType appType,
2188     std::vector<Security::Verify::HapVerifyResult> &hapVerifyRes,
2189     std::unordered_map<std::string, InnerBundleInfo> &infos)
2190 {
2191     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2192     InstallCheckParam checkParam;
2193     checkParam.isPreInstallApp = installParam.isPreInstallApp;
2194     checkParam.crowdtestDeadline = installParam.crowdtestDeadline;
2195     checkParam.appType = appType;
2196     checkParam.removable = installParam.removable;
2197     ErrCode ret = bundleInstallChecker_->ParseHapFiles(
2198         bundlePaths, checkParam, hapVerifyRes, infos);
2199     if (ret != ERR_OK) {
2200         APP_LOGE("parse hap file failed due to errorCode : %{public}d", ret);
2201         return ret;
2202     }
2203     isContainEntry_ = bundleInstallChecker_->IsContainEntry();
2204     ret = bundleInstallChecker_->CheckDeviceType(infos);
2205     if (ret != ERR_OK) {
2206         APP_LOGE("CheckDeviceType failed due to errorCode : %{public}d", ret);
2207     }
2208     return ret;
2209 }
2210 
CheckDependency(std::unordered_map<std::string,InnerBundleInfo> & infos)2211 ErrCode BaseBundleInstaller::CheckDependency(std::unordered_map<std::string, InnerBundleInfo> &infos)
2212 {
2213     return bundleInstallChecker_->CheckDependency(infos);
2214 }
2215 
CheckHapHashParams(std::unordered_map<std::string,InnerBundleInfo> & infos,std::map<std::string,std::string> hashParams)2216 ErrCode BaseBundleInstaller::CheckHapHashParams(
2217     std::unordered_map<std::string, InnerBundleInfo> &infos,
2218     std::map<std::string, std::string> hashParams)
2219 {
2220     return bundleInstallChecker_->CheckHapHashParams(infos, hashParams);
2221 }
2222 
CheckAppLabelInfo(const std::unordered_map<std::string,InnerBundleInfo> & infos)2223 ErrCode BaseBundleInstaller::CheckAppLabelInfo(const std::unordered_map<std::string, InnerBundleInfo> &infos)
2224 {
2225     ErrCode ret = bundleInstallChecker_->CheckAppLabelInfo(infos);
2226     if (ret != ERR_OK) {
2227         return ret;
2228     }
2229 
2230     bundleName_ = (infos.begin()->second).GetBundleName();
2231     versionCode_ = (infos.begin()->second).GetVersionCode();
2232     return ERR_OK;
2233 }
2234 
CheckMultiNativeFile(std::unordered_map<std::string,InnerBundleInfo> & infos)2235 ErrCode BaseBundleInstaller::CheckMultiNativeFile(
2236     std::unordered_map<std::string, InnerBundleInfo> &infos)
2237 {
2238     return bundleInstallChecker_->CheckMultiNativeFile(infos);
2239 }
2240 
GetInnerBundleInfo(InnerBundleInfo & info,bool & isAppExist)2241 bool BaseBundleInstaller::GetInnerBundleInfo(InnerBundleInfo &info, bool &isAppExist)
2242 {
2243     if (dataMgr_ == nullptr) {
2244         dataMgr_ = DelayedSingleton<BundleMgrService>::GetInstance()->GetDataMgr();
2245         if (dataMgr_ == nullptr) {
2246             APP_LOGE("Get dataMgr shared_ptr nullptr");
2247             return false;
2248         }
2249     }
2250     isAppExist = dataMgr_->GetInnerBundleInfo(bundleName_, info);
2251     return true;
2252 }
2253 
CheckVersionCompatibility(const InnerBundleInfo & oldInfo)2254 ErrCode BaseBundleInstaller::CheckVersionCompatibility(const InnerBundleInfo &oldInfo)
2255 {
2256     if (oldInfo.GetEntryInstallationFree()) {
2257         return CheckVersionCompatibilityForHmService(oldInfo);
2258     }
2259     return CheckVersionCompatibilityForApplication(oldInfo);
2260 }
2261 
2262 // In the process of hap updating, the version code of the entry hap which is about to be updated must not less the
2263 // version code of the current entry haps in the device; if no-entry hap in the device, the updating haps should
2264 // have same version code with the current version code; if the no-entry haps is to be updated, which should has the
2265 // same version code with that of the entry hap in the device.
CheckVersionCompatibilityForApplication(const InnerBundleInfo & oldInfo)2266 ErrCode BaseBundleInstaller::CheckVersionCompatibilityForApplication(const InnerBundleInfo &oldInfo)
2267 {
2268     APP_LOGD("start to check version compatibility for application");
2269     if (oldInfo.HasEntry()) {
2270         if (isContainEntry_ && versionCode_ < oldInfo.GetVersionCode()) {
2271             APP_LOGE("fail to update lower version bundle");
2272             return ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
2273         }
2274         if (!isContainEntry_ && versionCode_ > oldInfo.GetVersionCode()) {
2275             APP_LOGE("version code is not compatible");
2276             return ERR_APPEXECFWK_INSTALL_VERSION_NOT_COMPATIBLE;
2277         }
2278         if (!isContainEntry_ && versionCode_ < oldInfo.GetVersionCode()) {
2279             APP_LOGE("version code is not compatible");
2280             return ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
2281         }
2282     } else {
2283         if (versionCode_ < oldInfo.GetVersionCode()) {
2284             APP_LOGE("fail to update lower version bundle");
2285             return ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
2286         }
2287     }
2288 
2289     if (versionCode_ > oldInfo.GetVersionCode()) {
2290         APP_LOGD("need to uninstall lower version feature hap");
2291         isFeatureNeedUninstall_ = true;
2292     }
2293     APP_LOGD("finish to check version compatibility for application");
2294     return ERR_OK;
2295 }
2296 
CheckVersionCompatibilityForHmService(const InnerBundleInfo & oldInfo)2297 ErrCode BaseBundleInstaller::CheckVersionCompatibilityForHmService(const InnerBundleInfo &oldInfo)
2298 {
2299     APP_LOGD("start to check version compatibility for hm service");
2300     if (versionCode_ < oldInfo.GetVersionCode()) {
2301         APP_LOGE("fail to update lower version bundle");
2302         return ERR_APPEXECFWK_INSTALL_VERSION_DOWNGRADE;
2303     }
2304     if (versionCode_ > oldInfo.GetVersionCode()) {
2305         APP_LOGD("need to uninstall lower version hap");
2306         isFeatureNeedUninstall_ = true;
2307     }
2308     APP_LOGD("finish to check version compatibility for hm service");
2309     return ERR_OK;
2310 }
2311 
UninstallLowerVersionFeature(const std::vector<std::string> & packageVec)2312 ErrCode BaseBundleInstaller::UninstallLowerVersionFeature(const std::vector<std::string> &packageVec)
2313 {
2314     APP_LOGD("start to uninstall lower version feature hap");
2315     InnerBundleInfo info;
2316     bool isExist = false;
2317     if (!GetInnerBundleInfo(info, isExist) || !isExist) {
2318         return ERR_APPEXECFWK_UNINSTALL_BUNDLE_MGR_SERVICE_ERROR;
2319     }
2320 
2321     if (!dataMgr_->UpdateBundleInstallState(bundleName_, InstallState::UNINSTALL_START)) {
2322         APP_LOGE("uninstall already start");
2323         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
2324     }
2325 
2326     // kill the bundle process during uninstall.
2327     if (!AbilityManagerHelper::UninstallApplicationProcesses(info.GetApplicationName(), info.GetUid(userId_))) {
2328         APP_LOGW("can not kill process");
2329     }
2330     std::vector<std::string> moduleVec = info.GetModuleNameVec();
2331     InnerBundleInfo oldInfo = info;
2332     for (const auto &package : moduleVec) {
2333         if (find(packageVec.begin(), packageVec.end(), package) == packageVec.end()) {
2334             APP_LOGD("uninstall package %{public}s", package.c_str());
2335             ErrCode result = RemoveModuleAndDataDir(info, package, Constants::UNSPECIFIED_USERID, true);
2336             if (result != ERR_OK) {
2337                 APP_LOGE("remove module dir failed");
2338                 return result;
2339             }
2340             if (!dataMgr_->RemoveModuleInfo(bundleName_, package, info)) {
2341                 APP_LOGE("RemoveModuleInfo failed");
2342                 return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
2343             }
2344         }
2345     }
2346     // need to delete lower version feature hap definePermissions and requestPermissions
2347     APP_LOGD("delete lower version feature hap definePermissions and requestPermissions");
2348     ErrCode ret = UpdateDefineAndRequestPermissions(oldInfo, info);
2349     if (ret != ERR_OK) {
2350         return ret;
2351     }
2352     needDeleteQuickFixInfo_ = true;
2353     APP_LOGD("finish to uninstall lower version feature hap");
2354     return ERR_OK;
2355 }
2356 
GetConfirmUserId(const int32_t & userId,std::unordered_map<std::string,InnerBundleInfo> & newInfos)2357 int32_t BaseBundleInstaller::GetConfirmUserId(
2358     const int32_t &userId, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
2359 {
2360     if (userId != Constants::UNSPECIFIED_USERID || newInfos.size() <= 0) {
2361         return userId;
2362     }
2363 
2364     bool isSingleton = newInfos.begin()->second.IsSingleton();
2365     APP_LOGI("The userId is Unspecified and app is singleton(%{public}d) when install.",
2366         static_cast<int32_t>(isSingleton));
2367     return isSingleton ? Constants::DEFAULT_USERID : AccountHelper::GetCurrentActiveUserId();
2368 }
2369 
CheckUserId(const int32_t & userId) const2370 ErrCode BaseBundleInstaller::CheckUserId(const int32_t &userId) const
2371 {
2372     if (userId == Constants::UNSPECIFIED_USERID) {
2373         return ERR_OK;
2374     }
2375 
2376     if (!dataMgr_->HasUserId(userId)) {
2377         APP_LOGE("The user %{public}d does not exist when install.", userId);
2378         return ERR_APPEXECFWK_USER_NOT_EXIST;
2379     }
2380 
2381     return ERR_OK;
2382 }
2383 
GetUserId(const int32_t & userId) const2384 int32_t BaseBundleInstaller::GetUserId(const int32_t &userId) const
2385 {
2386     if (userId == Constants::UNSPECIFIED_USERID) {
2387         return userId;
2388     }
2389 
2390     if (userId < Constants::DEFAULT_USERID) {
2391         APP_LOGE("userId(%{public}d) is invalid.", userId);
2392         return Constants::INVALID_USERID;
2393     }
2394 
2395     APP_LOGD("BundleInstaller GetUserId, now userId is %{public}d", userId);
2396     return userId;
2397 }
2398 
CreateBundleUserData(InnerBundleInfo & innerBundleInfo)2399 ErrCode BaseBundleInstaller::CreateBundleUserData(InnerBundleInfo &innerBundleInfo)
2400 {
2401     APP_LOGD("CreateNewUserData %{public}s userId: %{public}d.",
2402         innerBundleInfo.GetBundleName().c_str(), userId_);
2403     if (!innerBundleInfo.HasInnerBundleUserInfo(userId_)) {
2404         return ERR_APPEXECFWK_USER_NOT_EXIST;
2405     }
2406 
2407     ErrCode result = CreateBundleDataDir(innerBundleInfo);
2408     if (result != ERR_OK) {
2409         RemoveBundleDataDir(innerBundleInfo);
2410         return result;
2411     }
2412 
2413     innerBundleInfo.SetBundleInstallTime(BundleUtil::GetCurrentTime(), userId_);
2414     InnerBundleUserInfo innerBundleUserInfo;
2415     if (!innerBundleInfo.GetInnerBundleUserInfo(userId_, innerBundleUserInfo)) {
2416         APP_LOGE("oldInfo do not have user");
2417         return ERR_APPEXECFWK_USER_NOT_EXIST;
2418     }
2419 
2420     if (!dataMgr_->AddInnerBundleUserInfo(innerBundleInfo.GetBundleName(), innerBundleUserInfo)) {
2421         APP_LOGE("update bundle user info to db failed %{public}s when createNewUser",
2422             innerBundleInfo.GetBundleName().c_str());
2423         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
2424     }
2425 
2426     return ERR_OK;
2427 }
2428 
UninstallAllSandboxApps(const std::string & bundleName,int32_t userId)2429 ErrCode BaseBundleInstaller::UninstallAllSandboxApps(const std::string &bundleName, int32_t userId)
2430 {
2431     // All sandbox will be uninstalled when the original application is updated or uninstalled
2432     APP_LOGD("UninstallAllSandboxApps begin");
2433     if (bundleName.empty()) {
2434         APP_LOGE("UninstallAllSandboxApps failed due to empty bundle name");
2435         return ERR_APPEXECFWK_INSTALL_PARAM_ERROR;
2436     }
2437     auto helper = DelayedSingleton<BundleSandboxAppHelper>::GetInstance();
2438     if (helper == nullptr) {
2439         APP_LOGE("UninstallAllSandboxApps failed due to helper nullptr");
2440         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
2441     }
2442     if (helper->UninstallAllSandboxApps(bundleName, userId) != ERR_OK) {
2443         APP_LOGW("UninstallAllSandboxApps failed");
2444         return ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR;
2445     }
2446     APP_LOGD("UninstallAllSandboxApps finish");
2447     return ERR_OK;
2448 }
2449 
CheckNativeFileWithOldInfo(const InnerBundleInfo & oldInfo,std::unordered_map<std::string,InnerBundleInfo> & newInfos)2450 ErrCode BaseBundleInstaller::CheckNativeFileWithOldInfo(
2451     const InnerBundleInfo &oldInfo, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
2452 {
2453     APP_LOGD("CheckNativeFileWithOldInfo begin");
2454     if (HasAllOldModuleUpdate(oldInfo, newInfos)) {
2455         APP_LOGD("All installed haps will be updated");
2456         return ERR_OK;
2457     }
2458 
2459     ErrCode result = CheckNativeSoWithOldInfo(oldInfo, newInfos);
2460     if (result != ERR_OK) {
2461         APP_LOGE("Check nativeSo with oldInfo failed, result: %{public}d", result);
2462         return result;
2463     }
2464 
2465     result = CheckArkNativeFileWithOldInfo(oldInfo, newInfos);
2466     if (result != ERR_OK) {
2467         APP_LOGE("Check arkNativeFile with oldInfo failed, result: %{public}d", result);
2468         return result;
2469     }
2470 
2471     APP_LOGD("CheckNativeFileWithOldInfo end");
2472     return ERR_OK;
2473 }
2474 
HasAllOldModuleUpdate(const InnerBundleInfo & oldInfo,std::unordered_map<std::string,InnerBundleInfo> & newInfos)2475 bool BaseBundleInstaller::HasAllOldModuleUpdate(
2476     const InnerBundleInfo &oldInfo, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
2477 {
2478     const auto &newInfo = newInfos.begin()->second;
2479     bool allOldModuleUpdate = true;
2480     if (newInfo.GetVersionCode() > oldInfo.GetVersionCode()) {
2481         APP_LOGD("All installed haps will be updated");
2482         DeleteOldArkNativeFile(oldInfo);
2483         return allOldModuleUpdate;
2484     }
2485 
2486     std::vector<std::string> installedModules = oldInfo.GetModuleNameVec();
2487     for (const auto &installedModule : installedModules) {
2488         auto updateModule = std::find_if(std::begin(newInfos), std::end(newInfos),
2489             [ &installedModule ] (const auto &item) { return item.second.FindModule(installedModule); });
2490         if (updateModule == newInfos.end()) {
2491             APP_LOGD("Some installed haps will not be updated");
2492             allOldModuleUpdate = false;
2493             break;
2494         }
2495     }
2496     return allOldModuleUpdate;
2497 }
2498 
CheckArkNativeFileWithOldInfo(const InnerBundleInfo & oldInfo,std::unordered_map<std::string,InnerBundleInfo> & newInfos)2499 ErrCode BaseBundleInstaller::CheckArkNativeFileWithOldInfo(
2500     const InnerBundleInfo &oldInfo, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
2501 {
2502     APP_LOGD("CheckArkNativeFileWithOldInfo begin");
2503     std::string oldArkNativeFileAbi = oldInfo.GetArkNativeFileAbi();
2504     if (oldArkNativeFileAbi.empty()) {
2505         APP_LOGD("OldInfo no arkNativeFile");
2506         return ERR_OK;
2507     }
2508 
2509     std::string arkNativeFileAbi = newInfos.begin()->second.GetArkNativeFileAbi();
2510     if (arkNativeFileAbi.empty()) {
2511         APP_LOGD("NewInfos no arkNativeFile");
2512         for (auto& item : newInfos) {
2513             item.second.SetArkNativeFileAbi(oldInfo.GetArkNativeFileAbi());
2514             item.second.SetArkNativeFilePath(oldInfo.GetArkNativeFilePath());
2515         }
2516         return ERR_OK;
2517     } else {
2518         if (arkNativeFileAbi != oldArkNativeFileAbi) {
2519             APP_LOGE("An incompatible in oldInfo and newInfo");
2520             return ERR_APPEXECFWK_INSTALL_AN_INCOMPATIBLE;
2521         }
2522     }
2523 
2524     APP_LOGD("CheckArkNativeFileWithOldInfo end");
2525     return ERR_OK;
2526 }
2527 
CheckNativeSoWithOldInfo(const InnerBundleInfo & oldInfo,std::unordered_map<std::string,InnerBundleInfo> & newInfos)2528 ErrCode BaseBundleInstaller::CheckNativeSoWithOldInfo(
2529     const InnerBundleInfo &oldInfo, std::unordered_map<std::string, InnerBundleInfo> &newInfos)
2530 {
2531     APP_LOGD("CheckNativeSoWithOldInfo begin");
2532     bool oldInfoHasSo = !oldInfo.GetNativeLibraryPath().empty();
2533     if (!oldInfoHasSo) {
2534         APP_LOGD("OldInfo does not has so");
2535         return ERR_OK;
2536     }
2537 
2538     const auto &newInfo = newInfos.begin()->second;
2539     bool newInfoHasSo = !newInfo.GetNativeLibraryPath().empty();
2540     if (newInfoHasSo && (oldInfo.GetNativeLibraryPath() != newInfo.GetNativeLibraryPath()
2541         || oldInfo.GetCpuAbi() != newInfo.GetCpuAbi())) {
2542         APP_LOGE("Install failed due to so incompatible in oldInfo and newInfo");
2543         return ERR_APPEXECFWK_INSTALL_SO_INCOMPATIBLE;
2544     }
2545 
2546     if (!newInfoHasSo) {
2547         for (auto& item : newInfos) {
2548             item.second.SetNativeLibraryPath(oldInfo.GetNativeLibraryPath());
2549             item.second.SetCpuAbi(oldInfo.GetCpuAbi());
2550         }
2551     }
2552 
2553     APP_LOGD("CheckNativeSoWithOldInfo end");
2554     return ERR_OK;
2555 }
2556 
CheckAppLabel(const InnerBundleInfo & oldInfo,const InnerBundleInfo & newInfo) const2557 ErrCode BaseBundleInstaller::CheckAppLabel(const InnerBundleInfo &oldInfo, const InnerBundleInfo &newInfo) const
2558 {
2559     // check app label for inheritance installation
2560     APP_LOGD("CheckAppLabel begin");
2561     if (oldInfo.GetVersionName() != newInfo.GetVersionName()) {
2562         return ERR_APPEXECFWK_INSTALL_VERSIONNAME_NOT_SAME;
2563     }
2564     if (oldInfo.GetMinCompatibleVersionCode() != newInfo.GetMinCompatibleVersionCode()) {
2565         return ERR_APPEXECFWK_INSTALL_MINCOMPATIBLE_VERSIONCODE_NOT_SAME;
2566     }
2567     if (oldInfo.GetVendor() != newInfo.GetVendor()) {
2568         return ERR_APPEXECFWK_INSTALL_VENDOR_NOT_SAME;
2569     }
2570     if (oldInfo.GetTargetVersion()!= newInfo.GetTargetVersion()) {
2571         return ERR_APPEXECFWK_INSTALL_RELEASETYPE_TARGET_NOT_SAME;
2572     }
2573     if (oldInfo.GetCompatibleVersion() != newInfo.GetCompatibleVersion()) {
2574         return ERR_APPEXECFWK_INSTALL_RELEASETYPE_COMPATIBLE_NOT_SAME;
2575     }
2576     if (oldInfo.GetReleaseType() != newInfo.GetReleaseType()) {
2577         return ERR_APPEXECFWK_INSTALL_RELEASETYPE_NOT_SAME;
2578     }
2579     if (oldInfo.GetAppDistributionType() != newInfo.GetAppDistributionType()) {
2580         return ERR_APPEXECFWK_INSTALL_APP_DISTRIBUTION_TYPE_NOT_SAME;
2581     }
2582     if (oldInfo.GetAppProvisionType() != newInfo.GetAppProvisionType()) {
2583         return ERR_APPEXECFWK_INSTALL_APP_PROVISION_TYPE_NOT_SAME;
2584     }
2585     if (oldInfo.GetIsNewVersion() != newInfo.GetIsNewVersion()) {
2586         APP_LOGE("same version update module condition, model type must be the same");
2587         return ERR_APPEXECFWK_INSTALL_STATE_ERROR;
2588     }
2589     if (oldInfo.GetAsanEnabled() != newInfo.GetAsanEnabled()) {
2590         APP_LOGE("asanEnabled is not same");
2591         return ERR_APPEXECFWK_INSTALL_ASAN_ENABLED_NOT_SAME;
2592     }
2593     if (oldInfo.GetApplicationBundleType() != newInfo.GetApplicationBundleType()) {
2594         return ERR_APPEXECFWK_BUNDLE_TYPE_NOT_SAME;
2595     }
2596     APP_LOGD("CheckAppLabel end");
2597     return ERR_OK;
2598 }
2599 
RemoveBundleUserData(InnerBundleInfo & innerBundleInfo,bool needRemoveData)2600 ErrCode BaseBundleInstaller::RemoveBundleUserData(InnerBundleInfo &innerBundleInfo, bool needRemoveData)
2601 {
2602     auto bundleName = innerBundleInfo.GetBundleName();
2603     APP_LOGD("remove user(%{public}d) in bundle(%{public}s).", userId_, bundleName.c_str());
2604     if (!innerBundleInfo.HasInnerBundleUserInfo(userId_)) {
2605         return ERR_APPEXECFWK_USER_NOT_EXIST;
2606     }
2607 
2608     ErrCode result = ERR_OK;
2609     if (!needRemoveData) {
2610         result = RemoveBundleDataDir(innerBundleInfo);
2611         if (result != ERR_OK) {
2612             APP_LOGE("remove user data directory failed.");
2613             return result;
2614         }
2615     }
2616 
2617     result = DeleteArkProfile(bundleName, userId_);
2618     if (result != ERR_OK) {
2619         APP_LOGE("fail to removeArkProfile, error is %{public}d", result);
2620         return result;
2621     }
2622 
2623     if ((result = CleanAsanDirectory(innerBundleInfo)) != ERR_OK) {
2624         APP_LOGE("fail to remove asan log path, error is %{public}d", result);
2625         return result;
2626     }
2627 
2628     // delete accessTokenId
2629     accessTokenId_ = innerBundleInfo.GetAccessTokenId(userId_);
2630     if (BundlePermissionMgr::DeleteAccessTokenId(accessTokenId_) !=
2631         AccessToken::AccessTokenKitRet::RET_SUCCESS) {
2632         APP_LOGE("delete accessToken failed");
2633     }
2634 
2635     innerBundleInfo.RemoveInnerBundleUserInfo(userId_);
2636     if (!dataMgr_->RemoveInnerBundleUserInfo(bundleName, userId_)) {
2637         APP_LOGE("update bundle user info to db failed %{public}s when remove user",
2638             bundleName.c_str());
2639         return ERR_APPEXECFWK_INSTALL_BUNDLE_MGR_SERVICE_ERROR;
2640     }
2641 
2642     return ERR_OK;
2643 }
2644 
VerifyUriPrefix(const InnerBundleInfo & info,int32_t userId,bool isUpdate) const2645 bool BaseBundleInstaller::VerifyUriPrefix(const InnerBundleInfo &info, int32_t userId, bool isUpdate) const
2646 {
2647     // uriPrefix must be unique
2648     // verify current module uriPrefix
2649     std::vector<std::string> currentUriPrefixList;
2650     info.GetUriPrefixList(currentUriPrefixList);
2651     if (currentUriPrefixList.empty()) {
2652         APP_LOGD("current module not include uri, verify uriPrefix success");
2653         return true;
2654     }
2655     std::set<std::string> set;
2656     for (const std::string &currentUriPrefix : currentUriPrefixList) {
2657         if (currentUriPrefix == Constants::DATA_ABILITY_URI_PREFIX) {
2658             APP_LOGE("uri format invalid");
2659             return false;
2660         }
2661         if (!set.insert(currentUriPrefix).second) {
2662             APP_LOGE("current module contains duplicate uriPrefix, verify uriPrefix failed");
2663             APP_LOGE("bundleName : %{public}s, moduleName : %{public}s, uriPrefix : %{public}s",
2664                 info.GetBundleName().c_str(), info.GetCurrentModulePackage().c_str(), currentUriPrefix.c_str());
2665             return false;
2666         }
2667     }
2668     set.clear();
2669     // verify exist bundle uriPrefix
2670     if (dataMgr_ == nullptr) {
2671         APP_LOGE("dataMgr_ is null, verify uriPrefix failed");
2672         return false;
2673     }
2674     std::vector<std::string> uriPrefixList;
2675     std::string excludeModule;
2676     if (isUpdate) {
2677         excludeModule.append(info.GetBundleName()).append(".").append(info.GetCurrentModulePackage()).append(".");
2678     }
2679     dataMgr_->GetAllUriPrefix(uriPrefixList, userId, excludeModule);
2680     if (uriPrefixList.empty()) {
2681         APP_LOGD("uriPrefixList empty, verify uriPrefix success");
2682         return true;
2683     }
2684     for (const std::string &currentUriPrefix : currentUriPrefixList) {
2685         auto iter = std::find(uriPrefixList.cbegin(), uriPrefixList.cend(), currentUriPrefix);
2686         if (iter != uriPrefixList.cend()) {
2687             APP_LOGE("uriPrefix alread exist in device, uriPrefix : %{public}s", currentUriPrefix.c_str());
2688             APP_LOGE("verify uriPrefix failed");
2689             return false;
2690         }
2691     }
2692     APP_LOGD("verify uriPrefix success");
2693     return true;
2694 }
2695 
CheckInstallationFree(const InnerBundleInfo & innerBundleInfo,const std::unordered_map<std::string,InnerBundleInfo> & infos) const2696 ErrCode BaseBundleInstaller::CheckInstallationFree(const InnerBundleInfo &innerBundleInfo,
2697     const std::unordered_map<std::string, InnerBundleInfo> &infos) const
2698 {
2699     for (const auto &item : infos) {
2700         if (innerBundleInfo.GetEntryInstallationFree() != item.second.GetEntryInstallationFree()) {
2701             APP_LOGE("CheckInstallationFree cannot install application and hm service simultaneously");
2702             return ERR_APPEXECFWK_INSTALL_TYPE_ERROR;
2703         }
2704     }
2705     return ERR_OK;
2706 }
2707 
SaveHapPathToRecords(bool isPreInstallApp,const std::unordered_map<std::string,InnerBundleInfo> & infos)2708 void BaseBundleInstaller::SaveHapPathToRecords(
2709     bool isPreInstallApp, const std::unordered_map<std::string, InnerBundleInfo> &infos)
2710 {
2711     if (isPreInstallApp) {
2712         APP_LOGD("PreInstallApp do not need to save hap path to record");
2713         return;
2714     }
2715 
2716     for (const auto &item : infos) {
2717         auto hapPathIter = hapPathRecords_.find(item.first);
2718         if (hapPathIter == hapPathRecords_.end()) {
2719             hapPathRecords_.emplace(item.first, GetHapPath(item.second));
2720         }
2721     }
2722 }
2723 
SaveHapToInstallPath()2724 bool BaseBundleInstaller::SaveHapToInstallPath()
2725 {
2726     for (const auto &hapPathRecord : hapPathRecords_) {
2727         APP_LOGD("Save from(%{public}s) to(%{public}s)",
2728             hapPathRecord.first.c_str(), hapPathRecord.second.c_str());
2729         if (InstalldClient::GetInstance()->CopyFile(
2730             hapPathRecord.first, hapPathRecord.second) != ERR_OK) {
2731             APP_LOGE("Copy hap to install path failed");
2732             return false;
2733         }
2734     }
2735     return true;
2736 }
2737 
ResetInstallProperties()2738 void BaseBundleInstaller::ResetInstallProperties()
2739 {
2740     bundleInstallChecker_->ResetProperties();
2741     isContainEntry_ = false;
2742     isAppExist_ = false;
2743     hasInstalledInUser_ = false;
2744     isFeatureNeedUninstall_ = false;
2745     versionCode_ = 0;
2746     uninstallModuleVec_.clear();
2747     installedModules_.clear();
2748     state_ = InstallerState::INSTALL_START;
2749     singletonState_ = SingletonState::DEFAULT;
2750     accessTokenId_ = 0;
2751     sysEventInfo_.Reset();
2752 }
2753 
OnSingletonChange(bool noSkipsKill)2754 void BaseBundleInstaller::OnSingletonChange(bool noSkipsKill)
2755 {
2756     if (singletonState_ == SingletonState::DEFAULT) {
2757         return;
2758     }
2759 
2760     InnerBundleInfo info;
2761     bool isExist = false;
2762     if (!GetInnerBundleInfo(info, isExist) || !isExist) {
2763         APP_LOGE("Get innerBundleInfo failed when singleton changed");
2764         return;
2765     }
2766 
2767     InstallParam installParam;
2768     installParam.needSendEvent = false;
2769     installParam.forceExecuted = true;
2770     installParam.noSkipsKill = noSkipsKill;
2771     if (singletonState_ == SingletonState::SINGLETON_TO_NON) {
2772         APP_LOGD("Bundle changes from singleton app to non singleton app");
2773         installParam.userId = Constants::DEFAULT_USERID;
2774         UninstallBundle(bundleName_, installParam);
2775         return;
2776     }
2777 
2778     if (singletonState_ == SingletonState::NON_TO_SINGLETON) {
2779         APP_LOGD("Bundle changes from non singleton app to singleton app");
2780         for (auto infoItem : info.GetInnerBundleUserInfos()) {
2781             int32_t installedUserId = infoItem.second.bundleUserInfo.userId;
2782             if (installedUserId == Constants::DEFAULT_USERID) {
2783                 continue;
2784             }
2785 
2786             installParam.userId = installedUserId;
2787             UninstallBundle(bundleName_, installParam);
2788         }
2789     }
2790 }
2791 
SendBundleSystemEvent(const std::string & bundleName,BundleEventType bundleEventType,const InstallParam & installParam,InstallScene preBundleScene,ErrCode errCode)2792 void BaseBundleInstaller::SendBundleSystemEvent(const std::string &bundleName, BundleEventType bundleEventType,
2793     const InstallParam &installParam, InstallScene preBundleScene, ErrCode errCode)
2794 {
2795     sysEventInfo_.bundleName = bundleName;
2796     sysEventInfo_.isPreInstallApp = installParam.isPreInstallApp;
2797     sysEventInfo_.errCode = errCode;
2798     sysEventInfo_.isFreeInstallMode = (installParam.installFlag == InstallFlag::FREE_INSTALL);
2799     sysEventInfo_.userId = userId_;
2800     sysEventInfo_.versionCode = versionCode_;
2801     sysEventInfo_.preBundleScene = preBundleScene;
2802     EventReport::SendBundleSystemEvent(bundleEventType, sysEventInfo_);
2803 }
2804 
NotifyBundleStatus(const NotifyBundleEvents & installRes)2805 ErrCode BaseBundleInstaller::NotifyBundleStatus(const NotifyBundleEvents &installRes)
2806 {
2807     std::shared_ptr<BundleCommonEventMgr> commonEventMgr = std::make_shared<BundleCommonEventMgr>();
2808     commonEventMgr->NotifyBundleStatus(installRes, dataMgr_);
2809     return ERR_OK;
2810 }
2811 
ProcessAsanDirectory(InnerBundleInfo & info) const2812 ErrCode BaseBundleInstaller::ProcessAsanDirectory(InnerBundleInfo &info) const
2813 {
2814     const std::string bundleName = info.GetBundleName();
2815     const std::string asanLogDir = Constants::BUNDLE_ASAN_LOG_DIR + Constants::PATH_SEPARATOR
2816         + std::to_string(userId_) + Constants::PATH_SEPARATOR + bundleName + Constants::PATH_SEPARATOR + LOG;
2817     bool dirExist = false;
2818     ErrCode errCode = InstalldClient::GetInstance()->IsExistDir(asanLogDir, dirExist);
2819     if (errCode != ERR_OK) {
2820         APP_LOGE("check asan log directory failed!");
2821         return errCode;
2822     }
2823     bool asanEnabled = info.GetAsanEnabled();
2824     // create asan log directory if asanEnabled is true
2825     if (!dirExist && asanEnabled) {
2826         InnerBundleUserInfo newInnerBundleUserInfo;
2827         if (!info.GetInnerBundleUserInfo(userId_, newInnerBundleUserInfo)) {
2828             APP_LOGE("bundle(%{public}s) get user(%{public}d) failed.",
2829                 info.GetBundleName().c_str(), userId_);
2830             return ERR_APPEXECFWK_USER_NOT_EXIST;
2831         }
2832 
2833         if (!dataMgr_->GenerateUidAndGid(newInnerBundleUserInfo)) {
2834             APP_LOGE("fail to gererate uid and gid");
2835             return ERR_APPEXECFWK_INSTALL_GENERATE_UID_ERROR;
2836         }
2837         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
2838         if ((errCode = InstalldClient::GetInstance()->Mkdir(asanLogDir, mode,
2839             newInnerBundleUserInfo.uid, newInnerBundleUserInfo.uid)) != ERR_OK) {
2840             APP_LOGE("create asan log directory failed!");
2841             return errCode;
2842         }
2843     }
2844     if (asanEnabled) {
2845         info.SetAsanLogPath(asanLogDir);
2846     }
2847     // clean asan directory
2848     if (dirExist && !asanEnabled) {
2849         if ((errCode = CleanAsanDirectory(info)) != ERR_OK) {
2850             APP_LOGE("clean asan log directory failed!");
2851             return errCode;
2852         }
2853     }
2854     return ERR_OK;
2855 }
2856 
CleanAsanDirectory(InnerBundleInfo & info) const2857 ErrCode BaseBundleInstaller::CleanAsanDirectory(InnerBundleInfo &info) const
2858 {
2859     const std::string bundleName = info.GetBundleName();
2860     const std::string asanLogDir = Constants::BUNDLE_ASAN_LOG_DIR + Constants::PATH_SEPARATOR
2861         + std::to_string(userId_) + Constants::PATH_SEPARATOR + bundleName;
2862     ErrCode errCode =  InstalldClient::GetInstance()->RemoveDir(asanLogDir);
2863     if (errCode != ERR_OK) {
2864         APP_LOGE("clean asan log path failed!");
2865         return errCode;
2866     }
2867     info.SetAsanLogPath("");
2868     return errCode;
2869 }
2870 }  // namespace AppExecFwk
2871 }  // namespace OHOS
2872