diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index 7315efd2a009550e9fce5531d8d6c374b42cb81e..45333f52ae9387824de0e19f4ad764811aa2a5e3 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -178,11 +178,25 @@ private: const std::vector &smallFiles, const std::vector &bigFiles); - void CompareFiles(UniqueFd incrementalFd, - UniqueFd manifestFd, - vector &allFiles, + void FillFileInfos(UniqueFd incrementalFd, + UniqueFd manifestFd, + vector &allFiles, + vector &smallFiles, + vector &bigFiles); + void FillFileInfosWithoutCmp(vector &allFiles, + vector &smallFiles, + vector &bigFiles, + UniqueFd incrementalFd); + void FillFileInfosWithCmp(vector &allFiles, + vector &smallFiles, + vector &bigFiles, + const unordered_map &cloudFiles, + UniqueFd incrementalFd); + void CompareFiles(vector &allFiles, vector &smallFiles, - vector &bigFiles); + vector &bigFiles, + const unordered_map &cloudFiles, + unordered_map &localFilesInfo); void AsyncTaskDoIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd); void AsyncTaskOnIncrementalBackup(); diff --git a/frameworks/native/backup_ext/src/ext_backup_js.cpp b/frameworks/native/backup_ext/src/ext_backup_js.cpp index 2daa22139f8da56e29d9908941015cb0d844afc6..9cf65e67059491a738edb6bf08e8b8b0b723e77b 100644 --- a/frameworks/native/backup_ext/src/ext_backup_js.cpp +++ b/frameworks/native/backup_ext/src/ext_backup_js.cpp @@ -891,7 +891,7 @@ std::function &argv)> ExtBackupJs::Pa napi_create_object(env, &backupExtInfoVal); HILOGI("backupExtInfo is:%{public}s", GetAnonyString(backupExtInfo).c_str()); napi_create_string_utf8(env, backupExtInfo.c_str(), backupExtInfo.size(), &backupExtInfoVal); - argv.push_back(backupExtInfoVal); + argv.emplace_back(backupExtInfoVal); return true; }; return onBackupExFun; @@ -909,8 +909,8 @@ std::function &argv)> ExtBackupJs::Pa napi_set_named_property(env, objValue, "code", AbilityRuntime::CreateJsValue(env, appVersionCode)); napi_set_named_property(env, objValue, "name", AbilityRuntime::CreateJsValue(env, appVersionStr.c_str())); napi_create_string_utf8(env, restoreExtInfo.c_str(), restoreExtInfo.size(), &restoreRetValue); - argv.push_back(objValue); - argv.push_back(restoreRetValue); + argv.emplace_back(objValue); + argv.emplace_back(restoreRetValue); return true; }; return onRestoreExFun; @@ -935,7 +935,7 @@ std::function &argv)> ExtBackupJs::Pa } napi_set_named_property(env, objValue, "code", AbilityRuntime::CreateJsValue(env, appVersionCodeFlag)); napi_set_named_property(env, objValue, "name", AbilityRuntime::CreateJsValue(env, appVersionStrFlag.c_str())); - argv.push_back(objValue); + argv.emplace_back(objValue); return true; }; return onRestoreFun; diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 77252b298ac621d30251438736c04a329537a8ef..058288d62cb8d16eef2f3e7e950daa5941446a01 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -738,7 +738,7 @@ void BackupExtExtension::DoPacket(const map &srcFiles, TarMap &t auto startTime = std::chrono::system_clock::now(); int fdNum = 0; auto reportCb = ReportErrFileByProc(wptr {this}, curScenario_); - for (auto small : srcFiles) { + for (const auto &small : srcFiles) { totalSize += small.second; fileCount += 1; packFiles.emplace_back(small.first); @@ -800,7 +800,7 @@ int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) for (const auto &item : bigFileInfo) { auto filePath = std::get<0>(item.second); if (!filePath.empty()) { - excludes.push_back(filePath); + excludes.emplace_back(filePath); } } @@ -877,7 +877,7 @@ int BackupExtExtension::DoRestore(const string &fileName, const off_t fileSize) return ERR_OK; } -static unordered_map GetTarIncludes(const string &tarName) +static void GetTarIncludes(const string &tarName, unordered_map &infos) { // 获取简报文件内容 string reportName = GetReportFileName(tarName); @@ -885,12 +885,12 @@ static unordered_map GetTarIncludes(const string UniqueFd fd(open(reportName.data(), O_RDONLY)); if (fd < 0) { HILOGE("Failed to open report file = %{private}s, err = %{public}d", reportName.c_str(), errno); - return {}; + return; } // 获取简报内容 BReportEntity rp(move(fd)); - return rp.GetReportInfos(); + rp.GetReportInfos(infos); } int BackupExtExtension::DealIncreUnPacketResult(const off_t tarFileSize, const std::string &tarFileName, @@ -923,10 +923,9 @@ int BackupExtExtension::DoIncrementalRestore() } auto fileSet = GetIdxFileData(bundleName_); auto extManageInfo = GetExtManageInfo(); - std::tuple unPacketRes; ErrCode err = ERR_OK; auto startTime = std::chrono::system_clock::now(); - for (auto item : fileSet) { // 处理要解压的tar文件 + for (const auto &item : fileSet) { // 处理要解压的tar文件 off_t tarFileSize = 0; if (ExtractFileExt(item) == "tar" && !IsUserTar(item, extManageInfo, tarFileSize)) { if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { @@ -940,22 +939,20 @@ int BackupExtExtension::DoIncrementalRestore() string tarName = path + item; // 当用户指定fullBackupOnly字段或指定版本的恢复,解压目录当前在/backup/restore - if (BDir::CheckFilePathInvalid(tarName)) { + if (BDir::CheckFilePathInvalid(tarName) || BDir::CheckAndRmSoftLink(tarName)) { HILOGE("Check incre tarfile path : %{public}s err, path is forbidden", GetAnonyPath(tarName).c_str()); - return ERR_INVALID_VALUE; - } - if (BDir::CheckAndRmSoftLink(tarName)) { - HILOGE("File soft links are forbidden"); return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE).GetCode(); } - unordered_map result = GetTarIncludes(tarName); + unordered_map result; + GetTarIncludes(tarName, result); if ((!extension_->SpecialVersionForCloneAndCloud()) && (!extension_->UseFullBackupOnly())) { path = "/"; } if (isDebug_) { FillEndFileInfos(path, result); } - unPacketRes = UntarFile::GetInstance().IncrementalUnPacket(tarName, path, result); + std::tuple unPacketRes = + UntarFile::GetInstance().IncrementalUnPacket(tarName, path, result); err = std::get(unPacketRes); if (int tmpErr = DealIncreUnPacketResult(tarFileSize, item, unPacketRes); tmpErr != ERR_OK) { return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE).GetCode(); @@ -1027,7 +1024,7 @@ void BackupExtExtension::RestoreBigFilesForSpecialCloneCloud(const ExtManageInfo string fileName = item.hashName; if (BDir::CheckFilePathInvalid(fileName)) { HILOGE("Check big spec file path : %{public}s err, path is forbidden", GetAnonyPath(fileName).c_str()); - errFileInfos_[fileName].push_back(DEFAULT_INVAL_VALUE); + errFileInfos_[fileName].emplace_back(DEFAULT_INVAL_VALUE); if (!RemoveFile(fileName)) { HILOGE("Failed to delete the backup bigFile %{public}s", GetAnonyPath(fileName).c_str()); } @@ -1042,21 +1039,21 @@ void BackupExtExtension::RestoreBigFilesForSpecialCloneCloud(const ExtManageInfo AuditLog auditLog = {false, "chmod file failed", "ADD", "", 1, "FAILED", "RestoreBigFilesForSpecialCloneCloud", "CommonFile", GetAnonyPath(fileName)}; HiAudit::GetInstance(false).Write(auditLog); - errFileInfos_[fileName].push_back(errno); + errFileInfos_[fileName].emplace_back(errno); } struct timespec tv[2] = {sta.st_atim, sta.st_mtim}; UniqueFd fd(open(fileName.data(), O_RDONLY)); if (fd < 0) { HILOGE("Failed to open file = %{public}s, err = %{public}d", GetAnonyPath(fileName).c_str(), errno); - errFileInfos_[fileName].push_back(errno); + errFileInfos_[fileName].emplace_back(errno); AuditLog auditLog = {false, "open fd failed", "ADD", "", 1, "FAILED", "RestoreBigFilesForSpecialCloneCloud", "CommonFile", GetAnonyPath(fileName)}; HiAudit::GetInstance(false).Write(auditLog); return; } if (futimens(fd.Get(), tv) != 0) { - errFileInfos_[fileName].push_back(errno); + errFileInfos_[fileName].emplace_back(errno); HILOGE("Failed to change the file time. %{public}s , %{public}d", GetAnonyPath(fileName).c_str(), errno); } } @@ -1120,7 +1117,7 @@ ErrCode BackupExtExtension::RestoreFilesForSpecialCloneCloud() auto info = cache.GetExtManageInfo(); HILOGI("Start do restore for SpecialCloneCloud."); auto startTime = std::chrono::system_clock::now(); - for (auto &item : info) { + for (const auto &item : info) { if (item.hashName.empty()) { HILOGE("Hash name empty"); continue; @@ -1136,7 +1133,7 @@ ErrCode BackupExtExtension::RestoreFilesForSpecialCloneCloud() radarRestoreInfo_.tarFileSize += static_cast(item.sta.st_size); int ret = RestoreTarForSpecialCloneCloud(item); if (isDebug_ && ret != ERR_OK) { - errFileInfos_[item.hashName].push_back(ret); + errFileInfos_[item.hashName].emplace_back(ret); endFileInfos_[item.hashName] = item.sta.st_size; } if (ret != ERR_OK) { @@ -1180,13 +1177,13 @@ static bool RestoreBigFilePrecheck(string &fileName, const string &path, const s void BackupExtExtension::RestoreBigFileAfter(const string &filePath, const struct stat &sta) { if (chmod(filePath.c_str(), sta.st_mode) != 0) { - errFileInfos_[filePath].push_back(errno); + errFileInfos_[filePath].emplace_back(errno); HILOGE("Failed to chmod filePath, err = %{public}d", errno); } struct timespec tv[2] = {sta.st_atim, sta.st_mtim}; UniqueFd fd(open(filePath.data(), O_RDONLY)); if (fd < 0) { - errFileInfos_[filePath].push_back(errno); + errFileInfos_[filePath].emplace_back(errno); HILOGE("Failed to open file = %{public}s, err = %{public}d", GetAnonyPath(filePath).c_str(), errno); AuditLog auditLog = {false, "open fd failed", "ADD", "", 1, "FAILED", "RestoreBigFileAfter", "CommonFile", GetAnonyPath(filePath)}; @@ -1194,7 +1191,7 @@ void BackupExtExtension::RestoreBigFileAfter(const string &filePath, const struc return; } if (futimens(fd.Get(), tv) != 0) { - errFileInfos_[filePath].push_back(errno); + errFileInfos_[filePath].emplace_back(errno); HILOGE("failed to change the file time. %{public}s , %{public}d", GetAnonyPath(filePath).c_str(), errno); } } @@ -1211,7 +1208,7 @@ void BackupExtExtension::RestoreOneBigFile(const std::string &path, UniqueFd fd(open(reportPath.data(), O_RDONLY)); if (fd < 0) { HILOGE("Failed to open report file = %{public}s, err = %{public}d", reportPath.c_str(), errno); - errFileInfos_[item.hashName].push_back(errno); + errFileInfos_[item.hashName].emplace_back(errno); AuditLog auditLog = {false, "Open fd failed", "ADD", "", 1, "FAILED", "RestoreOneBigFile", "RestoreOneBigFile", GetAnonyPath(reportPath)}; HiAudit::GetInstance(false).Write(auditLog); @@ -1241,7 +1238,7 @@ void BackupExtExtension::RestoreOneBigFile(const std::string &path, return; } if (!BFile::MoveFile(fileName, filePath)) { - errFileInfos_[filePath].push_back(errno); + errFileInfos_[filePath].emplace_back(errno); HILOGE("failed to move the file. err = %{public}d", errno); AuditLog auditLog = {false, "Move file failed", "ADD", "", 1, "FAILED", "MoveFile", "RestoreOneBigFile", GetAnonyPath(filePath)}; @@ -1271,7 +1268,7 @@ void BackupExtExtension::RestoreBigFiles(bool appendTargetPath) auto info = cache.GetExtManageInfo(); HILOGI("Start Restore Big Files"); auto start = std::chrono::system_clock::now(); - for (auto &item : info) { + for (const auto &item : info) { if (item.hashName.empty() || (!item.isUserTar && !item.isBigFile)) { continue; } @@ -1370,7 +1367,7 @@ void BackupExtExtension::AsyncTaskRestore(std::set fileSet, return; } // 解压 - for (auto item : fileSet) { // 处理要解压的tar文件 + for (const auto &item : fileSet) { // 处理要解压的tar文件 off_t tarFileSize = 0; if (ExtractFileExt(item) == "tar" && !IsUserTar(item, extManageInfo, tarFileSize)) { ret = ptr->DoRestore(item, tarFileSize); @@ -1806,11 +1803,6 @@ ErrCode BackupExtExtension::HandleRestore(bool isClearData) } } -static bool CheckTar(const string &fileName) -{ - return ExtractFileExt(fileName) == "tar"; -} - static bool IfEquality(const ReportFileInfo &info, const ReportFileInfo &infoAd) { return info.filePath < infoAd.filePath; @@ -1825,61 +1817,25 @@ static void AdDeduplication(vector &FilesList) FilesList.erase(it, FilesList.end()); } -void BackupExtExtension::CompareFiles(UniqueFd incrementalFd, - UniqueFd manifestFd, - vector &allFiles, - vector &smallFiles, - vector &bigFiles) +void BackupExtExtension::FillFileInfos(UniqueFd incrementalFd, + UniqueFd manifestFd, + vector &allFiles, + vector &smallFiles, + vector &bigFiles) { HILOGI("Begin Compare"); - struct ReportFileInfo storageFiles; BReportEntity cloudRp(move(manifestFd)); - unordered_map cloudFiles = cloudRp.GetReportInfos(); - BReportEntity storageRp(move(incrementalFd)); - - while (storageRp.GetStorageReportInfos(storageFiles)) { - // 进行文件对比 - const string &path = storageFiles.filePath; - if (path.empty()) { - HILOGD("GetStorageReportInfos failed"); - continue; - } - auto it = cloudFiles.find(path); - bool isExist = (it != cloudFiles.end()) ? true : false; - if (storageFiles.isIncremental == true && storageFiles.isDir == true && !isExist) { - smallFiles.push_back(storageFiles); - } - bool isChange = (isExist && storageFiles.size == it->second.size && - storageFiles.mtime == it->second.mtime) ? false : true; - if (storageFiles.isDir == false && isChange) { - auto [res, fileHash] = BackupFileHash::HashWithSHA256(path); - if (fileHash.empty()) { - continue; - } - storageFiles.hash = fileHash; - } else if (storageFiles.isDir == false) { - storageFiles.hash = it->second.hash; - } - - if (storageFiles.isDir == false && CheckTar(path)) { - storageFiles.userTar = 1; - } - - allFiles.push_back(storageFiles); - if (storageFiles.isDir == false && storageFiles.isIncremental == true && (!isExist || - cloudFiles.find(path)->second.hash != storageFiles.hash)) { - // 在云空间简报里不存在或者hash不一致 - if (storageFiles.size <= BConstants::BIG_FILE_BOUNDARY) { - smallFiles.push_back(storageFiles); - continue; - } - bigFiles.push_back(storageFiles); - } + unordered_map cloudFiles; + cloudRp.GetReportInfos(cloudFiles); + if (cloudFiles.empty()) { + FillFileInfosWithoutCmp(allFiles, smallFiles, bigFiles, move(incrementalFd)); + } else { + FillFileInfosWithCmp(allFiles, smallFiles, bigFiles, cloudFiles, move(incrementalFd)); } AdDeduplication(allFiles); AdDeduplication(smallFiles); AdDeduplication(bigFiles); - HILOGI("End Compare, allfile is %{public}zu, samllfile is %{public}zu, bigfile is %{public}zu", + HILOGI("End Compare, allfile is %{public}zu, smallfile is %{public}zu, bigfile is %{public}zu", allFiles.size(), smallFiles.size(), bigFiles.size()); } @@ -1930,7 +1886,7 @@ static void WriteFile(const string &filename, const vector noPermissionFiles; - for (auto &item : pkgInfo) { + for (const auto &item : pkgInfo) { if (item.first.empty()) { continue; } diff --git a/frameworks/native/backup_ext/src/sub_ext_extension.cpp b/frameworks/native/backup_ext/src/sub_ext_extension.cpp index 3586eab8606acec09d386ba4ceb7483b11095bac..e859de8e052b7af421072e3ce9cb668fe3508057 100644 --- a/frameworks/native/backup_ext/src/sub_ext_extension.cpp +++ b/frameworks/native/backup_ext/src/sub_ext_extension.cpp @@ -134,11 +134,11 @@ void BackupExtExtension::CheckTmpDirFileInfos(bool isSpecialVersion) ErrFileInfo errFiles; auto idxFileInfos = GetIdxFileInfos(isSpecialVersion); struct stat attr; - for (auto it : idxFileInfos) { + for (const auto &it : idxFileInfos) { if (it.first.size() >= PATH_MAX || stat(it.first.data(), &attr) == -1) { HILOGE("(Debug) Failed to get stat of %{public}s, errno = %{public}d", GetAnonyPath(it.first).c_str(), errno); - errFiles[it.first].push_back(errno); + errFiles[it.first].emplace_back(errno); } else if (it.second != attr.st_size) { HILOGE("(Debug) RecFile:%{public}s size err, recSize: %{public}" PRId64 ", idxSize: %{public}" PRId64 "", GetAnonyPath(it.first).c_str(), attr.st_size, it.second); @@ -169,12 +169,12 @@ tuple> BackupExtExtension::CheckRestoreFileInfos() if (lstat(it.first.c_str(), &curFileStat) != 0) { HILOGE("Failed to lstat %{public}s, err = %{public}d", GetAnonyPath(it.first).c_str(), errno); errFiles.emplace_back(it.first); - errFileInfos_[it.first].push_back(errno); + errFileInfos_[it.first].emplace_back(errno); } else if (curFileStat.st_size != it.second) { HILOGE("File size error, file: %{public}s, idx: %{public}" PRId64 ", act: %{public}" PRId64 "", GetAnonyPath(it.first).c_str(), it.second, curFileStat.st_size); errFiles.emplace_back(it.first); - errFileInfos_[it.first].push_back(errno); + errFileInfos_[it.first].emplace_back(errno); } } for (const auto &it : errFileInfos_) { @@ -993,7 +993,7 @@ int BackupExtExtension::DoIncrementalBackupTask(UniqueFd incrementalFd, UniqueFd vector allFiles; vector smallFiles; vector bigFiles; - CompareFiles(move(incrementalFd), move(manifestFd), allFiles, smallFiles, bigFiles); + FillFileInfos(move(incrementalFd), move(manifestFd), allFiles, smallFiles, bigFiles); auto ret = DoIncrementalBackup(allFiles, smallFiles, bigFiles); if (ret == ERR_OK) { auto end = std::chrono::system_clock::now(); @@ -1122,7 +1122,7 @@ void BackupExtExtension::IncrementalPacket(const vector & int fdNum = 0; string partName = GetIncrmentPartName(); auto reportCb = ReportErrFileByProc(wptr {this}, curScenario_); - for (auto small : infos) { + for (const auto &small : infos) { totalSize += static_cast(small.size); fileCount += 1; packFiles.emplace_back(small.filePath); @@ -1177,7 +1177,7 @@ int BackupExtExtension::DoIncrementalBackup(const vector throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); } // 获取增量文件和全量数据 - if (smallFiles.size() == 0 && bigFiles.size() == 0) { + if (smallFiles.empty() && bigFiles.empty()) { // 没有增量,则不需要上传 TarMap tMap; ErrCode err = IncrementalAllFileReady(tMap, allFiles, proxy); @@ -1243,4 +1243,109 @@ std::function BackupExtExtension::ReportOnProcessRes extPtr->reportOnProcessRetPool_.AddTask([task]() { task(); }); }; } + +void BackupExtExtension::FillFileInfosWithoutCmp(vector &allFiles, + vector &smallFiles, + vector &bigFiles, + UniqueFd incrementalFd) +{ + BReportEntity storageRp(move(incrementalFd)); + unordered_map localFilesInfo; + while (storageRp.GetStorageReportInfos(localFilesInfo)) { + for (auto localIter = localFilesInfo.begin(); localIter != localFilesInfo.end(); ++localIter) { + const string &path = localIter->second.filePath; + if (path.empty()) { + HILOGD("GetStorageReportInfos failed"); + continue; + } + if (localIter->second.isIncremental == true && localIter->second.isDir) { + smallFiles.emplace_back(localIter->second); + allFiles.emplace_back(localIter->second); + continue; + } + auto [res, fileHash] = BackupFileHash::HashWithSHA256(path); + if (fileHash.empty()) { + HILOGE("Do hash err, fileHash is empty"); + continue; + } + localIter->second.hash = fileHash; + if (ExtractFileExt(path) == "tar") { + localIter->second.userTar = 1; + } + allFiles.emplace_back(localIter->second); + if (localIter->second.size <= BConstants::BIG_FILE_BOUNDARY) { + smallFiles.emplace_back(localIter->second); + continue; + } + bigFiles.emplace_back(localIter->second); + } + localFilesInfo.clear(); + } +} + +void BackupExtExtension::FillFileInfosWithCmp(vector &allFiles, + vector &smallFiles, + vector &bigFiles, + const unordered_map &cloudFiles, + UniqueFd incrementalFd) +{ + BReportEntity storageRp(move(incrementalFd)); + unordered_map localFilesInfo; + while (storageRp.GetStorageReportInfos(localFilesInfo)) { + CompareFiles(allFiles, smallFiles, bigFiles, cloudFiles, localFilesInfo); + localFilesInfo.clear(); + } +} + +void BackupExtExtension::CompareFiles(vector &allFiles, + vector &smallFiles, + vector &bigFiles, + const unordered_map &cloudFiles, + unordered_map &localFilesInfo) +{ + for (auto localIter = localFilesInfo.begin(); localIter != localFilesInfo.end(); ++localIter) { + // 进行文件对比, 当后续使用 isUserTar 字段时需注意 字段解析函数 + const string &path = localIter->second.filePath; + if (path.empty()) { + HILOGD("GetStorageReportInfos failed"); + continue; + } + auto it = cloudFiles.find(path); + bool isExist = it != cloudFiles.end(); + if (localIter->second.isIncremental == true && !isExist && localIter->second.isDir == true) { + smallFiles.emplace_back(localIter->second); + allFiles.emplace_back(localIter->second); + } + if (localIter->second.isDir) { + continue; + } + bool isChange = !(isExist && localIter->second.size == it->second.size && + localIter->second.mtime == it->second.mtime); + if (isChange) { + auto [res, fileHash] = BackupFileHash::HashWithSHA256(path); + if (fileHash.empty()) { + HILOGE("Do hash err, fileHash is empty"); + continue; + } + localIter->second.hash = fileHash; + } else { + localIter->second.hash = it->second.hash; + } + + if (ExtractFileExt(path) == "tar") { + localIter->second.userTar = 1; + } + + allFiles.emplace_back(localIter->second); + if (localIter->second.isIncremental == true && (!isExist || + it->second.hash != localIter->second.hash)) { + // 在云空间简报里不存在或者hash不一致 + if (localIter->second.size <= BConstants::BIG_FILE_BOUNDARY) { + smallFiles.emplace_back(localIter->second); + continue; + } + bigFiles.emplace_back(localIter->second); + } + } +} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/tar_file.cpp b/frameworks/native/backup_ext/src/tar_file.cpp index 162d6760e25fdaeeb4626833bc8ea5a336a4570e..165840a78dc649f81c94a3cf197e5cef4f9fc7d0 100644 --- a/frameworks/native/backup_ext/src/tar_file.cpp +++ b/frameworks/native/backup_ext/src/tar_file.cpp @@ -308,7 +308,7 @@ bool TarFile::AddFile(string &fileName, const struct stat &st, int &err) HILOGE("Failed to write all"); return false; } - currentFileName_ = ""; + currentFileName_.clear(); return true; } @@ -322,7 +322,7 @@ bool TarFile::AddFile(string &fileName, const struct stat &st, int &err) HILOGE("Failed to write file content"); return false; } - currentFileName_ = ""; + currentFileName_.clear(); return true; } diff --git a/frameworks/native/backup_ext/src/untar_file.cpp b/frameworks/native/backup_ext/src/untar_file.cpp index b78a17d26503dd15632cd2726a3308a9ba42fed0..558354d0aeea9c9b0afd4e4c89056f928b02594f 100644 --- a/frameworks/native/backup_ext/src/untar_file.cpp +++ b/frameworks/native/backup_ext/src/untar_file.cpp @@ -98,12 +98,12 @@ std::tuple UntarFile::ReadLongName(FileStatInfo &info) } ErrFileInfo errFileInfo; if (ret != 0) { - errFileInfo[info.fullPath].push_back(ret); + errFileInfo[info.fullPath].emplace_back(ret); return {-1, errFileInfo}; } if (fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET) != 0) { HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno); - errFileInfo[info.fullPath].push_back(errno); + errFileInfo[info.fullPath].emplace_back(errno); return {-1, errFileInfo}; } return {0, errFileInfo}; @@ -382,14 +382,14 @@ bool UntarFile::DealFileTag(ErrFileInfo &errFileInfo, if (!includes_.empty() && includes_.find(tmpFullPath) == includes_.end()) { // not in includes if (fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET) != 0) { HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno); - errFileInfo[info.fullPath].push_back(DEFAULT_ERR); + errFileInfo[info.fullPath].emplace_back(DEFAULT_ERR); } return false; } info.fullPath = GenRealPath(rootPath_, info.fullPath); if (BDir::CheckFilePathInvalid(info.fullPath)) { HILOGE("Check file path : %{public}s err, path is forbidden", GetAnonyPath(info.fullPath).c_str()); - errFileInfo[info.fullPath].push_back(DEFAULT_ERR); + errFileInfo[info.fullPath].emplace_back(DEFAULT_ERR); return false; } errFileInfo = ParseRegularFile(info); @@ -465,12 +465,12 @@ ErrFileInfo UntarFile::ParseRegularFile(FileStatInfo &info) fclose(destFile); if (chmod(info.fullPath.data(), info.mode) != 0) { HILOGE("Failed to chmod of %{public}s, err = %{public}d", GetAnonyPath(info.fullPath).c_str(), errno); - errFileInfo[info.fullPath].push_back(errno); + errFileInfo[info.fullPath].emplace_back(errno); } struct utimbuf times; struct stat attr; if (stat(info.fullPath.c_str(), &attr) != 0) { - errFileInfo[info.fullPath].push_back(errno); + errFileInfo[info.fullPath].emplace_back(errno); HILOGE("Failed to get stat of %{public}s, err = %{public}d", GetAnonyPath(info.fullPath).c_str(), errno); times.actime = info.mtime; } else { @@ -478,14 +478,14 @@ ErrFileInfo UntarFile::ParseRegularFile(FileStatInfo &info) } times.modtime = info.mtime; if (info.mtime != 0 && utime(info.fullPath.c_str(), ×) != 0) { - errFileInfo[info.fullPath].push_back(errno); + errFileInfo[info.fullPath].emplace_back(errno); HILOGE("Failed to set mtime of %{public}s, err = %{public}d", GetAnonyPath(info.fullPath).c_str(), errno); } // anyway, go to correct fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET); } else { HILOGE("Failed to create file %{public}s, err = %{public}d", GetAnonyPath(info.fullPath).c_str(), errno); - errFileInfo[info.fullPath].push_back(errno); + errFileInfo[info.fullPath].emplace_back(errno); fseeko(tarFilePtr_, tarFileBlockCnt_ * BLOCK_SIZE, SEEK_CUR); } return errFileInfo; @@ -551,7 +551,7 @@ ErrFileInfo UntarFile::CreateDir(string &path, mode_t mode) HILOGE("directory does not exist, path:%{public}s, err = %{public}d", path.c_str(), errno); if (!ForceCreateDirectoryWithMode(path, mode)) { HILOGE("Failed to force create directory %{public}s, err = %{public}d", path.c_str(), errno); - errFileInfo[path].push_back(errno); + errFileInfo[path].emplace_back(errno); } } return errFileInfo; diff --git a/interfaces/kits/js/backup/session_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_backup_n_exporter.cpp index cbcd9fbccfc80d356cd38761fc4b0f7a971241eb..233974d585b7584b4c0b0557e254c6cc851009c4 100644 --- a/interfaces/kits/js/backup/session_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_backup_n_exporter.cpp @@ -241,10 +241,10 @@ static void OnResultReport(weak_ptr pCallbacks, const std::str auto cbCompl = [bName {bundleName}, res {result}](napi_env env, vector &argv) -> bool { napi_value napi_bName = nullptr; napi_create_string_utf8(env, bName.c_str(), bName.size(), &napi_bName); - argv.push_back(napi_bName); + argv.emplace_back(napi_bName); napi_value napi_res = nullptr; napi_create_string_utf8(env, res.c_str(), res.size(), &napi_res); - argv.push_back(napi_res); + argv.emplace_back(napi_res); return true; }; callbacks->onResultReport.CallJsMethod(cbCompl); @@ -268,10 +268,10 @@ static void OnBackupServiceDied(weak_ptr pCallbacks) } auto cbCompl = [](napi_env env, vector &argv) -> bool { - argv.push_back(nullptr); + argv.emplace_back(nullptr); napi_value napi_res = nullptr; napi_get_undefined(env, &napi_res); - argv.push_back(napi_res); + argv.emplace_back(napi_res); return true; }; callbacks->onBackupServiceDied.CallJsMethod(cbCompl); @@ -296,10 +296,10 @@ static void OnProcess(weak_ptr pCallbacks, const BundleName na auto cbCompl = [bundleName {name}, process {processInfo}](napi_env env, vector &argv) -> bool { napi_value napi_bName = nullptr; napi_create_string_utf8(env, bundleName.c_str(), bundleName.size(), &napi_bName); - argv.push_back(napi_bName); + argv.emplace_back(napi_bName); napi_value napi_process = nullptr; napi_create_string_utf8(env, process.c_str(), process.size(), &napi_process); - argv.push_back(napi_process); + argv.emplace_back(napi_process); return true; }; callbacks->onProcess.CallJsMethod(cbCompl); diff --git a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp index d33e0c5e805f51aa4684d2d39e5a9721dc7ec6fb..17186fc35872571c42f7bccf3073445d5309d0d0 100644 --- a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp @@ -245,10 +245,10 @@ static void OnResultReport(weak_ptr pCallbacks, const std::str auto cbCompl = [bName {bundleName}, res {result}](napi_env env, vector &argv) -> bool { napi_value napi_bName = nullptr; napi_create_string_utf8(env, bName.c_str(), bName.size(), &napi_bName); - argv.push_back(napi_bName); + argv.emplace_back(napi_bName); napi_value napi_res = nullptr; napi_create_string_utf8(env, res.c_str(), res.size(), &napi_res); - argv.push_back(napi_res); + argv.emplace_back(napi_res); return true; }; callbacks->onResultReport.CallJsMethod(cbCompl); @@ -272,10 +272,10 @@ static void OnBackupServiceDied(weak_ptr pCallbacks) } auto cbCompl = [](napi_env env, vector &argv) -> bool { - argv.push_back(nullptr); + argv.emplace_back(nullptr); napi_value napi_res = nullptr; napi_get_undefined(env, &napi_res); - argv.push_back(napi_res); + argv.emplace_back(napi_res); return true; }; callbacks->onBackupServiceDied.CallJsMethod(cbCompl); @@ -300,10 +300,10 @@ static void OnProcess(weak_ptr pCallbacks, const BundleName na auto cbCompl = [bundleName {name}, process {processInfo}](napi_env env, vector &argv) -> bool { napi_value napi_bName = nullptr; napi_create_string_utf8(env, bundleName.c_str(), bundleName.size(), &napi_bName); - argv.push_back(napi_bName); + argv.emplace_back(napi_bName); napi_value napi_process = nullptr; napi_create_string_utf8(env, process.c_str(), process.size(), &napi_process); - argv.push_back(napi_process); + argv.emplace_back(napi_process); return true; }; callbacks->onProcess.CallJsMethod(cbCompl); diff --git a/interfaces/kits/js/backup/session_restore_n_exporter.cpp b/interfaces/kits/js/backup/session_restore_n_exporter.cpp index 6257637efce94b1c4743174f9bd3eb5cee7c4880..20176f9b87da7de858daefc0990bbfa0369594aa 100644 --- a/interfaces/kits/js/backup/session_restore_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_restore_n_exporter.cpp @@ -245,10 +245,10 @@ static void OnBackupServiceDied(weak_ptr pCallbacks) } auto cbCompl = [](napi_env env, vector &argv) -> bool { - argv.push_back(nullptr); + argv.emplace_back(nullptr); napi_value napi_res = nullptr; napi_get_undefined(env, &napi_res); - argv.push_back(napi_res); + argv.emplace_back(napi_res); return true; }; callbacks->onBackupServiceDied.CallJsMethod(cbCompl); @@ -274,10 +274,10 @@ static void OnResultReport(weak_ptr pCallbacks, const std::str auto cbCompl = [bName {bundleName}, res {result}](napi_env env, vector &argv) -> bool { napi_value napi_bName = nullptr; napi_create_string_utf8(env, bName.c_str(), bName.size(), &napi_bName); - argv.push_back(napi_bName); + argv.emplace_back(napi_bName); napi_value napi_res = nullptr; napi_create_string_utf8(env, res.c_str(), res.size(), &napi_res); - argv.push_back(napi_res); + argv.emplace_back(napi_res); return true; }; callbacks->onResultReport.CallJsMethod(cbCompl); @@ -302,10 +302,10 @@ static void OnProcess(weak_ptr pCallbacks, const BundleName na auto cbCompl = [bundleName {name}, process {processInfo}](napi_env env, vector &argv) -> bool { napi_value napi_bName = nullptr; napi_create_string_utf8(env, bundleName.c_str(), bundleName.size(), &napi_bName); - argv.push_back(napi_bName); + argv.emplace_back(napi_bName); napi_value napi_process = nullptr; napi_create_string_utf8(env, process.c_str(), process.size(), &napi_process); - argv.push_back(napi_process); + argv.emplace_back(napi_process); return true; }; callbacks->onProcess.CallJsMethod(cbCompl); diff --git a/interfaces/kits/js/file_uri/file_uri_n_exporter.cpp b/interfaces/kits/js/file_uri/file_uri_n_exporter.cpp index f1a212a3e6a5b0503ee1db078036d8c02438d2ad..f89d08bff8845a0e42a4d0d8122306adbebcf70f 100644 --- a/interfaces/kits/js/file_uri/file_uri_n_exporter.cpp +++ b/interfaces/kits/js/file_uri/file_uri_n_exporter.cpp @@ -195,23 +195,23 @@ static std::string NormalizeUri(Uri &uri) size_t pos = 0; size_t left = 0; while ((pos = uri.GetPath().find('/', left)) != std::string::npos) { - temp.push_back(uri.GetPath().substr(left, pos - left)); + temp.emplace_back(uri.GetPath().substr(left, pos - left)); left = pos + 1; } if (left != pathLen) { - temp.push_back(uri.GetPath().substr(left)); + temp.emplace_back(uri.GetPath().substr(left)); } size_t tempLen = temp.size(); std::vector normalizeTemp; for (size_t i = 0; i < tempLen; ++i) { if (!temp[i].empty() && !(temp[i] == ".") && !(temp[i] == "..")) { - normalizeTemp.push_back(temp[i]); + normalizeTemp.emplace_back(temp[i]); } if (temp[i] == "..") { if (!normalizeTemp.empty() && normalizeTemp.back() != "..") { normalizeTemp.pop_back(); } else { - normalizeTemp.push_back(temp[i]); + normalizeTemp.emplace_back(temp[i]); } } } diff --git a/services/backup_sa/src/module_external/bms_adapter.cpp b/services/backup_sa/src/module_external/bms_adapter.cpp index 7f94e2c276495cd45c7ef120316abcf5e1c0935e..66b706962beeb05fe01d401da479819c8641b272 100644 --- a/services/backup_sa/src/module_external/bms_adapter.cpp +++ b/services/backup_sa/src/module_external/bms_adapter.cpp @@ -117,7 +117,7 @@ vector BundleMgrAdapter::GetBundleInfos(const vecto vector bundleInfos; auto bms = GetBundleManager(); HILOGI("Start, bundleNames size:%{public}zu", bundleNames.size()); - for (auto const &bundleName : bundleNames) { + for (const auto &bundleName : bundleNames) { HILOGI("Begin Get bundleName:%{public}s", bundleName.c_str()); if (SAUtils::IsSABundleName(bundleName)) { GetBundleInfoForSA(bundleName, bundleInfos); @@ -288,7 +288,7 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement vector incrementalBackTimes; vector bundleInfos; auto bms = GetBundleManager(); - for (auto const &bundleNameTime : incrementalDataList) { + for (const auto &bundleNameTime : incrementalDataList) { auto bundleName = bundleNameTime.bundleName; AppExecFwk::BundleInfo installedBundle; std::vector extensionInfos; @@ -345,7 +345,7 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement vector bundleNames; vector bundleInfos; HILOGI("End get installedBundles count is:%{public}zu", installedBundles.size()); - for (auto const &installedBundle : installedBundles) { + for (const auto &installedBundle : installedBundles) { if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { HILOGI("Unsupported applications, name : %{public}s", installedBundle.name.data()); @@ -388,7 +388,7 @@ vector BundleMgrAdapter::GetFullBundleInfos(int32_t vector bundleNames; vector bundleInfos; HILOGI("End get installedBundles count is:%{public}zu", installedBundles.size()); - for (auto const &installedBundle : installedBundles) { + for (const auto &installedBundle : installedBundles) { if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { HILOGI("Unsupported applications, name : %{public}s", installedBundle.name.data()); @@ -427,13 +427,13 @@ string BundleMgrAdapter::GetExtName(string bundleName, int32_t userId) if (!bms->GetBundleInfos(AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundles, userId)) { throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get bundle infos"); } - for (auto const &installedBundle : installedBundles) { + for (const auto &installedBundle : installedBundles) { if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { HILOGI("Unsupported applications, name : %{public}s", installedBundle.name.data()); continue; } - for (auto ext : installedBundle.extensionInfos) { + for (const auto &ext : installedBundle.extensionInfos) { if (ext.bundleName != bundleName) { continue; } @@ -459,7 +459,7 @@ std::vector BundleMgrAdapter::GetBundleInfosForSA() } int32_t ret = samgrProxy->GetExtensionSaIds(BConstants::EXTENSION_BACKUP, saIds); HILOGI("GetExtensionSaIds ret: %{public}d", ret); - for (auto saId : saIds) { + for (const auto &saId : saIds) { saBundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {std::to_string(saId), 0, 0, "", 0, 0, true, false, "", "", "", ""}); } @@ -515,7 +515,7 @@ bool BundleMgrAdapter::GetCurBundleExtenionInfo(AppExecFwk::BundleInfo &installe return false; } std::vector hapModuleInfos = installedBundle.hapModuleInfos; - for (auto &hapModuleInfo : hapModuleInfos) { + for (const auto &hapModuleInfo : hapModuleInfos) { extensionInfos.insert(extensionInfos.end(), hapModuleInfo.extensionInfos.begin(), hapModuleInfo.extensionInfos.end()); } @@ -550,7 +550,7 @@ vector BundleMgrAdapter::GetBundleInfosForAppend(co int32_t userId) { auto bundleInfos = BundleMgrAdapter::GetBundleInfosForIncremental(list, userId); - for (auto const &info : list) { + for (const auto &info : list) { if (SAUtils::IsSABundleName(info.bundleName)) { GetBundleInfoForSA(info.bundleName, bundleInfos); } diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 463df88a00b515eb317c971070455e4f849b564e..85c0cd94872e97eb53f207a84a50f3152fa5b9fc 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -108,7 +108,7 @@ void OnStartResRadarReport(const std::vector &bundleNameList, int32 { std::stringstream ss; ss << "failedBundles:{"; - for (auto &bundleName : bundleNameList) { + for (const auto &bundleName : bundleNameList) { ss << bundleName << ", "; } ss << "}"; @@ -331,7 +331,7 @@ void Service::StopAll(const wptr &obj, bool force) std::stringstream ss; ss << "successBundleNum:" << successBundlesNum_ << "," << "failedBundleNum:" << fail_cnt << "," << "failedBundles:{"; - for (auto &failBundle : failedBundles_) { + for (const auto &failBundle : failedBundles_) { ss << "\"" << failBundle.first << "\":" << "{errCode:" << failBundle.second.errCode << "," << "reportTime:" << failBundle.second.reportTime << "},"; } @@ -546,7 +546,7 @@ static vector GetRestoreBundleNames(UniqueFd fd, } HILOGI("restoreInfos size is:%{public}zu", restoreInfos.size()); vector restoreBundleInfos {}; - for (auto &restoreInfo : restoreInfos) { + for (const auto &restoreInfo : restoreInfos) { if (SAUtils::IsSABundleName(restoreInfo.name)) { BJsonEntityCaps::BundleInfo info = {.name = restoreInfo.name, .appIndex = restoreInfo.appIndex, @@ -588,7 +588,7 @@ void Service::HandleExceptionOnAppendBundles(sptr session, if (appendBundleNames.size() != restoreBundleNames.size()) { HILOGE("AppendBundleNames not equal restoreBundleNames, appendBundleNames size:%{public}zu," "restoreBundleNames size:%{public}zu", appendBundleNames.size(), restoreBundleNames.size()); - for (auto bundleName : appendBundleNames) { + for (const auto &bundleName : appendBundleNames) { auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), [&bundleName](const auto &obj) { return obj == bundleName; }); if (it == restoreBundleNames.end()) { @@ -654,7 +654,7 @@ void Service::SetCurrentSessProperties(std::vector std::vector &restoreBundleNames, RestoreTypeEnum restoreType) { HILOGI("Start"); - for (auto restoreInfo : restoreBundleInfos) { + for (const auto &restoreInfo : restoreBundleInfos) { auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), [&restoreInfo](const auto &bundleName) { std::string bundleNameIndex = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, restoreInfo.appIndex); return bundleName == bundleNameIndex; @@ -735,7 +735,7 @@ void Service::SetCurrentSessProperties(std::vector std::map &isClearDataFlags, RestoreTypeEnum restoreType) { HILOGI("Start"); - for (auto restoreInfo : restoreBundleInfos) { + for (const auto &restoreInfo : restoreBundleInfos) { auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), [&restoreInfo](const auto &bundleName) { std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, @@ -1133,7 +1133,7 @@ void Service::ExtStart(const string &bundleName) session_->GetServiceReverseProxy()->RestoreOnBundleStarted(ret, bundleName); BundleBeginRadarReport(bundleName, ret, scenario); auto fileNameVec = session_->GetExtFileNameRequest(bundleName); - for (auto &fileName : fileNameVec) { + for (const auto &fileName : fileNameVec) { int32_t errCode = 0; UniqueFd fd = proxy->GetFileHandle(fileName, errCode); session_->GetServiceReverseProxy()->RestoreOnFileReady(bundleName, fileName, move(fd), errCode); @@ -1331,7 +1331,7 @@ void Service::HandleRestoreDepsBundle(const string &bundleName) } session_->AppendBundles(restoreBundleNames); for (const auto &bundle : restoreBundleMap) { - for (auto &bundleInfo : SvcRestoreDepsManager::GetInstance().GetAllBundles()) { + for (const auto &bundleInfo : SvcRestoreDepsManager::GetInstance().GetAllBundles()) { if (bundle.first != bundleInfo.name) { continue; } @@ -1340,7 +1340,7 @@ void Service::HandleRestoreDepsBundle(const string &bundleName) session_->SetBundleVersionCode(bundleInfo.name, bundleInfo.versionCode); session_->SetBundleVersionName(bundleInfo.name, bundleInfo.versionName); session_->SetBundleDataSize(bundleInfo.name, bundleInfo.spaceOccupied); - for (auto &fileName : info.fileNames_) { + for (const auto &fileName : info.fileNames_) { session_->SetExtFileNameRequest(bundleInfo.name, fileName); } session_->SetBackupExtName(bundleInfo.name, bundleInfo.extensionName); @@ -1739,12 +1739,12 @@ ErrCode Service::AppendBundlesClearSession(const std::vector &bundle session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); std::vector supportBundleNames; - for (auto info : backupInfos) { + for (const auto &info : backupInfos) { std::string bundleNameIndexStr = BJsonUtil::BuildBundleNameIndexInfo(info.name, info.appIndex); supportBundleNames.emplace_back(bundleNameIndexStr); } session_->AppendBundles(supportBundleNames); - for (auto info : backupInfos) { + for (const auto &info : backupInfos) { std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(info.name, info.appIndex); session_->SetBackupExtName(bundleNameIndexInfo, info.extensionName); session_->SetIsReadyLaunch(bundleNameIndexInfo); diff --git a/services/backup_sa/src/module_ipc/service_incremental.cpp b/services/backup_sa/src/module_ipc/service_incremental.cpp index 8583f06e2b92fad6e2c470a4d64942aa1566fcdd..b4ba0d731d91f2889d239aee6461a30cb369b5a9 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -252,7 +252,7 @@ void Service::RefreshBundleDataSize(const vector &n HILOGE("session is nullptr"); return; } - for (auto &info : newBundleInfos) { + for (const auto &info : newBundleInfos) { if (info.name == bundleName) { session->SetBundleDataSize(bundleName, info.increSpaceOccupied); HILOGI("RefreshBundleDataSize, bundlename = %{public}s , datasize = %{public}" PRId64 "", @@ -331,7 +331,7 @@ ErrCode Service::InitIncrementalBackupSession(sptr remote) vector Service::GetBundleNameByDetails(const std::vector &bundlesToBackup) { vector bundleNames {}; - for (auto bundle : bundlesToBackup) { + for (const auto &bundle : bundlesToBackup) { bundleNames.emplace_back(bundle.bundleName); } return bundleNames; @@ -655,7 +655,7 @@ bool Service::IncrementalBackup(const string &bundleName) session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleStarted(ret, bundleName); BundleBeginRadarReport(bundleName, ret, IServiceReverse::Scenario::RESTORE); auto fileNameVec = session_->GetExtFileNameRequest(bundleName); - for (auto &fileName : fileNameVec) { + for (const auto &fileName : fileNameVec) { ret = proxy->GetIncrementalFileHandle(fileName); if (ret) { HILOGE("Failed to extension file handle %{public}s", GetAnonyString(fileName).c_str()); @@ -716,11 +716,11 @@ void Service::SetCurrentBackupSessProperties(const vector &bundleNames, { HILOGI("start SetCurrentBackupSessProperties"); std::map bundleNameIndexBundleInfoMap; - for (auto &bundleInfo : backupBundleInfos) { + for (const auto &bundleInfo : backupBundleInfos) { std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(bundleInfo.name, bundleInfo.appIndex); bundleNameIndexBundleInfoMap[bundleNameIndexInfo] = bundleInfo; } - for (auto item : bundleNames) { + for (const auto &item : bundleNames) { std::string bundleName = item; if (BundleMgrAdapter::IsUser0BundleName(bundleName, userId)) { HILOGE("bundleName:%{public}s is zero user bundle", bundleName.c_str()); @@ -748,7 +748,7 @@ void Service::SetCurrentBackupSessProperties(const vector &bundleNames, void Service::SetBundleIncDataInfo(const std::vector& bundlesToBackup, std::vector& supportBundleNames) { - for (auto &bundleInfo : bundlesToBackup) { + for (const auto &bundleInfo : bundlesToBackup) { std::string bundleName = bundleInfo.bundleName; auto it = std::find(supportBundleNames.begin(), supportBundleNames.end(), bundleName); if (it == supportBundleNames.end()) { diff --git a/services/backup_sa/src/module_ipc/sub_service.cpp b/services/backup_sa/src/module_ipc/sub_service.cpp index 8bbdf24822fd1c8958c992402912632f43990c8f..6615360074e4cb32732f4a123b7d64eb4f84ef56 100644 --- a/services/backup_sa/src/module_ipc/sub_service.cpp +++ b/services/backup_sa/src/module_ipc/sub_service.cpp @@ -68,7 +68,7 @@ using namespace std; vector Service::MakeDetailList(const vector &bundleNames) { vector bundleDetails {}; - for (auto bundleName : bundleNames) { + for (const auto &bundleName : bundleNames) { bundleDetails.emplace_back(BIncrementalData {bundleName, 0}); } return bundleDetails; @@ -307,7 +307,7 @@ std::vector Service::GetSupportBackupBundleNames(vector supportBackupNames; - for (auto info : backupInfos) { + for (const auto &info : backupInfos) { HILOGI("Current backupInfo bundleName:%{public}s, index:%{public}d, extName:%{public}s", info.name.c_str(), info.appIndex, info.extensionName.c_str()); std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(info.name, info.appIndex); @@ -349,7 +349,7 @@ void Service::SetCurrentSessProperties(BJsonEntityCaps::BundleInfo &info, void Service::HandleNotSupportBundleNames(const std::vector &srcBundleNames, std::vector &supportBundleNames, bool isIncBackup) { - for (auto bundleName : srcBundleNames) { + for (const auto &bundleName : srcBundleNames) { auto it = std::find(supportBundleNames.begin(), supportBundleNames.end(), bundleName); if (it != supportBundleNames.end()) { continue; diff --git a/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp b/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp index 70879196a310d2eff12400e017c4bb4832d96ab4..681821422a931a1284b55c0688bdaff703c59347 100644 --- a/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp @@ -51,10 +51,10 @@ map SvcRestoreDepsManager::GetRestor string bundleName = it->first; if (IsAllDepsRestored(bundleName)) { RestoreInfo restoreInfo = it->second; - restoreBundleMap.insert(make_pair(bundleName, restoreInfo)); - toRestoreBundleMap_.erase(it++); + restoreBundleMap.emplace(make_pair(bundleName, restoreInfo)); + it = toRestoreBundleMap_.erase(it); } else { - it++; + ++it; } } return restoreBundleMap; @@ -95,7 +95,7 @@ void SvcRestoreDepsManager::BuildDepsMap(const vector SvcRestoreDepsManager::SplitString(const string &srcStr, const st tempStr.erase(0, tempStr.find_first_not_of(" ")); tempStr.erase(tempStr.find_last_not_of(" ") + 1); tempStr.erase(tempStr.find_last_not_of("\r") + 1); - dst.push_back(tempStr); + dst.emplace_back(tempStr); } start = index + 1; index = srcStr.find_first_of(separator, start); @@ -125,7 +125,7 @@ vector SvcRestoreDepsManager::SplitString(const string &srcStr, const st tempStr.erase(0, tempStr.find_first_not_of(" ")); tempStr.erase(tempStr.find_last_not_of(" ") + 1); tempStr.erase(tempStr.find_last_not_of("\r") + 1); - dst.push_back(tempStr); + dst.emplace_back(tempStr); } return dst; } @@ -133,7 +133,7 @@ vector SvcRestoreDepsManager::SplitString(const string &srcStr, const st void SvcRestoreDepsManager::AddRestoredBundles(const string &bundleName) { unique_lock lock(lock_); - restoredBundles_.insert(bundleName); + restoredBundles_.emplace(bundleName); } vector SvcRestoreDepsManager::GetAllBundles() const @@ -151,7 +151,7 @@ bool SvcRestoreDepsManager::UpdateToRestoreBundleMap(const string &bundleName, c unique_lock lock(lock_); auto it = toRestoreBundleMap_.find(bundleName); if (it != toRestoreBundleMap_.end()) { - it->second.fileNames_.insert(fileName); + it->second.fileNames_.emplace(fileName); return true; } return false; diff --git a/services/backup_sa/src/module_ipc/svc_session_manager.cpp b/services/backup_sa/src/module_ipc/svc_session_manager.cpp index f47d3e151d3389145ec075492394fc9591adb615..576028342ffa346c321064cdf589670540093404 100644 --- a/services/backup_sa/src/module_ipc/svc_session_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_session_manager.cpp @@ -186,7 +186,7 @@ bool SvcSessionManager::OnBundleFileReady(const string &bundleName, const string return true; } else if (impl_.scenario == IServiceReverse::Scenario::BACKUP) { if (!fileName.empty() && fileName != BConstants::EXT_BACKUP_MANAGE) { - auto ret = it->second.fileNameInfo.insert(fileName); + auto ret = it->second.fileNameInfo.emplace(fileName); if (!ret.second) { it->second.fileNameInfo.erase(fileName); } @@ -216,7 +216,7 @@ UniqueFd SvcSessionManager::OnBundleExtManageInfo(const string &bundleName, Uniq auto cache = cachedEntity.Structuralize(); auto info = cache.GetExtManage(); - for (auto &fileName : info) { + for (const auto &fileName : info) { HILOGE("fileName %{public}s", GetAnonyString(fileName).data()); OnBundleFileReady(bundleName, fileName); } @@ -399,7 +399,7 @@ void SvcSessionManager::SetExtFileNameRequest(const string &bundleName, const st } auto it = GetBackupExtNameMap(bundleName); - it->second.fileNameInfo.insert(fileName); + it->second.fileNameInfo.emplace(fileName); } std::set SvcSessionManager::GetExtFileNameRequest(const std::string &bundleName) @@ -544,7 +544,7 @@ void SvcSessionManager::AppendBundles(const vector &bundleNames) } else { info.backUpConnection = GetBackupAbilityExt(bundleName); } - impl_.backupExtNameMap.insert(make_pair(bundleName, info)); + impl_.backupExtNameMap.emplace(make_pair(bundleName, info)); } impl_.isBackupStart = true; impl_.isAppendFinish = true; @@ -992,7 +992,7 @@ bool SvcSessionManager::CleanAndCheckIfNeedWait(ErrCode &ret, std::vectorHandleClear(); } if (retTmp == ERR_OK) { - bundleNameList.push_back(it->first); + bundleNameList.emplace_back(it->first); } else { ret = retTmp; } diff --git a/services/backup_sa/src/module_sched/sched_scheduler.cpp b/services/backup_sa/src/module_sched/sched_scheduler.cpp index 4510666123e4d68f077c8d150994828fa08a4947..602416f4c9a89ac69de3e30b69833b40ac75dbdb 100644 --- a/services/backup_sa/src/module_sched/sched_scheduler.cpp +++ b/services/backup_sa/src/module_sched/sched_scheduler.cpp @@ -223,7 +223,7 @@ void SchedScheduler::TryUnloadService() void SchedScheduler::ClearSchedulerData() { unique_lock lock(lock_); - for (auto &bundleTime : bundleTimeVec_) { + for (const auto &bundleTime : bundleTimeVec_) { auto &[bName, iTime] = bundleTime; extTime_.Unregister(iTime); } diff --git a/tests/mock/backup_ext/include/ext_extension_mock.h b/tests/mock/backup_ext/include/ext_extension_mock.h index 1e97a71f6c7496c0a02a6f708ebef4596f3c1879..ab2745590c7f81c0c4b93beed25a92ff68bb9100 100644 --- a/tests/mock/backup_ext/include/ext_extension_mock.h +++ b/tests/mock/backup_ext/include/ext_extension_mock.h @@ -45,7 +45,7 @@ public: virtual void AppResultReport(const std::string, BackupRestoreScenario, ErrCode) = 0; virtual void AsyncTaskOnBackup() = 0; virtual ErrCode HandleRestore() = 0; - virtual void CompareFiles(UniqueFd, UniqueFd, std::vector&, + virtual void PreparaBackupFiles(UniqueFd, UniqueFd, std::vector&, std::vector&, std::vector&) = 0; virtual ErrCode HandleIncrementalBackup(UniqueFd, UniqueFd) = 0; virtual ErrCode IncrementalOnBackup() = 0; @@ -98,7 +98,7 @@ public: MOCK_METHOD(void, AppResultReport, (const std::string, BackupRestoreScenario, ErrCode)); MOCK_METHOD(void, AsyncTaskOnBackup, ()); MOCK_METHOD(ErrCode, HandleRestore, ()); - MOCK_METHOD(void, CompareFiles, (UniqueFd, UniqueFd, (std::vector&), + MOCK_METHOD(void, FillFileInfos, (UniqueFd, UniqueFd, (std::vector&), (std::vector&), (std::vector&))); MOCK_METHOD(ErrCode, HandleIncrementalBackup, (UniqueFd, UniqueFd)); MOCK_METHOD(ErrCode, IncrementalOnBackup, ()); diff --git a/tests/mock/backup_ext/src/ext_extension_mock.cpp b/tests/mock/backup_ext/src/ext_extension_mock.cpp index 80b8d6dc6f98005563b738c68063c281097902c0..4c54b88bfaf2a4414a1edb2d5da816a73aa8c335 100644 --- a/tests/mock/backup_ext/src/ext_extension_mock.cpp +++ b/tests/mock/backup_ext/src/ext_extension_mock.cpp @@ -123,11 +123,11 @@ ErrCode BackupExtExtension::HandleRestore() return BExtExtension::extExtension->HandleRestore(); } -void BackupExtExtension::CompareFiles(UniqueFd incrementalFd, - UniqueFd manifestFd, - vector &allFiles, - vector &smallFiles, - vector &bigFiles) +void BackupExtExtension::PreparaBackupFiles(UniqueFd incrementalFd, + UniqueFd manifestFd, + vector &allFiles, + vector &smallFiles, + vector &bigFiles) { } diff --git a/tests/unittests/backup_ext/ext_extension_test.cpp b/tests/unittests/backup_ext/ext_extension_test.cpp index 9a73d1a97b1b0b50e0106cbf8a477b3808972fd8..63d917b7d5149f1bf08eb59b53decf04dcfbb394 100644 --- a/tests/unittests/backup_ext/ext_extension_test.cpp +++ b/tests/unittests/backup_ext/ext_extension_test.cpp @@ -236,9 +236,9 @@ HWTEST_F(ExtExtensionTest, Ext_Extension_Test_0400, testing::ext::TestSize.Level GTEST_LOG_(INFO) << "ExtExtensionTest-begin Ext_Extension_Test_0400"; try { string tarName = " "; - auto ret = GetTarIncludes(tarName); - size_t size = ret.size(); - EXPECT_EQ(size, 0); + unordered_map infos; + GetTarIncludes(tarName, infos); + EXPECT_EQ(infos.size(), 0); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ExtExtensionTest-an exception occurred by construction."; diff --git a/tests/unittests/backup_utils/b_json/b_report_entity_test.cpp b/tests/unittests/backup_utils/b_json/b_report_entity_test.cpp index 9286793fb258df6cf4d9b7fba5a9ca016715613c..5bc9fd7472bc363c2913486005d066a7f2243e7d 100644 --- a/tests/unittests/backup_utils/b_json/b_report_entity_test.cpp +++ b/tests/unittests/backup_utils/b_json/b_report_entity_test.cpp @@ -31,13 +31,6 @@ namespace OHOS::FileManagement::Backup { using namespace std; -const int MODE_KEY = 0; -const int DIR_KEY = 1; -const int SIZE_KEY = 2; -const int MTIME_KEY = 3; -const int HASH_KEY = 4; -const int IS_INCREMENTAL_KEY = 5; - class BReportEntityTest : public testing::Test { public: static void SetUpTestCase(void) {}; @@ -80,14 +73,16 @@ HWTEST_F(BReportEntityTest, b_report_entity_GetReportInfos_0100, testing::ext::T string size = "1"; string mtime = "1501927260"; string hash = "ASDasadSDASDA"; + string isIncremental = "1"; - string content = "version=1.0&attrNum=6\r\npath;mode;dir;size;mtime;hash\r\n"; - content += fileName + ";" + mode + ";" + isDir + ";" + size + ";" + mtime + ";" + hash; + string content = "version=1.0&attrNum=6\r\npath;mode;dir;size;mtime;hash;isIncremetal\r\n"; + content += fileName + ";" + mode + ";" + isDir + ";" + size + ";" + mtime + ";" + hash + ";" + isIncremental; TestManager tm(__func__); const auto [filePath, res] = GetTestFile(tm, content); BReportEntity cloudRp(UniqueFd(open(filePath.data(), O_RDONLY, 0))); - unordered_map cloudFiles = cloudRp.GetReportInfos(); + unordered_map cloudFiles; + cloudRp.GetReportInfos(cloudFiles); bool flag = false; fileName = fileName.substr(1, fileName.length() - 1); @@ -100,6 +95,7 @@ HWTEST_F(BReportEntityTest, b_report_entity_GetReportInfos_0100, testing::ext::T EXPECT_EQ(to_string(item.second.size), size); EXPECT_EQ(to_string(item.second.mtime), mtime); EXPECT_EQ(item.second.hash, hash); + EXPECT_EQ(to_string(item.second.isIncremental), isIncremental); flag = true; break; @@ -128,15 +124,17 @@ HWTEST_F(BReportEntityTest, b_report_entity_SplitStringByChar_0100, testing::ext try { string str = ""; char sep = ATTR_SEP; - auto splits = SplitStringByChar(str, sep); + vector splits; + SplitStringByChar(str, sep, splits); EXPECT_EQ(splits.size(), 0); str = "test;"; - splits = SplitStringByChar(str, sep); + SplitStringByChar(str, sep, splits); EXPECT_EQ(splits.size(), 2); str = "test"; - splits = SplitStringByChar(str, sep); + splits.clear(); + SplitStringByChar(str, sep, splits); EXPECT_EQ(splits.size(), 1); } catch (const exception &e) { GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by SplitStringByChar. " << e.what(); @@ -159,31 +157,27 @@ HWTEST_F(BReportEntityTest, b_report_entity_ParseReportInfo_0100, testing::ext:: try { struct ReportFileInfo fileStat; vector splits; - unordered_map keys; - auto err = ParseReportInfo(fileStat, splits, keys); + std::vector keys; + int testLen = 1; + auto err = ParseReportInfo(fileStat, splits, testLen); + EXPECT_EQ(err, EPERM); + + splits.emplace_back("test"); + testLen = 1; + err = ParseReportInfo(fileStat, splits, testLen); EXPECT_EQ(err, EPERM); fileStat = {}; splits = {"/test", "0", "0", "0", "0", "0", "0"}; - keys.emplace(INFO_MODE, 0); - keys.emplace(INFO_DIR, 1); - keys.emplace(INFO_SIZE, 2); - keys.emplace(INFO_MTIME, 3); - keys.emplace(INFO_HASH, 4); - keys.emplace(INFO_IS_INCREMENTAL, 5); - err = ParseReportInfo(fileStat, splits, keys); + err = ParseReportInfo(fileStat, splits, splits.size()); EXPECT_EQ(err, ERR_OK); - fileStat = {}; - splits = {"test", "0", "1", "0", "0", "0", "1"}; - keys.clear(); - keys.emplace(INFO_MODE, 0); - keys.emplace(INFO_DIR, 1); - keys.emplace(INFO_SIZE, 2); - keys.emplace(INFO_MTIME, 3); - keys.emplace(INFO_HASH, 4); - keys.emplace(INFO_IS_INCREMENTAL, 5); - err = ParseReportInfo(fileStat, splits, keys); + splits = {"test", "0", "1", "0", "0", "0", "1", "1"}; + err = ParseReportInfo(fileStat, splits, splits.size()); + EXPECT_EQ(err, ERR_OK); + + splits = {"test", "0", "1", "test", "test", "0", "1", "1"}; + err = ParseReportInfo(fileStat, splits, splits.size()); EXPECT_EQ(err, ERR_OK); } catch (const exception &e) { GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by ParseReportInfo." << e.what(); @@ -204,7 +198,7 @@ HWTEST_F(BReportEntityTest, b_report_entity_DealLine_0100, testing::ext::TestSiz { GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_DealLine_0100"; try { - unordered_map keys; + std::vector keys; int num = 1; string line = "test\r"; unordered_map infos; @@ -217,14 +211,13 @@ HWTEST_F(BReportEntityTest, b_report_entity_DealLine_0100, testing::ext::TestSiz DealLine(keys, num, line, infos); EXPECT_EQ(infos.size(), 0); + line = "/test;0;0;0;0;0;0;0\r"; + keys = Data_Header; + DealLine(keys, num, line, infos); + EXPECT_EQ(infos.size(), 1); + line = "/test;0;0;0;0;0;0\r"; - keys.clear(); - keys.emplace(INFO_MODE, 0); - keys.emplace(INFO_DIR, 1); - keys.emplace(INFO_SIZE, 2); - keys.emplace(INFO_MTIME, 3); - keys.emplace(INFO_HASH, 4); - keys.emplace(INFO_IS_INCREMENTAL, 5); + keys.resize(keys.size() - 1); DealLine(keys, num, line, infos); EXPECT_EQ(infos.size(), 1); } catch (const exception &e) { @@ -246,113 +239,35 @@ HWTEST_F(BReportEntityTest, b_report_entity_DealLine_0101, testing::ext::TestSiz { GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_DealLine_0101"; try { - unordered_map keys; - int num = 1; + std::vector keys; + int num = 0; string line = ""; unordered_map infos; DealLine(keys, num, line, infos); EXPECT_EQ(infos.size(), 0); - } catch (const exception &e) { - GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); - EXPECT_TRUE(false); - } - GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_DealLine_0101"; -} + EXPECT_EQ(keys.size(), 0); -/** - * @tc.number: SUB_backup_b_report_entity_StorageDealLine_0100 - * @tc.name: b_report_entity_StorageDealLine_0100 - * @tc.desc: Test function of DealLine interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - */ -HWTEST_F(BReportEntityTest, b_report_entity_StorageDealLine_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_StorageDealLine_0100"; - try { - unordered_map keys; - int num = 1; - string line = ""; - StorageDealLine(keys, num, line); - EXPECT_TRUE(true); - } catch (const exception &e) { - GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); - EXPECT_TRUE(false); - } - GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_StorageDealLine_0100"; -} - -/** - * @tc.number: SUB_backup_b_report_entity_StorageDealLine_0101 - * @tc.name: b_report_entity_StorageDealLine_0101 - * @tc.desc: Test function of DealLine interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - */ -HWTEST_F(BReportEntityTest, b_report_entity_StorageDealLine_0101, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_StorageDealLine_0101"; - try { - unordered_map keys; - int num = 0; - string line = "test\r"; - StorageDealLine(keys, num, line); - EXPECT_TRUE(true); - } catch (const exception &e) { - GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); - EXPECT_TRUE(false); - } - GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_StorageDealLine_0101"; -} + num = 1; + DealLine(keys, num, line, infos); + EXPECT_EQ(infos.size(), 0); + EXPECT_EQ(keys.size(), 0); -/** - * @tc.number: SUB_backup_b_report_entity_StorageDealLine_0102 - * @tc.name: b_report_entity_StorageDealLine_0102 - * @tc.desc: Test function of DealLine interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - */ -HWTEST_F(BReportEntityTest, b_report_entity_StorageDealLine_0102, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_StorageDealLine_0102"; - try { - unordered_map keys; - int num = 1; - string line = "key1;key2;key3"; - StorageDealLine(keys, num, line); - EXPECT_TRUE(true); - } catch (const exception &e) { - GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); - EXPECT_TRUE(false); - } - GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_StorageDealLine_0102"; -} + num = 2; + line = ""; + DealLine(keys, num, line, infos); + EXPECT_EQ(infos.size(), 0); + EXPECT_EQ(keys.size(), 0); -/** - * @tc.number: SUB_backup_b_report_entity_StorageDealLine_0103 - * @tc.name: b_report_entity_StorageDealLine_0103 - * @tc.desc: Test function of DealLine interface for SUCCESS. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - */ -HWTEST_F(BReportEntityTest, b_report_entity_StorageDealLine_0103, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_StorageDealLine_0103"; - try { - unordered_map keys; - int num = INFO_ALIGN_NUM; - string line = "key1;key2;key3"; - StorageDealLine(keys, num, line); - EXPECT_TRUE(true); + num = 2; + line = "test"; + DealLine(keys, num, line, infos); + EXPECT_EQ(infos.size(), 0); + EXPECT_EQ(keys.size(), 0); } catch (const exception &e) { GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); EXPECT_TRUE(false); } - GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_StorageDealLine_0103"; + GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_DealLine_0101"; } /** @@ -373,25 +288,16 @@ HWTEST_F(BReportEntityTest, b_report_entity_GetStorageReportInfos_0100, testing: string size = "1"; string mtime = "1501927260"; string hash = "ASDasadSDASDA"; + string isIncremental = "1"; - string content = "version=1.0&attrNum=6\r\npath;mode;dir;size;mtime;hash\r\n"; - content += fileName + ";" + mode + ";" + isDir + ";" + size + ";" + mtime + ";" + hash; + string content = "version=1.0&attrNum=6\r\npath;mode;dir;size;mtime;hash;isIncremental\r\n"; + content += fileName + ";" + mode + ";" + isDir + ";" + size + ";" + mtime + ";" + hash + ";" + isIncremental; TestManager tm(__func__); const auto [filePath, res] = GetTestFile(tm, content); BReportEntity cloudRp(UniqueFd(open(filePath.data(), O_RDONLY, 0))); - struct ReportFileInfo fileStat = {}; - vector splits = {"/test", "0", "0", "0", "0", "0", "0"}; - unordered_map keys; - keys.emplace(INFO_MODE, MODE_KEY); - keys.emplace(INFO_DIR, DIR_KEY); - keys.emplace(INFO_SIZE, SIZE_KEY); - keys.emplace(INFO_MTIME, MTIME_KEY); - keys.emplace(INFO_HASH, HASH_KEY); - keys.emplace(INFO_IS_INCREMENTAL, IS_INCREMENTAL_KEY); - auto err = ParseReportInfo(fileStat, splits, keys); - EXPECT_EQ(err, ERR_OK); - bool ret = cloudRp.GetStorageReportInfos(fileStat); + unordered_map localFilesInfo; + bool ret = cloudRp.GetStorageReportInfos(localFilesInfo); EXPECT_TRUE(ret); } catch (const exception &e) { GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by GetStorageReportInfos."; diff --git a/utils/include/b_json/b_report_entity.h b/utils/include/b_json/b_report_entity.h index f9380191e4539903b1d147d46b4d84252ed874fc..0fa644b0705e1e0047027c62ad0f3d44adc5c848 100644 --- a/utils/include/b_json/b_report_entity.h +++ b/utils/include/b_json/b_report_entity.h @@ -36,21 +36,30 @@ struct ReportFileInfo { bool encodeFlag {false}; }; +enum class KeyType { + PATH, + MODE, + DIR, + SIZE, + MTIME, + HASH, + IS_INCREMENTAL, + ENCODE_FLAG +}; + class BReportEntity { public: /** * @brief 获取Report信息 - * - * @return std::map */ - std::unordered_map GetReportInfos() const; + void GetReportInfos(std::unordered_map &infos) const; /** * @brief 获取本地Report信息 * * @return bool */ - bool GetStorageReportInfos(struct ReportFileInfo &fileStat); + bool GetStorageReportInfos(std::unordered_map &infos); /** * @brief Check if line is encode @@ -84,6 +93,10 @@ public: protected: UniqueFd srcFile_; +private: + std::string currLineInfo_; + int currLineNum_ = 0; + std::vector keys_; }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/src/b_filesystem/b_dir.cpp b/utils/src/b_filesystem/b_dir.cpp index baac25c55f185586a0fbfda3c2a43198876c4fc9..40adc4644bf7de4be327122de504ad07ba1cf799 100644 --- a/utils/src/b_filesystem/b_dir.cpp +++ b/utils/src/b_filesystem/b_dir.cpp @@ -73,7 +73,7 @@ static tuple, map> GetFile(con return {BError(BError::Codes::OK).GetCode(), files, smallFiles}; } if (sta.st_size <= size) { - smallFiles.insert(make_pair(path, sta.st_size)); + smallFiles.emplace(make_pair(path, sta.st_size)); } else { files.try_emplace(path, sta); } @@ -103,7 +103,7 @@ static tuple, map> GetDirFiles if (path.at(path.size()-1) != BConstants::FILE_SEPARATOR_CHAR) { newPath += BConstants::FILE_SEPARATOR_CHAR; } - smallFiles.insert(make_pair(newPath, 0)); + smallFiles.emplace(make_pair(newPath, 0)); return {ERR_OK, files, smallFiles}; } @@ -124,7 +124,7 @@ static tuple, map> GetDirFiles continue; } if (sta.st_size <= size) { - smallFiles.insert(make_pair(fileName, sta.st_size)); + smallFiles.emplace(make_pair(fileName, sta.st_size)); continue; } @@ -166,7 +166,7 @@ tuple> BDir::GetDirFiles(const string &path) } else if (ptr->d_type == DT_DIR) { continue; } else { - files.push_back(IncludeTrailingPathDelimiter(path) + string(ptr->d_name)); + files.emplace_back(IncludeTrailingPathDelimiter(path) + string(ptr->d_name)); } } @@ -248,7 +248,7 @@ static set ExpandPathWildcard(const vector &vec, bool onlyPath) } RmForceExcludePath(expandPath); for (auto it = expandPath.begin(); it != expandPath.end(); ++it) { - filteredPath.insert(*it); + filteredPath.emplace(*it); if (onlyPath && *it->rbegin() != BConstants::FILE_SEPARATOR_CHAR) { continue; } @@ -275,9 +275,12 @@ tuple, map> BDir::GetBigFiles( if (errCode == 0) { incFiles.merge(move(files)); HILOGW("big files: %{public}zu; small files: %{public}zu", files.size(), smallFiles.size()); - incSmallFiles.insert(smallFiles.begin(), smallFiles.end()); + incSmallFiles.merge(move(smallFiles)); } } + if (excludes.empty()) { + return {ERR_OK, move(incFiles), move(incSmallFiles)}; + } auto isMatch = [](const vector &s, const string &str) -> bool { if (str.empty()) { @@ -301,14 +304,14 @@ tuple, map> BDir::GetBigFiles( map resSmallFiles; for (const auto &item : incSmallFiles) { if (!isMatch(excludes, item.first)) { - resSmallFiles.insert(make_pair(item.first, item.second)); + resSmallFiles.emplace(item); } } map bigFiles; for (const auto &item : incFiles) { if (!isMatch(excludes, item.first)) { - bigFiles[item.first] = item.second; + bigFiles.emplace(item); } } HILOGW("total number of big files is %{public}zu", bigFiles.size()); @@ -345,8 +348,8 @@ void BDir::GetUser0FileStat(vector bigFile, storageFiles.mode = to_string(static_cast(sta.st_mode)); int64_t lastUpdateTime = static_cast(sta.st_mtime); storageFiles.mtime = lastUpdateTime; - allFiles.push_back(storageFiles); - smallFiles.push_back(storageFiles); + allFiles.emplace_back(storageFiles); + smallFiles.emplace_back(storageFiles); } for (const auto &item : bigFile) { struct ReportFileInfo storageFiles; @@ -365,8 +368,8 @@ void BDir::GetUser0FileStat(vector bigFile, int64_t lastUpdateTime = static_cast(sta.st_mtime); storageFiles.mtime = lastUpdateTime; storageFiles.userTar = 1; - allFiles.push_back(storageFiles); - bigFiles.push_back(storageFiles); + allFiles.emplace_back(storageFiles); + bigFiles.emplace_back(storageFiles); } HILOGI("get FileStat end, bigfiles = %{public}zu, smallFiles = %{public}zu, allFiles = %{public}zu,", bigFiles.size(), smallFiles.size(), allFiles.size()); @@ -380,11 +383,11 @@ static tuple, vector> IsNotPath(const string &path, vecto return {}; } if (sta.st_size <= size) { - smallFiles.push_back(path); + smallFiles.emplace_back(path); HILOGI("bigfiles = %{public}zu, smallfiles = %{public}zu", bigFiles.size(), smallFiles.size()); return {bigFiles, smallFiles}; } - bigFiles.push_back(path); + bigFiles.emplace_back(path); HILOGI("bigfiles = %{public}zu, smallfiles = %{public}zu", bigFiles.size(), smallFiles.size()); return {bigFiles, smallFiles}; } @@ -398,7 +401,7 @@ static tuple, vector> GetUser0DirFilesDetail(const string if (path.at(path.size()-1) != BConstants::FILE_SEPARATOR_CHAR) { newPath += BConstants::FILE_SEPARATOR_CHAR; } - smallFiles.push_back(newPath); + smallFiles.emplace_back(newPath); return {bigFiles, smallFiles}; } if (filesystem::is_regular_file(path)) { @@ -421,11 +424,11 @@ static tuple, vector> GetUser0DirFilesDetail(const string continue; } if (sta.st_size <= size) { - smallFiles.push_back(fileName); + smallFiles.emplace_back(fileName); continue; } - bigFiles.push_back(fileName); + bigFiles.emplace_back(fileName); continue; } else if (ptr->d_type != DT_DIR) { HILOGE("Not support file type"); @@ -502,6 +505,7 @@ vector BDir::GetDirs(const vector &paths) bool BDir::CheckFilePathInvalid(const std::string &filePath) { if (filePath.find("../") != std::string::npos) { + HILOGE("Relative path is not allowed, path = %{public}s", GetAnonyPath(filePath).c_str()); return true; } return false; diff --git a/utils/src/b_json/b_json_clear_data_config.cpp b/utils/src/b_json/b_json_clear_data_config.cpp index cd79b63b7aebdb6e416dbfff25fe2c27b58aba94..d21d314cad01ef4f66bf6aeab9d15cb2a5e23dc8 100644 --- a/utils/src/b_json/b_json_clear_data_config.cpp +++ b/utils/src/b_json/b_json_clear_data_config.cpp @@ -247,7 +247,7 @@ vector BJsonClearDataConfig::GetAllClearBundleRecords() cJSON *item = cJSON_GetArrayItem(configArray, i); if (item != nullptr && cJSON_GetObjectItem(item, "bundleName") != nullptr && cJSON_GetObjectItem(item, "bundleName")->type == cJSON_String) { - bundleNameList.push_back(cJSON_GetObjectItem(item, "bundleName")->valuestring); + bundleNameList.emplace_back(cJSON_GetObjectItem(item, "bundleName")->valuestring); } } cJSON_Delete(jsonObjectDis); diff --git a/utils/src/b_json/b_json_entity_extension_config.cpp b/utils/src/b_json/b_json_entity_extension_config.cpp index 915ece4cabfc699b5d3f145ded71782f07d4fdb6..a6e639d5104766d681d4fa708241c1151eb72d66 100644 --- a/utils/src/b_json/b_json_entity_extension_config.cpp +++ b/utils/src/b_json/b_json_entity_extension_config.cpp @@ -51,7 +51,7 @@ vector BJsonEntityExtensionConfig::GetIncludes() const HILOGE("Each item of array 'includes' must be of the type string"); continue; } - dirs.push_back(item.asString()); + dirs.emplace_back(item.asString()); } if (dirs.empty()) { @@ -81,7 +81,7 @@ vector BJsonEntityExtensionConfig::GetExcludes() const HILOGE("Each item of array 'excludes' must be of the type string"); continue; } - dirs.push_back(item.asString()); + dirs.emplace_back(item.asString()); } return dirs; } diff --git a/utils/src/b_json/b_json_service_disposal_config.cpp b/utils/src/b_json/b_json_service_disposal_config.cpp index 22dd89a43db28bb7b1ce73c5b104472fa6dc788d..1a6ac916c27fe31f83943bd3d8c7711e61d64626 100644 --- a/utils/src/b_json/b_json_service_disposal_config.cpp +++ b/utils/src/b_json/b_json_service_disposal_config.cpp @@ -255,7 +255,7 @@ vector BJsonDisposalConfig::GetBundleNameFromConfigFile() cJSON *item = cJSON_GetArrayItem(configArray, i); if (item != nullptr && cJSON_GetObjectItem(item, "bundleName") != nullptr && cJSON_GetObjectItem(item, "bundleName")->type == cJSON_String) { - bundleNameList.push_back(cJSON_GetObjectItem(item, "bundleName")->valuestring); + bundleNameList.emplace_back(cJSON_GetObjectItem(item, "bundleName")->valuestring); } } cJSON_Delete(jsonObjectDis); diff --git a/utils/src/b_json/b_report_entity.cpp b/utils/src/b_json/b_report_entity.cpp index fb5d342c1838aa648f3d5a8af73e7ffcdc84cf3a..1f5cfab9376b0e9aaee2060d276acb639da7f28d 100644 --- a/utils/src/b_json/b_report_entity.cpp +++ b/utils/src/b_json/b_report_entity.cpp @@ -32,25 +32,21 @@ namespace { const char ATTR_SEP = ';'; const char LINE_SEP = '\n'; const char LINE_WRAP = '\r'; -const int64_t HASH_BUFFER_SIZE = 4096; // 每次读取的siz +const int64_t HASH_BUFFER_SIZE = 4096; // 每次读取的size const int INFO_ALIGN_NUM = 2; -const int BUFFER_LENGTH = 2; -const string INFO_DIR = "dir"; -const string INFO_HASH = "hash"; -const string INFO_IS_INCREMENTAL = "isIncremental"; -const string INFO_MODE = "mode"; -const string INFO_MTIME = "mtime"; -const string INFO_PATH = "path"; -const string INFO_SIZE = "size"; -const string INFO_ENCODE_FLAG = "encodeFlag"; +const size_t LAST_VERSION_LEN = 7; // 7: "path", "mode", "dir", "size", "mtime", "hash", "isIncremental" +const std::string DEFAULT_VALUE = "1"; +const std::vector Data_Header = { + "path", "mode", "dir", "size", "mtime", "hash", "isIncremental", "encodeFlag" +}; + } // namespace -static vector SplitStringByChar(const string &str, const char &sep) +static void SplitStringByChar(const string &str, const char &sep, vector& splits) { - vector splits; string newStr = str; - if (str.empty() || str.size() < 1) { - return splits; + if (str.empty()) { + return; } if (str.rfind(sep) == str.size() - 1) { newStr += sep; @@ -58,71 +54,51 @@ static vector SplitStringByChar(const string &str, const char &sep) stringstream ss(newStr); string res; while (getline(ss, res, sep)) { - splits.push_back(res); - } - - return splits; -} - -static void ParseSplitsItem(const vector &splits, const unordered_map &keys, - vector &residue, string &path) -{ - size_t splitsLen = splits.size(); - for (size_t i = 0; i < splitsLen; i++) { - if (i <= splitsLen - keys.size()) { - path += splits[i] + ";"; - } else { - residue.emplace_back(splits[i]); - } + splits.emplace_back(res); } } static ErrCode ParseReportInfo(struct ReportFileInfo &fileStat, const vector &splits, - const unordered_map &keys) + const size_t keyLen) { // 根据数据拼接结构体 // 处理path路径 - string path; - vector residue; try { // 识别path字段与其他字段 - ParseSplitsItem(splits, keys, residue, path); - if (residue.size() != keys.size() - 1) { - HILOGE("Error residue size"); + size_t dataLen = splits.size(); + if (dataLen != keyLen || dataLen < LAST_VERSION_LEN) { + HILOGE("Error data size"); return EPERM; } - if (keys.find(INFO_ENCODE_FLAG) != keys.end()) { - fileStat.encodeFlag = residue[keys.find(INFO_ENCODE_FLAG)->second] == "1" ? true : false; + string path = splits[static_cast(KeyType::PATH)] + ATTR_SEP; + if (dataLen == LAST_VERSION_LEN) { + fileStat.encodeFlag = false; + } else { + fileStat.encodeFlag = splits[static_cast(KeyType::ENCODE_FLAG)] == DEFAULT_VALUE; } path = (path.length() > 0 && path[0] == '/') ? path.substr(1, path.length() - 1) : path; auto fileRawPath = (path.length() > 0) ? path.substr(0, path.length() - 1) : path; fileStat.filePath = BReportEntity::DecodeReportItem(fileRawPath, fileStat.encodeFlag); HILOGD("Briefings file %{public}s", fileStat.filePath.c_str()); - if (keys.find(INFO_MODE) != keys.end()) { - fileStat.mode = residue[keys.find(INFO_MODE)->second]; - } - if (keys.find(INFO_DIR) != keys.end()) { - fileStat.isDir = residue[keys.find(INFO_DIR)->second] == "1" ? true : false; - } - if (keys.find(INFO_SIZE) != keys.end()) { - stringstream sizeStr(residue[keys.find(INFO_SIZE)->second]); - off_t size = 0; - sizeStr >> size; - fileStat.size = size; - } - if (keys.find(INFO_MTIME) != keys.end()) { - stringstream mtimeStr(residue[keys.find(INFO_MTIME)->second]); - off_t mtime = 0; - mtimeStr >> mtime; - fileStat.mtime = mtime; - } - if (keys.find(INFO_HASH) != keys.end()) { - fileStat.hash = residue[keys.find(INFO_HASH)->second]; + fileStat.mode = splits[static_cast(KeyType::MODE)]; + fileStat.isDir = splits[static_cast(KeyType::DIR)] == DEFAULT_VALUE; + + stringstream sizeStream(splits[static_cast(KeyType::SIZE)]); + off_t size = 0; + if (!(sizeStream >> size)) { + HILOGE("Transfer size err"); } - if (keys.find(INFO_IS_INCREMENTAL) != keys.end()) { - fileStat.isIncremental = residue[keys.find(INFO_IS_INCREMENTAL)->second] == "1" ? true : false; + fileStat.size = size; + + stringstream mtimeStream(splits[static_cast(KeyType::MTIME)]); + off_t mtime = 0; + if (!(mtimeStream >> mtime)) { + HILOGE("Transfer mtime err"); } + fileStat.mtime = mtime; + fileStat.hash = splits[static_cast(KeyType::HASH)]; + fileStat.isIncremental = splits[static_cast(KeyType::IS_INCREMENTAL)] == DEFAULT_VALUE; return ERR_OK; } catch (...) { HILOGE("Failed to ParseReportInfo"); @@ -130,7 +106,7 @@ static ErrCode ParseReportInfo(struct ReportFileInfo &fileStat, } } -static void DealLine(unordered_map &keys, +static void DealLine(vector &keys, int &num, const string &line, unordered_map &infos) @@ -143,18 +119,19 @@ static void DealLine(unordered_map &keys, if (currentLine[currentLine.length() - 1] == LINE_WRAP) { currentLine.pop_back(); } - - vector splits = SplitStringByChar(currentLine, ATTR_SEP); + vector splits; + SplitStringByChar(currentLine, ATTR_SEP, splits); if (num < INFO_ALIGN_NUM) { if (num == 1) { - for (int j = 0; j < (int)splits.size(); j++) { - keys.emplace(splits[j], j - 1); + keys = splits; + if (keys != Data_Header) { + HILOGE("File halder check err"); } } num++; } else { struct ReportFileInfo fileState; - auto code = ParseReportInfo(fileState, splits, keys); + auto code = ParseReportInfo(fileState, splits, keys.size()); if (code != ERR_OK) { HILOGE("ParseReportInfo err:%{public}d, %{public}s", code, currentLine.c_str()); } else { @@ -163,45 +140,12 @@ static void DealLine(unordered_map &keys, } } -static struct ReportFileInfo StorageDealLine(unordered_map &keys, int &num, const string &line) -{ - if (line.empty()) { - return {}; - } - - string currentLine = line; - if (currentLine[currentLine.length() - 1] == LINE_WRAP) { - currentLine.pop_back(); - } - - vector splits = SplitStringByChar(currentLine, ATTR_SEP); - if (num < INFO_ALIGN_NUM) { - if (num == 1) { - for (int j = 0; j < (int)splits.size(); j++) { - keys.emplace(splits[j], j - 1); - } - } - num++; - } else { - struct ReportFileInfo fileState; - auto code = ParseReportInfo(fileState, splits, keys); - if (code != ERR_OK) { - HILOGE("ParseReportInfo err:%{public}d, %{public}s", code, currentLine.c_str()); - } else { - return fileState; - } - } - return {}; -} - -unordered_map BReportEntity::GetReportInfos() const +void BReportEntity::GetReportInfos(unordered_map &infos) const { - unordered_map infos {}; - char buffer[HASH_BUFFER_SIZE]; ssize_t bytesRead; string currentLine; - unordered_map keys; + vector keys; int num = 0; while ((bytesRead = read(srcFile_, buffer, sizeof(buffer))) > 0) { @@ -219,34 +163,29 @@ unordered_map BReportEntity::GetReportInfos() con if (!currentLine.empty()) { DealLine(keys, num, currentLine, infos); } - - return infos; } -bool BReportEntity::GetStorageReportInfos(struct ReportFileInfo &fileStat) +bool BReportEntity::GetStorageReportInfos(std::unordered_map &infos) { - char buffer[BUFFER_LENGTH]; - ssize_t bytesRead; - string currentLine; - static unordered_map keys; - static int num = 0; + char buffer[HASH_BUFFER_SIZE]; + ssize_t bytesRead = 0; - if ((bytesRead = read(srcFile_, buffer, 1)) <= 0) { - keys = {}; - num = 0; - return false; - } - do { - if (buffer[0] != LINE_SEP && buffer[0] != '\0') { - currentLine += buffer[0]; - } else { - currentLine += LINE_SEP; - fileStat = StorageDealLine(keys, num, currentLine); - return true; + if ((bytesRead = read(srcFile_, buffer, sizeof(buffer))) > 0) { + for (ssize_t i = 0; i < bytesRead; i++) { + if (buffer[i] == LINE_SEP) { + DealLine(keys_, currLineNum_, currLineInfo_, infos); + currLineInfo_.clear(); + } else { + currLineInfo_ += buffer[i]; + } } - } while ((bytesRead = read(srcFile_, buffer, 1)) > 0); - currentLine += LINE_SEP; - fileStat = StorageDealLine(keys, num, currentLine); + } else { + if (currLineInfo_.empty()) { + return false; + } + DealLine(keys_, currLineNum_, currLineInfo_, infos); + currLineInfo_.clear(); + } return true; } @@ -256,7 +195,8 @@ void BReportEntity::CheckAndUpdateIfReportLineEncoded(std::string &path) return; } - unordered_map infos = GetReportInfos(); + unordered_map infos; + GetReportInfos(infos); constexpr int BIG_FILE_REPORT_INFO_NUM = 1; if (infos.size() == BIG_FILE_REPORT_INFO_NUM) { auto info = infos.begin(); diff --git a/utils/src/b_jsonutil/b_jsonutil.cpp b/utils/src/b_jsonutil/b_jsonutil.cpp index 24c841ebea2ea2816ef15e6d252fe3bdf4f97c41..2d9c2c228abdca824ae89d0461ca7eeabb8dc811 100644 --- a/utils/src/b_jsonutil/b_jsonutil.cpp +++ b/utils/src/b_jsonutil/b_jsonutil.cpp @@ -264,7 +264,7 @@ bool BJsonUtil::FindBundleInfoByName(std::map bundleDetailInfos = iter->second; - for (auto &bundleDetailInfo : bundleDetailInfos) { + for (const auto &bundleDetailInfo : bundleDetailInfos) { if (bundleDetailInfo.type == jobType) { bundleDetail = bundleDetailInfo; return true; diff --git a/utils/src/b_tarball/b_tarball_factory.cpp b/utils/src/b_tarball/b_tarball_factory.cpp index bed3c7006f1601ee4a5f702bcefb19c0f577a9be..2a2e28bc8f8e02aaaaf508b296d664ae7bcd0e73 100644 --- a/utils/src/b_tarball/b_tarball_factory.cpp +++ b/utils/src/b_tarball/b_tarball_factory.cpp @@ -94,7 +94,7 @@ static tuple, vector> TarFilter(string_view tarballDir, for (auto &item : excludes) { string str = removeBackSlash(item); if (!str.empty()) { - newExcludes.push_back(str); + newExcludes.emplace_back(str); } }